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

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 cce0ad3 was a862cea0, checked in by Doucet, Mathieu <doucetm@…>, 10 years ago

Make sure the drop down acts like a drop down…

  • Property mode set to 100644
File size: 14.9 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        """
[0efb04d]259        self.npts_ctl.SetFocus()
[a00ee4c]260        # Get the output type selection
261        output_type = self.output_box.GetString(self.output_box.GetSelection())
[8b21fa7]262
[a00ee4c]263        # If the selected output type is part of the results ojbect,
[8b21fa7]264        # display the results.
[a00ee4c]265        # Note: by design, the output type should always be part of the
266        #       results object.
[8b21fa7]267        if self.results.outputs.has_key(output_type):
[a00ee4c]268            self.plotpanel.plot.x = self.results.d_max
269            self.plotpanel.plot.y = self.results.outputs[output_type][2]
270            self.plotpanel.plot.name = '_nolegend_'
[3e41f43]271            y_label = "\\rm{%s}" % self.results.outputs[output_type][0]
272            self.plotpanel.graph.yaxis(y_label,
273                                       self.results.outputs[output_type][1])
[8b21fa7]274
[a00ee4c]275            # Redraw
276            self.plotpanel.graph.render(self.plotpanel)
277            self.plotpanel.subplot.figure.canvas.draw_idle()
278        else:
[8b21fa7]279            msg = "ExploreDialog: the Results object's dictionary "
[3e41f43]280            msg += "does not contain "
281            msg += "the [%s] output type. This must be indicative of "
282            msg += "a change in the " % str(output_type)
[a00ee4c]283            msg += "ExploreDialog code."
284            logging.error(msg)
[8b21fa7]285
[a00ee4c]286    def __do_layout(self):
287        """
[7116b6e0]288        Do the layout of the dialog
[a00ee4c]289        """
290        # Dialog box properties
291        self.SetTitle("D_max Explorer")
292        self.SetSize((600, 595))
[8b21fa7]293
[a00ee4c]294        sizer_main = wx.BoxSizer(wx.VERTICAL)
295        sizer_button = wx.BoxSizer(wx.HORIZONTAL)
[3e41f43]296        sizer_params = wx.GridBagSizer(5, 5)
[a00ee4c]297
298        iy = 0
299        ix = 0
[8b21fa7]300        label_npts = wx.StaticText(self, -1, "Npts")
301        sizer_params.Add(label_npts, (iy, ix), (1, 1),
302                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
[a00ee4c]303        ix += 1
[8b21fa7]304        sizer_params.Add(self.npts_ctl, (iy, ix), (1, 1),
305                         wx.EXPAND | wx.ADJUST_MINSIZE, 0)
[a00ee4c]306        self.npts_ctl.SetValue("%g" % DEFAULT_NPTS)
[164c7d0]307        self.npts_ctl.Bind(wx.EVT_KILL_FOCUS, self._recalc)
[8b21fa7]308
[a00ee4c]309        ix += 1
[8b21fa7]310        label_dmin = wx.StaticText(self, -1, "Min Distance [A]")
[3e41f43]311        sizer_params.Add(label_dmin, (iy, ix), (1, 1),
[8b21fa7]312                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
[a00ee4c]313        ix += 1
[3e41f43]314        sizer_params.Add(self.dmin_ctl, (iy, ix), (1, 1),
[8b21fa7]315                         wx.EXPAND | wx.ADJUST_MINSIZE, 0)
[a00ee4c]316        self.dmin_ctl.SetValue(str(self._default_min))
[164c7d0]317        self.dmin_ctl.Bind(wx.EVT_KILL_FOCUS, self._recalc)
[8b21fa7]318
[a00ee4c]319        ix += 1
320        label_dmax = wx.StaticText(self, -1, "Max Distance [A]")
[3e41f43]321        sizer_params.Add(label_dmax, (iy, ix), (1, 1),
[8b21fa7]322                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 15)
[a00ee4c]323        ix += 1
[8b21fa7]324        sizer_params.Add(self.dmax_ctl, (iy, ix), (1, 1),
325                         wx.EXPAND | wx.ADJUST_MINSIZE, 0)
[a00ee4c]326        self.dmax_ctl.SetValue(str(self._default_max))
[164c7d0]327        self.dmax_ctl.Bind(wx.EVT_KILL_FOCUS, self._recalc)
[a00ee4c]328
329
330        # Ouput selection box
331        selection_msg = wx.StaticText(self, -1, "Select a dependent variable:")
[df9492d]332        self.output_box = wx.ComboBox(self, -1, style=wx.CB_READONLY)
[a00ee4c]333        for item in self.results.outputs.keys():
334            self.output_box.Append(item, "")
335        self.output_box.SetStringSelection(DEFAULT_OUTPUT)
[8b21fa7]336
[3e41f43]337        output_sizer = wx.GridBagSizer(5, 5)
338        output_sizer.Add(selection_msg, (0, 0), (1, 1),
[8b21fa7]339                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 10)
[3e41f43]340        output_sizer.Add(self.output_box, (0, 1), (1, 2),
[8b21fa7]341                         wx.LEFT | wx.EXPAND | wx.ADJUST_MINSIZE, 10)
342
[b3fd1c7]343        wx.EVT_COMBOBOX(self.output_box, -1, self._plot_output)
[a00ee4c]344        sizer_main.Add(output_sizer, 0, wx.EXPAND | wx.ALL, 10)
[8b21fa7]345
[a00ee4c]346        sizer_main.Add(self.plotpanel, 0, wx.EXPAND | wx.ALL, 10)
[3e41f43]347        sizer_main.SetItemMinSize(self.plotpanel, 400, 400)
[8b21fa7]348
349        sizer_main.Add(sizer_params, 0, wx.EXPAND | wx.ALL, 10)
[a00ee4c]350        static_line_3 = wx.StaticLine(self, -1)
351        sizer_main.Add(static_line_3, 0, wx.EXPAND, 0)
[8b21fa7]352
[a00ee4c]353        # Bottom area with the close button
[8b21fa7]354        sizer_button.Add((20, 20), 1, wx.EXPAND | wx.ADJUST_MINSIZE, 0)
[a00ee4c]355        button_OK = wx.Button(self, wx.ID_OK, "Close")
[8b21fa7]356        sizer_button.Add(button_OK, 0, wx.LEFT | wx.RIGHT | wx.ADJUST_MINSIZE, 10)
357
358        sizer_main.Add(sizer_button, 0, wx.EXPAND | wx.BOTTOM | wx.TOP, 10)
[a00ee4c]359        self.SetAutoLayout(True)
360        self.SetSizer(sizer_main)
361        self.Layout()
362        self.Centre()
[8b21fa7]363
[a00ee4c]364        # Bind the Enter key to recalculation
365        self.Bind(wx.EVT_TEXT_ENTER, self._recalc)
366
[e16e5c3]367    def set_plot_unfocus(self):
368        """
369        Not implemented
370        """
371        pass
[8b21fa7]372
[a00ee4c]373    def _recalc(self, event=None):
374        """
[7116b6e0]375        Invoked when the user changed a value on the form.
376        Process the form and compute the output to be plottted.
[a00ee4c]377        """
378        # Get the content of the form
379        content = self._get_values()
380        # If the content of the form is invalid, return and do nothing
381        if content is None:
382            return
[8b21fa7]383
[a00ee4c]384        # Results object to store the computation outputs.
385        results = Results()
[8b21fa7]386
[a00ee4c]387        # Loop over d_max values
[8b21fa7]388        for i in range(content.npts):
389            temp = (content.dmax - content.dmin) / (content.npts - 1.0)
[3e41f43]390            d = content.dmin + i * temp
[8b21fa7]391
[a00ee4c]392            self.pr_state.d_max = d
393            try:
[8b21fa7]394                out, cov = self.pr_state.invert(self.nfunc)
395
[3b865c1]396                # Store results
[a00ee4c]397                iq0 = self.pr_state.iq0(out)
398                rg = self.pr_state.rg(out)
399                pos = self.pr_state.get_positive(out)
400                pos_err = self.pr_state.get_pos_err(out, cov)
401                osc = self.pr_state.oscillations(out)
[8b21fa7]402
[a00ee4c]403                results.d_max.append(self.pr_state.d_max)
404                results.bck.append(self.pr_state.background)
405                results.chi2.append(self.pr_state.chi2)
406                results.iq0.append(iq0)
407                results.rg.append(rg)
408                results.pos.append(pos)
409                results.pos_err.append(pos_err)
[8b21fa7]410                results.osc.append(osc)
[a00ee4c]411            except:
412                # This inversion failed, skip this D_max value
[3e41f43]413                msg = "ExploreDialog: inversion failed "
414                msg += "for D_max=%s\n%s" % (str(d), sys.exc_value)
415                logging.error(msg)
[8b21fa7]416
417        self.results = results
418
[a00ee4c]419        # Plot the selected output
[8b21fa7]420        self._plot_output()
Note: See TracBrowser for help on using the repository browser.