source: sasview/guiframe/local_perspectives/plotting/Plotter1D.py @ b5ca223

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

working on pylint

  • Property mode set to 100644
File size: 20.0 KB
RevLine 
[1bf33c1]1
[d955bf19]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################################################################################
[1bf33c1]11
12
13import wx
[4ac8556]14import sys
15import os
16import pylab
17import math
18import numpy
19import time
[1bf33c1]20import danse.common.plottools
21from danse.common.plottools.PlotPanel import PlotPanel
[e5664f2]22from danse.common.plottools.plottables import Graph
[3b69ca6]23from sans.guiframe import dataFitting
[1bf33c1]24from sans.guicomm.events import EVT_NEW_PLOT
[32c0841]25from sans.guicomm.events import StatusEvent
26from sans.guicomm.events import NewPlotEvent
27from sans.guicomm.events import SlicerEvent
28from sans.guicomm.events import ErrorDataEvent
29from sans.guicomm.events import RemoveDataEvent
30from sans.guicomm.events import AddManyDataEvent
[0d9dae8]31from sans.guiframe.utils import PanelMenu
[4ac8556]32from sans.guiframe.dataFitting import Data1D
[e5664f2]33from sans.guiframe.dataFitting import Theory1D
[1bf33c1]34from binder import BindArtist
35
[0d9dae8]36DEFAULT_QMAX = 0.05
[1bf33c1]37DEFAULT_QSTEP = 0.001
38DEFAULT_BEAM = 0.005
[32c0841]39BIN_WIDTH = 1
[1bf33c1]40
[0d9dae8]41
[1bf33c1]42class ModelPanel1D(PlotPanel):
43    """
[d955bf19]44    Plot panel for use with the GUI manager
[1bf33c1]45    """
46   
47    ## Internal name for the AUI manager
48    window_name = "plotpanel"
49    ## Title to appear on top of the window
50    window_caption = "Plot Panel"
51    ## Flag to tell the GUI manager that this panel is not
52    #  tied to any perspective
53    ALWAYS_ON = True
54    ## Group ID
55    group_id = None
56   
[32c0841]57    def __init__(self, parent, id=-1, color = None,
58                 dpi=None, style=wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs):
[1bf33c1]59        """
[d955bf19]60        Initialize the panel
[1bf33c1]61        """
[32c0841]62        PlotPanel.__init__(self, parent, id=id, style=style, **kwargs)
[1bf33c1]63        ## Reference to the parent window
64        self.parent = parent
65        ## Plottables
66        self.plots = {}
[869c368]67        ## save errors dy  for each data plotted
[32c0841]68        self.err_dy = {}
[6c0568b]69        ## flag to determine if the hide or show context menu item should
70        ## be displayed
[32c0841]71        self.errors_hide = False
[1bf33c1]72        ## Unique ID (from gui_manager)
73        self.uid = None
74        ## Action IDs for internal call-backs
75        self.action_ids = {}
[6063b16]76        ## Default locations
77        self._default_save_location = os.getcwd()       
[1bf33c1]78        ## Graph       
79        self.graph = Graph()
80        self.graph.xaxis("\\rm{Q}", 'A^{-1}')
[32c0841]81        self.graph.yaxis("\\rm{Intensity} ", "cm^{-1}")
[1bf33c1]82        self.graph.render(self)
[4ed210f4]83   
[32c0841]84    def set_data(self, list=None):
[3c44c66]85        """
86        """
87        pass
88   
[1bf33c1]89    def _reset(self):
90        """
[d955bf19]91        Resets internal data and graph
[1bf33c1]92        """   
93        self.graph.reset()
94        self.plots      = {}
95        self.action_ids = {}
96   
97    def _onEVT_1DREPLOT(self, event):
98        """
[d955bf19]99        Data is ready to be displayed
100       
101        :param event: data event
[1bf33c1]102        """
103        #TODO: Check for existence of plot attribute
104        # Check whether this is a replot. If we ask for a replot
105        # and the plottable no longer exists, ignore the event.
[32c0841]106        if hasattr(event, "update") and event.update == True \
[1bf33c1]107            and event.plot.name not in self.plots.keys():
108            return
109        if hasattr(event, "reset"):
110            self._reset()
[f5fda87]111        # Check whether the plottable is empty
[32c0841]112        is_empty = len(event.plot.x) == 0
[f5fda87]113               
[1bf33c1]114        is_new = True
115        if event.plot.name in self.plots.keys():
[f5fda87]116            # If the plottable is empty, just remove the plottable from the graph
117            if is_empty:
118                self.graph.delete(self.plots[event.plot.name])
[21d99c2]119                del self.plots[event.plot.name]
120            else: 
121                # Check whether the class of plottable changed
[32c0841]122                if not event.plot.__class__ == self.plots[event.plot.name].__class__:
[21d99c2]123                    #overwrite a plottable using the same name
124                    self.graph.delete(self.plots[event.plot.name])             
125                else:
126                    # plottable is already draw on the panel
127                    is_new = False
[ffd23b5]128       
[f5fda87]129        if not is_empty:
130            if is_new:
131                # a new plottable overwrites a plotted one  using the same id
132                for plottable in self.plots.itervalues():
[32c0841]133                    if hasattr(event.plot, "id") and hasattr(plottable, "id"):
[0b57a57]134                        #remove the existing plot and same id and same name
[32c0841]135                        if event.plot.id == plottable.id and \
136                            event.plot.name == plottable.name:
[f5fda87]137                            self.graph.delete(plottable)
138               
139                self.plots[event.plot.name] = event.plot
140                self.graph.add(self.plots[event.plot.name])
141            else:
142                #replot the graph
143                self.plots[event.plot.name].x = event.plot.x   
144                self.plots[event.plot.name].y = event.plot.y   
145                self.plots[event.plot.name].dy = event.plot.dy 
[32c0841]146                if hasattr(event.plot, 'dx') and \
147                    hasattr(self.plots[event.plot.name], 'dx'):
[f5fda87]148                    self.plots[event.plot.name].dx = event.plot.dx   
[31482fc]149         
[1bf33c1]150        #TODO: Should re-factor this
[6c0568b]151        ## for all added plot the option to hide error show be displayed first
[31482fc]152        #self.errors_hide = 0
[6c0568b]153        ## Set axis labels
[1bf33c1]154        self.graph.xaxis(event.plot._xaxis, event.plot._xunit)
155        self.graph.yaxis(event.plot._yaxis, event.plot._yunit)
[6c0568b]156        ## Set the view scale for all plots
[1bf33c1]157        self._onEVT_FUNC_PROPERTY()
[6c0568b]158        ## render the graph
[1bf33c1]159        self.graph.render(self)
160        self.subplot.figure.canvas.draw_idle()
[0b57a57]161        #if self.errors_hide:
162        #    self._on_remove_errors(evt=None)
163        #else:
164        #    self._on_add_errors( evt=None)
[31482fc]165   
[1bf33c1]166    def onLeftDown(self,event): 
[6c0568b]167        """
[d955bf19]168        left button down and ready to drag
169        Display the position of the mouse on the statusbar
[6c0568b]170        """
[1bf33c1]171        PlotPanel.onLeftDown(self, event)
172        ax = event.inaxes
173        if ax != None:
174            position = "x: %8.3g    y: %8.3g" % (event.xdata, event.ydata)
175            wx.PostEvent(self.parent, StatusEvent(status=position))
[4ed210f4]176           
177        #post nd event to notify guiframe that this panel is on focus
178        wx.PostEvent(self.parent, AddManyDataEvent(panel=self))
179       
[1bf33c1]180    def _onRemove(self, event):
181        """
[d955bf19]182        Remove a plottable from the graph and render the graph
183       
184        :param event: Menu event
185       
[1bf33c1]186        """
[32c0841]187        selected_plot = self.plots[self.graph.selected_plottable]
[6c0568b]188        ## Check if there is a selected graph to remove
[1debb29]189        if not self.graph.selected_plottable == None and\
190            self.graph.selected_plottable in self.plots.keys():
[32c0841]191            color = self.graph.plottables[selected_plot]
192            event = RemoveDataEvent(data=selected_plot)
[1debb29]193            wx.PostEvent(self.parent, event)
[32c0841]194            self.graph.delete(selected_plot)
195            del selected_plot
[1debb29]196            ## increment graph color
197            self.graph.color += color
[1bf33c1]198            self.graph.render(self)
199            self.subplot.figure.canvas.draw_idle()   
[1debb29]200           
[1bf33c1]201    def onContextMenu(self, event):
202        """
[d955bf19]203        1D plot context menu
204       
205        :param event: wx context event
206       
[1bf33c1]207        """
208        slicerpop = PanelMenu()
209        slicerpop.set_plots(self.plots)
[32c0841]210        slicerpop.set_graph(self.graph)     
[9a585d0]211        # Various plot options
212        id = wx.NewId()
[32c0841]213        slicerpop.Append(id, '&Save image', 'Save image as PNG')
[9a585d0]214        wx.EVT_MENU(self, id, self.onSaveImage)
215        id = wx.NewId()
[32c0841]216        slicerpop.Append(id, '&Print image', 'Print image ')
[18eba35]217        wx.EVT_MENU(self, id, self.onPrint)
218        id = wx.NewId()
[32c0841]219        slicerpop.Append(id, '&Print Preview', 'image preview for print')
[18eba35]220        wx.EVT_MENU(self, id, self.onPrinterPreview)
[9a585d0]221        slicerpop.AppendSeparator()
222        item_list = self.parent.get_context_menu(self.graph)
[32c0841]223        if (not item_list == None) and (not len(item_list) == 0):
[9a585d0]224            for item in item_list:
225                try:
226                    id = wx.NewId()
227                    slicerpop.Append(id, item[0], item[1])
228                    wx.EVT_MENU(self, id, item[2])
229                except:
[32c0841]230                    msg = "ModelPanel1D.onContextMenu: "
231                    msg += "bad menu item  %s"%sys.exc_value
232                    wx.PostEvent(self.parent, StatusEvent(status=msg))
[9a585d0]233                    pass
234            slicerpop.AppendSeparator()
[6c0568b]235       
[1bf33c1]236        if self.graph.selected_plottable in self.plots:
237            plot = self.plots[self.graph.selected_plottable]
238            id = wx.NewId()
239            name = plot.name
[42d27f2]240            slicerpop.Append(id, "&Save points" )
[1bf33c1]241            self.action_ids[str(id)] = plot
242            wx.EVT_MENU(self, id, self._onSave)
243            id = wx.NewId()
244            slicerpop.Append(id, "Remove %s curve" % name)
245            self.action_ids[str(id)] = plot
246            wx.EVT_MENU(self, id, self._onRemove)
[9a585d0]247            slicerpop.AppendSeparator()
[1bf33c1]248            # Option to hide
249            #TODO: implement functionality to hide a plottable (legend click)
250        if self.graph.selected_plottable in self.plots:
[32c0841]251            selected_plot = self.plots[self.graph.selected_plottable]
[3cc533e]252            id = wx.NewId()
253            slicerpop.Append(id, '&Linear fit')
254            wx.EVT_MENU(self, id, self.onFitting)
[9a585d0]255            slicerpop.AppendSeparator()
[1bf33c1]256        id = wx.NewId()
257        slicerpop.Append(id, '&Change scale')
258        wx.EVT_MENU(self, id, self._onProperties)
259        id = wx.NewId()
260        slicerpop.Append(id, '&Reset Graph')
[d468daa]261        wx.EVT_MENU(self, id, self.onResetGraph) 
[1bf33c1]262        pos = event.GetPosition()
263        pos = self.ScreenToClient(pos)
264        self.PopupMenu(slicerpop, pos)
[18eba35]265       
[869c368]266    def _on_remove_errors(self, evt):
[6c0568b]267        """
[d955bf19]268        Save name and dy of data in dictionary self.err_dy
269        Create a new data1D with the same x, y
270        vector and dy with zeros.
271        post self.err_dy as event (ErrorDataEvent) for any object
272        which wants to reconstruct the initial data.
273       
274        :param evt: Menu event
275       
[6c0568b]276        """
[869c368]277        if not self.graph.selected_plottable == None:
[6c0568b]278            ## store existing dy
[869c368]279            name =self.plots[self.graph.selected_plottable].name
280            dy = self.plots[self.graph.selected_plottable].dy
[32c0841]281            self.err_dy[name] = dy
[6c0568b]282            ## Create a new dy for a new plottable
[32c0841]283            #import numpy
[d955bf19]284            dy = numpy.zeros(len(self.plots[self.graph.selected_plottable].y))
285            selected_plot = self.plots[self.graph.selected_plottable]
[c81140c]286           
[32c0841]287            if selected_plot.__class__.__name__ == "Data1D":
[8068b52]288                # Make sure that we can pass a basic Data1D
289                dxl = None
290                dxw = None
291                if hasattr(selected_plot, "dxl"):
292                    dxl = selected_plot.dxl
293                if hasattr(selected_plot, "dxw"):
294                    dxw = selected_plot.dxw
[32c0841]295                new_plot = Data1D(x=selected_plot.x, y=selected_plot.y,
296                               dx=selected_plot.dx, dy=dy)
297                new_plot.dxl = dxl
298                new_plot.dxw = dxw           
[0b16ee3]299            else:
[32c0841]300                 new_plot = Theory1D(x=selected_plot.x, 
301                                     y=selected_plot.y, dy=dy)
[869c368]302            new_plot.interactive = True
[31482fc]303            self.errors_hide = True
[869c368]304            new_plot.name = self.plots[self.graph.selected_plottable].name
305            if hasattr(self.plots[self.graph.selected_plottable], "group_id"):
306                new_plot.group_id = self.plots[self.graph.selected_plottable].group_id
[32c0841]307                if hasattr(self.plots[self.graph.selected_plottable], "id"):
[ba535a6]308                    new_plot.id = self.plots[self.graph.selected_plottable].id
309                else:
310                    new_plot.id = str(time.time())
[869c368]311            else:
312                new_plot.group_id = str(time.time())
313                new_plot.id = str(time.time())
314            label, unit = self.plots[self.graph.selected_plottable].get_xaxis()
315            new_plot.xaxis(label, unit)
316            label, unit = self.plots[self.graph.selected_plottable].get_yaxis()
317            new_plot.yaxis(label, unit)
[6c0568b]318            ## save the color of the selected plottable before it is deleted
[32c0841]319            color = self.graph.plottables[self.plots[self.graph.selected_plottable]]
[18eba35]320            self.graph.delete(self.plots[self.graph.selected_plottable])
[6c0568b]321            ## add newly created plottable to the graph with the save color
[0b16ee3]322            self.graph.color += color
[32c0841]323            self.graph.add(new_plot, color)
324            ## transforming the view of the new data into the same of
325            #the previous data
[869c368]326            self._onEVT_FUNC_PROPERTY()
[6c0568b]327            ## save the plot
[32c0841]328            self.plots[self.graph.selected_plottable] = new_plot
[6c0568b]329            ## Render the graph
[869c368]330            self.graph.render(self)
331            self.subplot.figure.canvas.draw_idle() 
[c81140c]332            event = ErrorDataEvent(err_dy=self.err_dy)
333            wx.PostEvent(self.parent, event)
[d955bf19]334
[1bf33c1]335    def _on_add_errors(self, evt):
336        """
[d955bf19]337        create a new data1D witht the errors saved in self.err_dy
338        to show errors of the plot.
339        Compute reasonable errors for a data set without
340        errors and transorm the plottable to a Data1D
341       
342        :param evt: Menu event
[c81140c]343       
[d955bf19]344        """
[1debb29]345        if not self.graph.selected_plottable == None \
346            and self.graph.selected_plottable in self.plots.keys():
[6c0568b]347            ##Reset the flag to display the hide option on the context menu
[31482fc]348            self.errors_hide = False
[6c0568b]349            ## restore dy
[1bf33c1]350            length = len(self.plots[self.graph.selected_plottable].x)
351            dy = numpy.zeros(length)
[32c0841]352            selected_plot = self.plots[self.graph.selected_plottable]
[869c368]353            try:
[c81140c]354                dy = self.err_dy[selected_plot.name]
[869c368]355            except:
[32c0841]356                if hasattr(selected_plot, "dy"):
357                    dy = selected_plot.dy
[0b16ee3]358                else:
359                    dy = numpy.zeros(selected_plot.dy)
[6c0568b]360            ## Create a new plottable data1D
[32c0841]361            if selected_plot.__class__.__name__ == "Data1D":
[8068b52]362                # Make sure that we can pass a basic Data1D
363                dxl = None
364                dxw = None
365                if hasattr(selected_plot, "dxl"):
366                    dxl = selected_plot.dxl
367                if hasattr(selected_plot, "dxw"):
368                    dxw = selected_plot.dxw
[32c0841]369                new_plot = Data1D(x=selected_plot.x,
370                                               y=selected_plot.y,
[3b69ca6]371                                               dx=selected_plot.dx,
[4ac8556]372                                               dy=dy)
373                new_plot.dxl = dxl
[32c0841]374                new_plot.dxw = dxw                       
[0b16ee3]375            else:
376                ## Create a new plottable Theory1D
[32c0841]377                new_plot = Theory1D(x=selected_plot.x, y=selected_plot.y, dy=dy)
[1bf33c1]378            new_plot.interactive = True
379            new_plot.name = self.plots[self.graph.selected_plottable].name
380            if hasattr(self.plots[self.graph.selected_plottable], "group_id"):
381                new_plot.group_id = self.plots[self.graph.selected_plottable].group_id
[ba535a6]382                if hasattr(self.plots[self.graph.selected_plottable],"id"):
383                    new_plot.id = self.plots[self.graph.selected_plottable].id
384                else:
385                    new_plot.id = str(time.time())
[1bf33c1]386            else:
387                new_plot.group_id = str(time.time())
[d1dd9d4]388                new_plot.id = str(time.time())
[1bf33c1]389           
390            label, unit = self.plots[self.graph.selected_plottable].get_xaxis()
391            new_plot.xaxis(label, unit)
392            label, unit = self.plots[self.graph.selected_plottable].get_yaxis()
393            new_plot.yaxis(label, unit)
[6c0568b]394            ## save the color of the selected plottable before it is deleted
[18eba35]395            color=self.graph.plottables[self.plots[self.graph.selected_plottable]]
396            self.graph.delete(self.plots[self.graph.selected_plottable])
[0b16ee3]397            self.graph.color += color
[6c0568b]398            ## add newly created plottable to the graph with the save color
[18eba35]399            self.graph.add(new_plot, color)
[32c0841]400            ## transforming the view of the new data into the same of
401            # the previous data
[ffd23b5]402            self._onEVT_FUNC_PROPERTY()
[6c0568b]403            ## save the plot
[1bf33c1]404            self.plots[self.graph.selected_plottable]=new_plot
[6c0568b]405            ## render the graph with its new content
[1bf33c1]406            self.graph.render(self)
[8bd764d]407            self.subplot.figure.canvas.draw_idle() 
408               
[6c0568b]409               
[42d27f2]410    def _onsaveTXT(self, path):
411        """
[d955bf19]412        Save file as txt
[1abcb04]413           
[d955bf19]414        :TODO: Refactor and remove this method. See TODO in _onSave.
415       
[42d27f2]416        """
417        data = self.plots[self.graph.selected_plottable]
418       
419        if not path == None:
420            out = open(path, 'w')
421            has_errors = True
[32c0841]422            if data.dy == None or data.dy == []:
[42d27f2]423                has_errors = False
424            # Sanity check
425            if has_errors:
426                try:
427                    if len(data.y) != len(data.dy):
428                        has_errors = False
429                except:
430                    has_errors = False
431            if has_errors:
432                out.write("<X>   <Y>   <dY>\n")
433            else:
434                out.write("<X>   <Y>\n")
435               
436            for i in range(len(data.x)):
437                if has_errors:
438                    out.write("%g  %g  %g\n" % (data.x[i], 
439                                                data.y[i],
440                                               data.dy[i]))
441                else:
442                    out.write("%g  %g\n" % (data.x[i], 
443                                            data.y[i]))
444            out.close()                 
[6063b16]445            try:
446                self._default_save_location = os.path.dirname(path)
447            except:
448                pass   
[8bd764d]449               
[1bf33c1]450    def _onSave(self, evt):
451        """
[d955bf19]452        Save a data set to a text file
453       
454        :param evt: Menu event
455       
[1bf33c1]456        """
457        id = str(evt.GetId())
458        if id in self.action_ids:         
459           
460            path = None
[5fe5871c]461            wildcard = "Text files (*.txt)|*.txt|"\
[7959f297]462            "CanSAS 1D files(*.xml)|*.xml" 
[6063b16]463            dlg = wx.FileDialog(self, "Choose a file",
[32c0841]464                                self._default_save_location,
465                                 "", wildcard , wx.SAVE)
[42d27f2]466           
[1bf33c1]467            if dlg.ShowModal() == wx.ID_OK:
468                path = dlg.GetPath()
469                mypath = os.path.basename(path)
[1abcb04]470               
[32c0841]471                #TODO: This is bad design. The DataLoader is designed
472                #to recognize extensions.
473                # It should be a simple matter of calling the .
474                #save(file, data, '.xml') method
[f0a9a3cc]475                # of the DataLoader.loader.Loader class.
476                from DataLoader.loader import  Loader
477                #Instantiate a loader
478                loader = Loader() 
479                data = self.plots[self.graph.selected_plottable]
[32c0841]480                format = ".txt"
[f0a9a3cc]481                if os.path.splitext(mypath)[1].lower() == format:
482                     self._onsaveTXT( path)
[32c0841]483                format = ".xml"
484                if os.path.splitext(mypath)[1].lower() == format:
485                    loader.save(path, data, format)
[f0a9a3cc]486                try:
487                    self._default_save_location = os.path.dirname(path)
488                except:
489                    pass   
[1bf33c1]490            dlg.Destroy()
Note: See TracBrowser for help on using the repository browser.