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

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.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 7432acb was 7432acb, checked in by andyfaff, 7 years ago

MAINT: search+replace '!= None' by 'is not None'

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