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

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 93b145a was 93b145a, checked in by lewis, 8 years ago

Show warning when bg is negative and/or results in negative I values

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