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

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

Resize input controls

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