Changeset 10bfeb3 in sasview


Ignore:
Timestamp:
Apr 27, 2012 8:23:08 AM (12 years ago)
Author:
Mathieu Doucet <doucetm@…>
Branches:
master, ESS_GUI, ESS_GUI_Docs, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_iss959, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc, costrafo411, magnetic_scatt, release-4.1.1, release-4.1.2, release-4.2.2, release_4.0.1, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
Children:
f60a8c2
Parents:
8a621ac
Message:

Pep-8-ification

Location:
plottools/src/danse/common/plottools
Files:
15 edited

Legend:

Unmodified
Added
Removed
  • plottools/src/danse/common/plottools/BaseInteractor.py

    r82a54b8 r10bfeb3  
    2222        update() - draw the interactors 
    2323         
    24     The following are provided by the base class:  
     24    The following are provided by the base class: 
    2525     
    2626        connect_markers(markers) - register callbacks for all markers 
     
    5353        Clear old markers and interfaces. 
    5454        ''' 
    55         for h in self.markers: h.remove() 
    56         if self.markers: self.base.connect.clear(*self.markers) 
     55        for h in self.markers: 
     56            h.remove() 
     57        if self.markers: 
     58            self.base.connect.clear(*self.markers) 
    5759        self.markers = [] 
    5860 
     
    127129        the mouse leaves the window. 
    128130        """ 
    129         inside, prop = self.axes.contains(ev) 
     131        inside, _ = self.axes.contains(ev) 
    130132        if inside: 
    131133            self.clickx, self.clicky = ev.xdata, ev.ydata 
     
    147149        elif ev.key in ['up', 'down', 'right', 'left']: 
    148150            dx, dy = self.dpixel(self.clickx, self.clicky, nudge=ev.control) 
    149             if ev.key == 'up': self.clicky += dy 
    150             elif ev.key == 'down': self.clicky -= dy 
    151             elif ev.key == 'right': self.clickx += dx 
    152             else: self.clickx -= dx 
     151            if ev.key == 'up': 
     152                self.clicky += dy 
     153            elif ev.key == 'down': 
     154                self.clicky -= dy 
     155            elif ev.key == 'right': 
     156                self.clickx += dx 
     157            else: 
     158                self.clickx -= dx 
    153159            self.move(self.clickx, self.clicky, ev) 
    154160        else: 
     
    172178        dx, dy = nx-x, ny-y 
    173179        return dx, dy 
    174  
  • plottools/src/danse/common/plottools/PlotPanel.py

    r6e75ed0 r10bfeb3  
    1313from matplotlib.figure import Figure 
    1414import os 
    15 import fittings 
    1615import transform 
    17 from matplotlib.widgets import RectangleSelector 
    18 from pylab import  gca, gcf 
    1916from plottables import Data1D 
    2017#TODO: make the plottables interactive 
    2118from binder import BindArtist 
    2219from matplotlib.font_manager import FontProperties 
    23  
    24 #from matplotlib import cm 
    25 #from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter 
    26  
    2720DEBUG = False 
    2821 
     
    3326import operator 
    3427 
    35 import math, pylab, re 
     28import math 
     29import pylab 
    3630DEFAULT_CMAP = pylab.cm.jet 
    3731import copy 
    3832import numpy 
    3933 
    40 def show_tree(obj,d=0): 
     34 
     35def show_tree(obj, d=0): 
    4136    """Handy function for displaying a tree of graph objects""" 
    4237    print "%s%s" % ("-"*d, obj.__class__.__name__) 
     
    4439        for a in obj.get_children(): show_tree(a, d+1) 
    4540      
    46 from unitConverter import UnitConvertion as convertUnit    
     41from unitConverter import UnitConvertion as convertUnit 
     42 
    4743 
    4844def _rescale(lo, hi, step, pt=None, bal=None, scale='linear'): 
     
    6056        loprev = lo 
    6157        hiprev = hi 
    62         ptprev = pt 
    6358        if scale == 'log': 
    6459            assert lo > 0 
    65             if lo > 0 : 
     60            if lo > 0: 
    6661                lo = math.log10(lo) 
    67             if hi > 0 : 
     62            if hi > 0: 
    6863                hi = math.log10(hi) 
    69             if pt is not None: pt = math.log10(pt) 
     64            if pt is not None: 
     65                pt = math.log10(pt) 
    7066         
    7167        # Compute delta from axis range * %, or 1-% if persent is negative 
     
    9490 
    9591def CopyImage(canvas): 
    96      """ 
    97      0: matplotlib plot 
    98      1: wx.lib.plot 
    99      2: other 
    100       
    101      """ 
    102      bmp = wx.BitmapDataObject() 
    103      bmp.SetBitmap(canvas.bitmap) 
    104  
    105      wx.TheClipboard.Open() 
    106      wx.TheClipboard.SetData(bmp) 
    107      wx.TheClipboard.Close() 
     92    """ 
     93    0: matplotlib plot 
     94    1: wx.lib.plot 
     95    2: other 
     96    """ 
     97    bmp = wx.BitmapDataObject() 
     98    bmp.SetBitmap(canvas.bitmap) 
     99     
     100    wx.TheClipboard.Open() 
     101    wx.TheClipboard.SetData(bmp) 
     102    wx.TheClipboard.Close() 
    108103 
    109104 
     
    116111    """ 
    117112    def __init__(self, parent, id=-1, xtransform=None, 
    118                   ytransform=None, scale='log_{10}',  
     113                  ytransform=None, scale='log_{10}', 
    119114                  color=None, dpi=None, **kwargs): 
    120115        """ 
     
    123118        self.parent = parent 
    124119        self.dimension = 1 
    125         self.gotLegend = 0  #to begin, legend is not picked.  
     120        self.gotLegend = 0  # to begin, legend is not picked. 
    126121        self.legend_pos_loc = None 
    127122        self.legend = None 
    128         self.line_collections_list = []  
     123        self.line_collections_list = [] 
    129124        self.figure = Figure(None, dpi, linewidth=2.0) 
    130         self.color = '#b3b3b3'   
     125        self.color = '#b3b3b3' 
    131126        from canvas import FigureCanvas 
    132         self.canvas = FigureCanvas(self, -1, self.figure)  
     127        self.canvas = FigureCanvas(self, -1, self.figure) 
    133128        self.SetColor(color) 
    134129        #self.SetBackgroundColour(parent.GetBackgroundColour()) 
    135130        self._resizeflag = True 
    136         self._SetSize()  
     131        self._SetSize() 
    137132        self.subplot = self.figure.add_subplot(111) 
    138133        self.figure.subplots_adjust(left=0.2, bottom=.2) 
     
    171166        if xtransform != None: 
    172167            self.xLabel = xtransform 
    173         else:    
     168        else: 
    174169            self.xLabel = "log10(x)" 
    175170        if ytransform != None: 
     
    203198        #self.selected_plottable = None 
    204199         
    205         # new data for the fit  
     200        # new data for the fit 
    206201        self.fit_result = Data1D(x=[], y=[], dy=None) 
    207202        self.fit_result.symbol = 13 
     
    239234        self.zmax_2D = None 
    240235         
    241         #index array  
     236        #index array 
    242237        self.index_x = None 
    243238        self.index_y = None 
     
    275270         
    276271        # Default locations 
    277         self._default_save_location = os.getcwd()     
     272        self._default_save_location = os.getcwd() 
    278273        # let canvas know about axes 
    279274        self.canvas.set_panel(self) 
    280275         
    281         #Bind focus to change the border color       
     276        #Bind focus to change the border color 
    282277        self.canvas.Bind(wx.EVT_SET_FOCUS, self.on_set_focus) 
    283278        self.canvas.Bind(wx.EVT_KILL_FOCUS, self.on_kill_focus) 
     
    288283        pixels = self.parent.GetClientSize() 
    289284        self.canvas.SetSize(pixels) 
    290         self.figure.set_size_inches( (pixels[0])/self.figure.get_dpi(), 
    291          (pixels[1])/self.figure.get_dpi(), forward=True )    
     285        self.figure.set_size_inches(pixels[0] / self.figure.get_dpi(), 
     286         pixels[1] / self.figure.get_dpi(), forward=True) 
    292287           
    293288    def On_Paint(self, event): 
     
    295290        """ 
    296291        self.canvas.SetBackgroundColour(self.color) 
    297         #dc = wx.PaintDC(self.canvas) 
    298         #dc.SetPen(wx.Pen(self.color)) 
    299         #x, y = self.GetSize() 
    300         #dc.DrawRectangle(0, 0, x, y) 
    301         #dc.DrawRectangle(1, 1, x-1, y-1) 
    302         #self.draw() 
     292 
    303293    def on_set_focus(self, event): 
    304294        """ 
     
    323313        Set the resizing (True/False) 
    324314        """ 
    325         pass # Not implemented 
     315        pass  # Not implemented 
    326316     
    327     def schedule_full_draw(self, func='append'):     
     317    def schedule_full_draw(self, func='append'): 
    328318        """ 
    329319        Put self in schedule to full redraw list 
    330320        """ 
    331         pass # Not implemented 
     321        pass  # Not implemented 
    332322     
    333323    def add_toolbar(self): 
     
    359349        self.toolbar.update() 
    360350         
    361     def onLeftDown(self, event):  
     351    def onLeftDown(self, event): 
    362352        """ 
    363353        left button down and ready to drag 
     
    371361                self.xInit, self.yInit = event.xdata, event.ydata 
    372362                try: 
    373                     pos_x = float(event.xdata)# / size_x 
    374                     pos_y = float(event.ydata)# / size_y 
    375                     pos_x = "%8.3g"% pos_x 
    376                     pos_y = "%8.3g"% pos_y 
     363                    pos_x = float(event.xdata)  # / size_x 
     364                    pos_y = float(event.ydata)  # / size_y 
     365                    pos_x = "%8.3g" % pos_x 
     366                    pos_y = "%8.3g" % pos_y 
    377367                    self.position = str(pos_x), str(pos_y) 
    378368                    wx.PostEvent(self.parent, StatusEvent(status=self.position)) 
    379369                except: 
    380                     self.position = None   
    381         #size_x, size_y =  self.GetClientSizeTuple() 
    382  
    383       
    384     def onLeftUp(self, event):  
     370                    self.position = None 
     371 
     372    def onLeftUp(self, event): 
    385373        """ 
    386374        Dragging is done 
    387          
    388375        """ 
    389376        # Check that the LEFT button was released 
    390377        if event.button == 1: 
    391378            self.leftdown = False 
    392             self.mousemotion = False  
     379            self.mousemotion = False 
    393380            self.leftup = True 
    394381             
    395         #release the legend     
     382        #release the legend 
    396383        if self.gotLegend == 1: 
    397384            self.gotLegend = 0 
     
    405392            self.legend.legendPatch.set_alpha(alpha) 
    406393         
    407     def onPick(self, event):     
     394    def onPick(self, event): 
    408395        """ 
    409396        On pick legend 
     
    412399        if event.artist == legend: 
    413400            #gets the box of the legend. 
    414             bbox = self.legend.get_window_extent()   
     401            bbox = self.legend.get_window_extent() 
    415402            #get mouse coordinates at time of pick. 
    416             self.mouse_x = event.mouseevent.x   
     403            self.mouse_x = event.mouseevent.x 
    417404            self.mouse_y = event.mouseevent.y 
    418405            #get legend coordinates at time of pick. 
    419             self.legend_x = bbox.xmin           
     406            self.legend_x = bbox.xmin 
    420407            self.legend_y = bbox.ymin 
    421408            #indicates we picked up the legend. 
    422             self.gotLegend = 1    
     409            self.gotLegend = 1 
    423410            self.set_legend_alpha(0.5) 
    424    
    425              
    426     def _on_legend_motion(self, event):  
     411     
     412    def _on_legend_motion(self, event): 
    427413        """ 
    428414        On legend in motion 
     
    435421        lo_y, hi_y = ax.get_ylim() 
    436422        # How much the mouse moved. 
    437         x = mouse_diff_x = self.mouse_x - event.x   
     423        x = mouse_diff_x = self.mouse_x - event.x 
    438424        y = mouse_diff_y = self.mouse_y - event.y 
    439425        # Put back inside 
     
    444430        if y < lo_y: 
    445431            y = lo_y 
    446         if y> hi_y: 
     432        if y > hi_y: 
    447433            y = hi_y 
    448434        # Move the legend from its previous location by that same amount 
     
    456442        self.resizing = True 
    457443        self.canvas.set_resizing(self.resizing) 
    458         self.canvas.draw()  
     444        self.canvas.draw() 
    459445            
    460     def onMouseMotion(self, event):  
     446    def onMouseMotion(self, event): 
    461447        """ 
    462448        check if the left button is press and the mouse in moving. 
    463         computer delta for x and y coordinates and then calls draghelper  
     449        computer delta for x and y coordinates and then calls draghelper 
    464450        to perform the drag 
    465451         
     
    471457            #Disable dragging without the toolbar to allow zooming with toolbar 
    472458            return 
    473         self.mousemotion = True  
     459        self.mousemotion = True 
    474460        if self.leftdown == True and self.mousemotion == True: 
    475461            ax = event.inaxes 
    476             if ax != None:#the dragging is perform inside the figure 
     462            if ax != None:  # the dragging is perform inside the figure 
    477463                self.xFinal, self.yFinal = event.xdata, event.ydata 
    478464                # Check whether this is the first point 
     
    489475                    ydelta = math.log10(self.yFinal) - math.log10(self.yInit) 
    490476                self._dragHelper(xdelta, ydelta) 
    491             else:# no dragging is perform elsewhere 
    492                 self._dragHelper(0,0) 
    493  
    494                  
     477            else:  # no dragging is perform elsewhere 
     478                self._dragHelper(0, 0) 
     479 
    495480    def _offset_graph(self): 
    496481        """ 
    497         Zoom and offset the graph to the last known settings  
    498          
     482        Zoom and offset the graph to the last known settings 
    499483        """ 
    500484        for ax in self.axes: 
     
    580564            # Event occurred inside a plotting area 
    581565            lo, hi = ax.get_xlim() 
    582             lo, hi = _rescale(lo, hi, step,  
     566            lo, hi = _rescale(lo, hi, step, 
    583567                             pt=event.xdata, scale=ax.get_xscale()) 
    584568            if not self.xscale == 'log' or lo > 0: 
     
    593577                self._scale_ylo = lo 
    594578                self._scale_yhi = hi 
    595                 ax.set_ylim((lo,hi)) 
     579                ax.set_ylim((lo, hi)) 
    596580        else: 
    597581            # Check if zoom happens in the axes 
     
    602586                insidex, _ = ax.xaxis.contains(event) 
    603587                if insidex: 
    604                     xdata, _ = ax.transAxes.inverted().transform_point((x, y))  
    605                     #xdata,_ = ax.transAxes.inverse_xy_tup((x,y)) 
     588                    xdata, _ = ax.transAxes.inverted().transform_point((x, y)) 
    606589                insidey, _ = ax.yaxis.contains(event) 
    607590                if insidey: 
    608                     _, ydata = ax.transAxes.inverted().transform_point((x, y))  
    609                     #_,ydata = ax.transAxes.inverse_xy_tup((x,y)) 
     591                    _, ydata = ax.transAxes.inverted().transform_point((x, y)) 
    610592            if xdata is not None: 
    611593                lo, hi = ax.get_xlim() 
    612                 lo, hi = _rescale(lo, hi, step,  
     594                lo, hi = _rescale(lo, hi, step, 
    613595                                  bal=xdata, scale=ax.get_xscale()) 
    614596                if not self.xscale == 'log' or lo > 0: 
     
    618600            if ydata is not None: 
    619601                lo, hi = ax.get_ylim() 
    620                 lo, hi = _rescale(lo, hi, step, bal=ydata,  
     602                lo, hi = _rescale(lo, hi, step, bal=ydata, 
    621603                                  scale=ax.get_yscale()) 
    622                 if not self.yscale=='log' or lo>0: 
     604                if not self.yscale == 'log' or lo > 0: 
    623605                    self._scale_ylo = lo 
    624606                    self._scale_yhi = hi 
     
    630612        Return values and labels used by Fit Dialog 
    631613        """ 
    632         return self.xLabel,self.yLabel, self.Avalue, self.Bvalue,\ 
     614        return self.xLabel, self.yLabel, self.Avalue, self.Bvalue,\ 
    633615                self.ErrAvalue, self.ErrBvalue, self.Chivalue 
    634616     
    635     def setTrans(self, xtrans, ytrans):  
     617    def setTrans(self, xtrans, ytrans): 
    636618        """ 
    637619         
     
    643625        self.prevYtrans = ytrans 
    644626    
    645     def onFitting(self, event):  
     627    def onFitting(self, event): 
    646628        """ 
    647629        when clicking on linear Fit on context menu , display Fitting Dialog 
     
    660642        from fitDialog import LinearFit 
    661643         
    662         if len(list.keys())>0: 
     644        if len(list.keys()) > 0: 
    663645            first_item = list.keys()[0] 
    664             dlg = LinearFit(parent=None, plottable=first_item,  
     646            dlg = LinearFit(parent=None, plottable=first_item, 
    665647                            push_data=self.onFitDisplay, 
    666                             transform=self.returnTrans,  
     648                            transform=self.returnTrans, 
    667649                            title='Linear Fit') 
    668650            
    669651            if (self.xmin != 0.0)and (self.xmax != 0.0)\ 
    670652                and(self.xminView != 0.0)and (self.xmaxView != 0.0): 
    671                 dlg.setFitRange(self.xminView, self.xmaxView,  
     653                dlg.setFitRange(self.xminView, self.xmaxView, 
    672654                                self.xmin, self.xmax) 
    673             dlg.ShowModal()  
     655            dlg.ShowModal() 
    674656             
    675657    def set_selected_from_menu(self, menu, id): 
     
    688670                break 
    689671             
    690     def linear_plottable_fit(self, plot):  
    691         """ 
    692             when clicking on linear Fit on context menu , display Fitting Dialog 
     672    def linear_plottable_fit(self, plot): 
     673        """ 
     674            when clicking on linear Fit on context menu, display Fitting Dialog 
    693675             
    694676            :param plot: PlotPanel owning the graph 
     
    706688        self._fit_dialog.register_close(self._linear_fit_close) 
    707689        # Show a non-model dialog 
    708         self._fit_dialog.Show()  
     690        self._fit_dialog.Show() 
    709691 
    710692    def _linear_fit_close(self): 
     
    714696        self._fit_dialog = None 
    715697         
    716  
    717698    def _onProperties(self, event): 
    718699        """ 
    719700        when clicking on Properties on context menu , 
    720701        The Property dialog is displayed 
    721         The user selects a transformation for x or y value and  
     702        The user selects a transformation for x or y value and 
    722703        a new plot is displayed 
    723704        """ 
     
    734715                dial.setValues(self.prevXtrans, self.prevYtrans, self.viewModel) 
    735716                if dial.ShowModal() == wx.ID_OK: 
    736                     self.xLabel, self.yLabel,self.viewModel = dial.getValues() 
     717                    self.xLabel, self.yLabel, self.viewModel = dial.getValues() 
    737718                    if self.viewModel == "Guinier lny vs x^(2)": 
    738719                        self.xLabel = "x^(2)" 
     
    809790            self.draw() 
    810791 
    811     def _SetSize(self, pixels = None): 
     792    def _SetSize(self, pixels=None): 
    812793        """ 
    813794        This method can be called to force the Plot to be a desired size, 
     
    818799            pixels = tuple(self.GetClientSize()) 
    819800        self.canvas.SetSize(pixels) 
    820         self.figure.set_size_inches( float( pixels[0] )/self.figure.get_dpi(), 
    821                                      float( pixels[1] )/self.figure.get_dpi() )  
     801        self.figure.set_size_inches(float(pixels[0]) / self.figure.get_dpi(), 
     802                                    float(pixels[1]) / self.figure.get_dpi()) 
    822803 
    823804    def draw(self): 
     
    828809        self.figure.canvas.draw_idle() 
    829810         
    830         
    831     #pick up the legend patch 
    832811    def legend_picker(self, legend, event): 
    833         return self.legend.legendPatch.contains(event)       
     812        """ 
     813            Pick up the legend patch 
     814        """ 
     815        return self.legend.legendPatch.contains(event) 
    834816         
    835817    def get_loc_label(self): 
     
    880862         
    881863        id = wx.NewId() 
    882         slicerpop.Append(id,'&Printer setup', 'Set image size') 
     864        slicerpop.Append(id, '&Printer setup', 'Set image size') 
    883865        wx.EVT_MENU(self, id, self.onPrinterSetup) 
    884866         
    885867        id = wx.NewId() 
    886         slicerpop.Append(id,'&Printer Preview', 'Set image size') 
     868        slicerpop.Append(id, '&Printer Preview', 'Set image size') 
    887869        wx.EVT_MENU(self, id, self.onPrinterPreview) 
    888870     
     
    968950            handles2, labels2 = zip(*hl) 
    969951            self.line_collections_list = handles2 
    970             self.legend = self.subplot.legend(handles2, labels2,  
     952            self.legend = self.subplot.legend(handles2, labels2, 
    971953                                prop=FontProperties(size=10), numpoints=1, 
    972954                                handletextsep=.05, loc=self.legendLoc) 
    973955            if self.legend != None: 
    974                 self.legend.set_picker(self.legend_picker)  
    975                 self.legend.set_axes(self.subplot)  
    976          
    977         self.subplot.figure.canvas.draw_idle()        
     956                self.legend.set_picker(self.legend_picker) 
     957                self.legend.set_axes(self.subplot) 
     958         
     959        self.subplot.figure.canvas.draw_idle() 
    978960        self.legend_on = not self.legend_on 
    979961     
     
    984966        menu = event.GetEventObject() 
    985967        id = event.GetId() 
    986         label =  menu.GetLabel(id) 
     968        label = menu.GetLabel(id) 
    987969         
    988970        self.legendLoc = label 
     
    994976        handles2, labels2 = zip(*hl) 
    995977        self.line_collections_list = handles2 
    996         self.legend = self.subplot.legend(handles2, labels2,  
    997                             prop=FontProperties(size=10),  numpoints=1, 
     978        self.legend = self.subplot.legend(handles2, labels2, 
     979                            prop=FontProperties(size=10), numpoints=1, 
    998980                            handletextsep=.05, loc=self.legendLoc) 
    999981        if self.legend != None: 
    1000                 self.legend.set_picker(self.legend_picker)  
    1001                 self.legend.set_axes(self.subplot)  
    1002         self.subplot.figure.canvas.draw_idle()   
    1003         #self._onEVT_FUNC_PROPERTY() 
     982                self.legend.set_picker(self.legend_picker) 
     983                self.legend.set_axes(self.subplot) 
     984        self.subplot.figure.canvas.draw_idle() 
    1004985         
    1005986    def remove_legend(self, ax=None): 
     
    1007988        Remove legend for ax or the current axes. 
    1008989        """ 
    1009         from pylab import gca, draw 
     990        from pylab import gca 
    1010991        if ax is None: 
    1011992            ax = gca() 
    1012993        ax.legend_ = None 
    1013         #draw() 
    1014          
    1015     def _on_addtext(self, event):  
     994         
     995    def _on_addtext(self, event): 
    1016996        """ 
    1017997        Allows you to add text to the plot 
     
    10381018                colour = textdial.getColor() 
    10391019                if len(label) > 0 and xpos > 0 and ypos > 0: 
    1040                     new_text = self.subplot.text(str(xpos), str(ypos), label,  
     1020                    new_text = self.subplot.text(str(xpos), str(ypos), label, 
    10411021                                                   fontproperties=font, 
    10421022                                                   color=colour) 
    10431023                    self.textList.append(new_text) 
    1044                     self.subplot.figure.canvas.draw_idle()   
     1024                    self.subplot.figure.canvas.draw_idle() 
    10451025            except: 
    10461026                if self.parent != None: 
    10471027                    from sans.guiframe.events import StatusEvent  
    1048                     msg= "Add Text: Error. Check your property values..." 
     1028                    msg = "Add Text: Error. Check your property values..." 
    10491029                    wx.PostEvent(self.parent, StatusEvent(status = msg )) 
    10501030                else: 
     
    10551035        #based on this and plot it at user designated coordinates 
    10561036 
    1057     def onGridOnOff(self, event):  
     1037    def onGridOnOff(self, event): 
    10581038        """ 
    10591039        Allows ON/OFF Grid 
     
    10651045        self.subplot.figure.canvas.draw_idle() 
    10661046         
    1067     def _on_xaxis_label(self, event):  
     1047    def _on_xaxis_label(self, event): 
    10681048        """ 
    10691049        Allows you to add text to the plot 
     
    10901070            self._check_zoom_plot() 
    10911071     
    1092     def _check_zoom_plot(self):  
     1072    def _check_zoom_plot(self): 
    10931073        """ 
    10941074        Check the zoom range and plot (1D only) 
     
    11021082        if self.is_zoomed or toolbar_zoomed: 
    11031083            # Recover the x,y limits 
    1104             self.subplot.set_xlim((xlo, xhi))      
    1105             self.subplot.set_ylim((ylo, yhi))  
     1084            self.subplot.set_xlim((xlo, xhi)) 
     1085            self.subplot.set_ylim((ylo, yhi)) 
    11061086                    
    1107     def _on_yaxis_label(self, event):  
     1087    def _on_yaxis_label(self, event): 
    11081088        """ 
    11091089        Allows you to add text to the plot 
     
    11301110            self._check_zoom_plot() 
    11311111             
    1132          
    11331112    def _on_axis_label(self, axis='x'): 
    11341113        """ 
     
    11381117        """ 
    11391118        is_ok = True 
    1140         title = 'Modify %s axis label'% axis 
     1119        title = 'Modify %s axis label' % axis 
    11411120        font = 'serif' 
    11421121        colour = 'black' 
     
    11471126            label = self.yaxis_label 
    11481127            unit = self.yaxis_unit 
    1149         textdial = TextDialog(None, -1, title, label, unit)  
     1128        textdial = TextDialog(None, -1, title, label, unit) 
    11501129        if textdial.ShowModal() == wx.ID_OK: 
    11511130            try: 
     
    11601139                is_tick = textdial.getTickLabel() 
    11611140                label_temp = textdial.getText() 
    1162                 if label_temp.count("\%s"% "\\") > 0: 
     1141                if label_temp.count("\%s" % "\\") > 0: 
    11631142                    if self.parent != None: 
    11641143                        from sans.guiframe.events import StatusEvent  
    1165                         msg= "Add Label: Error. Can not use double '\\' " 
     1144                        msg = "Add Label: Error. Can not use double '\\' " 
    11661145                        msg += "characters..." 
    1167                         wx.PostEvent(self.parent, StatusEvent(status = msg )) 
     1146                        wx.PostEvent(self.parent, StatusEvent(status=msg)) 
    11681147                else: 
    11691148                    label = label_temp 
    11701149            except: 
    11711150                if self.parent != None: 
    1172                     from sans.guiframe.events import StatusEvent  
    1173                     msg= "Add Label: Error. Check your property values..." 
    1174                     wx.PostEvent(self.parent, StatusEvent(status = msg )) 
     1151                    from sans.guiframe.events import StatusEvent 
     1152                    msg = "Add Label: Error. Check your property values..." 
     1153                    wx.PostEvent(self.parent, StatusEvent(status=msg)) 
    11751154                else: 
    11761155                    pass 
     
    11891168        if num_text < 1: 
    11901169            if self.parent != None: 
    1191                 from sans.guiframe.events import StatusEvent  
     1170                from sans.guiframe.events import StatusEvent 
    11921171                msg= "Remove Text: Nothing to remove.  " 
    1193                 wx.PostEvent(self.parent, StatusEvent(status = msg )) 
     1172                wx.PostEvent(self.parent, StatusEvent(status=msg)) 
    11941173            else: 
    11951174                raise 
     
    12001179            txt.remove() 
    12011180            if self.parent != None: 
    1202                 from sans.guiframe.events import StatusEvent  
     1181                from sans.guiframe.events import StatusEvent 
    12031182                msg= "Removed Text: '%s'. " % text_remove 
    1204                 wx.PostEvent(self.parent, StatusEvent(status = msg )) 
     1183                wx.PostEvent(self.parent, StatusEvent(status=msg)) 
    12051184        except: 
    12061185            if self.parent != None: 
    1207                 from sans.guiframe.events import StatusEvent  
     1186                from sans.guiframe.events import StatusEvent 
    12081187                msg= "Remove Text: Error occurred. " 
    1209                 wx.PostEvent(self.parent, StatusEvent(status = msg )) 
     1188                wx.PostEvent(self.parent, StatusEvent(status=msg)) 
    12101189            else: 
    12111190                raise 
    12121191        self.textList.remove(txt) 
    12131192             
    1214         self.subplot.figure.canvas.draw_idle()  
     1193        self.subplot.figure.canvas.draw_idle() 
    12151194 
    12161195    def properties(self, prop): 
     
    12201199         
    12211200        """ 
    1222         # The particulars of how they are stored and manipulated (e.g., do  
     1201        # The particulars of how they are stored and manipulated (e.g., do 
    12231202        # we want an inventory internally) is not settled.  I've used a 
    12241203        # property dictionary for now. 
     
    12311210        self.subplot.set_ylabel(r"$%s$" % prop["ylabel"]) 
    12321211        self.subplot.set_title(prop["title"]) 
    1233  
    1234         # Properties defined by user 
    1235         #self.axes.grid(True) 
    12361212 
    12371213    def clear(self): 
     
    12451221        """Commit the plot after all objects are drawn""" 
    12461222        # TODO: this is when the backing store should be swapped in. 
    1247         if self.legend_on:           
     1223        if self.legend_on: 
    12481224            ax = self.subplot 
    12491225            ax.texts = self.textList 
     
    12551231                handles2, labels2 = zip(*hl) 
    12561232                self.line_collections_list = handles2 
    1257                 self.legend = ax.legend(handles2, labels2,  numpoints=1, 
    1258                                 prop=FontProperties(size=10),  
     1233                self.legend = ax.legend(handles2, labels2, numpoints=1, 
     1234                                prop=FontProperties(size=10), 
    12591235                                handletextsep=.05, loc=self.legendLoc) 
    12601236                if self.legend != None: 
    12611237                    self.legend.set_picker(self.legend_picker) 
    1262                     self.legend.set_axes(self.subplot)  
     1238                    self.legend.set_axes(self.subplot) 
    12631239                 
    12641240            except: 
    1265                 self.legend = ax.legend(prop=FontProperties(size=10),  numpoints=1, 
    1266                                 handletextsep=.05, loc=self.legendLoc) 
     1241                self.legend = ax.legend(prop=FontProperties(size=10), 
     1242                                        numpoints=1, handletextsep=.05, 
     1243                                        loc=self.legendLoc) 
    12671244                  
    12681245    def xaxis(self, label, units, font=None, color='black', t_font=None): 
     
    12761253         
    12771254        """ 
    1278         if units != "":  
     1255        if units != "": 
    12791256            label = label + " (" + units + ")" 
    12801257        if label.count("{") > 0 and label.count("$") < 2: 
     
    12841261            if t_font != None: 
    12851262                for tick in self.subplot.xaxis.get_major_ticks(): 
    1286                     tick.label.set_fontproperties(t_font)  
     1263                    tick.label.set_fontproperties(t_font) 
    12871264                for line in self.subplot.xaxis.get_ticklines(): 
    12881265                    size = t_font.get_size() 
    12891266                    line.set_markersize(size / 3) 
    1290                     #line.set_markeredgewidth(int(size / 24 + 1)) 
    12911267        else: 
    12921268            self.subplot.set_xlabel(label, color=color) 
     
    12951271    def yaxis(self, label, units, font=None, color='black', t_font=None): 
    12961272        """yaxis label and units.""" 
    1297         if units != "":  
     1273        if units != "": 
    12981274            label = label + " (" + units + ")" 
    12991275        if label.count("{") > 0 and label.count("$") < 2: 
     
    13111287        pass 
    13121288 
    1313     def _connect_to_xlim(self,callback): 
     1289    def _connect_to_xlim(self, callback): 
    13141290        """Bind the xlim change notification to the callback""" 
    13151291        def process_xlim(axes): 
     
    13171293            callback(lo, hi) 
    13181294        self.subplot.callbacks.connect('xlim_changed', process_xlim) 
    1319      
    1320     #def connect(self,trigger,callback): 
    1321     #    print "PlotPanel.connect???" 
    1322     #    if trigger == 'xlim': self._connect_to_xlim(callback) 
    13231295 
    13241296    def interactive_points(self, x, y, dx=None, dy=None, name='', color=0, 
    1325                            symbol=0, markersize=5, id=None, label=None, hide_error=False): 
     1297                           symbol=0, markersize=5, id=None, label=None, 
     1298                           hide_error=False): 
    13261299        """Draw markers with error bars""" 
    13271300        self.subplot.set_yscale('linear') 
     
    13361309                 hide_error=hide_error) 
    13371310         
    1338         self.subplot.set_yscale(self.yscale,nonposy='clip') 
     1311        self.subplot.set_yscale(self.yscale, nonposy='clip') 
    13391312        self.subplot.set_xscale(self.xscale) 
    13401313        
    1341      
    1342     def interactive_curve(self,x,y,dy=None,name='',color=0,symbol=0,id=None,label=None): 
     1314    def interactive_curve(self, x, y, dy=None, name='', color=0, 
     1315                          symbol=0, id=None, label=None): 
    13431316        """Draw markers with error bars""" 
    13441317        self.subplot.set_yscale('linear') 
     
    13501323        p.curve(x, y, dy=dy, color=color, symbol=symbol, label=label) 
    13511324         
    1352         self.subplot.set_yscale(self.yscale,nonposy='clip') 
     1325        self.subplot.set_yscale(self.yscale, nonposy='clip') 
    13531326        self.subplot.set_xscale(self.xscale) 
    13541327         
    1355  
    13561328    def plottable_selected(self, id): 
    13571329        """ 
     
    13621334 
    13631335    def points(self, x, y, dx=None, dy=None, 
    1364                color=0, symbol=0, marker_size=5, label=None,id=None,  hide_error=False): 
     1336               color=0, symbol=0, marker_size=5, label=None, 
     1337               id=None, hide_error=False): 
    13651338        """Draw markers with error bars""" 
    1366         #self.subplot.set_yscale('linear') 
    1367         #self.subplot.set_xscale('linear') 
    13681339         
    13691340        # Convert tuple (lo,hi) to array [(x-lo),(hi-x)] 
     
    13771348                                   linestyle='', 
    13781349                                   label=label) 
    1379              
    13801350        else: 
    13811351            col = self._color(color) 
    13821352            if hide_error: 
    13831353                h = self.subplot.plot(x, y, color=col, 
    1384                                    marker=self._symbol(symbol), markersize=marker_size, 
     1354                                   marker=self._symbol(symbol), 
     1355                                   markersize=marker_size, 
    13851356                                   linestyle='', 
    13861357                                   label=label) 
    1387                  
    13881358            else: 
    1389                 h= self.subplot.errorbar(x, y, yerr=dy, xerr=None, 
    1390                                   ecolor=col, capsize=2, linestyle='',  
     1359                h = self.subplot.errorbar(x, y, yerr=dy, xerr=None, 
     1360                                  ecolor=col, capsize=2, linestyle='', 
    13911361                                  barsabove=False, 
    13921362                                  mec=col, mfc=col, 
     
    14231393                zmax_2D_temp = math.log10(self.zmax_2D) 
    14241394                  
    1425         self.image(data=self.data, qx_data=self.qx_data,  
    1426                    qy_data=self.qy_data, xmin=self.xmin_2D,  
     1395        self.image(data=self.data, qx_data=self.qx_data, 
     1396                   qy_data=self.qy_data, xmin=self.xmin_2D, 
    14271397                   xmax=self.xmax_2D, 
    1428                    ymin=self.ymin_2D, ymax=self.ymax_2D,  
     1398                   ymin=self.ymin_2D, ymax=self.ymax_2D, 
    14291399                   cmap=self.cmap, zmin=zmin_2D_temp, 
    14301400                   zmax=zmax_2D_temp) 
    14311401       
    1432     def image(self, data, qx_data, qy_data, xmin, xmax, ymin, ymax,  
    1433               zmin, zmax, color=0, symbol=0, markersize=0, label='data2D', cmap=DEFAULT_CMAP): 
     1402    def image(self, data, qx_data, qy_data, xmin, xmax, ymin, ymax, 
     1403              zmin, zmax, color=0, symbol=0, markersize=0, 
     1404              label='data2D', cmap=DEFAULT_CMAP): 
    14341405        """ 
    14351406        Render the current data 
     
    14431414        self.ymin_2D = ymin 
    14441415        self.ymax_2D = ymax 
    1445         self.zmin_2D = zmin  
     1416        self.zmin_2D = zmin 
    14461417        self.zmax_2D = zmax 
    14471418        c = self._color(color) 
     
    14491420        if self.data == None: 
    14501421            return 
    1451         if self.data.ndim == 1:     
     1422        if self.data.ndim == 1: 
    14521423            output = self._build_matrix() 
    14531424        else: 
     
    14561427        if self.scale == 'log_{10}': 
    14571428            try: 
    1458                 if  self.zmin_2D  <= 0  and len(output[output > 0]) > 0: 
    1459                     zmin_temp = self.zmin_2D  
     1429                if  self.zmin_2D <= 0  and len(output[output > 0]) > 0: 
     1430                    zmin_temp = self.zmin_2D 
    14601431                    output[output>0] = numpy.log10(output[output>0]) 
    14611432                    #In log scale Negative values are not correct in general 
    14621433                    #output[output<=0] = math.log(numpy.min(output[output>0])) 
    1463                 elif self.zmin_2D  <= 0: 
     1434                elif self.zmin_2D <= 0: 
    14641435                    zmin_temp = self.zmin_2D 
    1465                     output[output>0] = numpy.zeros(len(output))   
    1466                     output[output<=0] = -32        
     1436                    output[output>0] = numpy.zeros(len(output)) 
     1437                    output[output<=0] = -32 
    14671438                else:  
    14681439                    zmin_temp = self.zmin_2D 
     
    14811452            self.subplot.figure.subplots_adjust(left=0.2, right=.8, bottom=.2) 
    14821453             
    1483             im = self.subplot.imshow(output, interpolation='nearest',  
     1454            im = self.subplot.imshow(output, interpolation='nearest', 
    14841455                                     origin='lower', 
    14851456                                     vmin=zmin_temp, vmax=self.zmax_2D, 
    1486                                      cmap=self.cmap,  
     1457                                     cmap=self.cmap, 
    14871458                                     extent=(self.xmin_2D, self.xmax_2D, 
    14881459                                                self.ymin_2D, self.ymax_2D)) 
     
    14941465            self.subplot.figure.clear() 
    14951466 
    1496             self.subplot.figure.subplots_adjust(left=0.1, right=.8, bottom=.1)   
     1467            self.subplot.figure.subplots_adjust(left=0.1, right=.8, bottom=.1) 
    14971468 
    14981469            X = self.x_bins[0:-1] 
     
    15141485                    logging.error("PlotPanel could not import Axes3D") 
    15151486                self.subplot.figure.clear() 
    1516                 ax =  Axes3D(self.subplot.figure) 
     1487                ax = Axes3D(self.subplot.figure) 
    15171488                if len(X) > 60: 
    15181489                    ax.cla() 
     
    15211492            im = ax.plot_surface(X, Y, output, rstride=1, cstride=1, cmap=cmap, 
    15221493                                   linewidth=0, antialiased=False) 
    1523             #ax.set_zlim3d(zmin_temp, self.zmax_2D) 
    1524             #ax.set_frame_on(False) 
    1525             self.subplot.set_axis_off()   
     1494            self.subplot.set_axis_off() 
    15261495             
    15271496        if cbax == None: 
    15281497            ax.set_frame_on(False) 
    1529             cb =self.subplot.figure.colorbar(im, shrink=0.8, aspect=20) 
     1498            cb = self.subplot.figure.colorbar(im, shrink=0.8, aspect=20) 
    15301499        else: 
    1531             cb =self.subplot.figure.colorbar(im, cax=cbax) 
     1500            cb = self.subplot.figure.colorbar(im, cax=cbax) 
    15321501        cb.update_bruteforce(im) 
    15331502        cb.set_label('$' + self.scale + '$') 
     
    15381507     
    15391508    def _build_matrix(self): 
    1540         """  
     1509        """ 
    15411510        Build a matrix for 2d plot from a vector 
    15421511        Returns a matrix (image) with ~ square binning 
    1543         Requirement: need 1d array formats of  
     1512        Requirement: need 1d array formats of 
    15441513        self.data, self.qx_data, and self.qy_data 
    15451514        where each one corresponds to z, x, or y axis values 
     
    15611530        #Note: Can not use scipy.interpolate.Rbf: 
    15621531        # 'cause too many data points (>10000)<=JHC. 
    1563         # 1d array to use for weighting the data point averaging  
    1564         #when they fall into a same bin.           
    1565         weights_data  = numpy.ones([self.data.size]) 
    1566         # get histogram of ones w/len(data); this will provide  
     1532        # 1d array to use for weighting the data point averaging 
     1533        #when they fall into a same bin. 
     1534        weights_data = numpy.ones([self.data.size]) 
     1535        # get histogram of ones w/len(data); this will provide 
    15671536        #the weights of data on each bins 
    1568         weights, xedges, yedges = numpy.histogram2d(x=self.qy_data,  
     1537        weights, xedges, yedges = numpy.histogram2d(x=self.qy_data, 
    15691538                                                    y=self.qx_data, 
    1570                                                 bins=[self.y_bins, self.x_bins], 
    1571                                                     weights=weights_data) 
     1539                                            bins=[self.y_bins, self.x_bins], 
     1540                                            weights=weights_data) 
    15721541        # get histogram of data, all points into a bin in a way of summing 
    1573         image, xedges, yedges = numpy.histogram2d(x=self.qy_data,  
     1542        image, xedges, yedges = numpy.histogram2d(x=self.qy_data, 
    15741543                                                  y=self.qx_data, 
    1575                                                 bins=[self.y_bins, self.x_bins], 
    1576                                                 weights=self.data) 
     1544                                            bins=[self.y_bins, self.x_bins], 
     1545                                            weights=self.data) 
    15771546        # Now, normalize the image by weights only for weights>1:  
    15781547        # If weight == 1, there is only one data point in the bin so 
    15791548        # that no normalization is required. 
    1580         image[weights>1] = image[weights>1]/weights[weights>1] 
     1549        image[weights > 1] = image[weights>1]/weights[weights>1] 
    15811550        # Set image bins w/o a data point (weight==0) as None (was set to zero 
    15821551        # by histogram2d.) 
    1583         image[weights==0] = None 
     1552        image[weights == 0] = None 
    15841553 
    15851554        # Fill empty bins with 8 nearest neighbors only when at least 
     
    15871556        loop = 0 
    15881557         
    1589         # do while loop until all vacant bins are filled up up  
     1558        # do while loop until all vacant bins are filled up up 
    15901559        #to loop = max_loop 
    15911560        while(not(numpy.isfinite(image[weights == 0])).all()): 
    1592             if loop >= max_loop: # this protects never-ending loop 
     1561            if loop >= max_loop:  # this protects never-ending loop 
    15931562                break 
    15941563            image = self._fillup_pixels(image=image, weights=weights) 
     
    15971566        return image 
    15981567     
    1599     def _get_bins(self):  
     1568    def _get_bins(self): 
    16001569        """ 
    16011570        get bins 
    1602         set x_bins and y_bins into self, 1d arrays of the index with  
     1571        set x_bins and y_bins into self, 1d arrays of the index with 
    16031572        ~ square binning 
    1604         Requirement: need 1d array formats of  
     1573        Requirement: need 1d array formats of 
    16051574        self.qx_data, and self.qy_data 
    16061575        where each one corresponds to  x, or y axis values 
    1607          
    16081576        """ 
    16091577        # No qx or qy given in a vector format 
     
    16241592        y_size = ymax - ymin 
    16251593         
    1626         # estimate the # of pixels on each axes   
     1594        # estimate the # of pixels on each axes 
    16271595        npix_y = int(math.floor(math.sqrt(len(self.qy_data)))) 
    16281596        npix_x = int(math.floor(len(self.qy_data) / npix_y)) 
    16291597 
    1630         # bin size: x- & y-directions      
     1598        # bin size: x- & y-directions 
    16311599        xstep = x_size / (npix_x - 1) 
    16321600        ystep = y_size / (npix_y - 1) 
     
    16401608        # store x and y bin centers in q space 
    16411609        x_bins = numpy.arange(xmin, xmax + xstep / 10, xstep) 
    1642         y_bins = numpy.arange(ymin, ymax + ystep / 10, ystep)  
     1610        y_bins = numpy.arange(ymin, ymax + ystep / 10, ystep) 
    16431611       
    16441612        #set x_bins and y_bins 
    1645         self.x_bins = x_bins  
    1646         self.y_bins = y_bins  
    1647  
    1648     def _fillup_pixels(self, image=None, weights=None):  
    1649         """ 
    1650         Fill z values of the empty cells of 2d image matrix  
     1613        self.x_bins = x_bins 
     1614        self.y_bins = y_bins 
     1615 
     1616    def _fillup_pixels(self, image=None, weights=None): 
     1617        """ 
     1618        Fill z values of the empty cells of 2d image matrix 
    16511619        with the average over up-to next nearest neighbor points 
    16521620         
     
    16911659                    # go 4 next nearest neighbors when no non-zero 
    16921660                    # neighbor exists 
    1693                     #if weight[n_y][n_x] == 0: 
    16941661                    if n_y != 0 and n_x != 0 and\ 
    16951662                         numpy.isfinite(image[n_y-1][n_x-1]): 
     
    17211688        self.subplot.set_xscale('linear') 
    17221689         
    1723         hlist = self.subplot.plot(x, y, color=c, marker='',  
    1724                                   linestyle='-', label=label) 
     1690        self.subplot.plot(x, y, color=c, marker='', 
     1691                          linestyle='-', label=label) 
    17251692        self.subplot.set_yscale(self.yscale) 
    17261693        self.subplot.set_xscale(self.xscale) 
     
    17281695    def _color(self, c): 
    17291696        """Return a particular colour""" 
    1730         return self.colorlist[c%len(self.colorlist)] 
     1697        return self.colorlist[c % len(self.colorlist)] 
    17311698 
    17321699    def _symbol(self, s): 
    17331700        """Return a particular symbol""" 
    1734         return self.symbollist[s%len(self.symbollist)] 
     1701        return self.symbollist[s % len(self.symbollist)] 
    17351702    
    17361703    def _replot(self, remove_fit=False): 
     
    17531720        Receive the x and y transformation from myDialog, 
    17541721        Transforms x and y in View 
    1755         and set the scale     
    1756         """  
     1722        and set the scale 
     1723        """ 
    17571724        # The logic should be in the right order 
    17581725        # Delete first, and then get the whole list... 
     
    17631730        list = self.graph.returnPlottable() 
    17641731        # Changing the scale might be incompatible with 
    1765         # currently displayed data (for instance, going  
     1732        # currently displayed data (for instance, going 
    17661733        # from ln to log when all plotted values have 
    1767         # negative natural logs).  
     1734        # negative natural logs). 
    17681735        # Go linear and only change the scale at the end. 
    17691736        self.set_xscale("linear") 
     
    17891756                self.xaxis_label = xname 
    17901757                self.xaxis_unit = xunits 
    1791             # Goes through all possible scales     
     1758            # Goes through all possible scales 
    17921759            if(self.xLabel == "x"): 
    17931760                item.transformX(transform.toX, transform.errToX) 
     
    17951762            if(self.xLabel == "x^(2)"): 
    17961763                item.transformX(transform.toX2, transform.errToX2) 
    1797                 xunits = convertUnit(2,xunits)  
     1764                xunits = convertUnit(2, xunits) 
    17981765                self.graph._xaxis_transformed("%s^{2}" % xname, "%s" % xunits) 
    17991766            if(self.xLabel == "x^(4)"): 
    18001767                item.transformX(transform.toX4, transform.errToX4) 
    1801                 xunits = convertUnit(4,xunits)  
     1768                xunits = convertUnit(4, xunits) 
    18021769                self.graph._xaxis_transformed("%s^{4}" % xname, "%s" % xunits) 
    18031770            if(self.xLabel == "ln(x)"): 
    1804                 item.transformX(transform.toLogX,transform.errToLogX) 
    1805                 self.graph._xaxis_transformed("\ln\\ %s" % xname, "%s" % xunits)  
     1771                item.transformX(transform.toLogX, transform.errToLogX) 
     1772                self.graph._xaxis_transformed("\ln\\ %s" % xname, "%s" % xunits) 
    18061773            if(self.xLabel == "log10(x)"): 
    18071774                item.transformX(transform.toX_pos, transform.errToX_pos) 
     
    18101777            if(self.xLabel == "log10(x^(4))"): 
    18111778                item.transformX(transform.toX4, transform.errToX4) 
    1812                 xunits = convertUnit(4,xunits)  
     1779                xunits = convertUnit(4, xunits) 
    18131780                self.graph._xaxis_transformed("%s^{4}" % xname, "%s" % xunits) 
    18141781                _xscale = 'log' 
     
    18191786                item.transformY(transform.toX, transform.errToX) 
    18201787                self.graph._yaxis_transformed("%s" % yname, "%s" % yunits) 
    1821             if(self.yLabel == "log10(y)"):  
     1788            if(self.yLabel == "log10(y)"): 
    18221789                item.transformY(transform.toX_pos, transform.errToX_pos) 
    1823                 _yscale = 'log'   
     1790                _yscale = 'log' 
    18241791                self.graph._yaxis_transformed("%s" % yname, "%s" % yunits) 
    18251792            if(self.yLabel == "y^(2)"): 
    1826                 item.transformY(transform.toX2, transform.errToX2)     
    1827                 yunits = convertUnit(2, yunits)  
     1793                item.transformY(transform.toX2, transform.errToX2) 
     1794                yunits = convertUnit(2, yunits) 
    18281795                self.graph._yaxis_transformed("%s^{2}" % yname, "%s" % yunits) 
    18291796            if(self.yLabel == "1/y"): 
     
    18331800            if(self.yLabel == "y*x^(4)"): 
    18341801                item.transformY(transform.toYX4, transform.errToYX4) 
    1835                 xunits = convertUnit(4, self.xaxis_unit)  
    1836                 self.graph._yaxis_transformed("%s \ \ %s^{4}" % (yname,xname),  
    1837                                                "%s%s" % (yunits,xunits)) 
     1802                xunits = convertUnit(4, self.xaxis_unit) 
     1803                self.graph._yaxis_transformed("%s \ \ %s^{4}" % (yname, xname), 
     1804                                               "%s%s" % (yunits, xunits)) 
    18381805            if(self.yLabel == "1/sqrt(y)"): 
    18391806                item.transformY(transform.toOneOverSqrtX, 
    1840                                 transform.errOneOverSqrtX ) 
     1807                                transform.errOneOverSqrtX) 
    18411808                yunits = convertUnit(-0.5, yunits) 
    1842                 self.graph._yaxis_transformed("1/\sqrt{%s}" %yname, "%s" % yunits) 
     1809                self.graph._yaxis_transformed("1/\sqrt{%s}" % yname, 
     1810                                              "%s" % yunits) 
    18431811            if(self.yLabel == "ln(y*x)"): 
    18441812                item.transformY(transform.toLogXY, transform.errToLogXY) 
    1845                 self.graph._yaxis_transformed("\ln (%s \ \ %s)" % (yname,xname), 
    1846                                                 "%s%s" % (yunits, self.xaxis_unit)) 
     1813                self.graph._yaxis_transformed("\ln (%s \ \ %s)" % (yname, xname), 
     1814                                            "%s%s" % (yunits, self.xaxis_unit)) 
    18471815            if(self.yLabel == "ln(y*x^(2))"): 
    18481816                item.transformY( transform.toLogYX2, transform.errToLogYX2)  
    1849                 xunits = convertUnit(2, self.xaxis_unit)  
    1850                 self.graph._yaxis_transformed("\ln (%s \ \ %s^{2})" % (yname,xname),  
    1851                                                "%s%s" % (yunits,xunits)) 
     1817                xunits = convertUnit(2, self.xaxis_unit) 
     1818                self.graph._yaxis_transformed("\ln (%s \ \ %s^{2})" % (yname, xname), 
     1819                                               "%s%s" % (yunits, xunits)) 
    18521820            if(self.yLabel == "ln(y*x^(4))"): 
    18531821                item.transformY(transform.toLogYX4, transform.errToLogYX4) 
    1854                 xunits = convertUnit(4, self.xaxis_unit)  
    1855                 self.graph._yaxis_transformed("\ln (%s \ \ %s^{4})" % (yname,xname),  
    1856                                                "%s%s" % (yunits,xunits)) 
     1822                xunits = convertUnit(4, self.xaxis_unit) 
     1823                self.graph._yaxis_transformed("\ln (%s \ \ %s^{4})" % (yname, xname), 
     1824                                               "%s%s" % (yunits, xunits)) 
    18571825            if(self.yLabel == "log10(y*x^(4))"): 
    18581826                item.transformY(transform.toYX4, transform.errToYX4) 
    1859                 xunits = convertUnit(4, self.xaxis_unit)  
    1860                 _yscale = 'log'  
    1861                 self.graph._yaxis_transformed("%s \ \ %s^{4}" % (yname,xname),  
    1862                                                "%s%s" % (yunits,xunits)) 
     1827                xunits = convertUnit(4, self.xaxis_unit) 
     1828                _yscale = 'log' 
     1829                self.graph._yaxis_transformed("%s \ \ %s^{4}" % (yname, xname), 
     1830                                               "%s%s" % (yunits, xunits)) 
    18631831            if(self.viewModel == "Guinier lny vs x^(2)"): 
    18641832                item.transformX(transform.toX2, transform.errToX2) 
    1865                 xunits = convertUnit(2, xunits)  
    1866                 self.graph._xaxis_transformed("%s^{2}" % xname,  "%s" % xunits) 
    1867                 item.transformY(transform.toLogX,transform.errToLogX ) 
    1868                 self.graph._yaxis_transformed("\ln\ \ %s" % yname,  "%s" % yunits) 
     1833                xunits = convertUnit(2, xunits) 
     1834                self.graph._xaxis_transformed("%s^{2}" % xname, "%s" % xunits) 
     1835                item.transformY(transform.toLogX,transform.errToLogX) 
     1836                self.graph._yaxis_transformed("\ln\ \ %s" % yname, "%s" % yunits) 
    18691837            if(self.viewModel == "Porod y*x^(4) vs x^(4)"): 
    18701838                item.transformX(transform.toX4, transform.errToX4) 
    1871                 xunits = convertUnit(4, self.xaxis_unit)  
     1839                xunits = convertUnit(4, self.xaxis_unit) 
    18721840                self.graph._xaxis_transformed("%s^{4}" % xname, "%s" % xunits) 
    18731841                item.transformY(transform.toYX4, transform.errToYX4) 
    1874                 self.graph._yaxis_transformed("%s \ \ %s^{4}" % (yname,xname),  
    1875                                                "%s%s" % (yunits,xunits)) 
     1842                self.graph._yaxis_transformed("%s \ \ %s^{4}" % (yname, xname), 
     1843                                               "%s%s" % (yunits, xunits)) 
    18761844            item.transformView() 
    18771845   
     
    18811849        xname = self.graph.prop["xlabel"] 
    18821850        xunits = '' 
    1883         #self.yaxis_label = yname 
    1884         #self.yaxis_unit = yunits 
    1885         #self.xaxis_label = xname 
    1886         #self.xaxis_unit = xunits 
    18871851                 
    1888         self.resetFitView()    
    1889         self.prevXtrans = self.xLabel  
    1890         self.prevYtrans = self.yLabel   
     1852        self.resetFitView() 
     1853        self.prevXtrans = self.xLabel 
     1854        self.prevYtrans = self.yLabel 
    18911855        self.graph.render(self) 
    18921856        self.set_xscale(_xscale) 
    18931857        self.set_yscale(_yscale) 
    18941858         
    1895         self.xaxis(xname, xunits, self.xaxis_font,  
     1859        self.xaxis(xname, xunits, self.xaxis_font, 
    18961860                   self.xaxis_color, self.xaxis_tick) 
    1897         self.yaxis(yname, yunits, self.yaxis_font,  
     1861        self.yaxis(yname, yunits, self.yaxis_font, 
    18981862                   self.yaxis_color, self.yaxis_tick) 
    18991863        self.subplot.texts = self.textList 
    19001864        self.subplot.figure.canvas.draw_idle() 
    19011865         
    1902     def onFitDisplay(self, tempx, tempy, xminView,  
     1866    def onFitDisplay(self, tempx, tempy, xminView, 
    19031867                     xmaxView, xmin, xmax, func): 
    19041868        """ 
     
    19281892            item.onFitRange(None, None) 
    19291893        # Create new data plottable with result 
    1930         self.fit_result.x = []  
     1894        self.fit_result.x = [] 
    19311895        self.fit_result.y = [] 
    1932         self.fit_result.x = tempx   
    1933         self.fit_result.y = tempy      
     1896        self.fit_result.x = tempx 
     1897        self.fit_result.y = tempy 
    19341898        self.fit_result.dx = None 
    19351899        self.fit_result.dy = None 
    19361900        #Load the view with the new values 
    19371901        self.fit_result.reset_view() 
    1938         # Add the new plottable to the graph  
    1939         self.graph.add(self.fit_result)  
     1902        # Add the new plottable to the graph 
     1903        self.graph.add(self.fit_result) 
    19401904        self.graph.render(self) 
    19411905        self._offset_graph() 
     
    19521916        dial = LabelDialog(None, -1, 'Modify Window Title', old_caption) 
    19531917        if dial.ShowModal() == wx.ID_OK: 
    1954             new_caption = dial.getText()  
     1918            new_caption = dial.getText() 
    19551919           
    19561920            # send to guiframe to change the panel caption 
    1957             caption = self.parent.on_change_caption(self.window_name,  
    1958                                                     old_caption, new_caption)  
     1921            caption = self.parent.on_change_caption(self.window_name, 
     1922                                                    old_caption, new_caption) 
    19591923             
    19601924            # also set new caption in plot_panels list 
     
    19671931    def onResetGraph(self, event): 
    19681932        """ 
    1969         Reset the graph by plotting the full range of data  
     1933        Reset the graph by plotting the full range of data 
    19701934        """ 
    19711935        list = [] 
     
    20121976            print "Error in copy Image" 
    20131977 
    2014  
    2015              
    2016 #---------------------------------------------------------------         
     1978  
     1979#--------------------------------------------------------------- 
    20171980class NoRepaintCanvas(FigureCanvasWxAgg): 
    20181981    """ 
     
    20361999            self.realize() 
    20372000        if self._drawn < 2: 
    2038             self.draw(repaint = False) 
     2001            self.draw(repaint=False) 
    20392002            self._drawn += 1 
    20402003        self.gui_repaint(drawDC=wx.PaintDC(self)) 
    2041             
    2042  
  • plottools/src/danse/common/plottools/PropertyDialog.py

    rb4da6df r10bfeb3  
    1 #!/usr/bin/python 
    2  
    3 # myDialog.py 
    41""" 
    52""" 
     
    1512        """ 
    1613        self.parent = parent 
    17         vbox  = wx.BoxSizer(wx.VERTICAL) 
     14        vbox = wx.BoxSizer(wx.VERTICAL) 
    1815        sizer = wx.GridBagSizer(5,5) 
    1916 
     
    4239        x_size += self.view.GetSize()[0] 
    4340        self.view.SetMinSize((160, 30)) 
    44         sizer.Add(self.view, (iy,ix), (1,1),  
     41        sizer.Add(self.view, (iy,ix), (1,1), 
    4542                  wx.EXPAND|wx.RIGHT|wx.ADJUST_MINSIZE, 10) 
    4643        self.SetMinSize((x_size, 50)) 
     
    5249        sizer_button.Add((20, 20), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
    5350        sizer_button.Add(btOk, 0, wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10) 
    54         sizer_button.Add(btCancel, 0, wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)         
    55         vbox.Add(sizer_button, 0,  
     51        sizer_button.Add(btCancel, 0, wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10) 
     52        vbox.Add(sizer_button, 0, 
    5653                 wx.EXPAND|wx.TOP|wx.BOTTOM|wx.ADJUST_MINSIZE, 10) 
    5754        # scale value for x 
     
    7774        self.yvalue.Insert("ln(y*x^(4))", 9) 
    7875        self.yvalue.Insert("log10(y*x^(4))", 10) 
    79         # type of view or model used  
     76        # type of view or model used 
    8077        self.view.SetValue("--") 
    8178        self.view.Insert("--", 0) 
     
    8380        self.view.Insert("Porod y*x^(4) vs x^(4)", 2) 
    8481        self.SetSizer(vbox) 
    85         self.Fit()         
     82        self.Fit() 
    8683        self.Centre() 
    8784            
     
    9794        return self.xvalue.GetValue(), self.yvalue.GetValue(),\ 
    9895                            self.view.GetValue() 
    99          
    100  
    101 if __name__ == "__main__":  
    102     app = wx.App() 
    103     dialog = Properties(None, -1, 'Properties') 
    104     dialog.ShowModal() 
    105     app.MainLoop() 
    106  
    107  
  • plottools/src/danse/common/plottools/SizeDialog.py

    r82a54b8 r10bfeb3  
    11import wx 
     2 
    23 
    34class SizeDialog(wx.Dialog): 
     
    56        wx.Dialog.__init__(self, parent, id, title, size=(300, 175)) 
    67 
    7         #panel = wx.Panel(self, -1) 
    8          
    98        mainbox = wx.BoxSizer(wx.VERTICAL) 
    109        vbox = wx.BoxSizer(wx.VERTICAL) 
     
    1211        hbox = wx.BoxSizer(wx.HORIZONTAL) 
    1312        text1 = "Enter in a custom size (float values > 0 accepted)" 
    14         msg = wx.StaticText(self, -1, text1,(30,15), style=wx.ALIGN_CENTRE) 
     13        msg = wx.StaticText(self, -1, text1, (30,15), style=wx.ALIGN_CENTRE) 
    1514        msg.SetLabel(text1) 
    1615        self.myTxtCtrl = wx.TextCtrl(self, -1, '', (100, 50)) 
    1716         
    18         textbox.Add(self.myTxtCtrl, flag=wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE,  
     17        textbox.Add(self.myTxtCtrl, flag=wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 
    1918                 border=10, proportion=2) 
    2019        vbox.Add(msg, flag=wx.ALL, border=10, proportion=1) 
     
    2322        self.myTxtCtrl.SetValue(str(10)) 
    2423         
    25         okButton = wx.Button(self,wx.ID_OK, 'OK', size=(70, 25)) 
    26         closeButton = wx.Button(self,wx.ID_CANCEL, 'Cancel', size=(70, 25)) 
     24        okButton = wx.Button(self, wx.ID_OK, 'OK', size=(70, 25)) 
     25        closeButton = wx.Button(self, wx.ID_CANCEL, 'Cancel', size=(70, 25)) 
    2726 
    2827        hbox.Add(okButton) 
    29         hbox.Add((20,20)) 
     28        hbox.Add((20, 20)) 
    3029        hbox.Add(closeButton) 
    3130         
    3231        mainbox.Add(vbox, flag=wx.ALL, border=10) 
    3332        mainbox.Add(wx.StaticLine(self), 0, wx.ALL|wx.EXPAND, 5) 
    34         mainbox.Add(hbox, flag=wx.CENTER,  
     33        mainbox.Add(hbox, flag=wx.CENTER, 
    3534                    border=10) 
    3635        self.SetSizer(mainbox) 
     
    4140        """ 
    4241        return self.myTxtCtrl.GetValue() 
    43      
  • plottools/src/danse/common/plottools/TextDialog.py

    rf80236f r10bfeb3  
    1010FAMILY = ['serif', 'sans-serif', 'fantasy', 'monospace'] 
    1111SIZE = [8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72] 
    12 STYLE  = ['normal', 'italic'] 
     12STYLE = ['normal', 'italic'] 
    1313WEIGHT = ['light', 'normal', 'bold'] 
    1414COLOR = ['black', 'blue', 'green', 'red', 'cyan', 'magenta', 'yellow'] 
     15 
    1516 
    1617class TextDialog(wx.Dialog): 
     
    3637        _BOX_WIDTH = 60 
    3738        font_size = 12 
    38         font_description= wx.StaticBox(self, -1, 'Font',  
     39        font_description= wx.StaticBox(self, -1, 'Font', 
    3940                                       size=(PNL_WIDTH-20, 70)) 
    4041        font_box = wx.StaticBoxSizer(font_description, wx.VERTICAL) 
     
    7374            else: 
    7475                enter_text += ":" 
    75         self.textString  = wx.TextCtrl(self, -1, size=(PNL_WIDTH-30, height ),\ 
     76        self.textString = wx.TextCtrl(self, -1, size=(PNL_WIDTH-30, height ),\ 
    7677                                                        style=styles) 
    7778        self.textString.SetValue(str(label)) 
    7879        self.textString.SetToolTipString("The text that will be displayed.") 
    7980        #font family 
    80         self.fontFamily =  wx.ComboBox(self, -1, style=wx.CB_READONLY) 
     81        self.fontFamily = wx.ComboBox(self, -1, style=wx.CB_READONLY) 
    8182        wx.EVT_COMBOBOX(self.fontFamily, -1, self.on_family) 
    8283        self.fontFamily.SetMinSize((_BOX_WIDTH, -1)) 
     
    8586        self.fontFamily.SetToolTipString("Font family of the text.") 
    8687        #font weight 
    87         self.fontWeight =  wx.ComboBox(self, -1, style=wx.CB_READONLY) 
     88        self.fontWeight = wx.ComboBox(self, -1, style=wx.CB_READONLY) 
    8889        wx.EVT_COMBOBOX(self.fontWeight, -1, self.on_weight) 
    8990        self.fontWeight.SetMinSize((_BOX_WIDTH, -1)) 
     
    9293        self.fontWeight.SetToolTipString("Font weight of the text.") 
    9394        #font family 
    94         self.fontSize =  wx.ComboBox(self, -1, style=wx.CB_READONLY) 
     95        self.fontSize = wx.ComboBox(self, -1, style=wx.CB_READONLY) 
    9596        wx.EVT_COMBOBOX(self.fontSize, -1, self.on_size) 
    9697        self.fontSize.SetMinSize((_BOX_WIDTH, -1)) 
     
    99100        self.fontSize.SetToolTipString("Font size of the text.") 
    100101        #font style 
    101         self.fontStyle =  wx.ComboBox(self, -1, style=wx.CB_READONLY) 
     102        self.fontStyle = wx.ComboBox(self, -1, style=wx.CB_READONLY) 
    102103        wx.EVT_COMBOBOX(self.fontStyle, -1, self.on_style) 
    103104        self.fontStyle.SetMinSize((_BOX_WIDTH, -1)) 
     
    106107        self.fontStyle.SetToolTipString("Font style of the text.") 
    107108        #font color 
    108         self.fontColor =  wx.ComboBox(self, -1, style=wx.CB_READONLY) 
     109        self.fontColor = wx.ComboBox(self, -1, style=wx.CB_READONLY) 
    109110        wx.EVT_COMBOBOX(self.fontColor, -1, self.on_color) 
    110111        self.fontColor.SetMinSize((_BOX_WIDTH, -1)) 
     
    115116        self.static_line_1 = wx.StaticLine(self, -1) 
    116117        self.okButton = wx.Button(self,wx.ID_OK, 'OK', size=(_BOX_WIDTH, 25)) 
    117         self.closeButton = wx.Button(self,wx.ID_CANCEL, 'Cancel',  
     118        self.closeButton = wx.Button(self,wx.ID_CANCEL, 'Cancel', 
    118119                                     size=(_BOX_WIDTH, 25)) 
    119120         
    120121        # Intro 
    121         explanation  = "Select font properties :" 
     122        explanation = "Select font properties :" 
    122123        vbox.Add(sizer) 
    123124        ix = 0 
     
    131132        family_box.Add(self.fontSize, -1, 0) 
    132133        if unit_box != None: 
    133             family_box.Add((_BOX_WIDTH/2,-1)) 
     134            family_box.Add((_BOX_WIDTH/2, -1)) 
    134135            family_box.Add(tick_label_text, -1, 0) 
    135136            family_box.Add(self.tick_label_check, -1, 0) 
     
    152153        sizer.Add(wx.StaticText(self, -1, enter_text), (iy, ix), 
    153154                 (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
    154         text_box.Add((15,10)) 
     155        text_box.Add((15, 10)) 
    155156        text_box.Add(self.textString) 
    156157        vbox.Add(text_box, 0, wx.EXPAND, 15) 
     
    161162            vbox.Add(unit_box, 0,wx.LEFT, 15) 
    162163         
    163         vbox.Add((10,10)) 
     164        vbox.Add((10, 10)) 
    164165        vbox.Add(self.static_line_1, 0, wx.EXPAND, 10) 
    165166        sizer_button = wx.BoxSizer(wx.HORIZONTAL) 
     
    168169                         wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10) 
    169170        sizer_button.Add(self.closeButton, 0, 
    170                           wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)         
     171                          wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10) 
    171172        vbox.Add(sizer_button, 0, wx.EXPAND|wx.BOTTOM|wx.TOP, 10) 
    172173        self.SetSizer(vbox) 
     
    180181        list = FAMILY 
    181182        for idx in range(len(list)): 
    182             self.fontFamily.Append(list[idx],idx)   
     183            self.fontFamily.Append(list[idx], idx) 
    183184                  
    184185    def _set_size_list(self): 
     
    198199        list = WEIGHT 
    199200        for idx in range(len(list)): 
    200             self.fontWeight.Append(list[idx],idx)  
     201            self.fontWeight.Append(list[idx], idx) 
    201202             
    202203    def _set_style_list(self): 
     
    207208        list = STYLE 
    208209        for idx in range(len(list)): 
    209             self.fontStyle.Append(list[idx],idx)   
     210            self.fontStyle.Append(list[idx], idx) 
    210211             
    211212    def _set_color_list(self): 
     
    216217        list = COLOR 
    217218        for idx in range(len(list)): 
    218             self.fontColor.Append(list[idx],idx)  
     219            self.fontColor.Append(list[idx], idx) 
    219220             
    220221    def on_tick_label(self, event): 
     
    230231        """ 
    231232        event.Skip() 
    232         self.family = self.fontFamily.GetValue()  
     233        self.family = self.fontFamily.GetValue() 
    233234                  
    234235    def on_style(self, event): 
     
    251252        """ 
    252253        event.Skip() 
    253         self.size = self.fontSize.GetValue()  
     254        self.size = self.fontSize.GetValue() 
    254255     
    255256    def on_color(self, event): 
     
    258259        """ 
    259260        event.Skip() 
    260         self.color = self.fontColor.GetValue()  
     261        self.color = self.fontColor.GetValue() 
    261262            
    262263    def getText(self): 
     
    294295        Returns font tyle for the text box 
    295296        """ 
    296         return str(self.style)   
     297        return str(self.style) 
    297298 
    298299    def getWeight(self): 
  • plottools/src/danse/common/plottools/binder.py

    r0e553fd r10bfeb3  
    22Extension to MPL to support the binding of artists to key/mouse events. 
    33""" 
     4import sys 
     5 
    46 
    57class Selection: 
     
    1214    artist = None 
    1315    prop = {} 
     16     
    1417    def __init__(self, artist=None, prop={}): 
    1518        self.artist, self.prop = artist, self.prop 
     
    2326    def __nonzero__(self): 
    2427        return self.artist is not None 
     28 
    2529 
    2630class BindArtist: 
     
    6670            ] 
    6771             
    68  
    69         # Turn off picker if it hasn't already been done 
    70         #try: 
    71         #    canvas.mpl_disconnect(canvas.button_pick_id) 
    72         #    canvas.mpl_disconnect(canvas.scroll_pick_id) 
    73         #except:  
    74         #    pass 
    7572        self._current = None 
    7673        self._actions = {} 
     
    121118        In case we need to disconnect from the canvas... 
    122119        """ 
    123         try:  
     120        try: 
    124121            for cid in self._connections: self.canvas.mpl_disconnect(cid) 
    125         except:  
     122        except: 
     123            print "Error disconnection canvas: %s" % sys.exc_value 
    126124            pass 
    127125        self._connections = [] 
     
    165163            shift,control,alt,meta are flags which are true if the 
    166164                corresponding key is pressed at the time of the event. 
    167             details is a dictionary of artist specific details, such as the  
     165            details is a dictionary of artist specific details, such as the 
    168166                id(s) of the point that were clicked. 
    169167                 
     
    182180        TODO: Attach multiple callbacks to the same event? 
    183181        TODO: Clean up interaction with toolbar modes 
    184         TODO: push/pushclear/pop context so that binding changes for  
     182        TODO: push/pushclear/pop context so that binding changes for 
    185183             the duration 
    186184        TODO:   e.g., to support ? context sensitive help 
     
    193191        # Register the trigger callback 
    194192        self._actions[trigger][artist] = action 
    195         #print "==> added",artist,[artist],"to",trigger,":", 
    196         #self._actions[trigger].keys() 
    197193 
    198194        # Maintain a list of all artists 
    199         if artist not in self._artists:  
     195        if artist not in self._artists: 
    200196            self._artists.append(artist) 
    201197 
     
    239235        # TODO: sort by zorder of axes then by zorder within axes 
    240236        self._artists.sort(cmp=lambda x, y: cmp(y.zorder, x.zorder)) 
    241         # print "search"," ".join([str(h) for h in self._artists]) 
    242237        found = Selection() 
    243         #print "searching in",self._artists 
    244238        for artist in self._artists: 
    245239            # TODO: should contains() return false if invisible? 
    246             if not artist.get_visible():  
     240            if not artist.get_visible(): 
    247241                continue 
    248242            # TODO: optimization - exclude artists not inaxes 
     
    255249                found.artist, found.prop = artist, prop 
    256250                break 
    257         #print "found",found.artist 
    258251         
    259252        # TODO: how to check if prop is equal? 
     
    296289                x, y = transform.inverse_xy_tup((x, y)) 
    297290 
    298                 
    299291            event.xdata, event.ydata = x, y 
    300292            self.trigger(self._hasclick, 'drag', event) 
    301293        else: 
    302294            found = self._find_current(event) 
    303             #print "found",found.artist 
    304295            self.trigger(found, 'motion', event) 
    305296 
     
    312303        # Check for double-click 
    313304        event_time = time.time() 
    314         #print event_time,self._last_time,self.dclick_threshhold 
    315         #print (event_time > self._last_time + self.dclick_threshhold) 
    316         #print event.button,self._last_button 
    317305        if (event.button != self._last_button) or \ 
    318306                (event_time > self._last_time + self.dclick_threshhold): 
     
    376364        # TODO: Can we tab between items? 
    377365        # TODO: How do unhandled events get propogated to axes, figure and 
    378         # TODO: finally to application?  Do we need to implement a full tags  
     366        # TODO: finally to application?  Do we need to implement a full tags 
    379367        # TODO: architecture a la Tk? 
    380368        # TODO: Do modifiers cause a grab?  Does the artist see the modifiers? 
     
    408396        found = self._find_current(event) 
    409397        self.trigger(found, 'scroll', event) 
    410  
  • plottools/src/danse/common/plottools/canvas.py

    r4a4164c r10bfeb3  
    11""" 
    2 This module implements a faster canvas for plotting.  
     2This module implements a faster canvas for plotting. 
    33it ovewrites some matplolib methods to allow printing on sys.platform=='win32' 
    44""" 
     
    2727    """ 
    2828    pass 
    29 #print "overriding select" 
    30 def select(self):  
    31     """ 
    32     """ 
    33     #print "in new select" 
     29 
     30 
     31def select(self): 
     32    """ 
     33    """ 
    3434    pass 
    3535 
     36 
    3637def unselect(self): 
    3738    """ 
     
    3940    pass 
    4041 
     42 
    4143def OnPrintPage(self, page): 
    4244    """ 
    43     override printPage of matplotlib  
     45    override printPage of matplotlib 
    4446    """ 
    4547    self.canvas.draw() 
    46     dc        = self.GetDC() 
     48    dc = self.GetDC() 
    4749    try: 
    4850        (ppw, pph) = self.GetPPIPrinter()      # printer's pixels per in 
     
    6163 
    6264    # draw the bitmap, scaled appropriately 
    63     vscale    = float(ppw) / fig_dpi  
     65    vscale = float(ppw) / fig_dpi 
    6466 
    6567    # set figure resolution,bg color for printer 
     
    6769    self.canvas.figure.set_facecolor('#FFFFFF') 
    6870 
    69     renderer  = RendererWx(self.canvas.bitmap, self.canvas.figure.dpi) 
     71    renderer = RendererWx(self.canvas.bitmap, self.canvas.figure.dpi) 
    7072    self.canvas.figure.draw(renderer) 
    71     self.canvas.bitmap.SetWidth(  int(self.canvas.bitmap.GetWidth() * vscale)) 
    72     self.canvas.bitmap.SetHeight( int(self.canvas.bitmap.GetHeight()* vscale)) 
     73    self.canvas.bitmap.SetWidth(int(self.canvas.bitmap.GetWidth() * vscale)) 
     74    self.canvas.bitmap.SetHeight(int(self.canvas.bitmap.GetHeight() * vscale)) 
    7375    self.canvas.draw() 
    7476 
    7577    # page may need additional scaling on preview 
    7678    page_scale = 1.0 
    77     if self.IsPreview():   page_scale = float(dcw)/pgw 
     79    if self.IsPreview(): 
     80        page_scale = float(dcw)/pgw 
    7881 
    7982    # get margin in pixels = (margin in in) * (pixels/in) 
    80     top_margin  = int(self.margin * pph * page_scale) 
     83    top_margin = int(self.margin * pph * page_scale) 
    8184    left_margin = int(self.margin * ppw * page_scale) 
    8285 
    8386    # set scale so that width of output is self.width inches 
    8487    # (assuming grw is size of graph in inches....) 
    85     user_scale = (self.width * fig_dpi * page_scale)/float(grw) 
     88    user_scale = (self.width * fig_dpi * page_scale) / float(grw) 
    8689    dc.SetDeviceOrigin(left_margin, top_margin) 
    8790    dc.SetUserScale(user_scale, user_scale) 
     
    108111RendererBase.draw_image = draw_image 
    109112 
     113 
    110114class FigureCanvas(FigureCanvasWxAgg): 
    111115    """ 
    112116    Add features to the wx agg canvas for better support of AUI and 
    113117    faster plotting. 
    114      
    115118    """ 
    116119 
     
    136139    def set_panel(self, panel): 
    137140        """ 
    138         Set axes  
     141        Set axes 
    139142        """ 
    140143        # set panel 
     
    158161        if False and wx.GetApp().Pending(): 
    159162            self.idletimer.Restart(5, *args, **kwargs) 
    160         else:            
     163        else: 
    161164            # Draw plot, changes resizing too 
    162165            self.draw(*args, **kwargs) 
    163             self.resizing = False   
     166            self.resizing = False 
    164167             
    165     def _get_axes_switch(self):     
     168    def _get_axes_switch(self): 
    166169        """ 
    167170        """ 
     
    182185        self.set_resizing(False) 
    183186         
    184     def set_resizing(self, resizing=False):   
    185         """ 
    186         Setting the resizing  
    187         """   
     187    def set_resizing(self, resizing=False): 
     188        """ 
     189        Setting the resizing 
     190        """ 
    188191        self.resizing = resizing 
    189192        self.panel.set_resizing(False) 
     
    222225 
    223226        # Convert delta/rotation/rate into a floating point step size 
    224         delta = evt.GetWheelDelta()  
     227        delta = evt.GetWheelDelta() 
    225228        rotation = evt.GetWheelRotation() 
    226229        rate = evt.GetLinesPerAction() 
     
    237240        scroll wheel event.  x,y are the canvas coords: 0,0 is lower, 
    238241        left.  button and key are as defined in MouseEvent 
    239          
    240242        """ 
    241243        button = 'up' if step >= 0 else 'down' 
     
    262264            # This solves the focusing on rightclick. 
    263265            # Todo: better design 
    264             self.panel.parent.set_plot_unfocus()  
     266            self.panel.parent.set_plot_unfocus() 
    265267            self.panel.on_set_focus(None) 
    266268         
  • plottools/src/danse/common/plottools/config.py

    rcd8d4a7 r10bfeb3  
    5252    # if a backend has already been selected, make sure it is the correct one. 
    5353    raise ImportError("Matplotlib not using backend " + plot_backend) 
    54  
  • plottools/src/danse/common/plottools/fitDialog.py

    r82a54b8 r10bfeb3  
    1 #!/usr/bin/python 
    2  
    3 # fitDialog.py 
    4  
    51import wx 
    6 #from PlotPanel import PlotPanel 
    72from plottables import Theory1D 
    8 import math, numpy, fittings 
     3import math 
     4import numpy 
     5import fittings 
    96import transform 
    107import sys 
     
    1815    PNL_WIDTH = 450 
    1916     
     17     
    2018def format_number(value, high=False): 
    2119    """ 
    22     Return a float in a standardized, human-readable formatted string  
     20    Return a float in a standardized, human-readable formatted string 
    2321    """ 
    24     try:  
     22    try: 
    2523        value = float(value) 
    2624    except: 
     
    3634 
    3735 
    38  
    3936class LinearFit(wx.Dialog): 
    40     def __init__(self, parent, plottable, push_data,transform, title): 
     37    def __init__(self, parent, plottable, push_data, transform, title): 
    4138        """ 
    4239        Dialog window pops- up when select Linear fit on Context menu 
     
    107104         
    108105        # Intro 
    109         explanation  = "Perform fit for y(x) = Ax + B" 
     106        explanation = "Perform fit for y(x) = Ax + B" 
    110107        vbox.Add(sizer) 
    111108        ix = 0 
     
    122119                  (iy, ix), (1, 1), wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
    123120        ix += 1 
    124         sizer.Add(self.tcErrA, (iy, ix), (1, 1),  
     121        sizer.Add(self.tcErrA, (iy, ix), (1, 1), 
    125122                  wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
    126123        iy += 1 
     
    167164                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15) 
    168165        ix += 1 
    169         sizer.Add(self.xminFit, (iy, ix),(1,1), 
     166        sizer.Add(self.xminFit, (iy, ix), (1, 1), 
    170167                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
    171168        ix += 2 
     
    179176        sizer_button.Add(self.btFit, 0, wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10) 
    180177        sizer_button.Add(self.btClose, 0, 
    181                           wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)         
     178                          wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10) 
    182179        vbox.Add(sizer_button, 0, wx.EXPAND|wx.BOTTOM|wx.TOP, 10) 
    183180         
     
    190187        self.model = LineModel() 
    191188        #Display the fittings values 
    192         self.default_A = self.model.getParam('A')  
    193         self.default_B = self.model.getParam('B')  
     189        self.default_A = self.model.getParam('A') 
     190        self.default_B = self.model.getParam('B') 
    194191        self.cstA = fittings.Parameter(self.model, 'A', self.default_A) 
    195192        self.cstB = fittings.Parameter(self.model, 'B', self.default_B) 
     
    198195        if self.Avalue == None: 
    199196            self.tcA.SetValue(format_number(self.default_A)) 
    200         else : 
     197        else: 
    201198            self.tcA.SetLabel(format_number(self.Avalue)) 
    202199        if self.Bvalue == None: 
     
    231228            self.initXmin.SetValue(format_number(min(self.plottable.x))) 
    232229            self.initXmax.SetValue(format_number(max(self.plottable.x))) 
    233             #self.xminFit.SetLabel(format_number(self.mini)) 
    234             #self.xmaxFit.SetLabel(format_number(self.maxi)) 
    235230            self.mini = min(self.x) 
    236231            self.maxi = max(self.x) 
     
    251246    def _on_close(self, event): 
    252247        """ 
    253         Close event.  
     248        Close event. 
    254249        Notify registered owner if available. 
    255250        """ 
     
    263258        the button Fit.Computes chisqr , 
    264259        A and B parameters of the best linear fit y=Ax +B 
    265         Push a plottable to  
     260        Push a plottable to 
    266261        """ 
    267262        tempx = [] 
     
    271266        # Check if View contains a x array .we online fit when x exits 
    272267        # makes transformation for y as a line to fit 
    273         if self.x != []:  
     268        if self.x != []: 
    274269            if(self.checkFitValues(self.xminFit) == True): 
    275270                #Check if the field of Fit Dialog contain values 
     
    278273                #self.xmaxFit.GetValue()) 
    279274                if not self._checkVal(self.xminFit, self.xmaxFit): 
    280                     return  
     275                    return 
    281276                xminView = float(self.xminFit.GetValue()) 
    282277                xmaxView = float(self.xmaxFit.GetValue()) 
     
    291286                        for i in range(len(self.x)): 
    292287                            if self.x[i] >= math.log10(xmin): 
    293                                 tempy.append(math.log10(self.y[i]))  
     288                                tempy.append(math.log10(self.y[i])) 
    294289                                tempdy.append(transform.errToLogX(self.y[i], 
    295290                                                        0, self.dy[i], 0)) 
    296291                    else: 
    297292                        for i in range(len(self.y)): 
    298                             tempy.append(math.log10(self.y[i]))  
     293                            tempy.append(math.log10(self.y[i])) 
    299294                            tempdy.append(transform.errToLogX(self.y[i], 
    300295                                                            0, self.dy[i], 0)) 
     
    306301                    for x_i in self.x: 
    307302                        if x_i >= math.log10(xmin): 
    308                             tempx.append(math.log10(x_i))  
     303                            tempx.append(math.log10(x_i)) 
    309304                else: 
    310305                    tempx = self.x 
    311306               
    312307                #Find the fitting parameters 
    313                 # Always use the same defaults, so that fit history  
    314                 #doesn't play a role!  
     308                # Always use the same defaults, so that fit history 
     309                #doesn't play a role! 
    315310                self.cstA = fittings.Parameter(self.model, 'A', self.default_A) 
    316311                self.cstB = fittings.Parameter(self.model, 'B', self.default_B) 
     
    328323                    tempdy = numpy.asarray(tempdy) 
    329324                    tempdy[tempdy == 0] = 1 
    330                     chisqr, out, cov = fittings.sansfit(self.model,  
     325                    chisqr, out, cov = fittings.sansfit(self.model, 
    331326                                                        [self.cstA, self.cstB], 
    332327                                                        tempx, tempy, tempdy, 
     
    349344                    cstA = out[0] 
    350345                    cstB = out[1] 
    351                 # Reset model with the right values of A and B  
     346                # Reset model with the right values of A and B 
    352347                self.model.setParam('A', float(cstA)) 
    353348                self.model.setParam('B', float(cstB)) 
     
    380375                if self.yLabel == "log10(y)": 
    381376                    tempy.append(math.pow(10, y_model)) 
    382                 else:  
     377                else: 
    383378                    tempy.append(y_model) 
    384379                #Set the fit parameter display when  FitDialog is opened again 
     
    396391    def _onsetValues(self, cstA, cstB, errA, errB, Chi): 
    397392        """ 
    398         Display  the value on fit Dialog  
    399          
     393        Display  the value on fit Dialog 
    400394        """ 
    401395        self.tcA.SetValue(format_number(cstA)) 
     
    407401    def _ongetValues(self): 
    408402        """ 
    409         Display  the value on fit Dialog  
     403        Display  the value on fit Dialog 
    410404        """ 
    411405        return self.Avalue, self.Bvalue, self.ErrAvalue, \ 
     
    414408    def _checkVal(self, usermin, usermax): 
    415409        """ 
    416         Ensure that fields parameter contains a min and a max value  
     410        Ensure that fields parameter contains a min and a max value 
    417411        within x min and x max range 
    418412        """ 
     
    420414        self.maxi = float(self.xmaxFit.GetValue()) 
    421415        flag = True 
    422         try:  
     416        try: 
    423417            mini = float(usermin.GetValue()) 
    424418            maxi = float(usermax.GetValue()) 
     
    446440        if(self.xLabel == "x"): 
    447441            return transform.toX(x) 
    448         if(self.xLabel == "x^(2)"):  
     442        if(self.xLabel == "x^(2)"): 
    449443            return transform.toX2(x) 
    450444        if(self.xLabel == "ln(x)"): 
     
    463457        if(self.xLabel == "x"): 
    464458            return transform.toX(x) 
    465         if(self.xLabel == "x^(2)"):  
     459        if(self.xLabel == "x^(2)"): 
    466460            return transform.toX2(x) 
    467461        if(self.xLabel == "ln(x)"): 
     
    471465                return x 
    472466            else: 
    473                 raise ValueError,"cannot compute log of a negative number" 
     467                raise ValueError, "cannot compute log of a negative number" 
    474468             
    475469    def floatInvTransform(self, x): 
    476470        """ 
    477         transform a float.It is use to determine the x.View min and x.View  
     471        transform a float.It is use to determine the x.View min and x.View 
    478472        max for values not in x 
    479473         
     
    482476        # functionality work without rewritting the whole code 
    483477        # with good design (which really should be done...). 
    484         if(self.xLabel == "x^(2)"):  
     478        if(self.xLabel == "x^(2)"): 
    485479            return math.sqrt(x) 
    486480         
     
    488482            return math.pow(10, x) 
    489483         
    490         elif(self.xLabel == "ln(x)"):  
     484        elif(self.xLabel == "ln(x)"): 
    491485            return math.exp(x) 
    492486        return x 
     
    499493        value = item.GetValue() 
    500494        # Check for possible values entered 
    501         if (self.xLabel == "log10(x)") :#or self.xLabel=="ln(x)"): 
     495        if (self.xLabel == "log10(x)")#or self.xLabel=="ln(x)"): 
    502496            if(float(value) > 0): 
    503497                item.SetBackgroundColour(wx.WHITE) 
     
    520514        Set the fit region 
    521515        :param xmin: minimum x-value to be included in fit 
    522         :param xmax: maximum x-value to be included in fit  
     516        :param xmax: maximum x-value to be included in fit 
    523517        """ 
    524518        # Check values 
     
    532526        self.xmaxFit.SetValue(format_number(xmax)) 
    533527   
     528   
    534529class MyApp(wx.App): 
    535530    """ 
     
    540535        wx.InitAllImageHandlers() 
    541536        plot = Theory1D([], []) 
    542         dialog = LinearFit(parent=None, plottable=plot,  
     537        dialog = LinearFit(parent=None, plottable=plot, 
    543538                           push_data=self.onFitDisplay, 
    544                            transform=self.returnTrans,  
     539                           transform=self.returnTrans, 
    545540                            title='Linear Fit') 
    546541        if dialog.ShowModal() == wx.ID_OK: 
     
    558553        """ 
    559554        return '', '', 0, 0, 0, 0, 0 
    560  
    561 # end of class MyApp 
    562  
    563 if __name__ == "__main__": 
    564     app = MyApp(0) 
    565     app.MainLoop() 
  • plottools/src/danse/common/plottools/fittings.py

    rcfe1feb r10bfeb3  
    22""" 
    33from scipy import optimize 
    4 #from numpy import * 
     4 
    55 
    66class Parameter: 
     
    2121 
    2222    def __call__(self): 
    23         """  
     23        """ 
    2424            Return the current value of the parameter 
    2525        """ 
    2626        return self.model.getParam(self.name) 
     27     
    2728     
    2829def sansfit(model, pars, x, y, err_y , qmin=None, qmax=None): 
     
    3435    :param x: vector of x data 
    3536    :param y: vector of y data 
    36     :param err_y: vector of y errors  
    37      
     37    :param err_y: vector of y errors 
    3838    """ 
    3939    def f(params): 
    4040        """ 
    41         Calculates the vector of residuals for each point  
     41        Calculates the vector of residuals for each point 
    4242        in y for a given set of input parameters. 
    4343         
     
    7979        chisqr = chi2([out]) 
    8080         
    81     return chisqr, out, cov_x     
     81    return chisqr, out, cov_x 
     82 
    8283 
    8384def calcCommandline(event): 
     
    8586    # Fit a Line model 
    8687    from LineModel import LineModel 
    87     line    = LineModel() 
     88    line = LineModel() 
    8889    cstA = Parameter(line, 'A', event.cstA) 
    89     cstB  = Parameter(line, 'B', event.cstB)         
     90    cstB = Parameter(line, 'B', event.cstB) 
    9091    y = line.run() 
    91     chisqr, out, cov = sansfit(line, [cstA, cstB],  event.x, y, 0)  
     92    chisqr, out, cov = sansfit(line, [cstA, cstB], event.x, y, 0) 
    9293    # print "Output parameters:", out 
    9394    print "The right answer is [70.0, 1.0]" 
    9495    print chisqr, out, cov 
    95  
    96 if __name__ == "__main__":  
    97     calcCommandline() 
    98  
  • plottools/src/danse/common/plottools/plottable_interactor.py

    r82a54b8 r10bfeb3  
    1717        self.color = color 
    1818        self.colorlist = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] 
    19         self.symbollist = ['o', 'x', '^', 'v', '<', '>',  
    20                            '+', 's', 'd', 'D', 'h', 'H', 'p','-'] 
     19        self.symbollist = ['o', 'x', '^', 'v', '<', '>', 
     20                           '+', 's', 'd', 'D', 'h', 'H', 'p', '-'] 
    2121        self.markersize = None 
    2222        self.marker = None 
     
    3535        return self.symbollist[s % len(self.symbollist)] 
    3636 
    37     def points(self, x, y, dx=None, dy=None, color=0, symbol=0, markersize=5, label=None,  
    38                hide_error=False): 
     37    def points(self, x, y, dx=None, dy=None, color=0, symbol=0, markersize=5, 
     38               label=None, hide_error=False): 
    3939        """ 
    4040        """ 
     
    6666                zorder = 1 
    6767                self.marker = self.axes.plot(x, y, color=self.color, 
    68                                          marker=self._symbol(symbol), 
    69                                          markersize=markersize, 
    70                                          linestyle='', label=label, 
    71                                          zorder=zorder)[0] 
     68                                             marker=self._symbol(symbol), 
     69                                             markersize=markersize, 
     70                                             linestyle='', label=label, 
     71                                             zorder=zorder)[0] 
    7272            else: 
    7373                zorder = 2 
    7474                self.marker = self.axes.errorbar(x, y, yerr=dy, 
    75                                                   xerr=None, 
    76                                              ecolor=self.color,  
    77                                              color=self.color, 
    78                                              capsize=2,  
    79                                              linestyle='', 
    80                                             barsabove=False, 
    81                                             #mec=self.color, mfc=self.color, 
    82                                             marker=self._symbol(symbol), 
    83                                             markersize=markersize, 
    84                                             lolims=False, uplims=False, 
    85                                             xlolims=False, xuplims=False, 
    86                                             label=label, 
    87                                             zorder=zorder)[0] 
     75                                                 xerr=None, 
     76                                                 ecolor=self.color, 
     77                                                 color=self.color, 
     78                                                 capsize=2, 
     79                                                 linestyle='', 
     80                                                 barsabove=False, 
     81                                                 marker=self._symbol(symbol), 
     82                                                 markersize=markersize, 
     83                                                 lolims=False, uplims=False, 
     84                                                 xlolims=False, xuplims=False, 
     85                                                 label=label, 
     86                                                 zorder=zorder)[0] 
    8887             
    8988        self.connect_markers([self.marker]) 
     
    9695            self.base.connect.clear([self.marker]) 
    9796        self.color = self._color(color) 
    98         self.marker = self.axes.plot(x, y, color=self.color, lw = 1.5, 
     97        self.marker = self.axes.plot(x, y, color=self.color, lw=1.5, 
    9998                                     marker='', linestyle='-', label=label)[0] 
    10099             
     
    112111            connect('click', h, self._on_click) 
    113112            connect('release', h, self._on_release) 
    114             #connect('drag', h, self._on_drag) 
    115113            connect('key', h, self.onKey) 
    116114 
     
    128126            self._on_leave(evt) 
    129127 
    130     def _on_release(self, evt):  
     128    def _on_release(self, evt): 
    131129        """ 
    132130        Called when a mouse button is released 
    133131        within the boundaries of an artist 
    134132        """ 
    135         # Check to see whether we are about to pop  
     133        # Check to see whether we are about to pop 
    136134        # the context menu up 
    137135        if evt.button == 3: 
     
    148146            if evt.artist.get_color() == 'y': 
    149147                try: 
    150                      evt.artist.set_color('b') 
     148                    evt.artist.set_color('b') 
    151149                except: 
    152150                    evt.artist.set_color_cycle('b') 
     
    157155            else: 
    158156                try: 
    159                      evt.artist.set_color('y') 
     157                    evt.artist.set_color('y') 
    160158                except: 
    161159                    evt.artist.set_color_cycle('y') 
     
    181179                if hasattr(evt.artist, "set_facecolor"): 
    182180                    evt.artist.set_facecolor(self.color) 
    183                 if hasattr(evt.artist, "set_edgecolor"):             
     181                if hasattr(evt.artist, "set_edgecolor"): 
    184182                    evt.artist.set_edgecolor(self.color) 
    185183                self.axes.figure.canvas.draw_idle() 
     
    190188        """ 
    191189        pass 
    192  
  • plottools/src/danse/common/plottools/plottables.py

    r82a54b8 r10bfeb3  
    4444import copy 
    4545import numpy 
    46 import math 
    4746import sys 
    4847 
     
    5150    def any(L): 
    5251        for cond in L: 
    53             if cond: return True 
     52            if cond: 
     53                return True 
    5454        return False 
     55     
    5556    def all(L): 
    5657        for cond in L: 
     
    5960        return True 
    6061 
    61 # Graph structure for holding multiple plottables 
     62 
    6263class Graph: 
    6364    """ 
     
    129130        (as opposed to changing the basic properties) 
    130131        """ 
    131         if units != "":  
    132              name = "%s (%s)" % (name, units) 
     132        if units != "": 
     133            name = "%s (%s)" % (name, units) 
    133134        self.prop["xlabel"] = name 
    134135        self.prop["xunit"] = units 
     
    140141        (as opposed to changing the basic properties) 
    141142        """ 
    142         if units != "":  
    143              name = "%s (%s)" % (name, units) 
     143        if units != "": 
     144            name = "%s (%s)" % (name, units) 
    144145        self.prop["ylabel"] = name 
    145146        self.prop["yunit"] = units 
     
    149150        Properties of the x axis. 
    150151        """ 
    151         if units != "":  
    152              name = "%s (%s)" % (name, units) 
     152        if units != "": 
     153            name = "%s (%s)" % (name, units) 
    153154        self.prop["xlabel"] = name 
    154155        self.prop["xunit"] = units 
     
    160161        Properties of the y axis. 
    161162        """ 
    162         if units != "":  
    163              name = "%s (%s)" % (name, units) 
     163        if units != "": 
     164            name = "%s (%s)" % (name, units) 
    164165        self.prop["ylabel"] = name 
    165166        self.prop["yunit"] = units 
     
    200201        if plottable in self.plottables: 
    201202            return True 
    202         return False   
     203        return False 
    203204 
    204205    def add(self, plottable, color=None): 
     
    211212                self.color += plottable.colors() 
    212213                self.plottables[plottable] = self.color 
    213                  
     214 
    214215    def changed(self): 
    215216        """Detect if any graphed plottables have changed""" 
     
    250251        if plottable in self.plottables: 
    251252            del self.plottables[plottable] 
    252             self.color = len(self.plottables)  
     253            self.color = len(self.plottables) 
    253254             
    254255    def reset_scale(self): 
     
    263264        self.color = -1 
    264265        self.symbol = 0 
    265         self.prop = {"xlabel":"", "xunit":None, 
    266                      "ylabel":"","yunit":None, 
    267                      "title":""} 
     266        self.prop = {"xlabel": "", "xunit": None, 
     267                     "ylabel": "", "yunit": None, 
     268                     "title": ""} 
    268269        self.plottables = {} 
    269270     
     
    297298        """ 
    298299        This method returns a dictionary of plottables contained in graph 
    299         It is just by Plotpanel to interact with the complete list of plottables  
     300        It is just by Plotpanel to interact with the complete list of plottables 
    300301        inside the graph. 
    301302        """ 
     
    310311        for p in self.plottables: 
    311312            if p.custom_color is not None: 
    312                 p.render(plot, color=p.custom_color, symbol=0,  
     313                p.render(plot, color=p.custom_color, symbol=0, 
    313314                markersize=p.markersize, label=labels[p]) 
    314315            else: 
    315                 p.render(plot, color=self.plottables[p], symbol=0,  
     316                p.render(plot, color=self.plottables[p], symbol=0, 
    316317                     markersize=p.markersize, label=labels[p]) 
    317318        plot.render() 
     
    346347        menu for the graph. 
    347348         
    348     type: operational axis.  This determines whether the  
     349    type: operational axis.  This determines whether the 
    349350        transform should appear on x,y or z axis context 
    350351        menus, or if it should appear in the context menu for 
     
    353354    inventory: (not implemented)  
    354355        a dictionary of user settable parameter names and 
    355         their associated types.  These should appear as keyword  
    356         arguments to the transform call.  For example, Fresnel  
     356        their associated types.  These should appear as keyword 
     357        arguments to the transform call.  For example, Fresnel 
    357358        reflectivity requires the substrate density: 
    358359             { 'rho': type.Value(10e-6/units.angstrom**2) } 
    359360              
    360         Supply reasonable defaults in the callback so that  
    361         limited plotting clients work even though they cannot  
     361        Supply reasonable defaults in the callback so that 
     362        limited plotting clients work even though they cannot 
    362363        set the inventory. 
    363364         
     
    373374        the standard x,dx,y,dy,z,dz attributes appropriately. 
    374375         
    375         If the call raises a NotImplemented error the dataline  
     376        If the call raises a NotImplemented error the dataline 
    376377        will not be plotted.  The associated string will usually 
    377378        be 'Not a valid transform', though other strings are possible. 
     
    380381         
    381382        """ 
    382         raise NotImplemented,"Not a valid transform" 
     383        raise NotImplemented, "Not a valid transform" 
    383384 
    384385    # Related issues 
     
    387388    # log scale: 
    388389    #    All axes have implicit log/linear scaling options. 
    389     #  
     390    # 
    390391    # normalization: 
    391392    #    Want to display raw counts vs detector efficiency correction 
     
    401402    # 
    402403    # multiline graph: 
    403     #    How do we show/hide data parts.  E.g., data or theory, or  
     404    #    How do we show/hide data parts.  E.g., data or theory, or 
    404405    #    different polarization cross sections?  One way is with 
    405406    #    tags: each plottable has a set of tags and the tags are 
     
    420421    """ 
    421422    """ 
    422     # Short ascii name to refer to the plottable in a menu    
     423    # Short ascii name to refer to the plottable in a menu 
    423424    short_name = None 
    424425    # Fancy name 
     
    434435    interactive = True 
    435436    custom_color = None 
    436     markersize = 5 #default marker size is 'size 5' 
     437    markersize = 5  # default marker size is 'size 5' 
    437438     
    438439    def __init__(self): 
     
    441442        self._xunit = "" 
    442443        self._yaxis = "" 
    443         self._yunit = ""  
     444        self._yunit = "" 
    444445         
    445446    def __setattr__(self, name, value): 
     
    495496    def labels(cls, collection): 
    496497        """ 
    497         Construct a set of unique labels for a collection of plottables of  
     498        Construct a set of unique labels for a collection of plottables of 
    498499        the same type. 
    499500         
     
    509510            else: 
    510511                for i in xrange(len(collection)): 
    511                     map[collection[i]] = "%s %d"%(basename, i) 
     512                    map[collection[i]] = "%s %d" % (basename, i) 
    512513        return map 
     514 
    513515    ##Use the following if @classmethod doesn't work 
    514516    # labels = classmethod(labels) 
     
    526528    def set_View(self, x, y): 
    527529        """Load View""" 
    528         self.x= x 
     530        self.x = x 
    529531        self.y = y 
    530532        self.reset_view() 
     
    541543        """ 
    542544        The base class makes sure the correct units are being used for 
    543         subsequent plottable.   
    544          
    545         For now it is assumed that the graphs are commensurate, and if you  
     545        subsequent plottable. 
     546         
     547        For now it is assumed that the graphs are commensurate, and if you 
    546548        put a Qx object on a Temperature graph then you had better hope  
    547549        that it makes sense. 
     
    560562        return False 
    561563         
    562          
    563564    def colors(self): 
    564565        """Return the number of colors need to render the object""" 
     
    577578        return self.view.returnXview() 
    578579     
    579     def check_data_PlottableX(self):  
    580         """ 
    581         Since no transformation is made for log10(x), check that  
     580    def check_data_PlottableX(self): 
     581        """ 
     582        Since no transformation is made for log10(x), check that 
    582583        no negative values is plot in log scale 
    583584        """ 
    584585        self.view.check_data_logX() 
    585586         
    586     def check_data_PlottableY(self):  
     587    def check_data_PlottableY(self): 
    587588        """ 
    588589        Since no transformation is made for log10(y), check that  
    589590        no negative values is plot in log scale 
    590591        """ 
    591         self.view.check_data_logY()  
     592        self.view.check_data_logY() 
    592593         
    593594    def transformX(self, transx, transdx): 
    594595        """ 
    595         Receive pointers to function that transform x and dx  
     596        Receive pointers to function that transform x and dx 
    596597        and set corresponding View pointers 
    597598         
     
    604605    def transformY(self, transy, transdy): 
    605606        """ 
    606         Receive pointers to function that transform y and dy  
     607        Receive pointers to function that transform y and dy 
    607608        and set corresponding View pointers 
    608609         
     
    628629        """ 
    629630        self.view.onFitRangeView(xmin, xmax) 
    630          
     631     
     632     
    631633class View: 
    632634    """ 
     
    666668        :param x: array of x values 
    667669        :param y: array of y values 
    668         :param dx: array of  errors values on x  
     670        :param dx: array of  errors values on x 
    669671        :param dy: array of error values on y 
    670672         
     
    675677        has_err_y = not (dy == None or len(dy) == 0) 
    676678         
    677         if(x != None) and (y != None):  
    678             if not dx == None and not len(dx) == 0 and not len(x)== len(dx): 
     679        if(x != None) and (y != None): 
     680            if not dx == None and not len(dx) == 0 and not len(x) == len(dx): 
    679681                msg = "Plottable.View: Given x and dx are not" 
    680                 msg += " of the same length"  
     682                msg += " of the same length" 
    681683                raise ValueError, msg 
    682684            # Check length of y array 
     
    686688                raise ValueError, msg 
    687689         
    688             if not dy == None and not len(dy) == 0 and not len(y)==len(dy): 
     690            if not dy == None and not len(dy) == 0 and not len(y) == len(dy): 
    689691                msg = "Plottable.View: Given y and dy are not of the same " 
    690                 msg += "length: len(y)=%s, len(dy)=%s" %(len(y),len(dy)) 
     692                msg += "length: len(y)=%s, len(dy)=%s" % (len(y), len(dy)) 
    691693                raise ValueError, msg 
    692694            self.x = [] 
     
    708710            for i in range(len(x)): 
    709711                try: 
    710                     tempx =self.funcx(x[i],y[i]) 
    711                     tempy =self.funcy(y[i],x[i]) 
     712                    tempx = self.funcx(x[i], y[i]) 
     713                    tempy = self.funcy(y[i], x[i]) 
    712714                    if has_err_x: 
    713715                        tempdx = self.funcdx(x[i], y[i], dx[i], dy[i]) 
     
    727729            if not len(self.x) == len(self.y): 
    728730                msg = "Plottable.View: transformed x " 
    729                 msg += "and y are not of the same length"  
     731                msg += "and y are not of the same length" 
    730732                raise ValueError, msg 
    731733            if has_err_x and not (len(self.x) and len(self.dx)): 
    732734                msg = "Plottable.View: transformed x and dx" 
    733                 msg += " are not of the same length"  
     735                msg += " are not of the same length" 
    734736                raise ValueError, msg 
    735737            if has_err_y and not (len(self.y) and len(self.dy)): 
    736738                msg = "Plottable.View: transformed y" 
    737                 msg += " and dy are not of the same length"  
     739                msg += " and dy are not of the same length" 
    738740                raise ValueError, msg 
    739741            # Check that negative values are not plot on x and y axis for 
     
    750752        """ 
    751753        Reset x,y,dx and y in their full range  and in the initial scale 
    752         in case their previous range has changed   
    753          
     754        in case their previous range has changed 
    754755        """ 
    755756        self.x = self.Xreel 
     
    758759        self.dy = self.DYreel 
    759760         
    760     def setTransformX(self, funcx, funcdx):   
    761         """ 
    762         Receive pointers to function that transform x and dx  
     761    def setTransformX(self, funcx, funcdx): 
     762        """ 
     763        Receive pointers to function that transform x and dx 
    763764        and set corresponding View pointers 
    764765         
    765766        :param transx: pointer to function that transforms x 
    766767        :param transdx: pointer to function that transforms dx 
    767          
    768768        """ 
    769769        self.funcx = funcx 
     
    772772    def setTransformY(self, funcy, funcdy): 
    773773        """ 
    774         Receive pointers to function that transform y and dy  
     774        Receive pointers to function that transform y and dy 
    775775        and set corresponding View pointers 
    776776         
    777777        :param transx: pointer to function that transforms y 
    778778        :param transdx: pointer to function that transforms dy 
    779          
    780         """     
     779        """ 
    781780        self.funcy = funcy 
    782781        self.funcdy = funcdy 
     
    788787        return self.x, self.y, self.dx, self.dy 
    789788     
    790     def check_data_logX(self):  
     789    def check_data_logX(self): 
    791790        """ 
    792791        Remove negative value in x vector to avoid plotting negative 
    793792        value of Log10 
    794          
    795793        """ 
    796794        tempx = [] 
     
    802800        if self.dy == None: 
    803801            self.dy = numpy.zeros(len(self.y)) 
    804         if self.xLabel == "log10(x)" : 
     802        if self.xLabel == "log10(x)": 
    805803            for i in range(len(self.x)): 
    806804                try: 
     
    812810                except: 
    813811                    print "check_data_logX: skipping point x %g" % self.x[i] 
    814                     print sys.exc_value   
     812                    print sys.exc_value 
    815813                    pass  
    816814            self.x = tempx 
     
    819817            self.dy = tempdy 
    820818         
    821     def check_data_logY(self):  
    822         """ 
    823         Remove negative value in y vector  
     819    def check_data_logY(self): 
     820        """ 
     821        Remove negative value in y vector 
    824822        to avoid plotting negative value of Log10 
    825823         
     
    833831        if self.dy == None: 
    834832            self.dy = numpy.zeros(len(self.y)) 
    835         if (self.yLabel == "log10(y)" ): 
     833        if (self.yLabel == "log10(y)"): 
    836834            for i in range(len(self.x)): 
    837                  try: 
     835                try: 
    838836                    if (self.y[i] > 0): 
    839837                        tempx.append(self.x[i]) 
     
    841839                        tempy.append(self.y[i]) 
    842840                        tempdy.append(self.dy[i]) 
    843                  except: 
    844                     print "check_data_logY: skipping point %g" %self.y[i] 
    845                     print sys.exc_value   
     841                except: 
     842                    print "check_data_logY: skipping point %g" % self.y[i] 
     843                    print sys.exc_value 
    846844                    pass 
    847845            self.x = tempx 
     
    865863            self.dx = numpy.zeros(len(self.x)) 
    866864        if self.dy == None: 
    867             self.dy=numpy.zeros(len(self.y)) 
     865            self.dy = numpy.zeros(len(self.y)) 
    868866        if (xmin != None) and (xmax != None): 
    869867            for i in range(len(self.x)): 
     
    876874            self.y = tempy 
    877875            self.dx = tempdx 
    878             self.dy = tempdy  
    879                         
     876            self.dy = tempdy 
     877 
     878               
    880879class Data2D(Plottable): 
    881880    """ 
     
    910909        self._yunit = 'A^{-1}' 
    911910         
    912         ### might remove that later  
     911        ### might remove that later 
    913912        ## Vector of Q-values at the center of each bin in x 
    914913        self.x_bins = [] 
     
    10031002        plot.image(self.data, self.qx_data, self.qy_data, 
    10041003                   self.xmin, self.xmax, self.ymin, 
    1005                    self.ymax, self.zmin, self.zmax, **kw)     
     1004                   self.ymax, self.zmin, self.zmax, **kw) 
    10061005        
    10071006    def changed(self): 
     
    10211020            map[item] = item.label 
    10221021        return map 
     1022 
    10231023 
    10241024class Data1D(Plottable): 
     
    10601060        if self.interactive == True: 
    10611061            kw['symbol'] = self.symbol 
    1062             kw['id'] =  self.id 
     1062            kw['id'] = self.id 
    10631063            kw['hide_error'] = self.hide_error 
    10641064            kw['markersize'] = self.markersize 
    10651065            plot.interactive_points(self.view.x, self.view.y, 
    10661066                                    dx=self.view.dx, dy=self.view.dy, 
    1067               name=self.name, **kw)             
     1067              name=self.name, **kw) 
    10681068        else: 
    10691069            kw['id'] =  self.id 
     
    10721072            kw['color'] = self.custom_color 
    10731073            kw['markersize'] = self.markersize 
    1074             plot.points(self.view.x, self.view.y, dx=self.view.dx,  
     1074            plot.points(self.view.x, self.view.y, dx=self.view.dx, 
    10751075                dy=self.view.dy, marker=self.symbollist[self.symbol], **kw) 
    10761076        
     
    10891089            map[item] = item.label 
    10901090        return map 
     1091     
    10911092     
    10921093class Theory1D(Plottable): 
     
    11211122        """ 
    11221123        """ 
    1123         if self.interactive==True: 
    1124        
    1125             kw['id'] =  self.id 
     1124        if self.interactive == True: 
     1125            kw['id'] = self.id 
    11261126            plot.interactive_curve(self.view.x, self.view.y, 
    11271127                                   dy=self.view.dy, 
    11281128                                   name=self.name, **kw) 
    11291129        else: 
    1130             kw['id'] =  self.id 
     1130            kw['id'] = self.id 
    11311131            plot.curve(self.view.x, self.view.y, dy=self.view.dy, **kw) 
    11321132             
     
    11391139        map = {} 
    11401140        for item in collection: 
    1141             #map[item] = label(item, collection) 
    1142             #map[item] = r"$\rm{%s}$" % item.name 
    11431141            if item.label == "theory": 
    11441142                item.label = item.name 
     
    11751173        return self.data.changed() or self.theory.changed() 
    11761174 
     1175 
    11771176# --------------------------------------------------------------- 
    11781177class Text(Plottable): 
     
    11901189        self.ypos = ypos 
    11911190         
    1192     def render(self,plot,**kw): 
     1191    def render(self, plot, **kw): 
    11931192        """ 
    11941193        """ 
    11951194        from matplotlib import transforms 
    11961195 
    1197         xcoords=transforms.blended_transform_factory(plot.subplot.transAxes, 
    1198                                                      plot.subplot.transAxes) 
     1196        xcoords = transforms.blended_transform_factory(plot.subplot.transAxes, 
     1197                                                       plot.subplot.transAxes) 
    11991198        plot.subplot.text(self.xpos, 
    12001199                          self.ypos, 
     
    12061205    def setText(self, text): 
    12071206        """Set the text string.""" 
    1208         self.text =  text 
     1207        self.text = text 
    12091208 
    12101209    def getText(self, text): 
     
    12301229class Chisq(Plottable): 
    12311230    """ 
    1232     Chisq plottable plots the chisq  
     1231    Chisq plottable plots the chisq 
    12331232    """ 
    12341233    def __init__(self, chisq=None): 
     
    12651264        Set the chisq value. 
    12661265        """ 
    1267         self._chisq =  chisq 
     1266        self._chisq = chisq 
    12681267 
    12691268 
     
    12751274    # Construct a simple graph 
    12761275    if False: 
    1277         x = nx.array([1,2,3,4,5,6],'d') 
    1278         y = nx.array([4,5,6,5,4,5],'d') 
     1276        x = nx.array([1,2,3,4,5,6], 'd') 
     1277        y = nx.array([4,5,6,5,4,5], 'd') 
    12791278        dy = nx.array([0.2, 0.3, 0.1, 0.2, 0.9, 0.3]) 
    12801279    else: 
    1281         x = nx.linspace(0,1.,10000) 
     1280        x = nx.linspace(0, 1., 10000) 
    12821281        y = nx.sin(2 * nx.pi * x * 2.8) 
    12831282        dy = nx.sqrt(100 * nx.abs(y)) / 100 
     
    12891288    graph.add(data) 
    12901289    graph.add(Theory1D(x, y, dy=dy)) 
    1291     return graph  
     1290    return graph 
     1291 
    12921292 
    12931293def demo_plotter(graph): 
     
    13061306     
    13071307    class GraphUpdate: 
    1308         callnum=0 
     1308        callnum = 0 
     1309         
    13091310        def __init__(self, graph, plotter): 
    13101311            self.graph, self.plotter = graph, plotter 
     1312         
    13111313        def __call__(self): 
    1312             if self.graph.changed():  
     1314            if self.graph.changed(): 
    13131315                self.graph.render(self.plotter) 
    13141316                return True 
    13151317            return False 
     1318         
    13161319        def onIdle(self, event): 
    1317             #print "On Idle checker %d"%(self.callnum) 
    13181320            self.callnum = self.callnum + 1 
    13191321            if self.__call__():  
    1320                 pass # event.RequestMore() 
     1322                pass  # event.RequestMore() 
    13211323    update = GraphUpdate(graph, plotter) 
    13221324    frame.Bind(wx.EVT_IDLE, update.onIdle) 
    13231325    app.MainLoop() 
    1324  
    1325 import sys; print sys.version 
    1326 if __name__ == "__main__": 
    1327     demo_plotter(sample_graph()) 
    1328      
  • plottools/src/danse/common/plottools/toolbar.py

    r82a54b8 r10bfeb3  
    1  
    21""" 
    3 this module overwrite matplotlib toolbar 
    4  
     2    This module overwrites matplotlib toolbar 
    53""" 
    64import wx 
    75from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg 
    8 from matplotlib.backends.backend_wx import _load_bitmap 
    96 
    107class NavigationToolBar(NavigationToolbar2WxAgg): 
     
    2825        """ 
    2926        #delte reset button 
    30         self.DeleteToolByPos(0)  
     27        self.DeleteToolByPos(0) 
    3128        #delete unwanted button that configures subplot parameters 
    32         self.DeleteToolByPos(5)  
     29        self.DeleteToolByPos(5) 
    3330         
    3431    def add_option(self): 
     
    4138        context_tip += '    For more menu options, \n' 
    4239        context_tip += '    right-click the data symbols.' 
    43         context =  wx.ArtProvider.GetBitmap(wx.ART_LIST_VIEW, wx.ART_TOOLBAR) 
    44         self.InsertSimpleTool(0, id_context, context,  
     40        context = wx.ArtProvider.GetBitmap(wx.ART_LIST_VIEW, wx.ART_TOOLBAR) 
     41        self.InsertSimpleTool(0, id_context, context, 
    4542                                   context_tip, context_tip) 
    46         wx.EVT_TOOL(self, id_context,  self.on_menu) 
     43        wx.EVT_TOOL(self, id_context, self.on_menu) 
    4744        self.InsertSeparator(1) 
    4845         
    4946        id_print = wx.NewId() 
    50         print_bmp =  wx.ArtProvider.GetBitmap(wx.ART_PRINT, wx.ART_TOOLBAR) 
     47        print_bmp = wx.ArtProvider.GetBitmap(wx.ART_PRINT, wx.ART_TOOLBAR) 
    5148        self.AddSimpleTool(id_print, print_bmp, 
    5249                           'Print', 'Activate printing') 
     
    5451        #add reset button 
    5552        id_reset = wx.NewId() 
    56         reset_bmp =  wx.ArtProvider.GetBitmap(wx.ART_GO_HOME, wx.ART_TOOLBAR) 
     53        reset_bmp = wx.ArtProvider.GetBitmap(wx.ART_GO_HOME, wx.ART_TOOLBAR) 
    5754        self.AddSimpleTool(id_reset, reset_bmp, 
    5855                           'Reset Graph Range', 'Reset graph range') 
     
    8582        except: 
    8683            pass 
     84         
  • plottools/src/danse/common/plottools/transform.py

    r8d27cac r10bfeb3  
    1 import math   
     1import math 
     2          
    23          
    34def toX(x, y=None): 
     
    1213    return x 
    1314 
     15 
    1416def toX_pos(x, y=None): 
    1517    """ 
     
    2628        return x 
    2729 
     30 
    2831def toX2(x, y=None): 
    2932    """ 
     
    3740    return x * x 
    3841 
     42 
    3943def fromX2(x, y=None): 
    4044    """ 
     
    4549      
    4650    """ 
    47     if not x >= 0 : 
     51    if not x >= 0: 
    4852        raise ValueError, "square root of a negative value " 
    4953    else: 
    5054        return math.sqrt(x) 
    5155 
     56 
    5257def toX4(x, y=None): 
    5358    """ 
     
    6166    return x * x * x * x 
    6267 
     68 
    6369def fromX4(x, y=None): 
    6470    """ 
     
    6975      
    7076    """ 
    71     if not x >= 0 : 
     77    if not x >= 0: 
    7278        raise ValueError, "double square root of a negative value " 
    7379    else: 
    7480        return math.sqrt(math.sqrt(x)) 
    7581          
     82 
    7683def toLogX(x, y=None): 
    7784    """ 
     
    93100        return 1/x 
    94101    else: 
    95         raise ValueError,"cannot divide by zero" 
     102        raise ValueError, "cannot divide by zero" 
     103     
    96104     
    97105def toOneOverSqrtX(y, x=None): 
     
    101109        return 1/math.sqrt(y) 
    102110    else: 
    103         raise ValueError,"transform.toOneOverSqrtX: cannot be computed" 
     111        raise ValueError, "transform.toOneOverSqrtX: cannot be computed" 
     112     
    104113     
    105114def toLogYX2(y, x): 
    106115    """ 
    107116    """ 
    108     if (y *(x**2)) > 0: 
     117    if (y * (x**2)) > 0: 
    109118        return math.log(y * (x**2)) 
    110119    else: 
    111          raise ValueError,"transform.toLogYX2: cannot be computed" 
     120        raise ValueError, "transform.toLogYX2: cannot be computed" 
     121      
    112122      
    113123def toLogYX4(y, x): 
     
    117127        return math.log(math.pow(x,4) * y) 
    118128    else: 
    119          raise ValueError,"transform.toLogYX4: input error" 
     129        raise ValueError,"transform.toLogYX4: input error" 
     130      
    120131      
    121132def toYX4(y, x): 
     
    123134    """ 
    124135    return math.pow(x, 4) * y 
     136 
    125137 
    126138def toLogXY(y, x): 
     
    137149        return math.log(x * y) 
    138150 
     151 
    139152def errToX(x, y=None, dx=None, dy=None): 
    140153    """ 
     
    149162    return dx 
    150163 
     164 
    151165def errToX_pos(x, y=None, dx=None, dy=None): 
    152166    """ 
     
    158172    """ 
    159173    if dx == None: 
    160         dx = 0    
     174        dx = 0 
    161175    return dx 
     176 
    162177 
    163178def errToX2(x, y=None, dx=None, dy=None): 
     
    175190        return 0.0 
    176191     
     192     
    177193def errFromX2(x, y=None, dx=None, dy=None): 
    178194    """ 
     
    185201    if (x > 0): 
    186202        if(dx != None): 
    187             err = dx/(2 * math.sqrt(x)) 
     203            err = dx / (2 * math.sqrt(x)) 
    188204        else: 
    189205            err = 0 
     
    193209        raise ValueError, msg 
    194210 
     211 
    195212def errToX4(x, y=None, dx=None, dy=None): 
    196213    """ 
     
    207224        return 0.0 
    208225     
     226     
    209227def errFromX4(x, y=None, dx=None, dy=None): 
    210228    """ 
     
    217235    if (x > 0): 
    218236        if(dx != None): 
    219             err = dx/(4 * math.pow(x, 3/4)) 
     237            err = dx / (4 * math.pow(x, 3/4)) 
    220238        else: 
    221239            err = 0 
     
    224242        msg = "transform.errFromX4: can't compute error of negative x" 
    225243        raise ValueError, msg 
     244  
    226245  
    227246def errToLog10X(x, y=None, dx=None, dy=None): 
     
    243262        raise ValueError, msg 
    244263    if x != 0: 
    245         dx = dx /(x * math.log(10)) 
     264        dx = dx / (x * math.log(10)) 
    246265    else: 
    247266        raise ValueError, "errToLogX: divide by zero" 
    248267    return dx 
     268     
    249269     
    250270def errToLogX(x, y=None, dx=None, dy=None): 
     
    266286    return dx 
    267287 
     288 
    268289def errToYX2(x, y, dx=None, dy=None): 
    269290    """ 
     
    274295        dy = 0 
    275296    err = math.sqrt((2 * x * y * dx)**2 + ((x**2) * dy)**2) 
    276     return err  
     297    return err 
     298     
    277299     
    278300def errToLogXY(x, y, dx=None, dy=None): 
     
    298320    return math.sqrt(math.fabs(err)) 
    299321     
     322     
    300323def errToLogYX2(x, y, dx=None, dy=None): 
    301324    """ 
     
    317340    else: 
    318341        raise ValueError, "cannot compute this error" 
    319     return math.sqrt(math.fabs(err))  
     342    return math.sqrt(math.fabs(err)) 
     343         
    320344         
    321345def errOneOverX(x, y=None, dx=None, dy=None): 
     
    329353        err = dx/x**2 
    330354    else: 
    331         raise ValueError,"Cannot compute this error" 
     355        raise ValueError, "Cannot compute this error" 
    332356    return math.fabs(err) 
     357 
    333358 
    334359def errOneOverSqrtX(x, y=None, dx=None, dy=None): 
     
    344369        raise ValueError, "Cannot compute this error" 
    345370    return math.fabs(err) 
     371 
    346372 
    347373def errToLogYX4(x, y=None, dx=None, dy=None): 
     
    363389        dy = 0 
    364390    err = math.sqrt((4.0 * dx/x)**2  + (dy/y)**2) 
    365     return err  
     391    return err 
     392 
    366393 
    367394def errToYX4(x, y=None, dx=None, dy=None): 
     
    380407        dy = 0 
    381408    err = math.sqrt((dy * pow(x, 4))**2  + (4 * y * dx * math.pow(x, 3))**2) 
    382     return err  
    383             
     409    return err 
  • plottools/src/danse/common/plottools/unitConverter.py

    r82a54b8 r10bfeb3  
    1 import re, string 
     1import re 
     2import string 
    23#Input   ->  new scale  ->  Output 
    34 
    4 unit1 = "A^{-1} "#           x                    A^{-1} 
     5unit1 = "A^{-1} "  #             x                    A^{-1} 
    56unit2 = "A"  #                   x                     A 
    6 unit3 = "A"  #                  x^2                  A^{2} 
     7unit3 = "A"  #                   x^2                  A^{2} 
    78unit4 = "A "  #                  1/x                  A^{-1} 
    8 unit5 = "A^{0.5} " #        x^2                      A 
    9 unit9 = "m^{1/2}" #         x^2               m 
     9unit5 = "A^{0.5} "  #        x^2                      A 
     10unit9 = "m^{1/2}"  #         x^2               m 
    1011 
    1112#If you don't recognize the pattern, give up 
     
    1314 
    1415unit6 = "m/s"  #                x^2               (m/s)^{2} 
    15 unit7 = "m/s^{2}" #         1/x                 (m/s^{2})^{-1} 
    16 unit8 = "m/s^{4}" #         x^2               (m/s^{4})^{2} 
     16unit7 = "m/s^{2}"  #         1/x                 (m/s^{2})^{-1} 
     17unit8 = "m/s^{4}"  #         x^2               (m/s^{4})^{2} 
    1718 
    1819 
     
    2122    """ 
    2223    if pow != 0: 
    23         if string.find(unit, "^") != -1:# if the unit contains a power ^ 
     24        if string.find(unit, "^") != -1:  # if the unit contains a power ^ 
    2425            unitSplitted = re.split("\^", unit) 
    25             if string.find(unitSplitted[0],"/") != -1 or\ 
    26                 string.find(unitSplitted[0],"-") != -1 : # find slash / 
     26            if string.find(unitSplitted[0], "/") != -1 or\ 
     27                string.find(unitSplitted[0], "-") != -1 : # find slash / 
    2728                if pow == 1: 
    2829                    unit = unit 
     
    3031                    unit = "("+unit+")" + "^{"+ str(pow) + "}" 
    3132            else: 
    32                 if string.find(unitSplitted[1],"{") != -1:# if found a { 
    33                     findPower = re.split("{",unitSplitted[1]) 
    34                     if string.find(findPower[1],"}") != -1:# found } 
     33                if string.find(unitSplitted[1], "{") != -1:  # if found a { 
     34                    findPower = re.split("{", unitSplitted[1]) 
     35                    if string.find(findPower[1], "}") != -1:  # found } 
    3536                        unitPower = re.split("}", findPower[1]) 
    36                         if(string.find(unitPower[0],".") != -1): 
    37                             power = float(unitPower[0]) * pow  
    38                         elif(string.find(unitPower[0],"/") != -1):  
     37                        if(string.find(unitPower[0], ".") != -1): 
     38                            power = float(unitPower[0]) * pow 
     39                        elif(string.find(unitPower[0], "/") != -1): 
    3940                            #power is a float 
    4041                            poweSplitted = re.split("/", unitPower[0]) 
    4142                            power = pow * int(poweSplitted[0])\ 
    42                                         /int(poweSplitted[1]) 
     43                                         /int(poweSplitted[1]) 
    4344                        else: 
    44                             power = int(unitPower[0]) * pow    
     45                            power = int(unitPower[0]) * pow 
    4546                        
    4647                        if power == 1.0: 
    47                            unit = unitSplitted[0] 
     48                            unit = unitSplitted[0] 
    4849                        elif power == 0.5: 
    49                             unit = unitSplitted[0] + "^{1/2}"   
     50                            unit = unitSplitted[0] + "^{1/2}" 
    5051                        elif power == -0.5: 
    51                             unit = unitSplitted[0] + "^{-1/2}"   
     52                            unit = unitSplitted[0] + "^{-1/2}" 
    5253                        else: 
    53                             unit = unitSplitted[0] + "^{" + str(power) + "}"   
     54                            unit = unitSplitted[0] + "^{" + str(power) + "}" 
    5455                else: 
    55                      raise ValueError, "missing } in unit expression"  
    56         else:#no power 
     56                     raise ValueError, "missing } in unit expression" 
     57        else:  # no power 
    5758            if  pow != 1: 
    5859                unit = "(" + unit + ")" + "^{" + str(pow) + "}" 
     
    6061        raise ValueError, "empty unit ,enter a power different from zero" 
    6162    return unit 
     63 
     64 
    6265if __name__ == "__main__":  
    6366    print "this unit1 %s ,its power %s , and value %s" % (unit1, 
    6467                                                1, UnitConvertion(1, unit1)) 
    65     print "this unit2 %s ,its power %s , and value %s" % (unit2,1, 
     68    print "this unit2 %s ,its power %s , and value %s" % (unit2, 1, 
    6669                                                UnitConvertion(1, unit2)) 
    67     print "this unit3 %s ,its power %s , and value %s" % (unit3, 2,  
     70    print "this unit3 %s ,its power %s , and value %s" % (unit3, 2, 
    6871                                                    UnitConvertion(2, unit3)) 
    69     print "this unit4 %s ,its power %s , and value %s" % (unit4, -1,  
     72    print "this unit4 %s ,its power %s , and value %s" % (unit4, -1, 
    7073                                                UnitConvertion(-1, unit4)) 
    7174    print "this unit5 %s ,its power %s , and value %s" % (unit5, 2, 
    7275                                                    UnitConvertion(2, unit5)) 
    73     print "this unit6 %s ,its power %s , and value %s" % (unit6, 2,  
     76    print "this unit6 %s ,its power %s , and value %s" % (unit6, 2, 
    7477                                                    UnitConvertion(2, unit6)) 
    75     print "this unit7 %s ,its power %s , and value %s" % (unit7, -1,  
     78    print "this unit7 %s ,its power %s , and value %s" % (unit7, -1, 
    7679                                                    UnitConvertion(-1, unit7)) 
    77     print "this unit8 %s ,its power %s , and value %s" % (unit8, 2,  
     80    print "this unit8 %s ,its power %s , and value %s" % (unit8, 2, 
    7881                                                    UnitConvertion(2, unit8)) 
    79     print "this unit9 %s ,its power %s , and value %s" % (unit9, 2,  
     82    print "this unit9 %s ,its power %s , and value %s" % (unit9, 2, 
    8083                                                    UnitConvertion(2, unit9)) 
    81      
Note: See TracChangeset for help on using the changeset viewer.