source: sasview/src/sas/sasgui/perspectives/corfunc/corfunc_panel.py @ a3ed157

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since a3ed157 was a3ed157, checked in by lewis, 8 years ago

More useful error messages when calculating bg fails

  • Property mode set to 100644
File size: 29.3 KB
RevLine 
[c23f303]1import wx
2import sys
[e73e723]3import numpy as np
[c23f303]4from wx.lib.scrolledpanel import ScrolledPanel
[3901e7c]5from sas.sasgui.guiframe.events import PlotQrangeEvent
6from sas.sasgui.guiframe.events import StatusEvent
[c23f303]7from sas.sasgui.guiframe.panel_base import PanelBase
[3901e7c]8from sas.sasgui.guiframe.utils import check_float
[3b8efec]9from sas.sasgui.guiframe.dataFitting import Data1D
[7858575]10from sas.sasgui.perspectives.invariant.invariant_widgets import OutputTextCtrl
[9f7dde3]11from sas.sasgui.perspectives.invariant.invariant_widgets import InvTextCtrl
[3901e7c]12from sas.sasgui.perspectives.fitting.basepage import ModelTextCtrl
[e02d8f6]13from sas.sasgui.perspectives.corfunc.corfunc_state import CorfuncState
[3b8efec]14import sas.sasgui.perspectives.corfunc.corfunc
15from sas.sascalc.corfunc.corfunc_calculator import CorfuncCalculator
[ebfdf4b]16from sas.sasgui.guiframe.documentation_window import DocumentationWindow
[37e7223]17from plot_labels import *
[c23f303]18
[033c14c]19OUTPUT_STRINGS = {
20    'max': "Long Period (A): ",
21    'Lc': "Average Hard Block Thickness (A): ",
22    'dtr': "Average Interface Thickness (A): ",
23    'd0': "Average Core Thickness: ",
[8bdc103]24    'A': "Polydispersity: ",
[c512f7d]25    'fill': "Local Crystallinity: "
[033c14c]26}
27
[c23f303]28if sys.platform.count("win32") > 0:
[7858575]29    _STATICBOX_WIDTH = 350
30    PANEL_WIDTH = 400
[c23f303]31    PANEL_HEIGHT = 700
32    FONT_VARIANT = 0
33else:
[7858575]34    _STATICBOX_WIDTH = 390
35    PANEL_WIDTH = 430
[c23f303]36    PANEL_HEIGHT = 700
37    FONT_VARIANT = 1
38
39class CorfuncPanel(ScrolledPanel,PanelBase):
40    window_name = "Correlation Function"
41    window_caption = "Correlation Function"
42    CENTER_PANE = True
43
44    def __init__(self, parent, data=None, manager=None, *args, **kwds):
45        kwds["size"] = (PANEL_WIDTH, PANEL_HEIGHT)
46        kwds["style"] = wx.FULL_REPAINT_ON_RESIZE
47        ScrolledPanel.__init__(self, parent=parent, *args, **kwds)
48        PanelBase.__init__(self, parent)
49        self.SetupScrolling()
50        self.SetWindowVariant(variant=FONT_VARIANT)
51        self._manager = manager
[911dbe4]52        # The data with no correction for background values
53        self._data = data # The data to be analysed (corrected fr background)
[3b8efec]54        self._extrapolated_data = None # The extrapolated data set
[033c14c]55        self._transformed_data = None # Fourier trans. of the extrapolated data
[911dbe4]56        self._calculator = CorfuncCalculator()
[3ec4b8f]57        self._data_name_box = None # Text box to show name of file
[b564ea2]58        self._background_input = None
[3901e7c]59        self._qmin_input = None
60        self._qmax1_input = None
61        self._qmax2_input = None
[711e157]62        self._extrapolate_btn = None
[911dbe4]63        self._transform_btn = None
[033c14c]64        self._extract_btn = None
[e02d8f6]65        self.qmin = 0
66        self.qmax = (0, 0)
[b564ea2]67        self.background = 0
[a684c64]68        self.extracted_params = None
[d03228e]69        self.transform_type = 'fourier'
[ff11b21]70        self._extrapolation_outputs = {}
[033c14c]71        # Dictionary for saving refs to text boxes used to display output data
72        self._output_boxes = None
[c23f303]73        self.state = None
74        self._do_layout()
[54a0989]75        self._disable_inputs()
[e02d8f6]76        self.set_state()
[b564ea2]77        self._qmin_input.Bind(wx.EVT_TEXT, self._on_enter_input)
78        self._qmax1_input.Bind(wx.EVT_TEXT, self._on_enter_input)
79        self._qmax2_input.Bind(wx.EVT_TEXT, self._on_enter_input)
[688d029]80        self._qmin_input.Bind(wx.EVT_MOUSE_EVENTS, self._on_click_qrange)
81        self._qmax1_input.Bind(wx.EVT_MOUSE_EVENTS, self._on_click_qrange)
82        self._qmax2_input.Bind(wx.EVT_MOUSE_EVENTS, self._on_click_qrange)
[3b8efec]83        self._background_input.Bind(wx.EVT_TEXT, self._on_enter_input)
[c23f303]84
85    def set_state(self, state=None, data=None):
[9c90cf3]86        """
87        Set the state of the panel. If no state is provided, the panel will
88        be set to the default state.
89
90        :param state: A CorfuncState object
91        :param data: A Data1D object
92        """
[e02d8f6]93        if state is None:
94            self.state = CorfuncState()
95        else:
96            self.state = state
97        if data is not None:
98            self.state.data = data
[3b8efec]99        self.set_data(data, set_qrange=False)
[e02d8f6]100        if self.state.qmin is not None:
101            self.set_qmin(self.state.qmin)
102        if self.state.qmax is not None and self.state.qmax != (None, None):
103            self.set_qmax(tuple(self.state.qmax))
[b564ea2]104        if self.state.background is not None:
105            self.set_background(self.state.background)
[2ff9e37]106        if self.state.is_extrapolated:
[6ccf18e]107            self.compute_extrapolation()
[2ff9e37]108        else:
109            return
110        if self.state.is_transformed:
[6ccf18e]111            self.compute_transform()
[2ff9e37]112        else:
113            return
114        if self.state.outputs is not None and self.state.outputs != {}:
[eb320682]115            self.set_extracted_params(self.state.outputs, reset=True)
[e02d8f6]116
117    def get_state(self):
118        """
119        Return the state of the panel
120        """
121        state = CorfuncState()
122        state.set_saved_state('qmin_tcl', self.qmin)
123        state.set_saved_state('qmax1_tcl', self.qmax[0])
124        state.set_saved_state('qmax2_tcl', self.qmax[1])
[b564ea2]125        state.set_saved_state('background_tcl', self.background)
[a684c64]126        state.outputs = self.extracted_params
[e02d8f6]127        if self._data is not None:
128            state.file = self._data.title
129            state.data = self._data
[2ff9e37]130        if self._extrapolated_data is not None:
131            state.is_extrapolated = True
132        if self._transformed_data is not None:
133            state.is_transformed = True
[e02d8f6]134        self.state = state
135
136        return self.state
[c23f303]137
[3901e7c]138    def onSetFocus(self, evt):
139        if evt is not None:
140            evt.Skip()
[b564ea2]141        self._validate_inputs()
[3901e7c]142
[e02d8f6]143    def set_data(self, data=None, set_qrange=True):
[7858575]144        """
145        Update the GUI to reflect new data that has been loaded in
146
147        :param data: The data that has been loaded
148        """
[e02d8f6]149        if data is None:
[da19985]150            self._disable_inputs()
[ff11b21]151            # Reset outputs
[da19985]152            self.set_extracted_params(reset=True)
[ff11b21]153            self.set_extrapolation_params()
[da19985]154            self._data = None
[e02d8f6]155            return
[54a0989]156        self._enable_inputs()
157        self._transform_btn.Disable()
[033c14c]158        self._extract_btn.Disable()
[e02d8f6]159        self._data_name_box.SetValue(str(data.title))
[3901e7c]160        self._data = data
[911dbe4]161        self._calculator.set_data(data)
[1150083]162        # Reset the outputs
[eb320682]163        self.set_extracted_params(None, reset=True)
[7858575]164        if self._manager is not None:
[1150083]165            self._manager.clear_data()
[911dbe4]166            self._manager.show_data(self._data, IQ_DATA_LABEL, reset=True)
[1150083]167
[e02d8f6]168        if set_qrange:
169            lower = data.x[-1]*0.05
170            upper1 = data.x[-1] - lower*5
171            upper2 = data.x[-1]
172            self.set_qmin(lower)
173            self.set_qmax((upper1, upper2))
[a3ed157]174            self._compute_background()
[e02d8f6]175
176    def get_data(self):
177        return self._data
178
[d03228e]179    def radio_changed(self, event=None):
180        if event is not None:
181            self.transform_type = event.GetEventObject().GetName()
182
[3b8efec]183    def compute_extrapolation(self, event=None):
[6970e51]184        """
185        Compute and plot the extrapolated data.
186        Called when Extrapolate button is pressed.
187        """
[3b8efec]188        if not self._validate_inputs:
189            msg = "Invalid Q range entered."
190            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
191            return
[93b145a]192
193        warning_msg = ""
194        if self.background < 0:
195            warning_msg += "Negative background value entered."
196        if any((self._data.y - self.background) < 0):
197            if warning_msg != "":
198                warning_msg += "\n"
199            warning_msg += "Background value entered results in negative Intensity values."
200        if warning_msg != "":
201            dlg = wx.MessageDialog(self.parent.parent, warning_msg, caption="Warning", style=wx.ICON_EXCLAMATION)
202            dlg.ShowModal()
203            dlg.Destroy()
204
[911dbe4]205        self._calculator.set_data(self._data)
206        self._calculator.lowerq = self.qmin
207        self._calculator.upperq = self.qmax
[275b448]208        self._calculator.background = self.background
[93b145a]209
[cdd1c3b]210        try:
[ff11b21]211            params, self._extrapolated_data = self._calculator.compute_extrapolation()
[a3ed157]212        except Exception as e:
213            msg = "Error extrapolating data:\n"
214            msg += str(e)
[cdd1c3b]215            wx.PostEvent(self._manager.parent,
[a3ed157]216                StatusEvent(status=msg, info="error"))
[cdd1c3b]217            self._transform_btn.Disable()
218            return
[3b8efec]219        # TODO: Find way to set xlim and ylim so full range of data can be
[5878a9ea]220        # plotted but zoomed in
[3b8efec]221        maxq = self._data.x.max()
222        mask = self._extrapolated_data.x <= maxq
223        numpts = len(self._extrapolated_data.x[mask]) + 250
224        plot_x = self._extrapolated_data.x[0:numpts]
225        plot_y = self._extrapolated_data.y[0:numpts]
226        to_plot = Data1D(plot_x, plot_y)
227        self._manager.show_data(to_plot, IQ_EXTRAPOLATED_DATA_LABEL)
[5878a9ea]228        # Update state of the GUI
[911dbe4]229        self._transform_btn.Enable()
[5878a9ea]230        self._extract_btn.Disable()
231        self.set_extracted_params(reset=True)
[ff11b21]232        self.set_extrapolation_params(params)
[911dbe4]233
234    def compute_transform(self, event=None):
[6970e51]235        """
236        Compute and plot the transformed data.
237        Called when Transform button is pressed.
238        """
[a2db1ab]239        if not self._calculator.transform_isrunning():
240            self._calculator.compute_transform(self._extrapolated_data,
[d03228e]241                self.transform_type, background=self.background,
242                completefn=self.transform_complete,
[a2db1ab]243                updatefn=self.transform_update)
[d03228e]244
[750a823]245            self._transform_btn.SetLabel("Stop Transform")
[a2db1ab]246        else:
247            self._calculator.stop_transform()
[d03228e]248            self.transform_update("Transform cancelled.")
[750a823]249            self._transform_btn.SetLabel("Transform")
[a2db1ab]250
251    def transform_update(self, msg=""):
252        """
[d03228e]253        Called from FourierThread to update on status of calculation
[a2db1ab]254        """
255        wx.PostEvent(self._manager.parent,
256            StatusEvent(status=msg))
257
258    def transform_complete(self, transform=None):
259        """
[d03228e]260        Called from FourierThread when calculation has completed
[a2db1ab]261        """
[2ed088a]262        self._transform_btn.SetLabel("Transform")
[a2db1ab]263        if transform is None:
[cdd1c3b]264            msg = "Error calculating Transform."
[d03228e]265            if self.transform_type == 'hilbert':
266                msg = "Not yet implemented"
[cdd1c3b]267            wx.PostEvent(self._manager.parent,
268                StatusEvent(status=msg, info="Error"))
269            self._extract_btn.Disable()
270            return
[a2db1ab]271        self._transformed_data = transform
[911dbe4]272        import numpy as np
[a2db1ab]273        plot_x = transform.x[np.where(transform.x <= 200)]
274        plot_y = transform.y[np.where(transform.x <= 200)]
[911dbe4]275        self._manager.show_data(Data1D(plot_x, plot_y), TRANSFORM_LABEL)
[d03228e]276        # Only enable extract params button if a fourier trans. has been done
277        if self.transform_type == 'fourier':
278            self._extract_btn.Enable()
279        else:
280            self._extract_btn.Disable()
[033c14c]281
282    def extract_parameters(self, event=None):
283        try:
284            params = self._calculator.extract_parameters(self._transformed_data)
285        except:
286            params = None
287        if params is None:
288            msg = "Error extracting parameters."
289            wx.PostEvent(self._manager.parent,
[cdd1c3b]290                StatusEvent(status=msg, info="Error"))
[033c14c]291            return
[a684c64]292        self.set_extracted_params(params)
[033c14c]293
[ebfdf4b]294    def on_help(self, event=None):
295        """
296        Show the corfunc documentation
297        """
298        tree_location = "user/sasgui/perspectives/corfunc/corfunc_help.html"
299        doc_viewer = DocumentationWindow(self, -1, tree_location, "",
300                                          "Correlation Function Help")
301
[e02d8f6]302    def save_project(self, doc=None):
303        """
304        Return an XML node containing the state of the panel
[9c90cf3]305
306        :param doc: Am xml node to attach the project state to (optional)
[e02d8f6]307        """
308        data = self._data
309        state = self.get_state()
[0bbebee]310        if data is not None:
[e02d8f6]311            new_doc, sasentry = self._manager.state_reader._to_xml_doc(data)
312            new_doc = state.toXML(doc=new_doc, entry_node=sasentry)
313            if new_doc is not None:
314                if doc is not None and hasattr(doc, "firstChild"):
315                    child = new_doc.getElementsByTagName("SASentry")
316                    for item in child:
317                        doc.firstChild.appendChild(item)
318                else:
319                    doc = new_doc
320        return doc
[3901e7c]321
[9c90cf3]322    def set_qmin(self, qmin):
323        self.qmin = qmin
324        self._qmin_input.SetValue(str(qmin))
325
326    def set_qmax(self, qmax):
327        self.qmax = qmax
328        self._qmax1_input.SetValue(str(qmax[0]))
329        self._qmax2_input.SetValue(str(qmax[1]))
330
[b564ea2]331    def set_background(self, bg):
332        self.background = bg
333        self._background_input.SetValue(str(bg))
[dc72638]334        self._calculator.background = bg
[7858575]335
[ff11b21]336    def set_extrapolation_params(self, params=None):
337        if params is None:
338            # Reset outputs
339            for output in self._extrapolation_outputs.values():
340                output.SetValue('-')
341            return
342        for key, value in params.iteritems():
343            output = self._extrapolation_outputs[key]
344            rounded = self._round_sig_figs(value, 6)
345            output.SetValue(rounded)
346
347
[eb320682]348    def set_extracted_params(self, params=None, reset=False):
[a684c64]349        self.extracted_params = params
[eb320682]350        error = False
[a684c64]351        if params is None:
[eb320682]352            if not reset: error = True
[ff11b21]353            for output in self._output_boxes.values():
354                output.SetValue('-')
[a684c64]355        else:
[eb320682]356            if len(params) < len(OUTPUT_STRINGS):
357                # Not all parameters were calculated
358                error = True
359            for key, value in params.iteritems():
[e73e723]360                rounded = self._round_sig_figs(value, 6)
361                self._output_boxes[key].SetValue(rounded)
[eb320682]362        if error:
363            msg = 'Not all parameters were able to be calculated'
364            wx.PostEvent(self._manager.parent, StatusEvent(
365                status=msg, info='error'))
366
[02a8779]367    def plot_qrange(self, active=None, leftdown=False):
368        if active is None:
369            active = self._qmin_input
370        wx.PostEvent(self._manager.parent, PlotQrangeEvent(
371            ctrl=[self._qmin_input, self._qmax1_input, self._qmax2_input],
372            active=active, id=IQ_DATA_LABEL, is_corfunc=True,
373            group_id=GROUP_ID_IQ_DATA, leftdown=leftdown))
374
[1150083]375
[911dbe4]376    def _compute_background(self, event=None):
[a3ed157]377        if event is not None:
378            event.Skip()
379        self._on_enter_input()
380        try:
381            bg = self._calculator.compute_background(self.qmax)
382            self.set_background(bg)
383        except Exception as e:
384            msg = "Error computing background level:\n"
385            msg += str(e)
386            wx.PostEvent(self._manager.parent,
387                StatusEvent(status=msg, info="error"))
[b564ea2]388
389    def _on_enter_input(self, event=None):
[3901e7c]390        """
391        Read values from input boxes and save to memory.
392        """
[e02d8f6]393        if event is not None: event.Skip()
[b564ea2]394        if not self._validate_inputs():
[3901e7c]395            return
[b564ea2]396        self.qmin = float(self._qmin_input.GetValue())
[3901e7c]397        new_qmax1 = float(self._qmax1_input.GetValue())
398        new_qmax2 = float(self._qmax2_input.GetValue())
399        self.qmax = (new_qmax1, new_qmax2)
[b564ea2]400        self.background = float(self._background_input.GetValue())
[688d029]401        self._calculator.background = self.background
[e02d8f6]402        if event is not None:
[688d029]403            active_ctrl = event.GetEventObject()
404            if active_ctrl == self._background_input:
[02a8779]405                self._manager.show_data(self._data, IQ_DATA_LABEL,
406                    reset=False, active_ctrl=active_ctrl)
[688d029]407
408    def _on_click_qrange(self, event=None):
409        if event is None:
410            return
411        event.Skip()
412        if not self._validate_inputs(): return
[02a8779]413        self.plot_qrange(active=event.GetEventObject(),
414            leftdown=event.LeftDown())
[3901e7c]415
[b564ea2]416    def _validate_inputs(self):
[3901e7c]417        """
418        Check that the values for qmin and qmax in the input boxes are valid
419        """
420        if self._data is None:
421            return False
422        qmin_valid = check_float(self._qmin_input)
423        qmax1_valid = check_float(self._qmax1_input)
424        qmax2_valid = check_float(self._qmax2_input)
425        qmax_valid = qmax1_valid and qmax2_valid
[b564ea2]426        background_valid = check_float(self._background_input)
[3901e7c]427        msg = ""
[b564ea2]428        if (qmin_valid and qmax_valid and background_valid):
429            qmin = float(self._qmin_input.GetValue())
430            qmax1 = float(self._qmax1_input.GetValue())
431            qmax2 = float(self._qmax2_input.GetValue())
432            background = float(self._background_input.GetValue())
433            if not qmin > self._data.x.min():
434                msg = "qmin must be greater than the lowest q value"
435                qmin_valid = False
436            elif qmax2 < qmax1:
437                msg = "qmax1 must be less than qmax2"
438                qmax_valid = False
439            elif qmin > qmax1:
440                msg = "qmin must be less than qmax"
441                qmin_valid = False
[033c14c]442            elif background > self._data.y.max():
443                msg = "background must be less than highest I"
[b564ea2]444                background_valid = False
445        if not qmin_valid:
446            self._qmin_input.SetBackgroundColour('pink')
447        if not qmax_valid:
448            self._qmax1_input.SetBackgroundColour('pink')
449            self._qmax2_input.SetBackgroundColour('pink')
450        if not background_valid:
451            self._background_input.SetBackgroundColour('pink')
452            if msg != "":
453                wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
454        if (qmin_valid and qmax_valid and background_valid):
[3901e7c]455            self._qmin_input.SetBackgroundColour(wx.WHITE)
456            self._qmax1_input.SetBackgroundColour(wx.WHITE)
457            self._qmax2_input.SetBackgroundColour(wx.WHITE)
[b564ea2]458            self._background_input.SetBackgroundColour(wx.WHITE)
[3901e7c]459        self._qmin_input.Refresh()
460        self._qmax1_input.Refresh()
461        self._qmax2_input.Refresh()
[f2bbabf]462        self._background_input.Refresh()
[b564ea2]463        return (qmin_valid and qmax_valid and background_valid)
[7858575]464
[c23f303]465    def _do_layout(self):
466        """
467        Draw the window content
468        """
[7858575]469        vbox = wx.GridBagSizer(0,0)
470
471        # I(q) data box
[9f7dde3]472        databox = wx.StaticBox(self, -1, "I(Q) Data Source")
473        databox_sizer = wx.StaticBoxSizer(databox, wx.VERTICAL)
[7858575]474
[9f7dde3]475        file_sizer = wx.GridBagSizer(5, 5)
[7858575]476
[ff11b21]477        y = 0
478
[7858575]479        file_name_label = wx.StaticText(self, -1, "Name:")
[9f7dde3]480        file_sizer.Add(file_name_label, (0, 0), (1, 1),
[7858575]481            wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
482
[9f7dde3]483        self._data_name_box = OutputTextCtrl(self, -1,
484            size=(300,20))
485        file_sizer.Add(self._data_name_box, (0, 1), (1, 1),
486            wx.CENTER | wx.ADJUST_MINSIZE, 15)
487
488        file_sizer.AddSpacer((1, 25), pos=(0,2))
489        databox_sizer.Add(file_sizer, wx.TOP, 15)
490
[ff11b21]491        vbox.Add(databox_sizer, (y, 0), (1, 1),
[9f7dde3]492            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE | wx.TOP, 15)
[ff11b21]493        y += 1
[9f7dde3]494
495        # Parameters
[d03228e]496        qbox = wx.StaticBox(self, -1, "Input Parameters")
[9f7dde3]497        qbox_sizer = wx.StaticBoxSizer(qbox, wx.VERTICAL)
498        qbox_sizer.SetMinSize((_STATICBOX_WIDTH, 75))
499
500        q_sizer = wx.GridBagSizer(5, 5)
501
502        # Explanation
503        explanation_txt = ("Corfunc will use all values in the lower range for"
504            " Guinier back extrapolation, and all values in the upper range "
505            "for Porod forward extrapolation.")
506        explanation_label = wx.StaticText(self, -1, explanation_txt,
507            size=(_STATICBOX_WIDTH, 60))
508
509        q_sizer.Add(explanation_label, (0,0), (1,4), wx.LEFT | wx.EXPAND, 5)
510
511        qrange_label = wx.StaticText(self, -1, "Q Range:", size=(50,20))
[7a219e3e]512        q_sizer.Add(qrange_label, (1,0), (1,1), wx.LEFT | wx.EXPAND, 5)
[9f7dde3]513
514        # Lower Q Range
515        qmin_label = wx.StaticText(self, -1, "Lower:", size=(50,20))
516        qmin_dash_label = wx.StaticText(self, -1, "-", size=(10,20),
517            style=wx.ALIGN_CENTER_HORIZONTAL)
518
[3560196]519        qmin_lower = OutputTextCtrl(self, -1, size=(75, 20), value="0.0")
520        self._qmin_input = ModelTextCtrl(self, -1, size=(75, 20),
[3901e7c]521                        style=wx.TE_PROCESS_ENTER, name='qmin_input',
[b564ea2]522                        text_enter_callback=self._on_enter_input)
[3901e7c]523        self._qmin_input.SetToolTipString(("Values with q < qmin will be used "
524            "for Guinier back extrapolation"))
[9f7dde3]525
[7a219e3e]526        q_sizer.Add(qmin_label, (2, 0), (1, 1), wx.LEFT | wx.EXPAND, 5)
527        q_sizer.Add(qmin_lower, (2, 1), (1, 1), wx.LEFT, 5)
528        q_sizer.Add(qmin_dash_label, (2, 2), (1, 1), wx.CENTER | wx.EXPAND, 5)
529        q_sizer.Add(self._qmin_input, (2, 3), (1, 1), wx.LEFT, 5)
[9f7dde3]530
531        # Upper Q range
532        qmax_tooltip = ("Values with qmax1 < q < qmax2 will be used for Porod"
533            " forward extrapolation")
534
535        qmax_label = wx.StaticText(self, -1, "Upper:", size=(50,20))
536        qmax_dash_label = wx.StaticText(self, -1, "-", size=(10,20),
537            style=wx.ALIGN_CENTER_HORIZONTAL)
538
[3560196]539        self._qmax1_input = ModelTextCtrl(self, -1, size=(75, 20),
[3901e7c]540            style=wx.TE_PROCESS_ENTER, name="qmax1_input",
[b564ea2]541            text_enter_callback=self._on_enter_input)
[3901e7c]542        self._qmax1_input.SetToolTipString(qmax_tooltip)
[3560196]543        self._qmax2_input = ModelTextCtrl(self, -1, size=(75, 20),
[3901e7c]544            style=wx.TE_PROCESS_ENTER, name="qmax2_input",
[b564ea2]545            text_enter_callback=self._on_enter_input)
[3901e7c]546        self._qmax2_input.SetToolTipString(qmax_tooltip)
[9f7dde3]547
[7a219e3e]548        q_sizer.Add(qmax_label, (3, 0), (1, 1), wx.LEFT | wx.EXPAND, 5)
549        q_sizer.Add(self._qmax1_input, (3, 1), (1, 1), wx.LEFT, 5)
550        q_sizer.Add(qmax_dash_label, (3, 2), (1, 1), wx.CENTER | wx.EXPAND, 5)
551        q_sizer.Add(self._qmax2_input, (3,3), (1, 1), wx.LEFT, 5)
552
[ff11b21]553        qbox_sizer.Add(q_sizer, wx.TOP, 0)
554
555        vbox.Add(qbox_sizer, (y, 0), (1, 1),
556            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
557        y += 1
558
559        extrapolation_box = wx.StaticBox(self, -1, "Extrapolation Parameters")
560        extrapolation_sizer = wx.StaticBoxSizer(extrapolation_box, wx.VERTICAL)
561        params_sizer = wx.GridBagSizer(5, 5)
562
563        guinier_label = wx.StaticText(self, -1, "Guinier:")
564        params_sizer.Add(guinier_label, (0, 0), (1,1),
565            wx.ALL | wx.EXPAND | wx.ADJUST_MINSIZE, 5)
566
567        a_label = wx.StaticText(self, -1, "A: ")
568        params_sizer.Add(a_label, (1, 0), (1, 1), wx.LEFT | wx.EXPAND, 15)
[7a219e3e]569
[ff11b21]570        a_output = OutputTextCtrl(self, wx.NewId(),
571            value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
572        params_sizer.Add(a_output, (1, 1), (1, 1), wx.RIGHT | wx.EXPAND, 15)
573        self._extrapolation_outputs['A'] = a_output
574
575        b_label = wx.StaticText(self, -1, "B: ")
576        params_sizer.Add(b_label, (2, 0), (1, 1), wx.LEFT | wx.EXPAND, 15)
577
578        b_output = OutputTextCtrl(self, wx.NewId(),
579            value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
580        params_sizer.Add(b_output, (2, 1), (1, 1), wx.RIGHT | wx.EXPAND, 15)
581        self._extrapolation_outputs['B'] = b_output
582
583        porod_label = wx.StaticText(self, -1, "Porod: ")
584        params_sizer.Add(porod_label, (0, 2), (1, 1),
585            wx.ALL | wx.EXPAND | wx.ADJUST_MINSIZE, 5)
586
587        k_label = wx.StaticText(self, -1, "K: ")
588        params_sizer.Add(k_label, (1, 2), (1, 1), wx.LEFT | wx.EXPAND, 15)
589
590        k_output = OutputTextCtrl(self, wx.NewId(),
591            value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
592        params_sizer.Add(k_output, (1, 3), (1, 1), wx.RIGHT | wx.EXPAND, 15)
593        self._extrapolation_outputs['K'] = k_output
594
595        sigma_label = wx.StaticText(self, -1, u'\u03C3: ')
596        params_sizer.Add(sigma_label, (2, 2), (1, 1), wx.LEFT | wx.EXPAND, 15)
597
598        sigma_output = OutputTextCtrl(self, wx.NewId(),
599            value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
600        params_sizer.Add(sigma_output, (2, 3), (1, 1), wx.RIGHT | wx.EXPAND, 15)
601        self._extrapolation_outputs['sigma'] = sigma_output
602
603        bg_label = wx.StaticText(self, -1, "Bg: ")
604        params_sizer.Add(bg_label, (3, 2), (1, 1), wx.LEFT | wx.EXPAND, 15)
605
[20ced5c]606        self._background_input = ModelTextCtrl(self, -1, value="0.0",
[ff11b21]607            style=wx.TE_PROCESS_ENTER | wx.TE_CENTRE, name='background_input',
[7a219e3e]608            text_enter_callback=self._on_enter_input)
609        self._background_input.SetToolTipString(("A background value to "
610            "subtract from all intensity values"))
[ff11b21]611        params_sizer.Add(self._background_input, (3, 3), (1, 1), wx.RIGHT | wx.EXPAND, 15)
[7a219e3e]612
[ff11b21]613        background_button = wx.Button(self, wx.NewId(), "Calculate Bg",
614            size=(75, -1))
[7a219e3e]615        background_button.Bind(wx.EVT_BUTTON, self._compute_background)
[ff11b21]616        params_sizer.Add(background_button, (4,3), (1, 1), wx.EXPAND | wx.RIGHT, 15)
[9f7dde3]617
[ff11b21]618        extrapolation_sizer.Add(params_sizer)
619        vbox.Add(extrapolation_sizer, (y, 0), (1, 1),
[9f7dde3]620            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
[ff11b21]621        y += 1
[9f7dde3]622
[d03228e]623        # Transform type
624        transform_box = wx.StaticBox(self, -1, "Transform Type")
625        transform_sizer = wx.StaticBoxSizer(transform_box, wx.VERTICAL)
626
627        radio_sizer = wx.GridBagSizer(5,5)
628
629        fourier_btn = wx.RadioButton(self, -1, "Fourier", name='fourier',
630            style=wx.RB_GROUP)
631        hilbert_btn = wx.RadioButton(self, -1, "Hilbert", name='hilbert')
632
633        fourier_btn.Bind(wx.EVT_RADIOBUTTON, self.radio_changed)
634        hilbert_btn.Bind(wx.EVT_RADIOBUTTON, self.radio_changed)
635
636        radio_sizer.Add(fourier_btn, (0,0), (1,1), wx.LEFT | wx.EXPAND)
637        radio_sizer.Add(hilbert_btn, (0,1), (1,1), wx.RIGHT | wx.EXPAND)
638
639        transform_sizer.Add(radio_sizer, wx.TOP, 0)
[ff11b21]640        vbox.Add(transform_sizer, (y, 0), (1, 1),
[d03228e]641            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
[ff11b21]642        y += 1
[d03228e]643
[9f7dde3]644        # Output data
[c512f7d]645        outputbox = wx.StaticBox(self, -1, "Output Parameters")
[9f7dde3]646        outputbox_sizer = wx.StaticBoxSizer(outputbox, wx.VERTICAL)
647
648        output_sizer = wx.GridBagSizer(5, 5)
649
[033c14c]650        self._output_boxes = dict()
651        i = 0
652        for key, value in OUTPUT_STRINGS.iteritems():
[3ec4b8f]653            # Create a label and a text box for each poperty
[033c14c]654            label = wx.StaticText(self, -1, value)
655            output_box = OutputTextCtrl(self, wx.NewId(),
[9f7dde3]656                value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
[3ec4b8f]657            # Save the ID of each of the text boxes for accessing after the
658            # output data has been calculated
[033c14c]659            self._output_boxes[key] = output_box
[9f7dde3]660            output_sizer.Add(label, (i, 0), (1, 1), wx.LEFT | wx.EXPAND, 15)
661            output_sizer.Add(output_box, (i, 2), (1, 1),
662                wx.RIGHT | wx.EXPAND, 15)
[033c14c]663            i += 1
[9f7dde3]664
665        outputbox_sizer.Add(output_sizer, wx.TOP, 0)
666
[ff11b21]667        vbox.Add(outputbox_sizer, (y, 0), (1, 1),
[9f7dde3]668            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
[ff11b21]669        y += 1
[9f7dde3]670
[3ec4b8f]671        # Controls
[9f7dde3]672        controlbox = wx.StaticBox(self, -1, "Controls")
673        controlbox_sizer = wx.StaticBoxSizer(controlbox, wx.VERTICAL)
674
675        controls_sizer = wx.BoxSizer(wx.VERTICAL)
676
[711e157]677        self._extrapolate_btn = wx.Button(self, wx.NewId(), "Extrapolate")
[911dbe4]678        self._transform_btn = wx.Button(self, wx.NewId(), "Transform")
[c512f7d]679        self._extract_btn = wx.Button(self, wx.NewId(), "Compute Parameters")
[ebfdf4b]680        help_btn = wx.Button(self, -1, "HELP")
[911dbe4]681
682        self._transform_btn.Disable()
[033c14c]683        self._extract_btn.Disable()
[9f7dde3]684
[711e157]685        self._extrapolate_btn.Bind(wx.EVT_BUTTON, self.compute_extrapolation)
[911dbe4]686        self._transform_btn.Bind(wx.EVT_BUTTON, self.compute_transform)
[033c14c]687        self._extract_btn.Bind(wx.EVT_BUTTON, self.extract_parameters)
[ebfdf4b]688        help_btn.Bind(wx.EVT_BUTTON, self.on_help)
[3b8efec]689
[711e157]690        controls_sizer.Add(self._extrapolate_btn, wx.CENTER | wx.EXPAND)
[911dbe4]691        controls_sizer.Add(self._transform_btn, wx.CENTER | wx.EXPAND)
[033c14c]692        controls_sizer.Add(self._extract_btn, wx.CENTER | wx.EXPAND)
[ebfdf4b]693        controls_sizer.Add(help_btn, wx.CENTER | wx.EXPAND)
[7858575]694
[9f7dde3]695        controlbox_sizer.Add(controls_sizer, wx.TOP | wx.EXPAND, 0)
[ff11b21]696        vbox.Add(controlbox_sizer, (y, 0), (1, 1),
[9f7dde3]697            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
[7858575]698
[ebfdf4b]699
[7858575]700        self.SetSizer(vbox)
[54a0989]701
702    def _disable_inputs(self):
[6970e51]703        """
704        Disable all input fields
705        """
[54a0989]706        self._qmin_input.Disable()
707        self._qmax1_input.Disable()
708        self._qmax2_input.Disable()
709        self._background_input.Disable()
[711e157]710        self._extrapolate_btn.Disable()
[54a0989]711
712    def _enable_inputs(self):
[6970e51]713        """
714        Enable all input fields
715        """
[54a0989]716        self._qmin_input.Enable()
717        self._qmax1_input.Enable()
718        self._qmax2_input.Enable()
719        self._background_input.Enable()
[711e157]720        self._extrapolate_btn.Enable()
[e73e723]721
722    def _round_sig_figs(self, x, sigfigs):
723        """
724        Round a number to a given number of significant figures.
725
726        :param x: The value to round
727        :param sigfigs: How many significant figures to round to
728        :return rounded_str: x rounded to the given number of significant
729            figures, as a string
730        """
[e8418bb]731        rounded_str = ""
732        try:
733            # Index of first significant digit
734            significant_digit = -int(np.floor(np.log10(np.abs(x))))
[ff11b21]735
736            if np.abs(significant_digit > 4):
737                # Use scientific notation if x > 1e5 or x < 1e4
738                rounded_str = "{1:.{0}E}".format(sigfigs-1, x)
739            else:
740                # Format as a standard decimal
741                # Number of digits required for correct number of sig figs
742                digits = significant_digit + (sigfigs - 1)
743                rounded = np.round(x, decimals=digits)
744                rounded_str = "{1:.{0}f}".format(sigfigs -1  + significant_digit,
745                    rounded)
[e8418bb]746        except:
747            # Method for finding significant_digit fails if x is 0 (since log10(0)=inf)
748            if x == 0.0:
749                rounded_str = "0.0"
750            else:
751                rounded_str = "-"
752
[e73e723]753        return rounded_str
Note: See TracBrowser for help on using the repository browser.