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

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

Plot data with background subtracted

  • 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        self._calculator.background = bg
212
213    def _compute_background(self, event=None):
214        self.set_background(self._calculator.compute_background(self.qmax))
215
216    def _on_enter_input(self, event=None):
217        """
218        Read values from input boxes and save to memory.
219        """
220        if event is not None: event.Skip()
221        if not self._validate_inputs():
222            return
223        self.qmin = float(self._qmin_input.GetValue())
224        new_qmax1 = float(self._qmax1_input.GetValue())
225        new_qmax2 = float(self._qmax2_input.GetValue())
226        self.qmax = (new_qmax1, new_qmax2)
227        self.background = float(self._background_input.GetValue())
228        from sas.sasgui.perspectives.corfunc.corfunc import GROUP_ID_IQ_DATA,\
229            IQ_DATA_LABEL
230        group_id = GROUP_ID_IQ_DATA
231        if event is not None:
232            if self._manager is not None and\
233                event.GetEventObject() == self._background_input:
234                from sas.sasgui.perspectives.corfunc.corfunc\
235                    import IQ_DATA_LABEL
236                self._manager.show_data(self._data, IQ_DATA_LABEL, reset=True)
237            wx.PostEvent(self._manager.parent, PlotQrangeEvent(
238                ctrl=[self._qmin_input, self._qmax1_input, self._qmax2_input],
239                active=event.GetEventObject(), id=IQ_DATA_LABEL,
240                group_id=group_id, leftdown=False))
241
242    def _validate_inputs(self):
243        """
244        Check that the values for qmin and qmax in the input boxes are valid
245        """
246        if self._data is None:
247            return False
248        qmin_valid = check_float(self._qmin_input)
249        qmax1_valid = check_float(self._qmax1_input)
250        qmax2_valid = check_float(self._qmax2_input)
251        qmax_valid = qmax1_valid and qmax2_valid
252        background_valid = check_float(self._background_input)
253        msg = ""
254        if (qmin_valid and qmax_valid and background_valid):
255            qmin = float(self._qmin_input.GetValue())
256            qmax1 = float(self._qmax1_input.GetValue())
257            qmax2 = float(self._qmax2_input.GetValue())
258            background = float(self._background_input.GetValue())
259            if not qmin > self._data.x.min():
260                msg = "qmin must be greater than the lowest q value"
261                qmin_valid = False
262            elif qmax2 < qmax1:
263                msg = "qmax1 must be less than qmax2"
264                qmax_valid = False
265            elif qmin > qmax1:
266                msg = "qmin must be less than qmax"
267                qmin_valid = False
268            elif background < 0 or background > self._data.y.max():
269                msg = "background must be positive and less than highest I"
270                background_valid = False
271        if not qmin_valid:
272            self._qmin_input.SetBackgroundColour('pink')
273        if not qmax_valid:
274            self._qmax1_input.SetBackgroundColour('pink')
275            self._qmax2_input.SetBackgroundColour('pink')
276        if not background_valid:
277            self._background_input.SetBackgroundColour('pink')
278            if msg != "":
279                wx.PostEvent(self._manager.parent, StatusEvent(status=msg))
280        if (qmin_valid and qmax_valid and background_valid):
281            self._qmin_input.SetBackgroundColour(wx.WHITE)
282            self._qmax1_input.SetBackgroundColour(wx.WHITE)
283            self._qmax2_input.SetBackgroundColour(wx.WHITE)
284            self._background_input.SetBackgroundColour(wx.WHITE)
285        self._qmin_input.Refresh()
286        self._qmax1_input.Refresh()
287        self._qmax2_input.Refresh()
288        self._background_input.Refresh()
289        return (qmin_valid and qmax_valid and background_valid)
290
291    def _do_layout(self):
292        """
293        Draw the window content
294        """
295        vbox = wx.GridBagSizer(0,0)
296
297        # I(q) data box
298        databox = wx.StaticBox(self, -1, "I(Q) Data Source")
299        databox_sizer = wx.StaticBoxSizer(databox, wx.VERTICAL)
300
301        file_sizer = wx.GridBagSizer(5, 5)
302
303        file_name_label = wx.StaticText(self, -1, "Name:")
304        file_sizer.Add(file_name_label, (0, 0), (1, 1),
305            wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
306
307        self._data_name_box = OutputTextCtrl(self, -1,
308            size=(300,20))
309        file_sizer.Add(self._data_name_box, (0, 1), (1, 1),
310            wx.CENTER | wx.ADJUST_MINSIZE, 15)
311
312        file_sizer.AddSpacer((1, 25), pos=(0,2))
313        databox_sizer.Add(file_sizer, wx.TOP, 15)
314
315        vbox.Add(databox_sizer, (0, 0), (1, 1),
316            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE | wx.TOP, 15)
317
318
319        # Parameters
320        qbox = wx.StaticBox(self, -1, "Parameters")
321        qbox_sizer = wx.StaticBoxSizer(qbox, wx.VERTICAL)
322        qbox_sizer.SetMinSize((_STATICBOX_WIDTH, 75))
323
324        q_sizer = wx.GridBagSizer(5, 5)
325
326        # Explanation
327        explanation_txt = ("Corfunc will use all values in the lower range for"
328            " Guinier back extrapolation, and all values in the upper range "
329            "for Porod forward extrapolation.")
330        explanation_label = wx.StaticText(self, -1, explanation_txt,
331            size=(_STATICBOX_WIDTH, 60))
332
333        q_sizer.Add(explanation_label, (0,0), (1,4), wx.LEFT | wx.EXPAND, 5)
334
335        qrange_label = wx.StaticText(self, -1, "Q Range:", size=(50,20))
336        q_sizer.Add(qrange_label, (1,0), (1,1), wx.LEFT | wx.EXPAND, 5)
337
338        # Lower Q Range
339        qmin_label = wx.StaticText(self, -1, "Lower:", size=(50,20))
340        qmin_dash_label = wx.StaticText(self, -1, "-", size=(10,20),
341            style=wx.ALIGN_CENTER_HORIZONTAL)
342
343        qmin_lower = OutputTextCtrl(self, -1, size=(50, 20), value="0.0")
344        self._qmin_input = ModelTextCtrl(self, -1, size=(50, 20),
345                        style=wx.TE_PROCESS_ENTER, name='qmin_input',
346                        text_enter_callback=self._on_enter_input)
347        self._qmin_input.SetToolTipString(("Values with q < qmin will be used "
348            "for Guinier back extrapolation"))
349
350        q_sizer.Add(qmin_label, (2, 0), (1, 1), wx.LEFT | wx.EXPAND, 5)
351        q_sizer.Add(qmin_lower, (2, 1), (1, 1), wx.LEFT, 5)
352        q_sizer.Add(qmin_dash_label, (2, 2), (1, 1), wx.CENTER | wx.EXPAND, 5)
353        q_sizer.Add(self._qmin_input, (2, 3), (1, 1), wx.LEFT, 5)
354
355        # Upper Q range
356        qmax_tooltip = ("Values with qmax1 < q < qmax2 will be used for Porod"
357            " forward extrapolation")
358
359        qmax_label = wx.StaticText(self, -1, "Upper:", size=(50,20))
360        qmax_dash_label = wx.StaticText(self, -1, "-", size=(10,20),
361            style=wx.ALIGN_CENTER_HORIZONTAL)
362
363        self._qmax1_input = ModelTextCtrl(self, -1, size=(50, 20),
364            style=wx.TE_PROCESS_ENTER, name="qmax1_input",
365            text_enter_callback=self._on_enter_input)
366        self._qmax1_input.SetToolTipString(qmax_tooltip)
367        self._qmax2_input = ModelTextCtrl(self, -1, size=(50, 20),
368            style=wx.TE_PROCESS_ENTER, name="qmax2_input",
369            text_enter_callback=self._on_enter_input)
370        self._qmax2_input.SetToolTipString(qmax_tooltip)
371
372        q_sizer.Add(qmax_label, (3, 0), (1, 1), wx.LEFT | wx.EXPAND, 5)
373        q_sizer.Add(self._qmax1_input, (3, 1), (1, 1), wx.LEFT, 5)
374        q_sizer.Add(qmax_dash_label, (3, 2), (1, 1), wx.CENTER | wx.EXPAND, 5)
375        q_sizer.Add(self._qmax2_input, (3,3), (1, 1), wx.LEFT, 5)
376
377        background_label = wx.StaticText(self, -1, "Background:", size=(80,20))
378        q_sizer.Add(background_label, (4,0), (1,1), wx.LEFT | wx.EXPAND, 5)
379
380        self._background_input = ModelTextCtrl(self, -1, size=(50,20),
381            style=wx.TE_PROCESS_ENTER, name='background_input',
382            text_enter_callback=self._on_enter_input)
383        self._background_input.SetToolTipString(("A background value to "
384            "subtract from all intensity values"))
385        q_sizer.Add(self._background_input, (4,1), (1,1),
386            wx.RIGHT, 5)
387
388        background_button = wx.Button(self, wx.NewId(), "Calculate",
389            size=(75, 20))
390        background_button.Bind(wx.EVT_BUTTON, self._compute_background)
391        q_sizer.Add(background_button, (4, 2), (1, 1), wx.RIGHT, 5)
392
393        qbox_sizer.Add(q_sizer, wx.TOP, 0)
394
395        vbox.Add(qbox_sizer, (1, 0), (1, 1),
396            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
397
398        # Output data
399        outputbox = wx.StaticBox(self, -1, "Output Measuments")
400        outputbox_sizer = wx.StaticBoxSizer(outputbox, wx.VERTICAL)
401
402        output_sizer = wx.GridBagSizer(5, 5)
403
404        label_strings = [
405            "Long Period (A): ",
406            "Average Hard Block Thickness (A): ",
407            "Average Interface Thickness (A): ",
408            "Average Core Thickness: ",
409            "PolyDispersity: ",
410            "Filling Fraction: "
411        ]
412        self._output_ids = dict()
413        for i in range(len(label_strings)):
414            # Create a label and a text box for each poperty
415            label = wx.StaticText(self, -1, label_strings[i])
416            output_box = OutputTextCtrl(self, wx.NewId(), size=(50, 20),
417                value="-", style=wx.ALIGN_CENTER_HORIZONTAL)
418            # Save the ID of each of the text boxes for accessing after the
419            # output data has been calculated
420            self._output_ids[label_strings[i]] = output_box.GetId()
421            output_sizer.Add(label, (i, 0), (1, 1), wx.LEFT | wx.EXPAND, 15)
422            output_sizer.Add(output_box, (i, 2), (1, 1),
423                wx.RIGHT | wx.EXPAND, 15)
424
425        outputbox_sizer.Add(output_sizer, wx.TOP, 0)
426
427        vbox.Add(outputbox_sizer, (2, 0), (1, 1),
428            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
429
430        # Controls
431        controlbox = wx.StaticBox(self, -1, "Controls")
432        controlbox_sizer = wx.StaticBoxSizer(controlbox, wx.VERTICAL)
433
434        controls_sizer = wx.BoxSizer(wx.VERTICAL)
435
436        extrapolate_btn = wx.Button(self, wx.NewId(), "Extrapolate")
437        self._transform_btn = wx.Button(self, wx.NewId(), "Transform")
438        self._compute_btn = wx.Button(self, wx.NewId(), "Compute Measuments")
439
440        self._transform_btn.Disable()
441        self._compute_btn.Disable()
442
443        extrapolate_btn.Bind(wx.EVT_BUTTON, self.compute_extrapolation)
444        self._transform_btn.Bind(wx.EVT_BUTTON, self.compute_transform)
445
446        controls_sizer.Add(extrapolate_btn, wx.CENTER | wx.EXPAND)
447        controls_sizer.Add(self._transform_btn, wx.CENTER | wx.EXPAND)
448        controls_sizer.Add(self._compute_btn, wx.CENTER | wx.EXPAND)
449
450        controlbox_sizer.Add(controls_sizer, wx.TOP | wx.EXPAND, 0)
451        vbox.Add(controlbox_sizer, (3, 0), (1, 1),
452            wx.LEFT | wx.RIGHT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
453
454        self.SetSizer(vbox)
455
456    def _disable_inputs(self):
457        """
458        Disable all input fields
459        """
460        self._qmin_input.Disable()
461        self._qmax1_input.Disable()
462        self._qmax2_input.Disable()
463        self._background_input.Disable()
464
465    def _enable_inputs(self):
466        """
467        Enable all input fields
468        """
469        self._qmin_input.Enable()
470        self._qmax1_input.Enable()
471        self._qmax2_input.Enable()
472        self._background_input.Enable()
Note: See TracBrowser for help on using the repository browser.