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

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

Reset panel correctly when new data is loaded

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