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

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

Fix bug where self.qmax wasn't updated when the qrange was changed

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