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

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

Plot extrapolation and transform when loading saved project

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