source: sasview/guitools/PlotPanel.py @ 3dd29e3

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 3dd29e3 was 052a66bc, checked in by Mathieu Doucet <doucetm@…>, 16 years ago

Bug fixing

  • Property mode set to 100644
File size: 25.9 KB
Line 
1import wx.lib.newevent
2import matplotlib
3matplotlib.interactive(False)
4#Use the WxAgg back end. The Wx one takes too long to render
5matplotlib.use('WXAgg')
6from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
7from matplotlib.figure import Figure
8import os
9import fittings
10import transform
11from canvas import FigureCanvas
12from matplotlib.widgets import RectangleSelector
13from pylab import  gca, gcf
14from plottables import Theory1D
15#from plottables import Data1D
16#TODO: make the plottables interactive
17
18DEBUG = False
19
20from plottables import Graph
21#(FuncFitEvent, EVT_FUNC_FIT) = wx.lib.newevent.NewEvent()
22import math,pylab,re
23
24def show_tree(obj,d=0):
25    """Handy function for displaying a tree of graph objects"""
26    print "%s%s" % ("-"*d,obj.__class__.__name__)
27    if 'get_children' in dir(obj):
28        for a in obj.get_children(): show_tree(a,d+1)
29       
30def convertUnit(pow,unit):
31    """
32        Displays the unit with the proper convertion
33        @param pow: the user set the power of the unit
34        @param unit: the unit of the data
35    """ 
36    return unit
37    toks=re.match("^", unit)
38    if not toks==None:
39        unitValue= re.split("{",unit)
40        unitPower= re.split("}",unitValue[1])
41        power= int(unitPower[0])*pow
42        word= unitValue[0]+"{"+str(power)+"}"
43        if power==1:
44            tempUnit=re.split("\^",unitValue[0])
45            unit=tempUnit[0]
46        else:
47            unit = word
48    #print"this is unit",unit
49    return unit
50def _rescale(lo,hi,step,pt=None,bal=None,scale='linear'):
51        """
52        Rescale (lo,hi) by step, returning the new (lo,hi)
53        The scaling is centered on pt, with positive values of step
54        driving lo/hi away from pt and negative values pulling them in.
55        If bal is given instead of point, it is already in [0,1] coordinates.
56   
57        This is a helper function for step-based zooming.
58        """
59        # Convert values into the correct scale for a linear transformation
60        # TODO: use proper scale transformers
61        loprev = lo
62        hiprev = hi
63        ptprev = pt
64        if scale=='log':
65            assert lo >0
66            if lo > 0 :
67                lo = math.log10(lo)
68            if hi > 0 :
69                hi = math.log10(hi)
70            if pt is not None: pt = math.log10(pt)
71       
72        # Compute delta from axis range * %, or 1-% if persent is negative
73        if step > 0:
74            delta = float(hi-lo)*step/100
75        else:
76            delta = float(hi-lo)*step/(100-step)
77   
78        # Add scale factor proportionally to the lo and hi values, preserving the
79        # point under the mouse
80        if bal is None:
81            bal = float(pt-lo)/(hi-lo)
82        lo = lo - bal*delta
83        hi = hi + (1-bal)*delta
84   
85        # Convert transformed values back to the original scale
86        if scale=='log':
87            if (lo <= -250) or (hi >= 250):
88                lo=loprev
89                hi=hiprev
90                print "Not possible to scale"
91           
92            else:
93                lo,hi = math.pow(10.,lo),math.pow(10.,hi)
94                #assert lo >0,"lo = %g"%lo
95                print "possible to scale"
96           
97            print "these are low and high",lo,hi
98
99        return (lo,hi)
100
101
102class PlotPanel(wx.Panel):
103    """
104    The PlotPanel has a Figure and a Canvas. OnSize events simply set a
105    flag, and the actually redrawing of the
106    figure is triggered by an Idle event.
107    """
108    def __init__(self, parent, id = -1, color = None,\
109        dpi = None, **kwargs):
110        wx.Panel.__init__(self, parent, id = id, **kwargs)
111        self.parent = parent
112        self.figure = Figure(None, dpi)
113        #self.figure = pylab.Figure(None, dpi)
114        #self.canvas = NoRepaintCanvas(self, -1, self.figure)
115        self.canvas = FigureCanvas(self, -1, self.figure)
116        self.SetColor(color)
117        #self.Bind(wx.EVT_IDLE, self._onIdle)
118        #self.Bind(wx.EVT_SIZE, self._onSize)
119        self._resizeflag = True
120        self._SetSize()
121        self.subplot = self.figure.add_subplot(111)
122        self.figure.subplots_adjust(left=.2, bottom=.2)
123        self.yscale = 'linear'
124        self.xscale = 'linear'
125        sizer = wx.BoxSizer(wx.VERTICAL)
126        sizer.Add(self.canvas,1,wx.EXPAND)
127        self.SetSizer(sizer)
128       
129        # Graph object to manage the plottables
130        self.graph = Graph()
131        #self.Bind(EVT_FUNC_FIT, self.onFitRange)
132        self.Bind(wx.EVT_CONTEXT_MENU, self.onContextMenu)
133        #self.Bind(EVT_PROPERTY, self._onEVT_FUNC_PROPERTY)
134        # Define some constants
135        self.colorlist = ['b','g','r','c','m','y']
136        self.symbollist = ['o','x','^','v','<','>','+','s','d','D','h','H','p']
137        #User scale
138        self.xLabel ="x"
139        self.yLabel ="y"
140        self.viewModel ="--"
141        # keep track if the previous transformation of x and y in Property dialog
142        self.prevXtrans ="x"
143        self.prevYtrans ="y"
144        self.canvas.mpl_connect('scroll_event',self.onWheel)
145        self.axes = [self.subplot]
146         # new data for the fit
147        self.fit_result = Theory1D(x=[], y=[], dy=None)
148        #self.fit_result = Data1D(x=[], y=[],dx=None, dy=None)
149        self.fit_result.name = "Fit"
150        # For fit Dialog initial display
151        self.xmin=0.0
152        self.xmax=0.0
153        self.xminView=0.0
154        self.xmaxView=0.0
155        self.Avalue=None
156        self.Bvalue=None
157        self.ErrAvalue=None
158        self.ErrBvalue=None
159        self.Chivalue=None
160       
161    def resetFitView(self):
162        """
163             For fit Dialog initial display
164        """
165        self.xmin=0.0
166        self.xmax=0.0
167        self.xminView=0.0
168        self.xmaxView=0.0
169        self.Avalue=None
170        self.Bvalue=None
171        self.ErrAvalue=None
172        self.ErrBvalue=None
173        self.Chivalue=None
174       
175    def onWheel(self, event):
176        """
177            Process mouse wheel as zoom events
178            @param event: Wheel event
179        """
180        ax = event.inaxes
181        step = event.step
182
183        if ax != None:
184            # Event occurred inside a plotting area
185            lo,hi = ax.get_xlim()
186            lo,hi = _rescale(lo,hi,step,pt=event.xdata,scale=ax.get_xscale())
187            if not self.xscale=='log' or lo>0:
188                ax.set_xlim((lo,hi))
189
190            lo,hi = ax.get_ylim()
191            lo,hi = _rescale(lo,hi,step,pt=event.ydata,scale=ax.get_yscale())
192            if not self.yscale=='log' or lo>0:
193                ax.set_ylim((lo,hi))
194        else:
195             # Check if zoom happens in the axes
196            xdata,ydata = None,None
197            x,y = event.x,event.y
198           
199            for ax in self.axes:
200                insidex,_ = ax.xaxis.contains(event)
201                if insidex:
202                    xdata,_ = ax.transAxes.inverse_xy_tup((x,y))
203                insidey,_ = ax.yaxis.contains(event)
204                if insidey:
205                    _,ydata = ax.transAxes.inverse_xy_tup((x,y))
206            if xdata is not None:
207                lo,hi = ax.get_xlim()
208                lo,hi = _rescale(lo,hi,step,bal=xdata,scale=ax.get_xscale())
209                if not self.xscale=='log' or lo>0:
210                    ax.set_xlim((lo,hi))
211            if ydata is not None:
212                lo,hi = ax.get_ylim()
213                lo,hi = _rescale(lo,hi,step,bal=ydata,scale=ax.get_yscale())
214                if not self.yscale=='log' or lo>0:
215                    ax.set_ylim((lo,hi))
216               
217        self.canvas.draw_idle()
218
219
220    def returnTrans(self):
221        """
222            Return values and labels used by Fit Dialog
223        """
224        return self.xLabel,self.yLabel, self.Avalue, self.Bvalue,\
225                self.ErrAvalue,self.ErrBvalue,self.Chivalue
226   
227    def setTrans(self,xtrans,ytrans): 
228        """
229            @param xtrans: set x transformation on Property dialog
230            @param ytrans: set y transformation on Property dialog
231        """
232        self.prevXtrans =xtrans
233        self.prevYtrans =ytrans
234   
235    def onFitting(self, event): 
236        """
237            when clicking on linear Fit on context menu , display Fitting Dialog
238        """
239        list =[]
240        list = self.graph.returnPlottable()
241        from fitDialog import LinearFit
242       
243        if len(list.keys())>0:
244            first_item = list.keys()[0]
245            dlg = LinearFit( None, first_item, self.onFitDisplay,self.returnTrans, -1, 'Linear Fit')
246           
247            if (self.xmin !=0.0 )and ( self.xmax !=0.0)\
248                and(self.xminView !=0.0 )and ( self.xmaxView !=0.0):
249                dlg.setFitRange(self.xminView,self.xmaxView,self.xmin,self.xmax)
250            dlg.ShowModal() 
251
252    def linear_plottable_fit(self, plot): 
253        """
254            when clicking on linear Fit on context menu , display Fitting Dialog
255        """
256        from fitDialog import LinearFit
257       
258        dlg = LinearFit( None, plot, self.onFitDisplay,self.returnTrans, -1, 'Linear Fit')
259       
260        if (self.xmin !=0.0 )and ( self.xmax !=0.0)\
261            and(self.xminView !=0.0 )and ( self.xmaxView !=0.0):
262            dlg.setFitRange(self.xminView,self.xmaxView,self.xmin,self.xmax)
263        dlg.ShowModal() 
264
265    def _onProperties(self, event):
266        """
267            when clicking on Properties on context menu ,The Property dialog is displayed
268            The user selects a transformation for x or y value and a new plot is displayed
269        """
270        list =[]
271        list = self.graph.returnPlottable()
272        if len(list.keys())>0:
273            first_item = list.keys()[0]
274            if first_item.x !=[]:
275                from PropertyDialog import Properties
276                dial = Properties(self, -1, 'Properties')
277                dial.setValues( self.prevXtrans, self.prevYtrans,self.viewModel )
278                if dial.ShowModal() == wx.ID_OK:
279                    self.xLabel, self.yLabel,self.viewModel = dial.getValues()
280                    if self.viewModel =="Guinier lny vs x^(2)":
281                        self.xLabel="x^(2)"
282                        self.yLabel="ln(y)"
283                        self.viewModel = "--"
284                        dial.setValues( self.xLabel, self.yLabel,self.viewModel )
285                    self._onEVT_FUNC_PROPERTY()
286                dial.Destroy()
287           
288 
289    def set_yscale(self, scale='linear'):
290        """
291            Set the scale on Y-axis
292            @param scale: the scale of y-axis
293        """
294        self.subplot.set_yscale(scale)
295        self.yscale = scale
296       
297    def get_yscale(self):
298        """
299             @return: Y-axis scale
300        """
301        return self.yscale
302   
303    def set_xscale(self, scale='linear'):
304        """
305            Set the scale on x-axis
306            @param scale: the scale of x-axis
307        """
308        self.subplot.set_xscale(scale)
309        self.xscale = scale
310       
311    def get_xscale(self):
312        """
313             @return: x-axis scale
314        """
315        return self.xscale
316
317    def SetColor(self, rgbtuple):
318        """Set figure and canvas colours to be the same"""
319        if not rgbtuple:
320            rgbtuple = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE).Get()
321        col = [c/255.0 for c in rgbtuple]
322        self.figure.set_facecolor(col)
323        self.figure.set_edgecolor(col)
324        self.canvas.SetBackgroundColour(wx.Colour(*rgbtuple))
325
326    def _onSize(self, event):
327        self._resizeflag = True
328
329    def _onIdle(self, evt):
330        if self._resizeflag:
331            self._resizeflag = False
332            self._SetSize()
333            self.draw()
334
335    def _SetSize(self, pixels = None):
336        """
337        This method can be called to force the Plot to be a desired size, which defaults to
338        the ClientSize of the panel
339        """
340        if not pixels:
341            pixels = self.GetClientSize()
342        self.canvas.SetSize(pixels)
343        self.figure.set_size_inches(pixels[0]/self.figure.get_dpi(),
344        pixels[1]/self.figure.get_dpi())
345
346    def draw(self):
347        """Where the actual drawing happens"""
348        self.figure.canvas.draw_idle()
349       
350
351 
352 
353       
354    def onSaveImage(self, evt):
355        #figure.savefig
356        #print "Save image not implemented"
357        path = None
358        dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.png", wx.SAVE)
359        if dlg.ShowModal() == wx.ID_OK:
360            path = dlg.GetPath()
361            mypath = os.path.basename(path)
362            print path
363        dlg.Destroy()
364        if not path == None:
365            self.subplot.figure.savefig(path,dpi=300, facecolor='w', edgecolor='w',
366                                        orentation='portrait', papertype=None, format='png')
367       
368    def onContextMenu(self, event):
369        """
370            Default context menu for a plot panel
371        """
372        # Slicer plot popup menu
373        id = wx.NewId()
374        slicerpop = wx.Menu()
375        slicerpop.Append(id,'&Save image', 'Save image as PNG')
376        wx.EVT_MENU(self, id, self.onSaveImage)
377       
378        id = wx.NewId()
379        slicerpop.Append(id, '&Load 1D data file')
380        wx.EVT_MENU(self, id, self._onLoad1DData)
381       
382        id = wx.NewId()
383        slicerpop.AppendSeparator()
384        slicerpop.Append(id, '&Properties')
385        wx.EVT_MENU(self, id, self._onProperties)
386       
387        id = wx.NewId()
388        slicerpop.AppendSeparator()
389        slicerpop.Append(id, '&Linear Fit')
390        wx.EVT_MENU(self, id, self.onFitting)
391       
392        id = wx.NewId()
393        slicerpop.AppendSeparator()
394        slicerpop.Append(id, '&Reset Graph')
395        wx.EVT_MENU(self, id, self.onResetGraph)
396       
397        pos = event.GetPosition()
398        pos = self.ScreenToClient(pos)
399        self.PopupMenu(slicerpop, pos)
400   
401    ## The following is plottable functionality
402
403
404    def properties(self,prop):
405        """Set some properties of the graph.
406       
407        The set of properties is not yet determined.
408        """
409        # The particulars of how they are stored and manipulated (e.g., do
410        # we want an inventory internally) is not settled.  I've used a
411        # property dictionary for now.
412        #
413        # How these properties interact with a user defined style file is
414        # even less clear.
415
416        # Properties defined by plot
417        self.subplot.set_xlabel(r"$%s$" % prop["xlabel"])
418        self.subplot.set_ylabel(r"$%s$" % prop["ylabel"])
419        self.subplot.set_title(prop["title"])
420
421        # Properties defined by user
422        #self.axes.grid(True)
423
424    def clear(self):
425        """Reset the plot"""
426       
427        # TODO: Redraw is brutal.  Render to a backing store and swap in
428        # TODO: rather than redrawing on the fly.
429        self.subplot.clear()
430        self.subplot.hold(True)
431   
432    def render(self):
433        """Commit the plot after all objects are drawn"""
434        # TODO: this is when the backing store should be swapped in.
435        from matplotlib.font_manager import FontProperties
436        self.subplot.legend(prop=FontProperties(size=10))
437        #self.subplot.legend()
438        pass
439
440    def xaxis(self,label,units):
441        """xaxis label and units.
442       
443        Axis labels know about units.
444       
445        We need to do this so that we can detect when axes are not
446        commesurate.  Currently this is ignored other than for formatting
447        purposes.
448        """
449        if units != "": label = label + " (" + units + ")"
450        self.subplot.set_xlabel(label)
451        pass
452   
453    def yaxis(self,label,units):
454        """yaxis label and units."""
455        if units != "": label = label + " (" + units + ")"
456        self.subplot.set_ylabel(label)
457        pass
458
459    def _connect_to_xlim(self,callback):
460        """Bind the xlim change notification to the callback"""
461        def process_xlim(axes):
462            lo,hi = subplot.get_xlim()
463            callback(lo,hi)
464        self.subplot.callbacks.connect('xlim_changed',process_xlim)
465   
466    #def connect(self,trigger,callback):
467    #    print "PlotPanel.connect???"
468    #    if trigger == 'xlim': self._connect_to_xlim(callback)
469
470    def points(self,x,y,dx=None,dy=None,color=0,symbol=0,label=None):
471        """Draw markers with error bars"""
472        self.subplot.set_yscale('linear')
473        self.subplot.set_xscale('linear')
474       
475        # Convert tuple (lo,hi) to array [(x-lo),(hi-x)]
476        if dx != None and type(dx) == type(()):
477            dx = nx.vstack((x-dx[0],dx[1]-x)).transpose()
478        if dy != None and type(dy) == type(()):
479            dy = nx.vstack((y-dy[0],dy[1]-y)).transpose()
480
481        if dx==None and dy==None:
482            h = self.subplot.plot(x,y,color=self._color(color),
483                                   marker=self._symbol(symbol),linestyle='',label=label)
484        else:
485            col = self._color(color)
486            self.subplot.errorbar(x, y, yerr=dy, xerr=None,
487             ecolor=col, capsize=2,linestyle='', barsabove=False,
488             mec=col, mfc=col,
489             marker=self._symbol(symbol),
490             lolims=False, uplims=False,
491             xlolims=False, xuplims=False,label=label)
492           
493        self.subplot.set_yscale(self.yscale)
494        self.subplot.set_xscale(self.xscale)
495
496    def curve(self,x,y,dy=None,color=0,symbol=0,label=None):
497        """Draw a line on a graph, possibly with confidence intervals."""
498        c = self._color(color)
499        self.subplot.set_yscale('linear')
500        self.subplot.set_xscale('linear')
501       
502        hlist = self.subplot.plot(x,y,color=c,marker='',linestyle='-',label=label)
503       
504        self.subplot.set_yscale(self.yscale)
505        self.subplot.set_xscale(self.xscale)
506
507    def _color(self,c):
508        """Return a particular colour"""
509        return self.colorlist[c%len(self.colorlist)]
510
511    def _symbol(self,s):
512        """Return a particular symbol"""
513        return self.symbollist[s%len(self.symbollist)]
514   
515    def _replot(self):
516        """
517            Rescale the plottables according to the latest
518            user selection and update the plot
519        """
520        self.graph.reset_scale()
521        self._onEVT_FUNC_PROPERTY(remove_fit=False)
522       
523        #TODO: Why do we have to have the following line?
524        self.fit_result.reset_view()
525       
526        self.graph.render(self)
527        self.subplot.figure.canvas.draw_idle()
528   
529    def _onEVT_FUNC_PROPERTY(self, remove_fit=True):
530        """
531             Receive the x and y transformation from myDialog,Transforms x and y in View
532              and set the scale   
533        """ 
534        list =[]
535        list = self.graph.returnPlottable()
536       
537        if remove_fit:
538            self.fit_result.x =[] 
539            self.fit_result.y =[] 
540            self.fit_result.dx=None
541            self.fit_result.dy=None
542            self.graph.delete(self.fit_result)
543       
544        for item in list:
545            item.setLabel(self.xLabel,self.yLabel)
546            if ( self.xLabel=="x" ):
547                item.transformX(transform.toX,transform.errToX)
548                self.set_xscale("linear")
549                name, units = item.get_xaxis()
550                self.graph.xaxis("%s" % name,  "%s" % units)
551               
552               
553            if ( self.xLabel=="x^(2)" ):
554                item.transformX(transform.toX2,transform.errToX2)
555                self.set_xscale('linear')
556                name, units = item.get_xaxis()
557                units=convertUnit(2,units) 
558                self.graph.xaxis("%s^{2}" % name,  "%s" % units)
559               
560               
561            if (self.xLabel=="log10(x)" ):
562                item.transformX(transform.toX,transform.errToX)
563                self.set_xscale("log")
564                name, units = item.get_xaxis() 
565                self.graph.xaxis("\log_{10}\ \  (%s)" % name,  "%s" % units)
566               
567               
568            if ( self.yLabel=="ln(y)" ):
569                item.transformY(transform.toLogX,transform.errToLogX)
570                self.set_yscale("linear")
571                name, units = item.get_yaxis()
572                self.graph.yaxis("log\ \ %s" % name,  "%s" % units)
573               
574               
575            if ( self.yLabel=="y" ):
576                item.transformY(transform.toX,transform.errToX)
577                self.set_yscale("linear")
578                name, units = item.get_yaxis()
579                self.graph.yaxis("%s" % name,  "%s" % units)
580               
581               
582            if ( self.yLabel=="log10(y)" ): 
583                item.transformY(transform.toX,transform.errToX)
584                self.set_yscale("log") 
585                name, units = item.get_yaxis()
586                self.graph.yaxis("\log_{10}\ \ (%s)" % name,  "%s" % units)
587               
588               
589            if ( self.yLabel=="y^(2)" ):
590                item.transformY( transform.toX2,transform.errToX2 )   
591                self.set_yscale("linear")
592                name, units = item.get_yaxis()
593                units=convertUnit(2,units) 
594                self.graph.yaxis("%s^{2}" % name,  "%s" % units)
595               
596               
597            if ( self.yLabel =="1/y"):
598                item.transformY(transform.toOneOverX,transform.errOneOverX )
599                self.set_yscale("linear")
600                name, units = item.get_yaxis()
601                units=convertUnit(-1,units)
602                self.graph.yaxis("1/%s" % name,  "%s" % units)
603               
604            if ( self.yLabel =="1/sqrt(y)" ):
605                item.transformY(transform.toOneOverSqrtX,transform.errOneOverSqrtX )
606                self.set_yscale("linear")
607                name, units = item.get_yaxis()
608                units=convertUnit(-1,units)
609                self.graph.yaxis("1/\sqrt{%s}" %name,  "%s" % units)
610               
611            if ( self.yLabel =="ln(y*x)"):
612                item.transformY( transform.toLogXY,transform.errToLogXY)
613                self.set_yscale("linear")
614                yname, yunits = item.get_yaxis()
615                xname, xunits = item.get_xaxis()
616                self.graph.yaxis("log\ (%s \ \ %s)" % (yname,xname),  "%s%s" % (yunits,xunits))
617               
618               
619            if ( self.yLabel =="ln(y*x^(2))"):
620                item.transformY( transform.toLogYX2,transform.errToLogYX2)
621                self.set_yscale("linear")
622                yname, yunits = item.get_yaxis()
623                xname, xunits = item.get_xaxis() 
624                xunits = convertUnit(2,xunits) 
625                self.graph.yaxis("Log (%s \ \ %s)" % (yname,xname),  "%s%s" % (yunits,xunits))
626               
627           
628            if ( self.yLabel =="ln(y*x^(4))"):
629                item.transformY(transform.toLogYX4,transform.errToLogYX4)
630                self.set_yscale("linear")
631                yname, yunits = item.get_yaxis()
632                xname, xunits = item.get_xaxis()
633                xunits = convertUnit(4,xunits) 
634                self.graph.yaxis("Log (%s \ \ %s)" % (yname,xname),  "%s%s" % (yunits,xunits))
635               
636            if ( self.viewModel == "Guinier lny vs x^(2)"):
637               
638                item.transformX(transform.toX2,transform.errToX2)
639                self.set_xscale('linear')
640                name, units = item.get_xaxis()
641                units = convertUnit(2,units) 
642                self.graph.xaxis("%s^{2}" % name,  "%s" % units)
643               
644               
645                item.transformY(transform.toLogX,transform.errToLogX )
646                self.set_yscale("linear")
647                name, units = item.get_yaxis()
648                self.graph.yaxis("$Log %s$" % name,  "%s" % units)
649               
650               
651            item.transformView()
652           
653         
654        self.resetFitView()   
655        self.prevXtrans = self.xLabel
656        self.prevYtrans = self.yLabel 
657        self.graph.render(self)
658        self.subplot.figure.canvas.draw_idle()
659       
660       
661   
662    def onFitDisplay(self, tempx,tempy,xminView,xmaxView,xmin,xmax,func):
663        """
664            Add a new plottable into the graph .In this case this plottable will be used
665            to fit some data
666            @param tempx: The x data of fit line
667            @param tempy: The y data of fit line
668            @param xminView: the lower bound of fitting range
669            @param xminView: the upper bound of  fitting range
670            @param xmin: the lowest value of data to fit to the line
671            @param xmax: the highest value of data to fit to the line
672        """
673        # Saving value to redisplay in Fit Dialog when it is opened again
674        self.Avalue,self.Bvalue,self.ErrAvalue,self.ErrBvalue,self.Chivalue=func
675        self.xminView=xminView
676        self.xmaxView=xmaxView
677        self.xmin= xmin
678        self.xmax= xmax
679        #In case need to change the range of data plotted
680        list =[]
681        list = self.graph.returnPlottable()
682        for item in list:
683            #item.onFitRange(xminView,xmaxView)
684            item.onFitRange(None,None)
685       
686        # Create new data plottable with result
687        self.fit_result.x =[] 
688        self.fit_result.y =[]
689        self.fit_result.x =tempx 
690        self.fit_result.y =tempy     
691        self.fit_result.dx=None
692        self.fit_result.dy=None
693        #Load the view with the new values
694        self.fit_result.reset_view()
695        # Add the new plottable to the graph
696        self.graph.add(self.fit_result) 
697        self.graph.render(self)
698        self.subplot.figure.canvas.draw_idle()
699       
700   
701    def onResetGraph(self,event):
702        """
703            Reset the graph by plotting the full range of data
704        """
705        list =[]
706        list = self.graph.returnPlottable()
707        for item in list:
708            item.onReset()
709        self.graph.render(self)
710        self.subplot.figure.canvas.draw_idle()
711       
712class NoRepaintCanvas(FigureCanvasWxAgg):
713    """We subclass FigureCanvasWxAgg, overriding the _onPaint method, so that
714    the draw method is only called for the first two paint events. After that,
715    the canvas will only be redrawn when it is resized.
716    """
717    def __init__(self, *args, **kwargs):
718        FigureCanvasWxAgg.__init__(self, *args, **kwargs)
719        self._drawn = 0
720
721    def _onPaint(self, evt):
722        """
723        Called when wxPaintEvt is generated
724        """
725        if not self._isRealized:
726            self.realize()
727        if self._drawn < 2:
728            self.draw(repaint = False)
729            self._drawn += 1
730        self.gui_repaint(drawDC=wx.PaintDC(self))
731           
Note: See TracBrowser for help on using the repository browser.