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

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 e8418bb 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
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        self._calculator.set_data(self._data)
190        self._calculator.lowerq = self.qmin
191        self._calculator.upperq = self.qmax
192        self._calculator.background = self.background
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
201        # TODO: Find way to set xlim and ylim so full range of data can be
202        # plotted but zoomed in
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)
210        # Update state of the GUI
211        self._transform_btn.Enable()
212        self._extract_btn.Disable()
213        self.set_extracted_params(reset=True)
214
215    def compute_transform(self, event=None):
216        """
217        Compute and plot the transformed data.
218        Called when Transform button is pressed.
219        """
220        if not self._calculator.transform_isrunning():
221            self._calculator.compute_transform(self._extrapolated_data,
222                self.transform_type, background=self.background,
223                completefn=self.transform_complete,
224                updatefn=self.transform_update)
225
226            self._transform_btn.SetLabel("Stop Transform")
227        else:
228            self._calculator.stop_transform()
229            self.transform_update("Transform cancelled.")
230            self._transform_btn.SetLabel("Transform")
231
232    def transform_update(self, msg=""):
233        """
234        Called from FourierThread to update on status of calculation
235        """
236        wx.PostEvent(self._manager.parent,
237            StatusEvent(status=msg))
238
239    def transform_complete(self, transform=None):
240        """
241        Called from FourierThread when calculation has completed
242        """
243        self._transform_btn.SetLabel("Transform")
244        if transform is None:
245            msg = "Error calculating Transform."
246            if self.transform_type == 'hilbert':
247                msg = "Not yet implemented"
248            wx.PostEvent(self._manager.parent,
249                StatusEvent(status=msg, info="Error"))
250            self._extract_btn.Disable()
251            return
252        self._transformed_data = transform
253        import numpy as np
254        plot_x = transform.x[np.where(transform.x <= 200)]
255        plot_y = transform.y[np.where(transform.x <= 200)]
256        self._manager.show_data(Data1D(plot_x, plot_y), TRANSFORM_LABEL)
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()
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,
271                StatusEvent(status=msg, info="Error"))
272            return
273        self.set_extracted_params(params)
274
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
283    def save_project(self, doc=None):
284        """
285        Return an XML node containing the state of the panel
286
287        :param doc: Am xml node to attach the project state to (optional)
288        """
289        data = self._data
290        state = self.get_state()
291        if data is not None:
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
302
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
312    def set_background(self, bg):
313        self.background = bg
314        self._background_input.SetValue(str(bg))
315        self._calculator.background = bg
316
317    def set_extracted_params(self, params=None, reset=False):
318        self.extracted_params = params
319        error = False
320        if params is None:
321            if not reset: error = True
322            for key in OUTPUT_STRINGS.keys():
323                self._output_boxes[key].SetValue('-')
324        else:
325            if len(params) < len(OUTPUT_STRINGS):
326                # Not all parameters were calculated
327                error = True
328            for key, value in params.iteritems():
329                rounded = self._round_sig_figs(value, 6)
330                self._output_boxes[key].SetValue(rounded)
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
336
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
345
346    def _compute_background(self, event=None):
347        self.set_background(self._calculator.compute_background(self.qmax))
348
349    def _on_enter_input(self, event=None):
350        """
351        Read values from input boxes and save to memory.
352        """
353        if event is not None: event.Skip()
354        if not self._validate_inputs():
355            return
356        self.qmin = float(self._qmin_input.GetValue())
357        new_qmax1 = float(self._qmax1_input.GetValue())
358        new_qmax2 = float(self._qmax2_input.GetValue())
359        self.qmax = (new_qmax1, new_qmax2)
360        self.background = float(self._background_input.GetValue())
361        self._calculator.background = self.background
362        if event is not None:
363            active_ctrl = event.GetEventObject()
364            if active_ctrl == self._background_input:
365                self._manager.show_data(self._data, IQ_DATA_LABEL,
366                    reset=False, active_ctrl=active_ctrl)
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
373        self.plot_qrange(active=event.GetEventObject(),
374            leftdown=event.LeftDown())
375
376    def _validate_inputs(self):
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
386        background_valid = check_float(self._background_input)
387        msg = ""
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
402            elif background > self._data.y.max():
403                msg = "background must be less than highest I"
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):
415            self._qmin_input.SetBackgroundColour(wx.WHITE)
416            self._qmax1_input.SetBackgroundColour(wx.WHITE)
417            self._qmax2_input.SetBackgroundColour(wx.WHITE)
418            self._background_input.SetBackgroundColour(wx.WHITE)
419        self._qmin_input.Refresh()
420        self._qmax1_input.Refresh()
421        self._qmax2_input.Refresh()
422        self._background_input.Refresh()
423        return (qmin_valid and qmax_valid and background_valid)
424
425    def _do_layout(self):
426        """
427        Draw the window content
428        """
429        vbox = wx.GridBagSizer(0,0)
430
431        # I(q) data box
432        databox = wx.StaticBox(self, -1, "I(Q) Data Source")
433        databox_sizer = wx.StaticBoxSizer(databox, wx.VERTICAL)
434
435        file_sizer = wx.GridBagSizer(5, 5)
436
437        file_name_label = wx.StaticText(self, -1, "Name:")
438        file_sizer.Add(file_name_label, (0, 0), (1, 1),
439            wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
440
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
454        qbox = wx.StaticBox(self, -1, "Input Parameters")
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))
470        q_sizer.Add(qrange_label, (1,0), (1,1), wx.LEFT | wx.EXPAND, 5)
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
477        qmin_lower = OutputTextCtrl(self, -1, size=(75, 20), value="0.0")
478        self._qmin_input = ModelTextCtrl(self, -1, size=(75, 20),
479                        style=wx.TE_PROCESS_ENTER, name='qmin_input',
480                        text_enter_callback=self._on_enter_input)
481        self._qmin_input.SetToolTipString(("Values with q < qmin will be used "
482            "for Guinier back extrapolation"))
483
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)
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
497        self._qmax1_input = ModelTextCtrl(self, -1, size=(75, 20),
498            style=wx.TE_PROCESS_ENTER, name="qmax1_input",
499            text_enter_callback=self._on_enter_input)
500        self._qmax1_input.SetToolTipString(qmax_tooltip)
501        self._qmax2_input = ModelTextCtrl(self, -1, size=(75, 20),
502            style=wx.TE_PROCESS_ENTER, name="qmax2_input",
503            text_enter_callback=self._on_enter_input)
504        self._qmax2_input.SetToolTipString(qmax_tooltip)
505
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
514        self._background_input = ModelTextCtrl(self, -1, size=(75,20),
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)
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
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
552        # Output data
553        outputbox = wx.StaticBox(self, -1, "Output Parameters")
554        outputbox_sizer = wx.StaticBoxSizer(outputbox, wx.VERTICAL)
555
556        output_sizer = wx.GridBagSizer(5, 5)
557
558        self._output_boxes = dict()
559        i = 0
560        for key, value in OUTPUT_STRINGS.iteritems():
561            # Create a label and a text box for each poperty
562            label = wx.StaticText(self, -1, value)
563            output_box = OutputTextCtrl(self, wx.NewId(),
564                value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
565            # Save the ID of each of the text boxes for accessing after the
566            # output data has been calculated
567            self._output_boxes[key] = output_box
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)
571            i += 1
572
573        outputbox_sizer.Add(output_sizer, wx.TOP, 0)
574
575        vbox.Add(outputbox_sizer, (3, 0), (1, 1),
576            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
577
578        # Controls
579        controlbox = wx.StaticBox(self, -1, "Controls")
580        controlbox_sizer = wx.StaticBoxSizer(controlbox, wx.VERTICAL)
581
582        controls_sizer = wx.BoxSizer(wx.VERTICAL)
583
584        self._extrapolate_btn = wx.Button(self, wx.NewId(), "Extrapolate")
585        self._transform_btn = wx.Button(self, wx.NewId(), "Transform")
586        self._extract_btn = wx.Button(self, wx.NewId(), "Compute Parameters")
587        help_btn = wx.Button(self, -1, "HELP")
588
589        self._transform_btn.Disable()
590        self._extract_btn.Disable()
591
592        self._extrapolate_btn.Bind(wx.EVT_BUTTON, self.compute_extrapolation)
593        self._transform_btn.Bind(wx.EVT_BUTTON, self.compute_transform)
594        self._extract_btn.Bind(wx.EVT_BUTTON, self.extract_parameters)
595        help_btn.Bind(wx.EVT_BUTTON, self.on_help)
596
597        controls_sizer.Add(self._extrapolate_btn, wx.CENTER | wx.EXPAND)
598        controls_sizer.Add(self._transform_btn, wx.CENTER | wx.EXPAND)
599        controls_sizer.Add(self._extract_btn, wx.CENTER | wx.EXPAND)
600        controls_sizer.Add(help_btn, wx.CENTER | wx.EXPAND)
601
602        controlbox_sizer.Add(controls_sizer, wx.TOP | wx.EXPAND, 0)
603        vbox.Add(controlbox_sizer, (4, 0), (1, 1),
604            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
605
606
607        self.SetSizer(vbox)
608
609    def _disable_inputs(self):
610        """
611        Disable all input fields
612        """
613        self._qmin_input.Disable()
614        self._qmax1_input.Disable()
615        self._qmax2_input.Disable()
616        self._background_input.Disable()
617        self._extrapolate_btn.Disable()
618
619    def _enable_inputs(self):
620        """
621        Enable all input fields
622        """
623        self._qmin_input.Enable()
624        self._qmax1_input.Enable()
625        self._qmax2_input.Enable()
626        self._background_input.Enable()
627        self._extrapolate_btn.Enable()
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        """
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
654        return rounded_str
Note: See TracBrowser for help on using the repository browser.