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

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

Implement save analysis in corfunc

  • Property mode set to 100644
File size: 30.9 KB
Line 
1import wx
2import sys
3import os
4import numpy as np
5from wx.lib.scrolledpanel import ScrolledPanel
6from sas.sasgui.guiframe.events import PlotQrangeEvent
7from sas.sasgui.guiframe.events import StatusEvent
8from sas.sasgui.guiframe.events import PanelOnFocusEvent
9from sas.sasgui.guiframe.panel_base import PanelBase
10from sas.sasgui.guiframe.utils import check_float
11from sas.sasgui.guiframe.dataFitting import Data1D
12from sas.sasgui.perspectives.invariant.invariant_widgets import OutputTextCtrl
13from sas.sasgui.perspectives.invariant.invariant_widgets import InvTextCtrl
14from sas.sasgui.perspectives.fitting.basepage import ModelTextCtrl
15from sas.sasgui.perspectives.corfunc.corfunc_state import CorfuncState
16import sas.sasgui.perspectives.corfunc.corfunc
17from sas.sascalc.corfunc.corfunc_calculator import CorfuncCalculator
18from sas.sasgui.guiframe.documentation_window import DocumentationWindow
19from plot_labels import *
20
21OUTPUT_STRINGS = {
22    'max': "Long Period (A): ",
23    'Lc': "Average Hard Block Thickness (A): ",
24    'dtr': "Average Interface Thickness (A): ",
25    'd0': "Average Core Thickness: ",
26    'A': "Polydispersity: ",
27    'fill': "Local Crystallinity: "
28}
29
30if sys.platform.count("win32") > 0:
31    _STATICBOX_WIDTH = 350
32    PANEL_WIDTH = 400
33    PANEL_HEIGHT = 700
34    FONT_VARIANT = 0
35else:
36    _STATICBOX_WIDTH = 390
37    PANEL_WIDTH = 430
38    PANEL_HEIGHT = 700
39    FONT_VARIANT = 1
40
41class CorfuncPanel(ScrolledPanel,PanelBase):
42    window_name = "Correlation Function"
43    window_caption = "Correlation Function"
44    CENTER_PANE = True
45
46    def __init__(self, parent, data=None, manager=None, *args, **kwds):
47        kwds["size"] = (PANEL_WIDTH, PANEL_HEIGHT)
48        kwds["style"] = wx.FULL_REPAINT_ON_RESIZE
49        ScrolledPanel.__init__(self, parent=parent, *args, **kwds)
50        PanelBase.__init__(self, parent)
51        self.SetupScrolling()
52        self.SetWindowVariant(variant=FONT_VARIANT)
53        self._manager = manager
54        # The data with no correction for background values
55        self._data = data # The data to be analysed (corrected fr background)
56        self._extrapolated_data = None # The extrapolated data set
57        self._transformed_data = None # Fourier trans. of the extrapolated data
58        self._calculator = CorfuncCalculator()
59        self._data_name_box = None # Text box to show name of file
60        self._background_input = None
61        self._qmin_input = None
62        self._qmax1_input = None
63        self._qmax2_input = None
64        self._extrapolate_btn = None
65        self._transform_btn = None
66        self._extract_btn = None
67        self.qmin = 0
68        self.qmax = (0, 0)
69        self.background = 0
70        self.extracted_params = None
71        self.transform_type = 'fourier'
72        self._extrapolation_outputs = {}
73        # Dictionary for saving refs to text boxes used to display output data
74        self._output_boxes = None
75        self.state = None
76        self._do_layout()
77        self._disable_inputs()
78        self.set_state()
79        self._qmin_input.Bind(wx.EVT_TEXT, self._on_enter_input)
80        self._qmax1_input.Bind(wx.EVT_TEXT, self._on_enter_input)
81        self._qmax2_input.Bind(wx.EVT_TEXT, self._on_enter_input)
82        self._qmin_input.Bind(wx.EVT_MOUSE_EVENTS, self._on_click_qrange)
83        self._qmax1_input.Bind(wx.EVT_MOUSE_EVENTS, self._on_click_qrange)
84        self._qmax2_input.Bind(wx.EVT_MOUSE_EVENTS, self._on_click_qrange)
85        self._background_input.Bind(wx.EVT_TEXT, self._on_enter_input)
86
87    def set_state(self, state=None, data=None):
88        """
89        Set the state of the panel. If no state is provided, the panel will
90        be set to the default state.
91
92        :param state: A CorfuncState object
93        :param data: A Data1D object
94        """
95        if state is None:
96            self.state = CorfuncState()
97        else:
98            self.state = state
99        if data is not None:
100            self.state.data = data
101        self.set_data(data, set_qrange=False)
102        if self.state.qmin is not None:
103            self.set_qmin(self.state.qmin)
104        if self.state.qmax is not None and self.state.qmax != (None, None):
105            self.set_qmax(tuple(self.state.qmax))
106        if self.state.background is not None:
107            self.set_background(self.state.background)
108        if self.state.is_extrapolated:
109            self.compute_extrapolation()
110        else:
111            return
112        if self.state.is_transformed:
113            self.compute_transform()
114        else:
115            return
116        if self.state.outputs is not None and self.state.outputs != {}:
117            self.set_extracted_params(self.state.outputs, reset=True)
118
119    def get_state(self):
120        """
121        Return the state of the panel
122        """
123        state = CorfuncState()
124        state.set_saved_state('qmin_tcl', self.qmin)
125        state.set_saved_state('qmax1_tcl', self.qmax[0])
126        state.set_saved_state('qmax2_tcl', self.qmax[1])
127        state.set_saved_state('background_tcl', self.background)
128        state.outputs = self.extracted_params
129        if self._data is not None:
130            state.file = self._data.title
131            state.data = self._data
132        if self._extrapolated_data is not None:
133            state.is_extrapolated = True
134        if self._transformed_data is not None:
135            state.is_transformed = True
136        self.state = state
137
138        return self.state
139
140    def onSetFocus(self, evt):
141        if evt is not None:
142            evt.Skip()
143        self._validate_inputs()
144
145    def set_data(self, data=None, set_qrange=True):
146        """
147        Update the GUI to reflect new data that has been loaded in
148
149        :param data: The data that has been loaded
150        """
151        if data is None:
152            self._disable_inputs()
153            # Reset outputs
154            self.set_extracted_params(reset=True)
155            self.set_extrapolation_params()
156            self._data = None
157            return
158        self._enable_inputs()
159        self._transform_btn.Disable()
160        self._extract_btn.Disable()
161        self._data_name_box.SetValue(str(data.title))
162        self._data = data
163        self._calculator.set_data(data)
164        # Reset the outputs
165        self.set_extracted_params(None, reset=True)
166        if self._manager is not None:
167            self._manager.clear_data()
168            self._manager.show_data(self._data, IQ_DATA_LABEL, reset=True)
169
170        if set_qrange:
171            lower = data.x[-1]*0.05
172            upper1 = data.x[-1] - lower*5
173            upper2 = data.x[-1]
174            self.set_qmin(lower)
175            self.set_qmax((upper1, upper2))
176            self._compute_background()
177
178    def get_data(self):
179        return self._data
180
181    def radio_changed(self, event=None):
182        """
183        Called when the "Transform type" radio button are changed
184        """
185        if event is not None:
186            self.transform_type = event.GetEventObject().GetName()
187
188    def compute_extrapolation(self, event=None):
189        """
190        Compute and plot the extrapolated data.
191        Called when Extrapolate button is pressed.
192        """
193        if not self._validate_inputs:
194            msg = "Invalid Q range entered."
195            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
196            return
197
198        warning_msg = ""
199        if self.background < 0:
200            warning_msg += "Negative background value entered."
201        if any((self._data.y - self.background) < 0):
202            if warning_msg != "":
203                warning_msg += "\n"
204            warning_msg += "Background value results in negative Intensity values."
205        if warning_msg != "":
206            self._background_input.SetBackgroundColour('yellow')
207            wx.PostEvent(self._manager.parent, StatusEvent(status=warning_msg, info='warning'))
208        else:
209            self._background_input.SetBackgroundColour(wx.WHITE)
210        self._background_input.Refresh()
211
212        self._calculator.set_data(self._data)
213        self._calculator.lowerq = self.qmin
214        self._calculator.upperq = self.qmax
215        self._calculator.background = self.background
216
217        try:
218            params, self._extrapolated_data = self._calculator.compute_extrapolation()
219        except Exception as e:
220            msg = "Error extrapolating data:\n"
221            msg += str(e)
222            wx.PostEvent(self._manager.parent,
223                StatusEvent(status=msg, info="error"))
224            self._transform_btn.Disable()
225            return
226        self._manager.show_data(self._extrapolated_data, 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        """
283        Called when "Extract Parameters" is clicked
284        """
285        try:
286            params = self._calculator.extract_parameters(self._transformed_data)
287        except:
288            params = None
289        if params is None:
290            msg = "Error extracting parameters."
291            wx.PostEvent(self._manager.parent,
292                StatusEvent(status=msg, info="Error"))
293            return
294        self.set_extracted_params(params)
295
296    def on_help(self, event=None):
297        """
298        Show the corfunc documentation
299        """
300        tree_location = "user/sasgui/perspectives/corfunc/corfunc_help.html"
301        doc_viewer = DocumentationWindow(self, -1, tree_location, "",
302                                          "Correlation Function Help")
303
304    def get_save_flag(self):
305        if self._data is not None:
306            return True
307        return False
308
309    def on_set_focus(self, event=None):
310        if self._manager.parent is not None:
311            wx.PostEvent(self._manager.parent, PanelOnFocusEvent(panel=self))
312
313    def on_save(self, event=None):
314        """
315        Save corfunc state into a file
316        """
317        # Ask the user the location of the file to write to.
318        path = None
319        default_save_location = os.getcwd()
320        if self._manager.parent != None:
321            default_save_location = self._manager.parent.get_save_location()
322
323        dlg = wx.FileDialog(self, "Choose a file",
324                            default_save_location, \
325                            self.window_caption, "*.cor", wx.SAVE)
326        if dlg.ShowModal() == wx.ID_OK:
327            path = dlg.GetPath()
328            default_save_location = os.path.dirname(path)
329            if self._manager.parent != None:
330                self._manager.parent._default_save_location = default_save_location
331        else:
332            return None
333
334        dlg.Destroy()
335        # MAC always needs the extension for saving
336        extens = ".cor"
337        # Make sure the ext included in the file name
338        f_name = os.path.splitext(path)[0] + extens
339        self._manager.state_reader.write(f_name, self._data, self.get_state())
340
341    def save_project(self, doc=None):
342        """
343        Return an XML node containing the state of the panel
344
345        :param doc: Am xml node to attach the project state to (optional)
346        """
347        data = self._data
348        state = self.get_state()
349        if data is not None:
350            new_doc, sasentry = self._manager.state_reader._to_xml_doc(data)
351            new_doc = state.toXML(doc=new_doc, entry_node=sasentry)
352            if new_doc is not None:
353                if doc is not None and hasattr(doc, "firstChild"):
354                    child = new_doc.getElementsByTagName("SASentry")
355                    for item in child:
356                        doc.firstChild.appendChild(item)
357                else:
358                    doc = new_doc
359        return doc
360
361    def set_qmin(self, qmin):
362        self.qmin = qmin
363        self._qmin_input.SetValue(str(qmin))
364
365    def set_qmax(self, qmax):
366        self.qmax = qmax
367        self._qmax1_input.SetValue(str(qmax[0]))
368        self._qmax2_input.SetValue(str(qmax[1]))
369
370    def set_background(self, bg):
371        self.background = bg
372        self._background_input.SetValue(str(bg))
373        self._calculator.background = bg
374
375    def set_extrapolation_params(self, params=None):
376        """
377        Displays the value of the parameters calculated in the extrapolation
378        """
379        if params is None:
380            # Reset outputs
381            for output in self._extrapolation_outputs.values():
382                output.SetValue('-')
383            return
384        for key, value in params.iteritems():
385            output = self._extrapolation_outputs[key]
386            rounded = self._round_sig_figs(value, 6)
387            output.SetValue(rounded)
388
389
390    def set_extracted_params(self, params=None, reset=False):
391        """
392        Displays the values of the parameters extracted from the Fourier
393        transform
394        """
395        self.extracted_params = params
396        error = False
397        if params is None:
398            if not reset: error = True
399            for output in self._output_boxes.values():
400                output.SetValue('-')
401        else:
402            if len(params) < len(OUTPUT_STRINGS):
403                # Not all parameters were calculated
404                error = True
405            for key, value in params.iteritems():
406                rounded = self._round_sig_figs(value, 6)
407                self._output_boxes[key].SetValue(rounded)
408        if error:
409            msg = 'Not all parameters were able to be calculated'
410            wx.PostEvent(self._manager.parent, StatusEvent(
411                status=msg, info='error'))
412
413    def plot_qrange(self, active=None, leftdown=False):
414        if active is None:
415            active = self._qmin_input
416        wx.PostEvent(self._manager.parent, PlotQrangeEvent(
417            ctrl=[self._qmin_input, self._qmax1_input, self._qmax2_input],
418            active=active, id=IQ_DATA_LABEL, is_corfunc=True,
419            group_id=GROUP_ID_IQ_DATA, leftdown=leftdown))
420
421
422    def _compute_background(self, event=None):
423        """
424        Compute the background level based on the position of the upper q bars
425        """
426        if event is not None:
427            event.Skip()
428        self._on_enter_input()
429        try:
430            bg = self._calculator.compute_background(self.qmax)
431            self.set_background(bg)
432        except Exception as e:
433            msg = "Error computing background level:\n"
434            msg += str(e)
435            wx.PostEvent(self._manager.parent,
436                StatusEvent(status=msg, info="error"))
437
438    def _on_enter_input(self, event=None):
439        """
440        Read values from input boxes and save to memory.
441        """
442        if event is not None: event.Skip()
443        if not self._validate_inputs():
444            return
445        self.qmin = float(self._qmin_input.GetValue())
446        new_qmax1 = float(self._qmax1_input.GetValue())
447        new_qmax2 = float(self._qmax2_input.GetValue())
448        self.qmax = (new_qmax1, new_qmax2)
449        self.background = float(self._background_input.GetValue())
450        self._calculator.background = self.background
451        if event is not None:
452            active_ctrl = event.GetEventObject()
453            if active_ctrl == self._background_input:
454                self._manager.show_data(self._data, IQ_DATA_LABEL,
455                    reset=False, active_ctrl=active_ctrl)
456
457    def _on_click_qrange(self, event=None):
458        if event is None:
459            return
460        event.Skip()
461        if not self._validate_inputs(): return
462        self.plot_qrange(active=event.GetEventObject(),
463            leftdown=event.LeftDown())
464
465    def _validate_inputs(self):
466        """
467        Check that the values for qmin and qmax in the input boxes are valid
468        """
469        if self._data is None:
470            return False
471        qmin_valid = check_float(self._qmin_input)
472        qmax1_valid = check_float(self._qmax1_input)
473        qmax2_valid = check_float(self._qmax2_input)
474        qmax_valid = qmax1_valid and qmax2_valid
475        background_valid = check_float(self._background_input)
476        msg = ""
477        if (qmin_valid and qmax_valid and background_valid):
478            qmin = float(self._qmin_input.GetValue())
479            qmax1 = float(self._qmax1_input.GetValue())
480            qmax2 = float(self._qmax2_input.GetValue())
481            background = float(self._background_input.GetValue())
482            if not qmin > self._data.x.min():
483                msg = "qmin must be greater than the lowest q value"
484                qmin_valid = False
485            elif qmax2 < qmax1:
486                msg = "qmax1 must be less than qmax2"
487                qmax_valid = False
488            elif qmin > qmax1:
489                msg = "qmin must be less than qmax"
490                qmin_valid = False
491            elif background > self._data.y.max():
492                msg = "background must be less than highest I"
493                background_valid = False
494        if not qmin_valid:
495            self._qmin_input.SetBackgroundColour('pink')
496        if not qmax_valid:
497            self._qmax1_input.SetBackgroundColour('pink')
498            self._qmax2_input.SetBackgroundColour('pink')
499        if not background_valid:
500            self._background_input.SetBackgroundColour('pink')
501            if msg != "":
502                wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
503        if (qmin_valid and qmax_valid and background_valid):
504            self._qmin_input.SetBackgroundColour(wx.WHITE)
505            self._qmax1_input.SetBackgroundColour(wx.WHITE)
506            self._qmax2_input.SetBackgroundColour(wx.WHITE)
507            self._background_input.SetBackgroundColour(wx.WHITE)
508        self._qmin_input.Refresh()
509        self._qmax1_input.Refresh()
510        self._qmax2_input.Refresh()
511        self._background_input.Refresh()
512        return (qmin_valid and qmax_valid and background_valid)
513
514    def _do_layout(self):
515        """
516        Draw the window content
517        """
518        vbox = wx.GridBagSizer(0,0)
519
520        # I(q) data box
521        databox = wx.StaticBox(self, -1, "I(Q) Data Source")
522        databox_sizer = wx.StaticBoxSizer(databox, wx.VERTICAL)
523
524        file_sizer = wx.GridBagSizer(5, 5)
525
526        y = 0
527
528        file_name_label = wx.StaticText(self, -1, "Name:")
529        file_sizer.Add(file_name_label, (0, 0), (1, 1),
530            wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
531
532        self._data_name_box = OutputTextCtrl(self, -1,
533            size=(300,20))
534        file_sizer.Add(self._data_name_box, (0, 1), (1, 1),
535            wx.CENTER | wx.ADJUST_MINSIZE, 15)
536
537        file_sizer.AddSpacer((1, 25), pos=(0,2))
538        databox_sizer.Add(file_sizer, wx.TOP, 15)
539
540        vbox.Add(databox_sizer, (y, 0), (1, 1),
541            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE | wx.TOP, 15)
542        y += 1
543
544        # Parameters
545        qbox = wx.StaticBox(self, -1, "Input Parameters")
546        qbox_sizer = wx.StaticBoxSizer(qbox, wx.VERTICAL)
547        qbox_sizer.SetMinSize((_STATICBOX_WIDTH, 75))
548
549        q_sizer = wx.GridBagSizer(5, 5)
550
551        # Explanation
552        explanation_txt = ("Corfunc will use all values in the lower range for"
553            " Guinier back extrapolation, and all values in the upper range "
554            "for Porod forward extrapolation.")
555        explanation_label = wx.StaticText(self, -1, explanation_txt,
556            size=(_STATICBOX_WIDTH, 60))
557
558        q_sizer.Add(explanation_label, (0,0), (1,4), wx.LEFT | wx.EXPAND, 5)
559
560        qrange_label = wx.StaticText(self, -1, "Q Range:", size=(50,20))
561        q_sizer.Add(qrange_label, (1,0), (1,1), wx.LEFT | wx.EXPAND, 5)
562
563        # Lower Q Range
564        qmin_label = wx.StaticText(self, -1, "Lower:", size=(50,20))
565        qmin_dash_label = wx.StaticText(self, -1, "-", size=(10,20),
566            style=wx.ALIGN_CENTER_HORIZONTAL)
567
568        qmin_lower = OutputTextCtrl(self, -1, size=(75, 20), value="0.0")
569        self._qmin_input = ModelTextCtrl(self, -1, size=(75, 20),
570                        style=wx.TE_PROCESS_ENTER, name='qmin_input',
571                        text_enter_callback=self._on_enter_input)
572        self._qmin_input.SetToolTipString(("Values with q < qmin will be used "
573            "for Guinier back extrapolation"))
574
575        q_sizer.Add(qmin_label, (2, 0), (1, 1), wx.LEFT | wx.EXPAND, 5)
576        q_sizer.Add(qmin_lower, (2, 1), (1, 1), wx.LEFT, 5)
577        q_sizer.Add(qmin_dash_label, (2, 2), (1, 1), wx.CENTER | wx.EXPAND, 5)
578        q_sizer.Add(self._qmin_input, (2, 3), (1, 1), wx.LEFT, 5)
579
580        # Upper Q range
581        qmax_tooltip = ("Values with qmax1 < q < qmax2 will be used for Porod"
582            " forward extrapolation")
583
584        qmax_label = wx.StaticText(self, -1, "Upper:", size=(50,20))
585        qmax_dash_label = wx.StaticText(self, -1, "-", size=(10,20),
586            style=wx.ALIGN_CENTER_HORIZONTAL)
587
588        self._qmax1_input = ModelTextCtrl(self, -1, size=(75, 20),
589            style=wx.TE_PROCESS_ENTER, name="qmax1_input",
590            text_enter_callback=self._on_enter_input)
591        self._qmax1_input.SetToolTipString(qmax_tooltip)
592        self._qmax2_input = ModelTextCtrl(self, -1, size=(75, 20),
593            style=wx.TE_PROCESS_ENTER, name="qmax2_input",
594            text_enter_callback=self._on_enter_input)
595        self._qmax2_input.SetToolTipString(qmax_tooltip)
596
597        q_sizer.Add(qmax_label, (3, 0), (1, 1), wx.LEFT | wx.EXPAND, 5)
598        q_sizer.Add(self._qmax1_input, (3, 1), (1, 1), wx.LEFT, 5)
599        q_sizer.Add(qmax_dash_label, (3, 2), (1, 1), wx.CENTER | wx.EXPAND, 5)
600        q_sizer.Add(self._qmax2_input, (3,3), (1, 1), wx.LEFT, 5)
601
602        qbox_sizer.Add(q_sizer, wx.TOP, 0)
603
604        vbox.Add(qbox_sizer, (y, 0), (1, 1),
605            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
606        y += 1
607
608        extrapolation_box = wx.StaticBox(self, -1, "Extrapolation Parameters")
609        extrapolation_sizer = wx.StaticBoxSizer(extrapolation_box, wx.VERTICAL)
610        params_sizer = wx.GridBagSizer(5, 5)
611
612        guinier_label = wx.StaticText(self, -1, "Guinier:")
613        params_sizer.Add(guinier_label, (0, 0), (1,1),
614            wx.ALL | wx.EXPAND | wx.ADJUST_MINSIZE, 5)
615
616        a_label = wx.StaticText(self, -1, "A: ")
617        params_sizer.Add(a_label, (1, 0), (1, 1), wx.LEFT | wx.EXPAND, 15)
618
619        a_output = OutputTextCtrl(self, wx.NewId(),
620            value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
621        params_sizer.Add(a_output, (1, 1), (1, 1), wx.RIGHT | wx.EXPAND, 15)
622        self._extrapolation_outputs['A'] = a_output
623
624        b_label = wx.StaticText(self, -1, "B: ")
625        params_sizer.Add(b_label, (2, 0), (1, 1), wx.LEFT | wx.EXPAND, 15)
626
627        b_output = OutputTextCtrl(self, wx.NewId(),
628            value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
629        params_sizer.Add(b_output, (2, 1), (1, 1), wx.RIGHT | wx.EXPAND, 15)
630        self._extrapolation_outputs['B'] = b_output
631
632        porod_label = wx.StaticText(self, -1, "Porod: ")
633        params_sizer.Add(porod_label, (0, 2), (1, 1),
634            wx.ALL | wx.EXPAND | wx.ADJUST_MINSIZE, 5)
635
636        k_label = wx.StaticText(self, -1, "K: ")
637        params_sizer.Add(k_label, (1, 2), (1, 1), wx.LEFT | wx.EXPAND, 15)
638
639        k_output = OutputTextCtrl(self, wx.NewId(),
640            value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
641        params_sizer.Add(k_output, (1, 3), (1, 1), wx.RIGHT | wx.EXPAND, 15)
642        self._extrapolation_outputs['K'] = k_output
643
644        sigma_label = wx.StaticText(self, -1, u'\u03C3: ')
645        params_sizer.Add(sigma_label, (2, 2), (1, 1), wx.LEFT | wx.EXPAND, 15)
646
647        sigma_output = OutputTextCtrl(self, wx.NewId(),
648            value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
649        params_sizer.Add(sigma_output, (2, 3), (1, 1), wx.RIGHT | wx.EXPAND, 15)
650        self._extrapolation_outputs['sigma'] = sigma_output
651
652        bg_label = wx.StaticText(self, -1, "Bg: ")
653        params_sizer.Add(bg_label, (3, 2), (1, 1), wx.LEFT | wx.EXPAND, 15)
654
655        self._background_input = ModelTextCtrl(self, -1, value="0.0",
656            style=wx.TE_PROCESS_ENTER | wx.TE_CENTRE, name='background_input',
657            text_enter_callback=self._on_enter_input)
658        self._background_input.SetToolTipString(("A background value to "
659            "subtract from all intensity values"))
660        params_sizer.Add(self._background_input, (3, 3), (1, 1), wx.RIGHT | wx.EXPAND, 15)
661
662        background_button = wx.Button(self, wx.NewId(), "Calculate Bg",
663            size=(75, -1))
664        background_button.Bind(wx.EVT_BUTTON, self._compute_background)
665        params_sizer.Add(background_button, (4,3), (1, 1), wx.EXPAND | wx.RIGHT, 15)
666
667        extrapolation_sizer.Add(params_sizer)
668        vbox.Add(extrapolation_sizer, (y, 0), (1, 1),
669            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
670        y += 1
671
672        # Transform type
673        transform_box = wx.StaticBox(self, -1, "Transform Type")
674        transform_sizer = wx.StaticBoxSizer(transform_box, wx.VERTICAL)
675
676        radio_sizer = wx.GridBagSizer(5,5)
677
678        fourier_btn = wx.RadioButton(self, -1, "Fourier", name='fourier',
679            style=wx.RB_GROUP)
680        hilbert_btn = wx.RadioButton(self, -1, "Hilbert", name='hilbert')
681
682        fourier_btn.Bind(wx.EVT_RADIOBUTTON, self.radio_changed)
683        hilbert_btn.Bind(wx.EVT_RADIOBUTTON, self.radio_changed)
684
685        radio_sizer.Add(fourier_btn, (0,0), (1,1), wx.LEFT | wx.EXPAND)
686        radio_sizer.Add(hilbert_btn, (0,1), (1,1), wx.RIGHT | wx.EXPAND)
687
688        transform_sizer.Add(radio_sizer, wx.TOP, 0)
689        vbox.Add(transform_sizer, (y, 0), (1, 1),
690            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
691        y += 1
692
693        # Output data
694        outputbox = wx.StaticBox(self, -1, "Output Parameters")
695        outputbox_sizer = wx.StaticBoxSizer(outputbox, wx.VERTICAL)
696
697        output_sizer = wx.GridBagSizer(5, 5)
698
699        self._output_boxes = dict()
700        i = 0
701        for key, value in OUTPUT_STRINGS.iteritems():
702            # Create a label and a text box for each poperty
703            label = wx.StaticText(self, -1, value)
704            output_box = OutputTextCtrl(self, wx.NewId(),
705                value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
706            # Save the ID of each of the text boxes for accessing after the
707            # output data has been calculated
708            self._output_boxes[key] = output_box
709            output_sizer.Add(label, (i, 0), (1, 1), wx.LEFT | wx.EXPAND, 15)
710            output_sizer.Add(output_box, (i, 2), (1, 1),
711                wx.RIGHT | wx.EXPAND, 15)
712            i += 1
713
714        outputbox_sizer.Add(output_sizer, wx.TOP, 0)
715
716        vbox.Add(outputbox_sizer, (y, 0), (1, 1),
717            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
718        y += 1
719
720        # Controls
721        controlbox = wx.StaticBox(self, -1, "Controls")
722        controlbox_sizer = wx.StaticBoxSizer(controlbox, wx.VERTICAL)
723
724        controls_sizer = wx.BoxSizer(wx.VERTICAL)
725
726        self._extrapolate_btn = wx.Button(self, wx.NewId(), "Extrapolate")
727        self._transform_btn = wx.Button(self, wx.NewId(), "Transform")
728        self._extract_btn = wx.Button(self, wx.NewId(), "Compute Parameters")
729        help_btn = wx.Button(self, -1, "HELP")
730
731        self._transform_btn.Disable()
732        self._extract_btn.Disable()
733
734        self._extrapolate_btn.Bind(wx.EVT_BUTTON, self.compute_extrapolation)
735        self._transform_btn.Bind(wx.EVT_BUTTON, self.compute_transform)
736        self._extract_btn.Bind(wx.EVT_BUTTON, self.extract_parameters)
737        help_btn.Bind(wx.EVT_BUTTON, self.on_help)
738
739        controls_sizer.Add(self._extrapolate_btn, wx.CENTER | wx.EXPAND)
740        controls_sizer.Add(self._transform_btn, wx.CENTER | wx.EXPAND)
741        controls_sizer.Add(self._extract_btn, wx.CENTER | wx.EXPAND)
742        controls_sizer.Add(help_btn, wx.CENTER | wx.EXPAND)
743
744        controlbox_sizer.Add(controls_sizer, wx.TOP | wx.EXPAND, 0)
745        vbox.Add(controlbox_sizer, (y, 0), (1, 1),
746            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
747
748
749        self.SetSizer(vbox)
750
751    def _disable_inputs(self):
752        """
753        Disable all input fields
754        """
755        self._qmin_input.Disable()
756        self._qmax1_input.Disable()
757        self._qmax2_input.Disable()
758        self._background_input.Disable()
759        self._extrapolate_btn.Disable()
760
761    def _enable_inputs(self):
762        """
763        Enable all input fields
764        """
765        self._qmin_input.Enable()
766        self._qmax1_input.Enable()
767        self._qmax2_input.Enable()
768        self._background_input.Enable()
769        self._extrapolate_btn.Enable()
770
771    def _round_sig_figs(self, x, sigfigs):
772        """
773        Round a number to a given number of significant figures.
774
775        :param x: The value to round
776        :param sigfigs: How many significant figures to round to
777        :return rounded_str: x rounded to the given number of significant
778            figures, as a string
779        """
780        rounded_str = ""
781        try:
782            # Index of first significant digit
783            significant_digit = -int(np.floor(np.log10(np.abs(x))))
784
785            if np.abs(significant_digit > 4):
786                # Use scientific notation if x > 1e5 or x < 1e4
787                rounded_str = "{1:.{0}E}".format(sigfigs-1, x)
788            else:
789                # Format as a standard decimal
790                # Number of digits required for correct number of sig figs
791                digits = significant_digit + (sigfigs - 1)
792                rounded = np.round(x, decimals=digits)
793                rounded_str = "{1:.{0}f}".format(sigfigs -1  + significant_digit,
794                    rounded)
795        except:
796            # Method for finding significant_digit fails if x is 0 (since log10(0)=inf)
797            if x == 0.0:
798                rounded_str = "0.0"
799            else:
800                rounded_str = "-"
801
802        return rounded_str
Note: See TracBrowser for help on using the repository browser.