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

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

Add some docstrings

  • Property mode set to 100644
File size: 18.8 KB
Line 
1import wx
2import sys
3from wx.lib.scrolledpanel import ScrolledPanel
4from sas.sasgui.guiframe.events import PlotQrangeEvent
5from sas.sasgui.guiframe.events import StatusEvent
6from sas.sasgui.guiframe.panel_base import PanelBase
7from sas.sasgui.guiframe.utils import check_float
8from sas.sasgui.guiframe.dataFitting import Data1D
9from sas.sasgui.perspectives.invariant.invariant_widgets import OutputTextCtrl
10from sas.sasgui.perspectives.invariant.invariant_widgets import InvTextCtrl
11from sas.sasgui.perspectives.fitting.basepage import ModelTextCtrl
12from sas.sasgui.perspectives.corfunc.corfunc_state import CorfuncState
13import sas.sasgui.perspectives.corfunc.corfunc
14from sas.sascalc.corfunc.corfunc_calculator import CorfuncCalculator
15
16if sys.platform.count("win32") > 0:
17    _STATICBOX_WIDTH = 350
18    PANEL_WIDTH = 400
19    PANEL_HEIGHT = 700
20    FONT_VARIANT = 0
21else:
22    _STATICBOX_WIDTH = 390
23    PANEL_WIDTH = 430
24    PANEL_HEIGHT = 700
25    FONT_VARIANT = 1
26
27class CorfuncPanel(ScrolledPanel,PanelBase):
28    window_name = "Correlation Function"
29    window_caption = "Correlation Function"
30    CENTER_PANE = True
31
32    def __init__(self, parent, data=None, manager=None, *args, **kwds):
33        kwds["size"] = (PANEL_WIDTH, PANEL_HEIGHT)
34        kwds["style"] = wx.FULL_REPAINT_ON_RESIZE
35        ScrolledPanel.__init__(self, parent=parent, *args, **kwds)
36        PanelBase.__init__(self, parent)
37        self.SetupScrolling()
38        self.SetWindowVariant(variant=FONT_VARIANT)
39        self._manager = manager
40        # The data with no correction for background values
41        self._data = data # The data to be analysed (corrected fr background)
42        self._extrapolated_data = None # The extrapolated data set
43        self._calculator = CorfuncCalculator()
44        self._data_name_box = None # Text box to show name of file
45        self._background_input = None
46        self._qmin_input = None
47        self._qmax1_input = None
48        self._qmax2_input = None
49        self._transform_btn = None
50        self._compute_btn = None
51        self.qmin = 0
52        self.qmax = (0, 0)
53        self.background = 0
54        # Dictionary for saving IDs of text boxes used to display output data
55        self._output_ids = None
56        self.state = None
57        self._do_layout()
58        self._disable_inputs()
59        self.set_state()
60        self._qmin_input.Bind(wx.EVT_TEXT, self._on_enter_input)
61        self._qmax1_input.Bind(wx.EVT_TEXT, self._on_enter_input)
62        self._qmax2_input.Bind(wx.EVT_TEXT, self._on_enter_input)
63        self._background_input.Bind(wx.EVT_TEXT, self._on_enter_input)
64
65    def set_state(self, state=None, data=None):
66        """
67        Set the state of the panel. If no state is provided, the panel will
68        be set to the default state.
69
70        :param state: A CorfuncState object
71        :param data: A Data1D object
72        """
73        if state is None:
74            self.state = CorfuncState()
75        else:
76            self.state = state
77        if data is not None:
78            self.state.data = data
79        self.set_data(data, set_qrange=False)
80        if self.state.qmin is not None:
81            self.set_qmin(self.state.qmin)
82        if self.state.qmax is not None and self.state.qmax != (None, None):
83            self.set_qmax(tuple(self.state.qmax))
84        if self.state.background is not None:
85            self.set_background(self.state.background)
86
87    def get_state(self):
88        """
89        Return the state of the panel
90        """
91        state = CorfuncState()
92        state.set_saved_state('qmin_tcl', self.qmin)
93        state.set_saved_state('qmax1_tcl', self.qmax[0])
94        state.set_saved_state('qmax2_tcl', self.qmax[1])
95        state.set_saved_state('background_tcl', self.background)
96        if self._data is not None:
97            state.file = self._data.title
98            state.data = self._data
99        self.state = state
100
101        return self.state
102
103    def onSetFocus(self, evt):
104        if evt is not None:
105            evt.Skip()
106        self._validate_inputs()
107
108    def set_data(self, data=None, set_qrange=True):
109        """
110        Update the GUI to reflect new data that has been loaded in
111
112        :param data: The data that has been loaded
113        """
114        if data is None:
115            return
116        self._enable_inputs()
117        self._transform_btn.Disable()
118        self._data_name_box.SetValue(str(data.title))
119        self._data = data
120        self._calculator.set_data(data)
121        if self._manager is not None:
122            from sas.sasgui.perspectives.corfunc.corfunc import IQ_DATA_LABEL
123            self._manager.show_data(self._data, IQ_DATA_LABEL, reset=True)
124        if set_qrange:
125            lower = data.x[-1]*0.05
126            upper1 = data.x[-1] - lower*5
127            upper2 = data.x[-1]
128            self.set_qmin(lower)
129            self.set_qmax((upper1, upper2))
130            self.set_background(self._calculator.compute_background(self.qmax))
131
132    def get_data(self):
133        return self._data
134
135    def compute_extrapolation(self, event=None):
136        """
137        Compute and plot the extrapolated data.
138        Called when Extrapolate button is pressed.
139        """
140        if self._data is None:
141            msg = "Data must be loaded in order to perform an extrapolation."
142            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
143            return
144        if not self._validate_inputs:
145            msg = "Invalid Q range entered."
146            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
147            return
148        self._calculator.set_data(self._data)
149        self._calculator.lowerq = self.qmin
150        self._calculator.upperq = self.qmax
151        self._extrapolated_data = self._calculator.compute_extrapolation()
152        # TODO: Find way to set xlim and ylim so full range of data can be
153        # plotted
154        maxq = self._data.x.max()
155        mask = self._extrapolated_data.x <= maxq
156        numpts = len(self._extrapolated_data.x[mask]) + 250
157        plot_x = self._extrapolated_data.x[0:numpts]
158        plot_y = self._extrapolated_data.y[0:numpts]
159        to_plot = Data1D(plot_x, plot_y)
160        from sas.sasgui.perspectives.corfunc.corfunc import\
161            IQ_EXTRAPOLATED_DATA_LABEL
162        self._manager.show_data(to_plot, IQ_EXTRAPOLATED_DATA_LABEL)
163        self._transform_btn.Enable()
164
165    def compute_transform(self, event=None):
166        """
167        Compute and plot the transformed data.
168        Called when Transform button is pressed.
169        """
170        transformed_data = self._calculator.compute_transform(
171            self._extrapolated_data, self.background)
172        from sas.sasgui.perspectives.corfunc.corfunc import TRANSFORM_LABEL
173        import numpy as np
174        plot_x = transformed_data.x[np.where(transformed_data.x <= 200)]
175        plot_y = transformed_data.y[np.where(transformed_data.x <= 200)]
176        self._manager.show_data(Data1D(plot_x, plot_y), TRANSFORM_LABEL)
177
178
179    def save_project(self, doc=None):
180        """
181        Return an XML node containing the state of the panel
182
183        :param doc: Am xml node to attach the project state to (optional)
184        """
185        data = self._data
186        state = self.get_state()
187        if data is not None:
188            new_doc, sasentry = self._manager.state_reader._to_xml_doc(data)
189            new_doc = state.toXML(doc=new_doc, entry_node=sasentry)
190            if new_doc is not None:
191                if doc is not None and hasattr(doc, "firstChild"):
192                    child = new_doc.getElementsByTagName("SASentry")
193                    for item in child:
194                        doc.firstChild.appendChild(item)
195                else:
196                    doc = new_doc
197        return doc
198
199    def set_qmin(self, qmin):
200        self.qmin = qmin
201        self._qmin_input.SetValue(str(qmin))
202
203    def set_qmax(self, qmax):
204        self.qmax = qmax
205        self._qmax1_input.SetValue(str(qmax[0]))
206        self._qmax2_input.SetValue(str(qmax[1]))
207
208    def set_background(self, bg):
209        self.background = bg
210        self._background_input.SetValue(str(bg))
211
212    def _compute_background(self, event=None):
213        self.set_background(self._calculator.compute_background(self.qmax))
214
215    def _on_enter_input(self, event=None):
216        """
217        Read values from input boxes and save to memory.
218        """
219        if event is not None: event.Skip()
220        if not self._validate_inputs():
221            return
222        self.qmin = float(self._qmin_input.GetValue())
223        new_qmax1 = float(self._qmax1_input.GetValue())
224        new_qmax2 = float(self._qmax2_input.GetValue())
225        self.qmax = (new_qmax1, new_qmax2)
226        self.background = float(self._background_input.GetValue())
227        from sas.sasgui.perspectives.corfunc.corfunc import GROUP_ID_IQ_DATA,\
228            IQ_DATA_LABEL
229        group_id = GROUP_ID_IQ_DATA
230        if event is not None:
231            if self._manager is not None and\
232                event.GetEventObject() == self._background_input:
233                from sas.sasgui.perspectives.corfunc.corfunc\
234                    import IQ_DATA_LABEL
235                self._manager.show_data(self._data, IQ_DATA_LABEL, reset=True)
236            wx.PostEvent(self._manager.parent, PlotQrangeEvent(
237                ctrl=[self._qmin_input, self._qmax1_input, self._qmax2_input],
238                active=event.GetEventObject(), id=IQ_DATA_LABEL,
239                group_id=group_id, leftdown=False))
240
241    def _validate_inputs(self):
242        """
243        Check that the values for qmin and qmax in the input boxes are valid
244        """
245        if self._data is None:
246            return False
247        qmin_valid = check_float(self._qmin_input)
248        qmax1_valid = check_float(self._qmax1_input)
249        qmax2_valid = check_float(self._qmax2_input)
250        qmax_valid = qmax1_valid and qmax2_valid
251        background_valid = check_float(self._background_input)
252        msg = ""
253        if (qmin_valid and qmax_valid and background_valid):
254            qmin = float(self._qmin_input.GetValue())
255            qmax1 = float(self._qmax1_input.GetValue())
256            qmax2 = float(self._qmax2_input.GetValue())
257            background = float(self._background_input.GetValue())
258            if not qmin > self._data.x.min():
259                msg = "qmin must be greater than the lowest q value"
260                qmin_valid = False
261            elif qmax2 < qmax1:
262                msg = "qmax1 must be less than qmax2"
263                qmax_valid = False
264            elif qmin > qmax1:
265                msg = "qmin must be less than qmax"
266                qmin_valid = False
267            elif background < 0 or background > self._data.y.max():
268                msg = "background must be positive and less than highest I"
269                background_valid = False
270        if not qmin_valid:
271            self._qmin_input.SetBackgroundColour('pink')
272        if not qmax_valid:
273            self._qmax1_input.SetBackgroundColour('pink')
274            self._qmax2_input.SetBackgroundColour('pink')
275        if not background_valid:
276            self._background_input.SetBackgroundColour('pink')
277            if msg != "":
278                wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
279        if (qmin_valid and qmax_valid and background_valid):
280            self._qmin_input.SetBackgroundColour(wx.WHITE)
281            self._qmax1_input.SetBackgroundColour(wx.WHITE)
282            self._qmax2_input.SetBackgroundColour(wx.WHITE)
283            self._background_input.SetBackgroundColour(wx.WHITE)
284        self._qmin_input.Refresh()
285        self._qmax1_input.Refresh()
286        self._qmax2_input.Refresh()
287        self._background_input.Refresh()
288        return (qmin_valid and qmax_valid and background_valid)
289
290    def _do_layout(self):
291        """
292        Draw the window content
293        """
294        vbox = wx.GridBagSizer(0,0)
295
296        # I(q) data box
297        databox = wx.StaticBox(self, -1, "I(Q) Data Source")
298        databox_sizer = wx.StaticBoxSizer(databox, wx.VERTICAL)
299
300        file_sizer = wx.GridBagSizer(5, 5)
301
302        file_name_label = wx.StaticText(self, -1, "Name:")
303        file_sizer.Add(file_name_label, (0, 0), (1, 1),
304            wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
305
306        self._data_name_box = OutputTextCtrl(self, -1,
307            size=(300,20))
308        file_sizer.Add(self._data_name_box, (0, 1), (1, 1),
309            wx.CENTER | wx.ADJUST_MINSIZE, 15)
310
311        file_sizer.AddSpacer((1, 25), pos=(0,2))
312        databox_sizer.Add(file_sizer, wx.TOP, 15)
313
314        vbox.Add(databox_sizer, (0, 0), (1, 1),
315            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE | wx.TOP, 15)
316
317
318        # Parameters
319        qbox = wx.StaticBox(self, -1, "Parameters")
320        qbox_sizer = wx.StaticBoxSizer(qbox, wx.VERTICAL)
321        qbox_sizer.SetMinSize((_STATICBOX_WIDTH, 75))
322
323        q_sizer = wx.GridBagSizer(5, 5)
324
325        # Explanation
326        explanation_txt = ("Corfunc will use all values in the lower range for"
327            " Guinier back extrapolation, and all values in the upper range "
328            "for Porod forward extrapolation.")
329        explanation_label = wx.StaticText(self, -1, explanation_txt,
330            size=(_STATICBOX_WIDTH, 60))
331
332        q_sizer.Add(explanation_label, (0,0), (1,4), wx.LEFT | wx.EXPAND, 5)
333
334        qrange_label = wx.StaticText(self, -1, "Q Range:", size=(50,20))
335        q_sizer.Add(qrange_label, (1,0), (1,1), wx.LEFT | wx.EXPAND, 5)
336
337        # Lower Q Range
338        qmin_label = wx.StaticText(self, -1, "Lower:", size=(50,20))
339        qmin_dash_label = wx.StaticText(self, -1, "-", size=(10,20),
340            style=wx.ALIGN_CENTER_HORIZONTAL)
341
342        qmin_lower = OutputTextCtrl(self, -1, size=(50, 20), value="0.0")
343        self._qmin_input = ModelTextCtrl(self, -1, size=(50, 20),
344                        style=wx.TE_PROCESS_ENTER, name='qmin_input',
345                        text_enter_callback=self._on_enter_input)
346        self._qmin_input.SetToolTipString(("Values with q < qmin will be used "
347            "for Guinier back extrapolation"))
348
349        q_sizer.Add(qmin_label, (2, 0), (1, 1), wx.LEFT | wx.EXPAND, 5)
350        q_sizer.Add(qmin_lower, (2, 1), (1, 1), wx.LEFT, 5)
351        q_sizer.Add(qmin_dash_label, (2, 2), (1, 1), wx.CENTER | wx.EXPAND, 5)
352        q_sizer.Add(self._qmin_input, (2, 3), (1, 1), wx.LEFT, 5)
353
354        # Upper Q range
355        qmax_tooltip = ("Values with qmax1 < q < qmax2 will be used for Porod"
356            " forward extrapolation")
357
358        qmax_label = wx.StaticText(self, -1, "Upper:", size=(50,20))
359        qmax_dash_label = wx.StaticText(self, -1, "-", size=(10,20),
360            style=wx.ALIGN_CENTER_HORIZONTAL)
361
362        self._qmax1_input = ModelTextCtrl(self, -1, size=(50, 20),
363            style=wx.TE_PROCESS_ENTER, name="qmax1_input",
364            text_enter_callback=self._on_enter_input)
365        self._qmax1_input.SetToolTipString(qmax_tooltip)
366        self._qmax2_input = ModelTextCtrl(self, -1, size=(50, 20),
367            style=wx.TE_PROCESS_ENTER, name="qmax2_input",
368            text_enter_callback=self._on_enter_input)
369        self._qmax2_input.SetToolTipString(qmax_tooltip)
370
371        q_sizer.Add(qmax_label, (3, 0), (1, 1), wx.LEFT | wx.EXPAND, 5)
372        q_sizer.Add(self._qmax1_input, (3, 1), (1, 1), wx.LEFT, 5)
373        q_sizer.Add(qmax_dash_label, (3, 2), (1, 1), wx.CENTER | wx.EXPAND, 5)
374        q_sizer.Add(self._qmax2_input, (3,3), (1, 1), wx.LEFT, 5)
375
376        background_label = wx.StaticText(self, -1, "Background:", size=(80,20))
377        q_sizer.Add(background_label, (4,0), (1,1), wx.LEFT | wx.EXPAND, 5)
378
379        self._background_input = ModelTextCtrl(self, -1, size=(50,20),
380            style=wx.TE_PROCESS_ENTER, name='background_input',
381            text_enter_callback=self._on_enter_input)
382        self._background_input.SetToolTipString(("A background value to "
383            "subtract from all intensity values"))
384        q_sizer.Add(self._background_input, (4,1), (1,1),
385            wx.RIGHT, 5)
386
387        background_button = wx.Button(self, wx.NewId(), "Calculate",
388            size=(75, 20))
389        background_button.Bind(wx.EVT_BUTTON, self._compute_background)
390        q_sizer.Add(background_button, (4, 2), (1, 1), wx.RIGHT, 5)
391
392        qbox_sizer.Add(q_sizer, wx.TOP, 0)
393
394        vbox.Add(qbox_sizer, (1, 0), (1, 1),
395            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
396
397        # Output data
398        outputbox = wx.StaticBox(self, -1, "Output Measuments")
399        outputbox_sizer = wx.StaticBoxSizer(outputbox, wx.VERTICAL)
400
401        output_sizer = wx.GridBagSizer(5, 5)
402
403        label_strings = [
404            "Long Period (A): ",
405            "Average Hard Block Thickness (A): ",
406            "Average Interface Thickness (A): ",
407            "Average Core Thickness: ",
408            "PolyDispersity: ",
409            "Filling Fraction: "
410        ]
411        self._output_ids = dict()
412        for i in range(len(label_strings)):
413            # Create a label and a text box for each poperty
414            label = wx.StaticText(self, -1, label_strings[i])
415            output_box = OutputTextCtrl(self, wx.NewId(), size=(50, 20),
416                value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
417            # Save the ID of each of the text boxes for accessing after the
418            # output data has been calculated
419            self._output_ids[label_strings[i]] = output_box.GetId()
420            output_sizer.Add(label, (i, 0), (1, 1), wx.LEFT | wx.EXPAND, 15)
421            output_sizer.Add(output_box, (i, 2), (1, 1),
422                wx.RIGHT | wx.EXPAND, 15)
423
424        outputbox_sizer.Add(output_sizer, wx.TOP, 0)
425
426        vbox.Add(outputbox_sizer, (2, 0), (1, 1),
427            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
428
429        # Controls
430        controlbox = wx.StaticBox(self, -1, "Controls")
431        controlbox_sizer = wx.StaticBoxSizer(controlbox, wx.VERTICAL)
432
433        controls_sizer = wx.BoxSizer(wx.VERTICAL)
434
435        extrapolate_btn = wx.Button(self, wx.NewId(), "Extrapolate")
436        self._transform_btn = wx.Button(self, wx.NewId(), "Transform")
437        self._compute_btn = wx.Button(self, wx.NewId(), "Compute Measuments")
438
439        self._transform_btn.Disable()
440        self._compute_btn.Disable()
441
442        extrapolate_btn.Bind(wx.EVT_BUTTON, self.compute_extrapolation)
443        self._transform_btn.Bind(wx.EVT_BUTTON, self.compute_transform)
444
445        controls_sizer.Add(extrapolate_btn, wx.CENTER | wx.EXPAND)
446        controls_sizer.Add(self._transform_btn, wx.CENTER | wx.EXPAND)
447        controls_sizer.Add(self._compute_btn, wx.CENTER | wx.EXPAND)
448
449        controlbox_sizer.Add(controls_sizer, wx.TOP | wx.EXPAND, 0)
450        vbox.Add(controlbox_sizer, (3, 0), (1, 1),
451            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
452
453        self.SetSizer(vbox)
454
455    def _disable_inputs(self):
456        """
457        Disable all input fields
458        """
459        self._qmin_input.Disable()
460        self._qmax1_input.Disable()
461        self._qmax2_input.Disable()
462        self._background_input.Disable()
463
464    def _enable_inputs(self):
465        """
466        Enable all input fields
467        """
468        self._qmin_input.Enable()
469        self._qmax1_input.Enable()
470        self._qmax2_input.Enable()
471        self._background_input.Enable()
Note: See TracBrowser for help on using the repository browser.