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

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

Change Bg input yellow and log warning instead of modal warning

  • Property mode set to 100644
File size: 29.1 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        self._extrapolation_outputs = {}
71        # Dictionary for saving refs to text boxes used to display output data
72        self._output_boxes = None
73        self.state = None
74        self._do_layout()
75        self._disable_inputs()
76        self.set_state()
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)
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)
83        self._background_input.Bind(wx.EVT_TEXT, self._on_enter_input)
84
85    def set_state(self, state=None, data=None):
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        """
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
99        self.set_data(data, set_qrange=False)
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))
104        if self.state.background is not None:
105            self.set_background(self.state.background)
106        if self.state.is_extrapolated:
107            self.compute_extrapolation()
108        else:
109            return
110        if self.state.is_transformed:
111            self.compute_transform()
112        else:
113            return
114        if self.state.outputs is not None and self.state.outputs != {}:
115            self.set_extracted_params(self.state.outputs, reset=True)
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])
125        state.set_saved_state('background_tcl', self.background)
126        state.outputs = self.extracted_params
127        if self._data is not None:
128            state.file = self._data.title
129            state.data = self._data
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
134        self.state = state
135
136        return self.state
137
138    def onSetFocus(self, evt):
139        if evt is not None:
140            evt.Skip()
141        self._validate_inputs()
142
143    def set_data(self, data=None, set_qrange=True):
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        """
149        if data is None:
150            self._disable_inputs()
151            # Reset outputs
152            self.set_extracted_params(reset=True)
153            self.set_extrapolation_params()
154            self._data = None
155            return
156        self._enable_inputs()
157        self._transform_btn.Disable()
158        self._extract_btn.Disable()
159        self._data_name_box.SetValue(str(data.title))
160        self._data = data
161        self._calculator.set_data(data)
162        # Reset the outputs
163        self.set_extracted_params(None, reset=True)
164        if self._manager is not None:
165            self._manager.clear_data()
166            self._manager.show_data(self._data, IQ_DATA_LABEL, reset=True)
167
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))
174            self._compute_background()
175
176    def get_data(self):
177        return self._data
178
179    def radio_changed(self, event=None):
180        if event is not None:
181            self.transform_type = event.GetEventObject().GetName()
182
183    def compute_extrapolation(self, event=None):
184        """
185        Compute and plot the extrapolated data.
186        Called when Extrapolate button is pressed.
187        """
188        if not self._validate_inputs:
189            msg = "Invalid Q range entered."
190            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
191            return
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 results in negative Intensity values."
200        if warning_msg != "":
201            self._background_input.SetBackgroundColour('yellow')
202            wx.PostEvent(self._manager.parent, StatusEvent(status=warning_msg, info='warning'))
203        else:
204            self._background_input.SetBackgroundColour(wx.WHITE)
205        self._background_input.Refresh()
206
207        self._calculator.set_data(self._data)
208        self._calculator.lowerq = self.qmin
209        self._calculator.upperq = self.qmax
210        self._calculator.background = self.background
211
212        try:
213            params, self._extrapolated_data = self._calculator.compute_extrapolation()
214        except Exception as e:
215            msg = "Error extrapolating data:\n"
216            msg += str(e)
217            wx.PostEvent(self._manager.parent,
218                StatusEvent(status=msg, info="error"))
219            self._transform_btn.Disable()
220            return
221        self._manager.show_data(self._extrapolated_data, IQ_EXTRAPOLATED_DATA_LABEL)
222        # Update state of the GUI
223        self._transform_btn.Enable()
224        self._extract_btn.Disable()
225        self.set_extracted_params(reset=True)
226        self.set_extrapolation_params(params)
227
228    def compute_transform(self, event=None):
229        """
230        Compute and plot the transformed data.
231        Called when Transform button is pressed.
232        """
233        if not self._calculator.transform_isrunning():
234            self._calculator.compute_transform(self._extrapolated_data,
235                self.transform_type, background=self.background,
236                completefn=self.transform_complete,
237                updatefn=self.transform_update)
238
239            self._transform_btn.SetLabel("Stop Transform")
240        else:
241            self._calculator.stop_transform()
242            self.transform_update("Transform cancelled.")
243            self._transform_btn.SetLabel("Transform")
244
245    def transform_update(self, msg=""):
246        """
247        Called from FourierThread to update on status of calculation
248        """
249        wx.PostEvent(self._manager.parent,
250            StatusEvent(status=msg))
251
252    def transform_complete(self, transform=None):
253        """
254        Called from FourierThread when calculation has completed
255        """
256        self._transform_btn.SetLabel("Transform")
257        if transform is None:
258            msg = "Error calculating Transform."
259            if self.transform_type == 'hilbert':
260                msg = "Not yet implemented"
261            wx.PostEvent(self._manager.parent,
262                StatusEvent(status=msg, info="Error"))
263            self._extract_btn.Disable()
264            return
265        self._transformed_data = transform
266        import numpy as np
267        plot_x = transform.x[np.where(transform.x <= 200)]
268        plot_y = transform.y[np.where(transform.x <= 200)]
269        self._manager.show_data(Data1D(plot_x, plot_y), TRANSFORM_LABEL)
270        # Only enable extract params button if a fourier trans. has been done
271        if self.transform_type == 'fourier':
272            self._extract_btn.Enable()
273        else:
274            self._extract_btn.Disable()
275
276    def extract_parameters(self, event=None):
277        try:
278            params = self._calculator.extract_parameters(self._transformed_data)
279        except:
280            params = None
281        if params is None:
282            msg = "Error extracting parameters."
283            wx.PostEvent(self._manager.parent,
284                StatusEvent(status=msg, info="Error"))
285            return
286        self.set_extracted_params(params)
287
288    def on_help(self, event=None):
289        """
290        Show the corfunc documentation
291        """
292        tree_location = "user/sasgui/perspectives/corfunc/corfunc_help.html"
293        doc_viewer = DocumentationWindow(self, -1, tree_location, "",
294                                          "Correlation Function Help")
295
296    def save_project(self, doc=None):
297        """
298        Return an XML node containing the state of the panel
299
300        :param doc: Am xml node to attach the project state to (optional)
301        """
302        data = self._data
303        state = self.get_state()
304        if data is not None:
305            new_doc, sasentry = self._manager.state_reader._to_xml_doc(data)
306            new_doc = state.toXML(doc=new_doc, entry_node=sasentry)
307            if new_doc is not None:
308                if doc is not None and hasattr(doc, "firstChild"):
309                    child = new_doc.getElementsByTagName("SASentry")
310                    for item in child:
311                        doc.firstChild.appendChild(item)
312                else:
313                    doc = new_doc
314        return doc
315
316    def set_qmin(self, qmin):
317        self.qmin = qmin
318        self._qmin_input.SetValue(str(qmin))
319
320    def set_qmax(self, qmax):
321        self.qmax = qmax
322        self._qmax1_input.SetValue(str(qmax[0]))
323        self._qmax2_input.SetValue(str(qmax[1]))
324
325    def set_background(self, bg):
326        self.background = bg
327        self._background_input.SetValue(str(bg))
328        self._calculator.background = bg
329
330    def set_extrapolation_params(self, params=None):
331        if params is None:
332            # Reset outputs
333            for output in self._extrapolation_outputs.values():
334                output.SetValue('-')
335            return
336        for key, value in params.iteritems():
337            output = self._extrapolation_outputs[key]
338            rounded = self._round_sig_figs(value, 6)
339            output.SetValue(rounded)
340
341
342    def set_extracted_params(self, params=None, reset=False):
343        self.extracted_params = params
344        error = False
345        if params is None:
346            if not reset: error = True
347            for output in self._output_boxes.values():
348                output.SetValue('-')
349        else:
350            if len(params) < len(OUTPUT_STRINGS):
351                # Not all parameters were calculated
352                error = True
353            for key, value in params.iteritems():
354                rounded = self._round_sig_figs(value, 6)
355                self._output_boxes[key].SetValue(rounded)
356        if error:
357            msg = 'Not all parameters were able to be calculated'
358            wx.PostEvent(self._manager.parent, StatusEvent(
359                status=msg, info='error'))
360
361    def plot_qrange(self, active=None, leftdown=False):
362        if active is None:
363            active = self._qmin_input
364        wx.PostEvent(self._manager.parent, PlotQrangeEvent(
365            ctrl=[self._qmin_input, self._qmax1_input, self._qmax2_input],
366            active=active, id=IQ_DATA_LABEL, is_corfunc=True,
367            group_id=GROUP_ID_IQ_DATA, leftdown=leftdown))
368
369
370    def _compute_background(self, event=None):
371        if event is not None:
372            event.Skip()
373        self._on_enter_input()
374        try:
375            bg = self._calculator.compute_background(self.qmax)
376            self.set_background(bg)
377        except Exception as e:
378            msg = "Error computing background level:\n"
379            msg += str(e)
380            wx.PostEvent(self._manager.parent,
381                StatusEvent(status=msg, info="error"))
382
383    def _on_enter_input(self, event=None):
384        """
385        Read values from input boxes and save to memory.
386        """
387        if event is not None: event.Skip()
388        if not self._validate_inputs():
389            return
390        self.qmin = float(self._qmin_input.GetValue())
391        new_qmax1 = float(self._qmax1_input.GetValue())
392        new_qmax2 = float(self._qmax2_input.GetValue())
393        self.qmax = (new_qmax1, new_qmax2)
394        self.background = float(self._background_input.GetValue())
395        self._calculator.background = self.background
396        if event is not None:
397            active_ctrl = event.GetEventObject()
398            if active_ctrl == self._background_input:
399                self._manager.show_data(self._data, IQ_DATA_LABEL,
400                    reset=False, active_ctrl=active_ctrl)
401
402    def _on_click_qrange(self, event=None):
403        if event is None:
404            return
405        event.Skip()
406        if not self._validate_inputs(): return
407        self.plot_qrange(active=event.GetEventObject(),
408            leftdown=event.LeftDown())
409
410    def _validate_inputs(self):
411        """
412        Check that the values for qmin and qmax in the input boxes are valid
413        """
414        if self._data is None:
415            return False
416        qmin_valid = check_float(self._qmin_input)
417        qmax1_valid = check_float(self._qmax1_input)
418        qmax2_valid = check_float(self._qmax2_input)
419        qmax_valid = qmax1_valid and qmax2_valid
420        background_valid = check_float(self._background_input)
421        msg = ""
422        if (qmin_valid and qmax_valid and background_valid):
423            qmin = float(self._qmin_input.GetValue())
424            qmax1 = float(self._qmax1_input.GetValue())
425            qmax2 = float(self._qmax2_input.GetValue())
426            background = float(self._background_input.GetValue())
427            if not qmin > self._data.x.min():
428                msg = "qmin must be greater than the lowest q value"
429                qmin_valid = False
430            elif qmax2 < qmax1:
431                msg = "qmax1 must be less than qmax2"
432                qmax_valid = False
433            elif qmin > qmax1:
434                msg = "qmin must be less than qmax"
435                qmin_valid = False
436            elif background > self._data.y.max():
437                msg = "background must be less than highest I"
438                background_valid = False
439        if not qmin_valid:
440            self._qmin_input.SetBackgroundColour('pink')
441        if not qmax_valid:
442            self._qmax1_input.SetBackgroundColour('pink')
443            self._qmax2_input.SetBackgroundColour('pink')
444        if not background_valid:
445            self._background_input.SetBackgroundColour('pink')
446            if msg != "":
447                wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
448        if (qmin_valid and qmax_valid and background_valid):
449            self._qmin_input.SetBackgroundColour(wx.WHITE)
450            self._qmax1_input.SetBackgroundColour(wx.WHITE)
451            self._qmax2_input.SetBackgroundColour(wx.WHITE)
452            self._background_input.SetBackgroundColour(wx.WHITE)
453        self._qmin_input.Refresh()
454        self._qmax1_input.Refresh()
455        self._qmax2_input.Refresh()
456        self._background_input.Refresh()
457        return (qmin_valid and qmax_valid and background_valid)
458
459    def _do_layout(self):
460        """
461        Draw the window content
462        """
463        vbox = wx.GridBagSizer(0,0)
464
465        # I(q) data box
466        databox = wx.StaticBox(self, -1, "I(Q) Data Source")
467        databox_sizer = wx.StaticBoxSizer(databox, wx.VERTICAL)
468
469        file_sizer = wx.GridBagSizer(5, 5)
470
471        y = 0
472
473        file_name_label = wx.StaticText(self, -1, "Name:")
474        file_sizer.Add(file_name_label, (0, 0), (1, 1),
475            wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
476
477        self._data_name_box = OutputTextCtrl(self, -1,
478            size=(300,20))
479        file_sizer.Add(self._data_name_box, (0, 1), (1, 1),
480            wx.CENTER | wx.ADJUST_MINSIZE, 15)
481
482        file_sizer.AddSpacer((1, 25), pos=(0,2))
483        databox_sizer.Add(file_sizer, wx.TOP, 15)
484
485        vbox.Add(databox_sizer, (y, 0), (1, 1),
486            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE | wx.TOP, 15)
487        y += 1
488
489        # Parameters
490        qbox = wx.StaticBox(self, -1, "Input Parameters")
491        qbox_sizer = wx.StaticBoxSizer(qbox, wx.VERTICAL)
492        qbox_sizer.SetMinSize((_STATICBOX_WIDTH, 75))
493
494        q_sizer = wx.GridBagSizer(5, 5)
495
496        # Explanation
497        explanation_txt = ("Corfunc will use all values in the lower range for"
498            " Guinier back extrapolation, and all values in the upper range "
499            "for Porod forward extrapolation.")
500        explanation_label = wx.StaticText(self, -1, explanation_txt,
501            size=(_STATICBOX_WIDTH, 60))
502
503        q_sizer.Add(explanation_label, (0,0), (1,4), wx.LEFT | wx.EXPAND, 5)
504
505        qrange_label = wx.StaticText(self, -1, "Q Range:", size=(50,20))
506        q_sizer.Add(qrange_label, (1,0), (1,1), wx.LEFT | wx.EXPAND, 5)
507
508        # Lower Q Range
509        qmin_label = wx.StaticText(self, -1, "Lower:", size=(50,20))
510        qmin_dash_label = wx.StaticText(self, -1, "-", size=(10,20),
511            style=wx.ALIGN_CENTER_HORIZONTAL)
512
513        qmin_lower = OutputTextCtrl(self, -1, size=(75, 20), value="0.0")
514        self._qmin_input = ModelTextCtrl(self, -1, size=(75, 20),
515                        style=wx.TE_PROCESS_ENTER, name='qmin_input',
516                        text_enter_callback=self._on_enter_input)
517        self._qmin_input.SetToolTipString(("Values with q < qmin will be used "
518            "for Guinier back extrapolation"))
519
520        q_sizer.Add(qmin_label, (2, 0), (1, 1), wx.LEFT | wx.EXPAND, 5)
521        q_sizer.Add(qmin_lower, (2, 1), (1, 1), wx.LEFT, 5)
522        q_sizer.Add(qmin_dash_label, (2, 2), (1, 1), wx.CENTER | wx.EXPAND, 5)
523        q_sizer.Add(self._qmin_input, (2, 3), (1, 1), wx.LEFT, 5)
524
525        # Upper Q range
526        qmax_tooltip = ("Values with qmax1 < q < qmax2 will be used for Porod"
527            " forward extrapolation")
528
529        qmax_label = wx.StaticText(self, -1, "Upper:", size=(50,20))
530        qmax_dash_label = wx.StaticText(self, -1, "-", size=(10,20),
531            style=wx.ALIGN_CENTER_HORIZONTAL)
532
533        self._qmax1_input = ModelTextCtrl(self, -1, size=(75, 20),
534            style=wx.TE_PROCESS_ENTER, name="qmax1_input",
535            text_enter_callback=self._on_enter_input)
536        self._qmax1_input.SetToolTipString(qmax_tooltip)
537        self._qmax2_input = ModelTextCtrl(self, -1, size=(75, 20),
538            style=wx.TE_PROCESS_ENTER, name="qmax2_input",
539            text_enter_callback=self._on_enter_input)
540        self._qmax2_input.SetToolTipString(qmax_tooltip)
541
542        q_sizer.Add(qmax_label, (3, 0), (1, 1), wx.LEFT | wx.EXPAND, 5)
543        q_sizer.Add(self._qmax1_input, (3, 1), (1, 1), wx.LEFT, 5)
544        q_sizer.Add(qmax_dash_label, (3, 2), (1, 1), wx.CENTER | wx.EXPAND, 5)
545        q_sizer.Add(self._qmax2_input, (3,3), (1, 1), wx.LEFT, 5)
546
547        qbox_sizer.Add(q_sizer, wx.TOP, 0)
548
549        vbox.Add(qbox_sizer, (y, 0), (1, 1),
550            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
551        y += 1
552
553        extrapolation_box = wx.StaticBox(self, -1, "Extrapolation Parameters")
554        extrapolation_sizer = wx.StaticBoxSizer(extrapolation_box, wx.VERTICAL)
555        params_sizer = wx.GridBagSizer(5, 5)
556
557        guinier_label = wx.StaticText(self, -1, "Guinier:")
558        params_sizer.Add(guinier_label, (0, 0), (1,1),
559            wx.ALL | wx.EXPAND | wx.ADJUST_MINSIZE, 5)
560
561        a_label = wx.StaticText(self, -1, "A: ")
562        params_sizer.Add(a_label, (1, 0), (1, 1), wx.LEFT | wx.EXPAND, 15)
563
564        a_output = OutputTextCtrl(self, wx.NewId(),
565            value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
566        params_sizer.Add(a_output, (1, 1), (1, 1), wx.RIGHT | wx.EXPAND, 15)
567        self._extrapolation_outputs['A'] = a_output
568
569        b_label = wx.StaticText(self, -1, "B: ")
570        params_sizer.Add(b_label, (2, 0), (1, 1), wx.LEFT | wx.EXPAND, 15)
571
572        b_output = OutputTextCtrl(self, wx.NewId(),
573            value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
574        params_sizer.Add(b_output, (2, 1), (1, 1), wx.RIGHT | wx.EXPAND, 15)
575        self._extrapolation_outputs['B'] = b_output
576
577        porod_label = wx.StaticText(self, -1, "Porod: ")
578        params_sizer.Add(porod_label, (0, 2), (1, 1),
579            wx.ALL | wx.EXPAND | wx.ADJUST_MINSIZE, 5)
580
581        k_label = wx.StaticText(self, -1, "K: ")
582        params_sizer.Add(k_label, (1, 2), (1, 1), wx.LEFT | wx.EXPAND, 15)
583
584        k_output = OutputTextCtrl(self, wx.NewId(),
585            value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
586        params_sizer.Add(k_output, (1, 3), (1, 1), wx.RIGHT | wx.EXPAND, 15)
587        self._extrapolation_outputs['K'] = k_output
588
589        sigma_label = wx.StaticText(self, -1, u'\u03C3: ')
590        params_sizer.Add(sigma_label, (2, 2), (1, 1), wx.LEFT | wx.EXPAND, 15)
591
592        sigma_output = OutputTextCtrl(self, wx.NewId(),
593            value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
594        params_sizer.Add(sigma_output, (2, 3), (1, 1), wx.RIGHT | wx.EXPAND, 15)
595        self._extrapolation_outputs['sigma'] = sigma_output
596
597        bg_label = wx.StaticText(self, -1, "Bg: ")
598        params_sizer.Add(bg_label, (3, 2), (1, 1), wx.LEFT | wx.EXPAND, 15)
599
600        self._background_input = ModelTextCtrl(self, -1, value="0.0",
601            style=wx.TE_PROCESS_ENTER | wx.TE_CENTRE, name='background_input',
602            text_enter_callback=self._on_enter_input)
603        self._background_input.SetToolTipString(("A background value to "
604            "subtract from all intensity values"))
605        params_sizer.Add(self._background_input, (3, 3), (1, 1), wx.RIGHT | wx.EXPAND, 15)
606
607        background_button = wx.Button(self, wx.NewId(), "Calculate Bg",
608            size=(75, -1))
609        background_button.Bind(wx.EVT_BUTTON, self._compute_background)
610        params_sizer.Add(background_button, (4,3), (1, 1), wx.EXPAND | wx.RIGHT, 15)
611
612        extrapolation_sizer.Add(params_sizer)
613        vbox.Add(extrapolation_sizer, (y, 0), (1, 1),
614            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
615        y += 1
616
617        # Transform type
618        transform_box = wx.StaticBox(self, -1, "Transform Type")
619        transform_sizer = wx.StaticBoxSizer(transform_box, wx.VERTICAL)
620
621        radio_sizer = wx.GridBagSizer(5,5)
622
623        fourier_btn = wx.RadioButton(self, -1, "Fourier", name='fourier',
624            style=wx.RB_GROUP)
625        hilbert_btn = wx.RadioButton(self, -1, "Hilbert", name='hilbert')
626
627        fourier_btn.Bind(wx.EVT_RADIOBUTTON, self.radio_changed)
628        hilbert_btn.Bind(wx.EVT_RADIOBUTTON, self.radio_changed)
629
630        radio_sizer.Add(fourier_btn, (0,0), (1,1), wx.LEFT | wx.EXPAND)
631        radio_sizer.Add(hilbert_btn, (0,1), (1,1), wx.RIGHT | wx.EXPAND)
632
633        transform_sizer.Add(radio_sizer, wx.TOP, 0)
634        vbox.Add(transform_sizer, (y, 0), (1, 1),
635            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
636        y += 1
637
638        # Output data
639        outputbox = wx.StaticBox(self, -1, "Output Parameters")
640        outputbox_sizer = wx.StaticBoxSizer(outputbox, wx.VERTICAL)
641
642        output_sizer = wx.GridBagSizer(5, 5)
643
644        self._output_boxes = dict()
645        i = 0
646        for key, value in OUTPUT_STRINGS.iteritems():
647            # Create a label and a text box for each poperty
648            label = wx.StaticText(self, -1, value)
649            output_box = OutputTextCtrl(self, wx.NewId(),
650                value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
651            # Save the ID of each of the text boxes for accessing after the
652            # output data has been calculated
653            self._output_boxes[key] = output_box
654            output_sizer.Add(label, (i, 0), (1, 1), wx.LEFT | wx.EXPAND, 15)
655            output_sizer.Add(output_box, (i, 2), (1, 1),
656                wx.RIGHT | wx.EXPAND, 15)
657            i += 1
658
659        outputbox_sizer.Add(output_sizer, wx.TOP, 0)
660
661        vbox.Add(outputbox_sizer, (y, 0), (1, 1),
662            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
663        y += 1
664
665        # Controls
666        controlbox = wx.StaticBox(self, -1, "Controls")
667        controlbox_sizer = wx.StaticBoxSizer(controlbox, wx.VERTICAL)
668
669        controls_sizer = wx.BoxSizer(wx.VERTICAL)
670
671        self._extrapolate_btn = wx.Button(self, wx.NewId(), "Extrapolate")
672        self._transform_btn = wx.Button(self, wx.NewId(), "Transform")
673        self._extract_btn = wx.Button(self, wx.NewId(), "Compute Parameters")
674        help_btn = wx.Button(self, -1, "HELP")
675
676        self._transform_btn.Disable()
677        self._extract_btn.Disable()
678
679        self._extrapolate_btn.Bind(wx.EVT_BUTTON, self.compute_extrapolation)
680        self._transform_btn.Bind(wx.EVT_BUTTON, self.compute_transform)
681        self._extract_btn.Bind(wx.EVT_BUTTON, self.extract_parameters)
682        help_btn.Bind(wx.EVT_BUTTON, self.on_help)
683
684        controls_sizer.Add(self._extrapolate_btn, wx.CENTER | wx.EXPAND)
685        controls_sizer.Add(self._transform_btn, wx.CENTER | wx.EXPAND)
686        controls_sizer.Add(self._extract_btn, wx.CENTER | wx.EXPAND)
687        controls_sizer.Add(help_btn, wx.CENTER | wx.EXPAND)
688
689        controlbox_sizer.Add(controls_sizer, wx.TOP | wx.EXPAND, 0)
690        vbox.Add(controlbox_sizer, (y, 0), (1, 1),
691            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
692
693
694        self.SetSizer(vbox)
695
696    def _disable_inputs(self):
697        """
698        Disable all input fields
699        """
700        self._qmin_input.Disable()
701        self._qmax1_input.Disable()
702        self._qmax2_input.Disable()
703        self._background_input.Disable()
704        self._extrapolate_btn.Disable()
705
706    def _enable_inputs(self):
707        """
708        Enable all input fields
709        """
710        self._qmin_input.Enable()
711        self._qmax1_input.Enable()
712        self._qmax2_input.Enable()
713        self._background_input.Enable()
714        self._extrapolate_btn.Enable()
715
716    def _round_sig_figs(self, x, sigfigs):
717        """
718        Round a number to a given number of significant figures.
719
720        :param x: The value to round
721        :param sigfigs: How many significant figures to round to
722        :return rounded_str: x rounded to the given number of significant
723            figures, as a string
724        """
725        rounded_str = ""
726        try:
727            # Index of first significant digit
728            significant_digit = -int(np.floor(np.log10(np.abs(x))))
729
730            if np.abs(significant_digit > 4):
731                # Use scientific notation if x > 1e5 or x < 1e4
732                rounded_str = "{1:.{0}E}".format(sigfigs-1, x)
733            else:
734                # Format as a standard decimal
735                # Number of digits required for correct number of sig figs
736                digits = significant_digit + (sigfigs - 1)
737                rounded = np.round(x, decimals=digits)
738                rounded_str = "{1:.{0}f}".format(sigfigs -1  + significant_digit,
739                    rounded)
740        except:
741            # Method for finding significant_digit fails if x is 0 (since log10(0)=inf)
742            if x == 0.0:
743                rounded_str = "0.0"
744            else:
745                rounded_str = "-"
746
747        return rounded_str
Note: See TracBrowser for help on using the repository browser.