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

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

Move background input below qrange input

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