source: sasview/src/sas/sasgui/perspectives/pr/explore_dialog.py @ 90d389d

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 90d389d was d85c194, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 9 years ago

Remaining modules refactored

  • Property mode set to 100644
File size: 14.9 KB
Line 
1
2################################################################################
3#This software was developed by the University of Tennessee as part of the
4#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
5#project funded by the US National Science Foundation.
6#
7#See the license text in license.txt
8#
9#copyright 2009, University of Tennessee
10################################################################################
11
12"""
13Dialog panel to explore the P(r) inversion results for a range
14of D_max value. User picks a number of points and a range of
15distances, then can toggle between inversion outputs and see
16their distribution as a function of D_max.
17"""
18
19
20import wx
21import numpy
22import logging
23import sys
24
25# Avoid Matplotlib complaining about the lack of legend on the plot
26import warnings
27warnings.simplefilter("ignore")
28
29# Import plotting classes
30from sas.sasgui.plottools.PlotPanel import PlotPanel
31from sas.sasgui.plottools import Data1D as Model1D
32from sas.sasgui.guiframe.gui_style import GUIFRAME_ID
33from sas.sasgui.plottools.plottables import Graph
34
35from pr_widgets import PrTextCtrl
36
37# Default number of points on the output plot
38DEFAULT_NPTS = 10
39# Default output parameter to plot
40DEFAULT_OUTPUT = 'Chi2/dof'
41
42class OutputPlot(PlotPanel):
43    """
44    Plot panel used to show the selected results as a function
45    of D_max
46    """
47    ## Title for plottools
48    window_caption = "D Explorer"
49
50    def __init__(self, d_min, d_max, parent, id= -1, color=None, \
51                 dpi=None, style=wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
52        """
53        Initialization. The parameters added to PlotPanel are:
54
55        :param d_min: Minimum value of D_max to explore
56        :param d_max: Maximum value of D_max to explore
57
58        """
59        PlotPanel.__init__(self, parent, id=id, style=style, **kwargs)
60
61        self.parent = parent
62        self.min = d_min
63        self.max = d_max
64        self.npts = DEFAULT_NPTS
65
66        step = (self.max - self.min) / (self.npts - 1)
67        self.x = numpy.arange(self.min, self.max + step * 0.01, step)
68        dx = numpy.zeros(len(self.x))
69        y = numpy.ones(len(self.x))
70        dy = numpy.zeros(len(self.x))
71
72        # Plot area
73        self.plot = Model1D(self.x, y=y, dy=dy)
74        self.plot.name = DEFAULT_OUTPUT
75        self.plot.symbol = GUIFRAME_ID.CURVE_SYMBOL_NUM
76
77        # Graph       
78        self.graph = Graph()
79        self.graph.xaxis("\\rm{D_{max}}", 'A')
80        self.graph.yaxis("\\rm{%s}" % DEFAULT_OUTPUT, "")
81        self.graph.add(self.plot)
82        self.graph.render(self)
83
84        self.toolbar.DeleteToolByPos(0)
85        self.toolbar.DeleteToolByPos(8)
86        self.toolbar.Realize()
87
88    def onContextMenu(self, event):
89        """
90        Default context menu for the plot panel
91
92        :TODO: Would be nice to add printing and log/linear scales.
93            The current verison of plottools no longer plays well with
94            plots outside of guiframe. Guiframe team needs to fix this.
95        """
96        # Slicer plot popup menu
97        wx_id = wx.NewId()
98        slicerpop = wx.Menu()
99        slicerpop.Append(wx_id, '&Save image', 'Save image as PNG')
100        wx.EVT_MENU(self, wx_id, self.onSaveImage)
101
102        wx_id = wx.NewId()
103        slicerpop.AppendSeparator()
104        slicerpop.Append(wx_id, '&Reset Graph')
105        wx.EVT_MENU(self, wx_id, self.onResetGraph)
106
107        pos = event.GetPosition()
108        pos = self.ScreenToClient(pos)
109        self.PopupMenu(slicerpop, pos)
110
111class Results(object):
112    """
113    Class to hold the inversion output parameters
114    as a function of D_max
115    """
116    def __init__(self):
117        """
118        Initialization. Create empty arrays
119        and dictionary of labels.
120        """
121        # Array of output for each inversion
122        self.chi2 = []
123        self.osc = []
124        self.pos = []
125        self.pos_err = []
126        self.rg = []
127        self.iq0 = []
128        self.bck = []
129        self.d_max = []
130
131        # Dictionary of outputs
132        self.outputs = {}
133        self.outputs['Chi2/dof'] = ["\chi^2/dof", "a.u.", self.chi2]
134        self.outputs['Oscillation parameter'] = ["Osc", "a.u.", self.osc]
135        self.outputs['Positive fraction'] = ["P^+", "a.u.", self.pos]
136        self.outputs['1-sigma positive fraction'] = ["P^+_{1\ \sigma}",
137                                                     "a.u.", self.pos_err]
138        self.outputs['Rg'] = ["R_g", "A", self.rg]
139        self.outputs['I(q=0)'] = ["I(q=0)", "1/A", self.iq0]
140        self.outputs['Background'] = ["Bck", "1/A", self.bck]
141
142class ExploreDialog(wx.Dialog):
143    """
144    The explorer dialog box. This dialog is meant to be
145    invoked by the InversionControl class.
146    """
147
148    def __init__(self, pr_state, nfunc, *args, **kwds):
149        """
150        Initialization. The parameters added to Dialog are:
151
152        :param pr_state: sas.sascalc.pr.invertor.Invertor object
153        :param nfunc: Number of terms in the expansion
154
155        """
156        kwds["style"] = wx.RESIZE_BORDER | wx.DEFAULT_DIALOG_STYLE
157        wx.Dialog.__init__(self, *args, **kwds)
158
159        # Initialize Results object
160        self.results = Results()
161
162        self.pr_state = pr_state
163        self._default_min = 0.9 * self.pr_state.d_max
164        self._default_max = 1.1 * self.pr_state.d_max
165        self.nfunc = nfunc
166
167        # Control for number of points
168        self.npts_ctl = PrTextCtrl(self, -1, style=wx.TE_PROCESS_ENTER,
169                                   size=(60, 20))
170        # Control for the minimum value of D_max
171        self.dmin_ctl = PrTextCtrl(self, -1, style=wx.TE_PROCESS_ENTER,
172                                   size=(60, 20))
173        # Control for the maximum value of D_max
174        self.dmax_ctl = PrTextCtrl(self, -1, style=wx.TE_PROCESS_ENTER,
175                                   size=(60, 20))
176
177        # Output selection box for the y axis
178        self.output_box = None
179
180        # Create the plot object
181        self.plotpanel = OutputPlot(self._default_min, self._default_max,
182                                    self, -1, style=wx.RAISED_BORDER)
183
184        # Create the layout of the dialog
185        self.__do_layout()
186        self.Fit()
187
188        # Calculate exploration results
189        self._recalc()
190        # Graph the default output curve
191        self._plot_output()
192
193    class Event(object):
194        """
195        Class that holds the content of the form
196        """
197        ## Number of points to be plotted
198        npts = 0
199        ## Minimum value of D_max
200        dmin = 0
201        ## Maximum value of D_max
202        dmax = 0
203
204    def _get_values(self, event=None):
205        """
206        Invoked when the user changes a value of the form.
207        Check that the values are of the right type.
208
209        :return: ExploreDialog.Event object if the content is good,
210            None otherwise
211        """
212        # Flag to make sure that all values are good
213        flag = True
214
215        # Empty ExploreDialog.Event content
216        content_event = self.Event()
217
218        # Read each text control and make sure the type is valid
219        # Let the user know if a type is invalid by changing the
220        # background color of the control.
221        try:
222            content_event.npts = int(self.npts_ctl.GetValue())
223            self.npts_ctl.SetBackgroundColour(wx.WHITE)
224            self.npts_ctl.Refresh()
225        except:
226            flag = False
227            self.npts_ctl.SetBackgroundColour("pink")
228            self.npts_ctl.Refresh()
229
230        try:
231            content_event.dmin = float(self.dmin_ctl.GetValue())
232            self.dmin_ctl.SetBackgroundColour(wx.WHITE)
233            self.dmin_ctl.Refresh()
234        except:
235            flag = False
236            self.dmin_ctl.SetBackgroundColour("pink")
237            self.dmin_ctl.Refresh()
238
239        try:
240            content_event.dmax = float(self.dmax_ctl.GetValue())
241            self.dmax_ctl.SetBackgroundColour(wx.WHITE)
242            self.dmax_ctl.Refresh()
243        except:
244            flag = False
245            self.dmax_ctl.SetBackgroundColour("pink")
246            self.dmax_ctl.Refresh()
247
248        # If the content of the form is valid, return the content,
249        # otherwise return None
250        if flag:
251            if event is not None:
252                event.Skip(True)
253            return content_event
254        else:
255            return None
256
257    def _plot_output(self, event=None):
258        """
259        Invoked when a new output type is selected for plotting,
260        or when a new computation is finished.
261        """
262        # Get the output type selection
263        output_type = self.output_box.GetString(self.output_box.GetSelection())
264
265        # If the selected output type is part of the results ojbect,
266        # display the results.
267        # Note: by design, the output type should always be part of the
268        #       results object.
269        if self.results.outputs.has_key(output_type):
270            self.plotpanel.plot.x = self.results.d_max
271            self.plotpanel.plot.y = self.results.outputs[output_type][2]
272            self.plotpanel.plot.name = '_nolegend_'
273            y_label = "\\rm{%s}" % self.results.outputs[output_type][0]
274            self.plotpanel.graph.yaxis(y_label,
275                                       self.results.outputs[output_type][1])
276
277            # Redraw
278            self.plotpanel.graph.render(self.plotpanel)
279            self.plotpanel.subplot.figure.canvas.draw_idle()
280        else:
281            msg = "ExploreDialog: the Results object's dictionary "
282            msg += "does not contain "
283            msg += "the [%s] output type. This must be indicative of "
284            msg += "a change in the " % str(output_type)
285            msg += "ExploreDialog code."
286            logging.error(msg)
287
288    def __do_layout(self):
289        """
290        Do the layout of the dialog
291        """
292        # Dialog box properties
293        self.SetTitle("D_max Explorer")
294        self.SetSize((600, 595))
295
296        sizer_main = wx.BoxSizer(wx.VERTICAL)
297        sizer_button = wx.BoxSizer(wx.HORIZONTAL)
298        sizer_params = wx.GridBagSizer(5, 5)
299
300        iy = 0
301        ix = 0
302        label_npts = wx.StaticText(self, -1, "Npts")
303        sizer_params.Add(label_npts, (iy, ix), (1, 1),
304                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
305        ix += 1
306        sizer_params.Add(self.npts_ctl, (iy, ix), (1, 1),
307                         wx.EXPAND | wx.ADJUST_MINSIZE, 0)
308        self.npts_ctl.SetValue("%g" % DEFAULT_NPTS)
309
310        ix += 1
311        label_dmin = wx.StaticText(self, -1, "Min Distance [A]")
312        sizer_params.Add(label_dmin, (iy, ix), (1, 1),
313                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
314        ix += 1
315        sizer_params.Add(self.dmin_ctl, (iy, ix), (1, 1),
316                         wx.EXPAND | wx.ADJUST_MINSIZE, 0)
317        self.dmin_ctl.SetValue(str(self._default_min))
318
319        ix += 1
320        label_dmax = wx.StaticText(self, -1, "Max Distance [A]")
321        sizer_params.Add(label_dmax, (iy, ix), (1, 1),
322                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
323        ix += 1
324        sizer_params.Add(self.dmax_ctl, (iy, ix), (1, 1),
325                         wx.EXPAND | wx.ADJUST_MINSIZE, 0)
326        self.dmax_ctl.SetValue(str(self._default_max))
327
328        # Ouput selection box
329        selection_msg = wx.StaticText(self, -1, "Select a dependent variable:")
330        self.output_box = wx.ComboBox(self, -1, style=wx.CB_READONLY)
331        for item in self.results.outputs.keys():
332            self.output_box.Append(item, "")
333        self.output_box.SetStringSelection(DEFAULT_OUTPUT)
334
335        output_sizer = wx.GridBagSizer(5, 5)
336        output_sizer.Add(selection_msg, (0, 0), (1, 1),
337                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 10)
338        output_sizer.Add(self.output_box, (0, 1), (1, 2),
339                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 10)
340
341        wx.EVT_COMBOBOX(self.output_box, -1, self._plot_output)
342        sizer_main.Add(output_sizer, 0, wx.EXPAND | wx.ALL, 10)
343
344        sizer_main.Add(self.plotpanel, 0, wx.EXPAND | wx.ALL, 10)
345        sizer_main.SetItemMinSize(self.plotpanel, 400, 400)
346
347        sizer_main.Add(sizer_params, 0, wx.EXPAND | wx.ALL, 10)
348        static_line_3 = wx.StaticLine(self, -1)
349        sizer_main.Add(static_line_3, 0, wx.EXPAND, 0)
350
351        # Bottom area with the close button
352        sizer_button.Add((20, 20), 1, wx.EXPAND | wx.ADJUST_MINSIZE, 0)
353        button_OK = wx.Button(self, wx.ID_OK, "Close")
354        sizer_button.Add(button_OK, 0, wx.LEFT | wx.RIGHT | wx.ADJUST_MINSIZE, 10)
355
356        sizer_main.Add(sizer_button, 0, wx.EXPAND | wx.BOTTOM | wx.TOP, 10)
357        self.SetAutoLayout(True)
358        self.SetSizer(sizer_main)
359        self.Layout()
360        self.Centre()
361
362        # Bind the Enter key to recalculation
363        self.Bind(wx.EVT_TEXT_ENTER, self._recalc)
364
365    def set_plot_unfocus(self):
366        """
367        Not implemented
368        """
369        pass
370
371    def send_focus_to_datapanel(self, name):
372        """
373            The GUI manager sometimes calls this method
374            TODO: refactor this
375        """
376        pass
377
378    def _recalc(self, event=None):
379        """
380        Invoked when the user changed a value on the form.
381        Process the form and compute the output to be plottted.
382        """
383        # Get the content of the form
384        content = self._get_values()
385        # If the content of the form is invalid, return and do nothing
386        if content is None:
387            return
388
389        # Results object to store the computation outputs.
390        results = Results()
391
392        # Loop over d_max values
393        for i in range(content.npts):
394            temp = (content.dmax - content.dmin) / (content.npts - 1.0)
395            d = content.dmin + i * temp
396
397            self.pr_state.d_max = d
398            try:
399                out, cov = self.pr_state.invert(self.nfunc)
400
401                # Store results
402                iq0 = self.pr_state.iq0(out)
403                rg = self.pr_state.rg(out)
404                pos = self.pr_state.get_positive(out)
405                pos_err = self.pr_state.get_pos_err(out, cov)
406                osc = self.pr_state.oscillations(out)
407
408                results.d_max.append(self.pr_state.d_max)
409                results.bck.append(self.pr_state.background)
410                results.chi2.append(self.pr_state.chi2)
411                results.iq0.append(iq0)
412                results.rg.append(rg)
413                results.pos.append(pos)
414                results.pos_err.append(pos_err)
415                results.osc.append(osc)
416            except:
417                # This inversion failed, skip this D_max value
418                msg = "ExploreDialog: inversion failed "
419                msg += "for D_max=%s\n%s" % (str(d), sys.exc_value)
420                logging.error(msg)
421
422        self.results = results
423
424        # Plot the selected output
425        self._plot_output()
Note: See TracBrowser for help on using the repository browser.