source: sasview/guiframe/local_perspectives/plotting/Plotter2D.py @ d955bf19

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 d955bf19 was d955bf19, checked in by Gervaise Alina <gervyh@…>, 14 years ago

working on documentation

  • Property mode set to 100644
File size: 21.0 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 2008, University of Tennessee
10################################################################################
11
12
13import wx
14import sys, math
15import pylab
16
17import danse.common.plottools
18from danse.common.plottools.PlotPanel import PlotPanel
19from danse.common.plottools.plottables import Graph
20from sans.guicomm.events import EVT_NEW_PLOT
21from sans.guicomm.events import EVT_SLICER_PARS
22from sans.guicomm.events import StatusEvent ,NewPlotEvent,SlicerEvent
23from sans.guiframe.utils import PanelMenu
24from binder import BindArtist
25from Plotter1D import ModelPanel1D
26 
27from sans.guiframe.dataFitting import Data1D
28(InternalEvent, EVT_INTERNAL)   = wx.lib.newevent.NewEvent()
29
30
31
32DEFAULT_QMAX = 0.05
33DEFAULT_QSTEP = 0.001
34DEFAULT_BEAM = 0.005
35BIN_WIDTH = 1.0
36from danse.common.plottools.toolbar import NavigationToolBar
37
38class NavigationToolBar2D(NavigationToolBar):
39    """
40    """
41    def __init__(self, canvas, parent=None):
42        NavigationToolBar.__init__(self, canvas=canvas, parent=parent)
43       
44    def delete_option(self):
45        """
46        remove default toolbar item
47        """
48        #delete reset button
49        self.DeleteToolByPos(0) 
50        #delete dragging
51        self.DeleteToolByPos(2) 
52        #delete unwanted button that configures subplot parameters
53        self.DeleteToolByPos(4)
54       
55    def add_option(self):
56        """
57        add item to the toolbar
58        """
59        #add print button
60        id_print = wx.NewId()
61        print_bmp =  wx.ArtProvider.GetBitmap(wx.ART_PRINT, wx.ART_TOOLBAR)
62        self.AddSimpleTool(id_print, print_bmp,
63                           'Print', 'Activate printing')
64        wx.EVT_TOOL(self, id_print, self.on_print)
65       
66       
67class ModelPanel2D(ModelPanel1D):
68    """
69    Plot panel for use with the GUI manager
70    """
71   
72    ## Internal name for the AUI manager
73    window_name = "plotpanel"
74    ## Title to appear on top of the window
75    window_caption = "Plot Panel"
76    ## Flag to tell the GUI manager that this panel is not
77    #  tied to any perspective
78    ALWAYS_ON = True
79    ## Group ID
80    group_id = None
81   
82   
83    def __init__(self, parent, id = -1,data2d=None, color = None,\
84        dpi = None, style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
85        """
86        Initialize the panel
87        """
88        ModelPanel1D.__init__(self, parent, id = id, style = style, **kwargs)
89       
90        ## Reference to the parent window
91        self.parent = parent
92        ## Dictionary containing Plottables
93        self.plots = {}
94        ## Save reference of the current plotted
95        self.data2D = data2d
96        ## Unique ID (from gui_manager)
97        self.uid = None
98        ## Action IDs for internal call-backs
99        self.action_ids = {}
100        ## Create Artist and bind it
101        self.connect = BindArtist(self.subplot.figure)
102        ## Beam stop
103        self.beamstop_radius = DEFAULT_BEAM
104        ## to set the order of lines drawn first.
105        self.slicer_z = 5
106        ## Reference to the current slicer
107        self.slicer = None
108        ## event to send slicer info
109        self.Bind(EVT_INTERNAL, self._onEVT_INTERNAL)
110       
111        self.axes_frozen = False
112        ## panel that contains result from slicer motion (ex: Boxsum info)
113        self.panel_slicer=None
114       
115        ## Graph       
116        self.graph = Graph()
117        self.graph.xaxis("\\rm{Q}", 'A^{-1}')
118        self.graph.yaxis("\\rm{Intensity} ","cm^{-1}")
119        self.graph.render(self)
120        ## store default value of zmin and zmax
121        self.default_zmin_ctl = self.zmin_2D
122        self.default_zmax_ctl = self.zmax_2D
123       
124    def add_toolbar(self):
125        """
126        add toolbar
127        """
128        self.enable_toolbar = True
129       
130        self.toolbar = NavigationToolBar2D(parent=self,canvas=self.canvas)
131        self.toolbar.Realize()
132     
133        # On Windows platform, default window size is incorrect, so set
134        # toolbar width to figure width.
135        tw, th = self.toolbar.GetSizeTuple()
136        fw, fh = self.canvas.GetSizeTuple()
137     
138        self.toolbar.SetSize(wx.Size(fw, th))
139        self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
140       
141        # update the axes menu on the toolbar
142        self.toolbar.update()
143         
144    def _onEVT_1DREPLOT(self, event):
145        """
146        Data is ready to be displayed
147       
148        :TODO: this name should be changed to something more appropriate
149             Don't forget that changing this name will mean changing code
150             in plotting.py
151         
152        :param event: data event
153        """
154        ## Update self.data2d with the current plot
155        self.data2D = event.plot
156       
157        #TODO: Check for existence of plot attribute
158       
159        # Check whether this is a replot. If we ask for a replot
160        # and the plottable no longer exists, ignore the event.
161        if hasattr(event, "update") and event.update==True \
162            and event.plot.name not in self.plots.keys():
163            return
164       
165        if hasattr(event, "reset"):
166            self._reset()
167        is_new = True
168        if event.plot.name in self.plots.keys():
169            # Check whether the class of plottable changed
170            if not event.plot.__class__==self.plots[event.plot.name].__class__:
171                #overwrite a plottable using the same name
172                self.graph.delete(self.plots[event.plot.name])
173            else:
174                # plottable is already draw on the panel
175                is_new = False
176           
177        if is_new:
178            # a new plottable overwrites a plotted one  using the same id
179            for plottable in self.plots.itervalues():
180                if hasattr(event.plot,"id"):
181                    if event.plot.id==plottable.id :
182                        self.graph.delete(plottable)
183           
184            self.plots[event.plot.name] = event.plot
185            self.graph.add(self.plots[event.plot.name])
186        else:
187            # Update the plottable with the new data
188           
189            #TODO: we should have a method to do this,
190            #      something along the lines of:
191            #      plottable1.update_data_from_plottable(plottable2)
192           
193            self.plots[event.plot.name].xmin = event.plot.xmin
194            self.plots[event.plot.name].xmax = event.plot.xmax
195            self.plots[event.plot.name].ymin = event.plot.ymin
196            self.plots[event.plot.name].ymax = event.plot.ymax
197            self.plots[event.plot.name].data = event.plot.data
198            self.plots[event.plot.name].qx_data = event.plot.qx_data
199            self.plots[event.plot.name].qy_data = event.plot.qy_data
200            self.plots[event.plot.name].err_data = event.plot.err_data
201            # update qmax with the new xmax of data plotted
202            self.qmax= event.plot.xmax
203           
204        self.slicer= None
205        # Check axis labels
206        #TODO: Should re-factor this
207        ## render the graph with its new content
208               
209        #data2D: put 'Pixel (Number)' for axis title and unit in case of having no detector info and none in _units
210        if len(self.data2D.detector) < 1: 
211            if len(event.plot._xunit)< 1 and len(event.plot._yunit) < 1:
212                event.plot._xaxis = '\\rm{x}'
213                event.plot._yaxis = '\\rm{y}'
214                event.plot._xunit = 'pixel'
215                event.plot._yunit = 'pixel'
216
217        self.graph.xaxis(event.plot._xaxis, event.plot._xunit)
218        self.graph.yaxis(event.plot._yaxis, event.plot._yunit)
219        self.graph.title(self.data2D.name)
220        self.graph.render(self)
221        self.subplot.figure.canvas.draw_idle()
222        ## store default value of zmin and zmax
223        self.default_zmin_ctl = self.zmin_2D
224        self.default_zmax_ctl = self.zmax_2D
225
226
227    def onContextMenu(self, event):
228        """
229        2D plot context menu
230       
231        :param event: wx context event
232       
233        """
234        slicerpop = PanelMenu()
235        slicerpop.set_plots(self.plots)
236        slicerpop.set_graph(self.graph)
237             
238        id = wx.NewId()
239        slicerpop.Append(id, '&Save image')
240        wx.EVT_MENU(self, id, self.onSaveImage)
241       
242        id = wx.NewId()
243        slicerpop.Append(id,'&Print image', 'Print image ')
244        wx.EVT_MENU(self, id, self.onPrint)
245       
246        id = wx.NewId()
247        slicerpop.Append(id,'&Print Preview', 'image preview for print')
248        wx.EVT_MENU(self, id, self.onPrinterPreview)
249       
250        slicerpop.AppendSeparator()
251        if len(self.data2D.detector) == 1:       
252           
253            item_list = self.parent.get_context_menu(self.graph)
254            if (not item_list==None) and (not len(item_list)==0):
255                   
256                    for item in item_list:
257                        try:
258                            id = wx.NewId()
259                            slicerpop.Append(id, item[0], item[1])
260                            wx.EVT_MENU(self, id, item[2])
261                        except:
262                            wx.PostEvent(self.parent, StatusEvent(status=\
263                            "ModelPanel1D.onContextMenu: bad menu item  %s"%sys.exc_value))
264                            pass
265                    slicerpop.AppendSeparator()
266           
267            id = wx.NewId()
268            slicerpop.Append(id, '&Perform circular average')
269            wx.EVT_MENU(self, id, self.onCircular) 
270           
271            id = wx.NewId()
272            slicerpop.Append(id, '&Sector [Q view]')
273            wx.EVT_MENU(self, id, self.onSectorQ) 
274           
275            id = wx.NewId()
276            slicerpop.Append(id, '&Annulus [Phi view ]')
277            wx.EVT_MENU(self, id, self.onSectorPhi) 
278           
279            id = wx.NewId()
280            slicerpop.Append(id, '&Box Sum')
281            wx.EVT_MENU(self, id, self.onBoxSum) 
282           
283            id = wx.NewId()
284            slicerpop.Append(id, '&Box averaging in Qx')
285            wx.EVT_MENU(self, id, self.onBoxavgX) 
286           
287            id = wx.NewId()
288            slicerpop.Append(id, '&Box averaging in Qy')
289            wx.EVT_MENU(self, id, self.onBoxavgY) 
290           
291            if self.slicer !=None :
292                id = wx.NewId()
293                slicerpop.Append(id, '&Clear slicer')
294                wx.EVT_MENU(self, id,  self.onClearSlicer) 
295               
296                if self.slicer.__class__.__name__ !="BoxSum":
297                    id = wx.NewId()
298                    slicerpop.Append(id, '&Edit Slicer Parameters')
299                    wx.EVT_MENU(self, id, self._onEditSlicer) 
300                   
301            slicerpop.AppendSeparator() 
302           
303        id = wx.NewId()
304        slicerpop.Append(id, '&Detector Parameters')
305        wx.EVT_MENU(self, id, self._onEditDetector) 
306       
307       
308        id = wx.NewId()
309        slicerpop.Append(id, '&Toggle Linear/Log scale')
310        wx.EVT_MENU(self, id, self._onToggleScale) 
311                 
312        pos = event.GetPosition()
313        pos = self.ScreenToClient(pos)
314        self.PopupMenu(slicerpop, pos)
315   
316   
317    def _onEditDetector(self, event):
318        """
319        Allow to view and edits  detector parameters
320       
321        :param event: wx.menu event
322       
323        """
324       
325        import detector_dialog
326       
327        dialog = detector_dialog.DetectorDialog(self, -1,base=self.parent,
328                       reset_zmin_ctl =self.default_zmin_ctl,
329                       reset_zmax_ctl = self.default_zmax_ctl,cmap=self.cmap)
330        ## info of current detector and data2D
331        xnpts = len(self.data2D.x_bins)
332        ynpts = len(self.data2D.y_bins)
333        xmax = max(self.data2D.xmin, self.data2D.xmax)
334        ymax = max(self.data2D.ymin, self.data2D.ymax)
335        qmax = math.sqrt(math.pow(xmax,2)+math.pow(ymax,2))
336        beam = self.data2D.xmin
337     
338        ## set dialog window content
339        dialog.setContent(xnpts=xnpts,ynpts=ynpts,qmax=qmax,
340                           beam=self.data2D.xmin,
341                           zmin = self.zmin_2D,
342                          zmax = self.zmax_2D)
343        if dialog.ShowModal() == wx.ID_OK:
344            evt = dialog.getContent()
345            self.zmin_2D = evt.zmin
346            self.zmax_2D = evt.zmax
347            self.cmap= evt.cmap
348       
349        dialog.Destroy()
350        ## Redraw the current image
351        self.image(data= self.data2D.data,
352                   qx_data=self.data2D.qx_data,
353                   qy_data=self.data2D.qy_data,
354                   xmin= self.data2D.xmin,
355                   xmax= self.data2D.xmax,
356                   ymin= self.data2D.ymin,
357                   ymax= self.data2D.ymax,
358                   zmin= self.zmin_2D,
359                   zmax= self.zmax_2D,
360                   cmap= self.cmap,
361                   color=0,symbol=0,label=self.data2D.name)#'data2D')
362        self.subplot.figure.canvas.draw_idle()
363       
364       
365 
366    def freeze_axes(self):
367        """
368        """
369        self.axes_frozen = True
370       
371    def thaw_axes(self):
372        """
373        """
374        self.axes_frozen = False
375       
376    def onMouseMotion(self,event):
377        """
378        """
379        pass
380   
381    def onWheel(self, event):
382        """
383        """
384        pass 
385     
386    def update(self, draw=True):
387        """
388        Respond to changes in the model by recalculating the
389        profiles and resetting the widgets.
390        """
391        self.draw()
392       
393    def _getEmptySlicerEvent(self):
394        """
395        create an empty slicervent
396        """
397        return SlicerEvent(type=None,
398                           params=None,
399                           obj_class=None)
400       
401    def _onEVT_INTERNAL(self, event):
402        """
403        Draw the slicer
404       
405        :param event: wx.lib.newevent (SlicerEvent) containing slicer
406            parameter
407           
408        """
409        self._setSlicer(event.slicer)
410           
411    def _setSlicer(self, slicer):
412        """
413        Clear the previous slicer and create a new one.Post an internal
414        event.
415       
416        :param slicer: slicer class to create
417       
418        """
419       
420        ## Clear current slicer
421        if not self.slicer == None: 
422            self.slicer.clear()           
423        ## Create a new slicer   
424        self.slicer_z += 1
425        self.slicer = slicer(self, self.subplot, zorder=self.slicer_z)
426        self.subplot.set_ylim(self.data2D.ymin, self.data2D.ymax)
427        self.subplot.set_xlim(self.data2D.xmin, self.data2D.xmax)
428        ## Draw slicer
429        self.update()
430        self.slicer.update()
431        wx.PostEvent(self.parent, StatusEvent(status=\
432                        "Plotter2D._setSlicer  %s"%self.slicer.__class__.__name__))
433        # Post slicer event
434        event = self._getEmptySlicerEvent()
435        event.type = self.slicer.__class__.__name__
436       
437        event.obj_class = self.slicer.__class__
438        event.params = self.slicer.get_params()
439        wx.PostEvent(self, event)
440
441
442    def onCircular(self, event):
443        """
444        perform circular averaging on Data2D
445       
446        :param event: wx.menu event
447       
448        """
449       
450        from DataLoader.manipulations import CircularAverage
451        ## compute the maximum radius of data2D
452        self.qmax= max(math.fabs(self.data2D.xmax),math.fabs(self.data2D.xmin))
453        self.ymax=max(math.fabs(self.data2D.ymax),math.fabs(self.data2D.ymin))
454        self.radius= math.sqrt( math.pow(self.qmax,2)+math.pow(self.ymax,2)) 
455        ##Compute beam width
456        bin_width = (self.qmax +self.qmax)/100
457        ## Create data1D circular average of data2D
458        Circle = CircularAverage( r_min=0, r_max=self.radius, bin_width=bin_width)
459        circ = Circle(self.data2D)
460       
461        from sans.guiframe.dataFitting import Data1D
462        if hasattr(circ,"dxl"):
463            dxl= circ.dxl
464        else:
465            dxl= None
466        if hasattr(circ,"dxw"):
467            dxw= circ.dxw
468        else:
469            dxw= None
470       
471        new_plot = Data1D(x=circ.x,y=circ.y,dy=circ.dy)
472        new_plot.dxl=dxl
473        new_plot.dxw=dxw
474        new_plot.name = "Circ avg "+ self.data2D.name
475        new_plot.source=self.data2D.source
476        #new_plot.info=self.data2D.info
477        new_plot.interactive = True
478        new_plot.detector =self.data2D.detector
479        ## If the data file does not tell us what the axes are, just assume...
480        new_plot.xaxis("\\rm{Q}","A^{-1}")
481        new_plot.yaxis("\\rm{Intensity} ","cm^{-1}")
482        new_plot.group_id = "Circ avg "+ self.data2D.name
483        new_plot.id = "Circ avg "+ self.data2D.name
484        new_plot.is_data= True
485        wx.PostEvent(self.parent, NewPlotEvent(plot=new_plot, title=new_plot.name))
486       
487    def _onEditSlicer(self, event):
488        """
489        Is available only when a slicer is drawn.Create a dialog
490        window where the user can enter value to reset slicer
491        parameters.
492       
493        :param event: wx.menu event
494       
495        """
496        if self.slicer !=None:
497            from SlicerParameters import SlicerParameterPanel
498            dialog = SlicerParameterPanel(self, -1, "Slicer Parameters")
499            dialog.set_slicer(self.slicer.__class__.__name__,
500                            self.slicer.get_params())
501            if dialog.ShowModal() == wx.ID_OK:
502                dialog.Destroy() 
503       
504    def onSectorQ(self, event):
505        """
506        Perform sector averaging on Q and draw sector slicer
507        """
508        from SectorSlicer import SectorInteractor
509        self.onClearSlicer(event)
510        wx.PostEvent(self, InternalEvent(slicer= SectorInteractor))
511       
512    def onSectorPhi(self, event):
513        """
514        Perform sector averaging on Phi and draw annulus slicer
515        """
516        from AnnulusSlicer import AnnulusInteractor
517        self.onClearSlicer(event)
518        wx.PostEvent(self, InternalEvent(slicer= AnnulusInteractor))
519       
520    def onBoxSum(self, event):
521        """
522        """
523        from boxSum import BoxSum
524        self.onClearSlicer(event)
525                   
526        self.slicer_z += 1
527        self.slicer =  BoxSum(self, self.subplot, zorder=self.slicer_z)
528       
529        self.subplot.set_ylim(self.data2D.ymin, self.data2D.ymax)
530        self.subplot.set_xlim(self.data2D.xmin, self.data2D.xmax)
531       
532        self.update()
533        self.slicer.update()
534        ## Value used to initially set the slicer panel
535        type = self.slicer.__class__.__name__
536        params = self.slicer.get_params()
537        ## Create a new panel to display results of summation of Data2D
538        from slicerpanel import SlicerPanel
539        new_panel = SlicerPanel(parent= self.parent, id= -1,
540                                    base= self, type= type,
541                                    params= params, style= wx.RAISED_BORDER)
542       
543        new_panel.window_caption=self.slicer.__class__.__name__+" "+ str(self.data2D.name)
544        new_panel.window_name = self.slicer.__class__.__name__+" "+ str(self.data2D.name)
545        ## Store a reference of the new created panel
546        self.panel_slicer= new_panel
547        ## save the window_caption of the new panel in the current slicer
548        self.slicer.set_panel_name( name= new_panel.window_caption)
549        ## post slicer panel to guiframe to display it
550        from sans.guicomm.events import SlicerPanelEvent
551        wx.PostEvent(self.parent, SlicerPanelEvent (panel= self.panel_slicer,
552                                                    main_panel =self))
553
554    def onBoxavgX(self,event):
555        """
556        Perform 2D data averaging on Qx
557        Create a new slicer .
558       
559        :param event: wx.menu event
560        """
561        from boxSlicer import BoxInteractorX
562        self.onClearSlicer(event)
563        wx.PostEvent(self, InternalEvent(slicer= BoxInteractorX))
564       
565    def onBoxavgY(self,event):
566        """
567        Perform 2D data averaging on Qy
568        Create a new slicer .
569       
570        :param event: wx.menu event
571       
572        """
573        from boxSlicer import BoxInteractorY
574        self.onClearSlicer(event)
575        wx.PostEvent(self, InternalEvent(slicer= BoxInteractorY))
576       
577    def onClearSlicer(self, event):
578        """
579        Clear the slicer on the plot
580        """
581        if not self.slicer==None:
582            self.slicer.clear()
583            self.subplot.figure.canvas.draw()
584            self.slicer = None
585       
586            # Post slicer None event
587            event = self._getEmptySlicerEvent()
588            wx.PostEvent(self, event)
589   
Note: See TracBrowser for help on using the repository browser.