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

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 32c5983 was e8418bb, checked in by lewis, 8 years ago

Fix bug when displaying output params if one of them is 0

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