source: sasview/src/sas/perspectives/pr/explore_dialog.py @ 0ea31ca

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.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 0ea31ca was 8b21fa7, checked in by Doucet, Mathieu <doucetm@…>, 10 years ago

pylint fixes

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