Ignore:
Timestamp:
08/02/10 17:28:20 (14 years ago)
Author:
Kana Sugimoto
Message:

New Development: No

JIRA Issue: No (merge alma branch to trunk)

Ready for Test: Yes

Interface Changes: No

Test Programs: regressions may work

Module(s): all single dish modules

Description:

Merged all changes in alma (r1386:1818) and newfiller (r1774:1818) branch.


Location:
trunk/python
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/python

  • trunk/python/asapplotter.py

    r1739 r1819  
    11from asap import rcParams, print_log, print_log_dec
    22from asap import selector, scantable
     3from asap import asaplog
    34import matplotlib.axes
    45from matplotlib.font_manager import FontProperties
     
    2122            self._visible = visible
    2223        self._plotter = self._newplotter(**kwargs)
     24        # additional tool bar
     25        self._plotter.figmgr.casabar=self._newcasabar()
    2326
    2427        self._panelling = None
     
    4346        self._hist = rcParams['plotter.histogram']
    4447        self._fp = FontProperties()
     48        self._panellayout = self.set_panellayout(refresh=False)
    4549
    4650    def _translate(self, instr):
     
    5357
    5458    def _newplotter(self, **kwargs):
    55         if self._visible:
     59        backend=matplotlib.get_backend()
     60        if not self._visible:
     61            from asap.asaplot import asaplot
     62        elif backend == 'TkAgg':
    5663            from asap.asaplotgui import asaplotgui as asaplot
     64        elif backend == 'Qt4Agg':
     65            from asap.asaplotgui_qt4 import asaplotgui as asaplot
     66        elif backend == 'GTkAgg':
     67            from asap.asaplotgui_gtk import asaplotgui as asaplot
    5768        else:
    5869            from asap.asaplot import asaplot
    5970        return asaplot(**kwargs)
     71
     72    def _newcasabar(self):
     73        backend=matplotlib.get_backend()
     74        if self._visible and backend == "TkAgg":
     75            from asap.casatoolbar import CustomToolbarTkAgg
     76            return CustomToolbarTkAgg(self)
     77        else: return None
    6078
    6179    @print_log_dec
     
    7290        """
    7391        if self._plotter.is_dead:
     92            if hasattr(self._plotter.figmgr,'casabar'):
     93                del self._plotter.figmgr.casabar
    7494            self._plotter = self._newplotter()
     95            self._plotter.figmgr.casabar=self._newcasabar()
    7596        self._plotter.hold()
    7697        self._plotter.clear()
    77         from asap import scantable
    7898        if not self._data and not scan:
    7999            msg = "Input is not a scantable"
    80100            if rcParams['verbose']:
    81                 print msg
     101                #print msg
     102                asaplog.push( msg )
     103                print_log( 'ERROR' )
    82104                return
    83105            raise TypeError(msg)
    84         if isinstance(scan, scantable):
    85             if self._data is not None:
    86                 if scan != self._data:
    87                     self._data = scan
    88                     # reset
    89                     self._reset()
    90             else:
    91                 self._data = scan
    92                 self._reset()
    93         # ranges become invalid when unit changes
    94         if self._abcunit and self._abcunit != self._data.get_unit():
    95             self._minmaxx = None
    96             self._minmaxy = None
    97             self._abcunit = self._data.get_unit()
    98             self._datamask = None
     106        if scan: self.set_data(scan,refresh=False)
    99107        self._plot(self._data)
    100108        if self._minmaxy is not None:
    101109            self._plotter.set_limits(ylim=self._minmaxy)
     110        if self._plotter.figmgr.casabar: self._plotter.figmgr.casabar.enable_button()
    102111        self._plotter.release()
    103112        self._plotter.tidy()
    104113        self._plotter.show(hardrefresh=False)
     114        print_log()
    105115        return
    106116
     
    238248                dpos = (pos[0][1], pos[1][1])
    239249                args = dpos + args
    240 
    241250        self._axes_callback("axhspan", *args, **kwargs)
    242251        # hack to preventy mpl from redrawing the patch
     
    265274    # end matplotlib.axes fowarding functions
    266275
    267 
    268     def set_mode(self, stacking=None, panelling=None):
     276    def set_data(self, scan, refresh=True):
     277        """
     278        Set a scantable to plot.
     279        Parameters:
     280            scan:      a scantable
     281            refresh:   True (default) or False. If True, the plot is
     282                       replotted based on the new parameter setting(s).
     283                       Otherwise,the parameter(s) are set without replotting.
     284        Note:
     285           The user specified masks and data selections will be reset
     286           if a new scantable is set. This method should be called before
     287           setting data selections (set_selection) and/or masks (set_mask).
     288        """
     289        from asap import scantable
     290        if isinstance(scan, scantable):
     291            if self._data is not None:
     292                if scan != self._data:
     293                    self._data = scan
     294                    # reset
     295                    self._reset()
     296                    msg = "A new scantable is set to the plotter. The masks and data selections are reset."
     297                    asaplog.push( msg )
     298                    print_log( 'INFO' )
     299            else:
     300                self._data = scan
     301                self._reset()
     302        else:
     303            msg = "Input is not a scantable"
     304            if rcParams['verbose']:
     305                #print msg
     306                asaplog.push( msg )
     307                print_log( 'ERROR' )
     308                return
     309            raise TypeError(msg)
     310
     311        # ranges become invalid when unit changes
     312        if self._abcunit and self._abcunit != self._data.get_unit():
     313            self._minmaxx = None
     314            self._minmaxy = None
     315            self._abcunit = self._data.get_unit()
     316            self._datamask = None
     317        if refresh: self.plot()
     318       
     319
     320    def set_mode(self, stacking=None, panelling=None, refresh=True):
    269321        """
    270322        Set the plots look and feel, i.e. what you want to see on the plot.
     
    274326            panelling:    tell the plotter which variable to plot
    275327                          across multiple panels (default 'scan'
     328            refresh:      True (default) or False. If True, the plot is
     329                          replotted based on the new parameter setting(s).
     330                          Otherwise,the parameter(s) are set without replotting.
    276331        Note:
    277332            Valid modes are:
     
    286341               not self.set_stacking(stacking):
    287342            if rcParams['verbose']:
    288                 print msg
     343                #print msg
     344                asaplog.push( msg )
     345                print_log( 'ERROR' )
    289346                return
    290347            else:
    291348                raise TypeError(msg)
    292         if self._data: self.plot(self._data)
     349        if refresh and self._data: self.plot(self._data)
    293350        return
    294351
     
    304361        return False
    305362
    306     def set_layout(self,rows=None,cols=None):
     363    def set_layout(self,rows=None,cols=None,refresh=True):
    307364        """
    308365        Set the multi-panel layout, i.e. how many rows and columns plots
     
    311368             rows:   The number of rows of plots
    312369             cols:   The number of columns of plots
     370             refresh:  True (default) or False. If True, the plot is
     371                       replotted based on the new parameter setting(s).
     372                       Otherwise,the parameter(s) are set without replotting.
    313373        Note:
    314374             If no argument is given, the potter reverts to its auto-plot
     
    317377        self._rows = rows
    318378        self._cols = cols
    319         if self._data: self.plot(self._data)
     379        if refresh and self._data: self.plot(self._data)
    320380        return
    321381
     
    331391        return False
    332392
    333     def set_range(self,xstart=None,xend=None,ystart=None,yend=None):
     393    def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True):
    334394        """
    335395        Set the range of interest on the abcissa of the plot
    336396        Parameters:
    337397            [x,y]start,[x,y]end:  The start and end points of the 'zoom' window
     398            refresh:  True (default) or False. If True, the plot is
     399                      replotted based on the new parameter setting(s).
     400                      Otherwise,the parameter(s) are set without replotting.
    338401        Note:
    339402            These become non-sensical when the unit changes.
     
    349412        else:
    350413            self._minmaxy = [ystart,yend]
    351         if self._data: self.plot(self._data)
     414        if refresh and self._data: self.plot(self._data)
    352415        return
    353416
    354     def set_legend(self, mp=None, fontsize = None, mode = 0):
     417    def set_legend(self, mp=None, fontsize = None, mode = 0, refresh=True):
    355418        """
    356419        Specify a mapping for the legend instead of using the default
     
    376439                        9: upper center
    377440                        10: center
     441            refresh:    True (default) or False. If True, the plot is
     442                        replotted based on the new parameter setting(s).
     443                        Otherwise,the parameter(s) are set without replotting.
    378444
    379445        Example:
     
    390456            from matplotlib import rc as rcp
    391457            rcp('legend', fontsize=fontsize)
    392         if self._data:
    393             self.plot(self._data)
     458        if refresh and self._data: self.plot(self._data)
    394459        return
    395460
    396     def set_title(self, title=None, fontsize=None):
     461    def set_title(self, title=None, fontsize=None, refresh=True):
    397462        """
    398463        Set the title of the plot. If multiple panels are plotted,
    399464        multiple titles have to be specified.
     465        Parameters:
     466            refresh:    True (default) or False. If True, the plot is
     467                        replotted based on the new parameter setting(s).
     468                        Otherwise,the parameter(s) are set without replotting.
    400469        Example:
    401470             # two panels are visible on the plotter
     
    406475            from matplotlib import rc as rcp
    407476            rcp('axes', titlesize=fontsize)
    408         if self._data: self.plot(self._data)
     477        if refresh and self._data: self.plot(self._data)
    409478        return
    410479
    411     def set_ordinate(self, ordinate=None, fontsize=None):
     480    def set_ordinate(self, ordinate=None, fontsize=None, refresh=True):
    412481        """
    413482        Set the y-axis label of the plot. If multiple panels are plotted,
     
    416485            ordinate:    a list of ordinate labels. None (default) let
    417486                         data determine the labels
     487            refresh:     True (default) or False. If True, the plot is
     488                         replotted based on the new parameter setting(s).
     489                         Otherwise,the parameter(s) are set without replotting.
    418490        Example:
    419491             # two panels are visible on the plotter
     
    425497            rcp('axes', labelsize=fontsize)
    426498            rcp('ytick', labelsize=fontsize)
    427         if self._data: self.plot(self._data)
     499        if refresh and self._data: self.plot(self._data)
    428500        return
    429501
    430     def set_abcissa(self, abcissa=None, fontsize=None):
     502    def set_abcissa(self, abcissa=None, fontsize=None, refresh=True):
    431503        """
    432504        Set the x-axis label of the plot. If multiple panels are plotted,
     
    435507            abcissa:     a list of abcissa labels. None (default) let
    436508                         data determine the labels
     509            refresh:     True (default) or False. If True, the plot is
     510                         replotted based on the new parameter setting(s).
     511                         Otherwise,the parameter(s) are set without replotting.
    437512        Example:
    438513             # two panels are visible on the plotter
     
    444519            rcp('axes', labelsize=fontsize)
    445520            rcp('xtick', labelsize=fontsize)
    446         if self._data: self.plot(self._data)
     521        if refresh and self._data: self.plot(self._data)
    447522        return
    448523
    449     def set_colors(self, colmap):
     524    def set_colors(self, colmap, refresh=True):
    450525        """
    451526        Set the colours to be used. The plotter will cycle through
     
    453528        Parameters:
    454529            colmap:     a list of colour names
     530            refresh:    True (default) or False. If True, the plot is
     531                        replotted based on the new parameter setting(s).
     532                        Otherwise,the parameter(s) are set without replotting.
    455533        Example:
    456534             plotter.set_colors("red green blue")
     
    462540            colmap = colmap.split()
    463541        self._plotter.palette(0, colormap=colmap)
    464         if self._data: self.plot(self._data)
     542        if refresh and self._data: self.plot(self._data)
    465543
    466544    # alias for english speakers
    467545    set_colours = set_colors
    468546
    469     def set_histogram(self, hist=True, linewidth=None):
     547    def set_histogram(self, hist=True, linewidth=None, refresh=True):
    470548        """
    471549        Enable/Disable histogram-like plotting.
     
    474552                         is taken from the .asaprc setting
    475553                         plotter.histogram
     554            refresh:     True (default) or False. If True, the plot is
     555                         replotted based on the new parameter setting(s).
     556                         Otherwise,the parameter(s) are set without replotting.
    476557        """
    477558        self._hist = hist
     
    479560            from matplotlib import rc as rcp
    480561            rcp('lines', linewidth=linewidth)
    481         if self._data: self.plot(self._data)
    482 
    483     def set_linestyles(self, linestyles=None, linewidth=None):
     562        if refresh and self._data: self.plot(self._data)
     563
     564    def set_linestyles(self, linestyles=None, linewidth=None, refresh=True):
    484565        """
    485566        Set the linestyles to be used. The plotter will cycle through
     
    491572                             'dashdotdot' and 'dashdashdot' are
    492573                             possible
    493 
     574            refresh:         True (default) or False. If True, the plot is
     575                             replotted based on the new parameter setting(s).
     576                             Otherwise,the parameter(s) are set without replotting.
    494577        Example:
    495578             plotter.set_colors("black")
     
    505588            from matplotlib import rc as rcp
    506589            rcp('lines', linewidth=linewidth)
    507         if self._data: self.plot(self._data)
    508 
    509     def set_font(self, **kwargs):
     590        if refresh and self._data: self.plot(self._data)
     591
     592    def set_font(self, refresh=True,**kwargs):
    510593        """
    511594        Set font properties.
     
    516599            size:      the 'general' font size, individual elements can be adjusted
    517600                       seperately
     601            refresh:   True (default) or False. If True, the plot is
     602                       replotted based on the new parameter setting(s).
     603                       Otherwise,the parameter(s) are set without replotting.
    518604        """
    519605        from matplotlib import rc as rcp
     
    523609                fdict[k] = v
    524610        self._fp = FontProperties(**fdict)
    525         if self._data:
    526             self.plot()
     611        if refresh and self._data: self.plot(self._data)
     612
     613    def set_panellayout(self,layout=[],refresh=True):
     614        """
     615        Set the layout of subplots.
     616        Parameters:
     617            layout:   a list of subplots layout in figure coordinate (0-1),
     618                      i.e., fraction of the figure width or height.
     619                      The order of elements should be:
     620                      [left, bottom, right, top, horizontal space btw panels,
     621                      vertical space btw panels].
     622            refresh:  True (default) or False. If True, the plot is
     623                      replotted based on the new parameter setting(s).
     624                      Otherwise,the parameter(s) are set without replotting.
     625        Note
     626        * When layout is not specified, the values are reset to the defaults
     627          of matplotlib.
     628        * If any element is set to be None, the current value is adopted.
     629        """
     630        if layout == []: self._panellayout=self._reset_panellayout()
     631        else:
     632            self._panellayout=[None]*6
     633            self._panellayout[0:len(layout)]=layout
     634        #print "panel layout set to ",self._panellayout
     635        if refresh and self._data: self.plot(self._data)
     636
     637    def _reset_panellayout(self):
     638        ks=map(lambda x: 'figure.subplot.'+x,
     639               ['left','bottom','right','top','hspace','wspace'])
     640        return map(matplotlib.rcParams.get,ks)
    527641
    528642    def plot_lines(self, linecat=None, doppler=0.0, deltachan=10, rotate=90.0,
     
    622736
    623737
    624     def set_mask(self, mask=None, selection=None):
     738    def set_mask(self, mask=None, selection=None, refresh=True):
    625739        """
    626740        Set a plotting mask for a specific polarization.
     
    629743             mask:           a mask from scantable.create_mask
    630744             selection:      the spectra to apply the mask to.
     745             refresh:        True (default) or False. If True, the plot is
     746                             replotted based on the new parameter setting(s).
     747                             Otherwise,the parameter(s) are set without replotting.
    631748        Example:
    632749             select = selector()
     
    637754            msg = "Can only set mask after a first call to plot()"
    638755            if rcParams['verbose']:
    639                 print msg
     756                #print msg
     757                asaplog.push( msg )
     758                print_log( 'ERROR' )
    640759                return
    641760            else:
     
    657776        else:
    658777            self._maskselection = None
    659         self.plot(self._data)
     778        if refresh: self.plot(self._data)
    660779
    661780    def _slice_indeces(self, data):
     
    671790            inc = -1
    672791        # find min index
    673         while start > 0 and data[start] < mn:
    674             start+= inc
     792        #while start > 0 and data[start] < mn:
     793        #    start+= inc
     794        minind=start
     795        for ind in xrange(start,end+inc,inc):
     796            if data[ind] > mn: break
     797            minind=ind
    675798        # find max index
    676         while end > 0 and data[end] > mx:
    677             end-=inc
    678         if end > 0: end +=1
     799        #while end > 0 and data[end] > mx:
     800        #    end-=inc
     801        #if end > 0: end +=1
     802        maxind=end
     803        for ind in xrange(end,start-inc,-inc):
     804            if data[ind] < mx: break
     805            maxind=ind
     806        start=minind
     807        end=maxind
    679808        if start > end:
    680             return end,start
    681         return start,end
     809            return end,start+1
     810        elif start < end:
     811            return start,end+1
     812        else:
     813            return start,end
    682814
    683815    def _reset(self):
     
    708840        maxpanel, maxstack = 16,16
    709841        if n > maxpanel or nstack > maxstack:
    710             from asap import asaplog
    711842            maxn = 0
    712843            if nstack > maxstack: maxn = maxstack
     
    715846                  "Selecting first %d selections..." % (maxn, maxn)
    716847            asaplog.push(msg)
    717             print_log()
     848            print_log('WARN')
    718849            n = min(n,maxpanel)
    719850            nstack = min(nstack,maxstack)
    720851        if n > 1:
    721852            ganged = rcParams['plotter.ganged']
     853            if self._panelling == 'i':
     854                ganged = False
    722855            if self._rows and self._cols:
    723856                n = min(n,self._rows*self._cols)
    724857                self._plotter.set_panels(rows=self._rows,cols=self._cols,
    725                                          nplots=n,ganged=ganged)
     858#                                         nplots=n,ganged=ganged)
     859                                         nplots=n,layout=self._panellayout,ganged=ganged)
    726860            else:
    727                 self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged)
     861#                self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged)
     862                self._plotter.set_panels(rows=n,cols=0,nplots=n,layout=self._panellayout,ganged=ganged)
    728863        else:
    729             self._plotter.set_panels()
     864#            self._plotter.set_panels()
     865            self._plotter.set_panels(layout=self._panellayout)
    730866        r=0
    731867        nr = scan.nrow()
     
    799935                    ylim= self._minmaxy or [ma.minimum(y),ma.maximum(y)]
    800936                    allylim += ylim
     937                else:
     938                    xlim = self._minmaxx or []
     939                    allxlim += xlim
     940                    ylim= self._minmaxy or []
     941                    allylim += ylim
    801942                stackcount += 1
    802943                # last in colour stack -> autoscale x
    803                 if stackcount == nstack:
     944                if stackcount == nstack and len(allxlim) > 0:
    804945                    allxlim.sort()
    805                     self._plotter.axes.set_xlim([allxlim[0],allxlim[-1]])
     946                    self._plotter.subplots[panelcount-1]['axes'].set_xlim([allxlim[0],allxlim[-1]])
    806947                    # clear
    807948                    allxlim =[]
     
    813954            if (panelcount == n) and (stackcount == nstack):
    814955                # last panel -> autoscale y if ganged
    815                 if rcParams['plotter.ganged']:
     956                if rcParams['plotter.ganged'] and len(allylim) > 0:
    816957                    allylim.sort()
    817958                    self._plotter.set_limits(ylim=[allylim[0],allylim[-1]])
     
    820961        #reset the selector to the scantable's original
    821962        scan.set_selection(savesel)
    822         if self._fp is not None:
     963       
     964        #temporary switch-off for older matplotlib
     965        #if self._fp is not None:
     966        if self._fp is not None and getattr(self._plotter.figure,'findobj',False):
    823967            for o in self._plotter.figure.findobj(Text):
    824968                o.set_fontproperties(self._fp)
    825969
    826 
    827970    def set_selection(self, selection=None, refresh=True, **kw):
     971        """
     972        Parameters:
     973            selection:  a selector object (default unset the selection)
     974            refresh:    True (default) or False. If True, the plot is
     975                        replotted based on the new parameter setting(s).
     976                        Otherwise,the parameter(s) are set without replotting.
     977        """
    828978        if selection is None:
    829979            # reset
     
    845995        order = [d0[self._panelling],d0[self._stacking]]
    846996        self._selection.set_order(order)
    847         if self._data and refresh: self.plot(self._data)
     997        if refresh and self._data: self.plot(self._data)
    848998
    849999    def _get_selected_n(self, scan):
     
    8681018            poleval = scan._getpollabel(scan.getpol(row),scan.poltype())
    8691019        d = {'b': "Beam "+str(scan.getbeam(row)),
    870              's': scan._getsourcename(row),
     1020             #'s': scan._getsourcename(row),
     1021             's': "Scan "+str(scan.getscan(row))+\
     1022                  " ("+str(scan._getsourcename(row))+")",
    8711023             'i': "IF"+str(scan.getif(row)),
    8721024             'p': poleval,
     
    8741026        return userlabel or d[mode]
    8751027
    876     def plotazel(self):
     1028    def plotazel(self, scan=None, outfile=None):
     1029    #def plotazel(self):
    8771030        """
    8781031        plot azimuth and elevation versus time of a scantable
     
    8831036        from matplotlib.ticker import MultipleLocator
    8841037        from numpy import array, pi
     1038        self._data = scan
     1039        self._outfile = outfile
    8851040        dates = self._data.get_time(asdatetime=True)
    8861041        t = PL.date2num(dates)
     
    8891044        PL.ioff()
    8901045        PL.clf()
     1046        # Adjust subplot layouts
     1047        if len(self._panellayout) !=6: self.set_panellayout(refresh=False)
     1048        lef, bot, rig, top, wsp, hsp = self._panellayout
     1049        PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top,
     1050                                 wspace=wsp,hspace=hsp)
     1051       
    8911052        tdel = max(t) - min(t)
    8921053        ax = PL.subplot(2,1,1)
     
    9101071
    9111072        PL.title(dstr)
    912         PL.plot_date(t,el,'b,', tz=tz)
     1073        if tdel == 0.0:
     1074            th = (t - PL.floor(t))*24.0
     1075            PL.plot(th,el,'o',markersize=2, markerfacecolor='b', markeredgecolor='b')
     1076        else:
     1077            PL.plot_date(t,el,'o', markersize=2, markerfacecolor='b', markeredgecolor='b',tz=tz)
     1078            #ax.grid(True)
     1079            ax.xaxis.set_major_formatter(timefmt)
     1080            ax.xaxis.set_major_locator(majloc)
     1081            ax.xaxis.set_minor_locator(minloc)
    9131082        ax.yaxis.grid(True)
    914 
     1083        yloc = MultipleLocator(30)
     1084        ax.set_ylim(0,90)
     1085        ax.yaxis.set_major_locator(yloc)
    9151086        if tdel > 1.0:
    9161087            labels = ax.get_xticklabels()
    9171088        #    PL.setp(labels, fontsize=10, rotation=45)
    9181089            PL.setp(labels, fontsize=10)
     1090
    9191091        # Az plot
    9201092        az = array(self._data.get_azimuth())*180./pi
     
    9231095                if az[irow] < 0: az[irow] += 360.0
    9241096
    925         ax2 = ax.figure.add_subplot(2,1,2, sharex=ax)
    926         ax2.set_xlabel('Time (UT)')
    927         ax2.set_ylabel('Az [deg.]')
    928         ax2.plot_date(t,az,'b,', tz=tz)
     1097        ax2 = PL.subplot(2,1,2)
     1098        #PL.xlabel('Time (UT [hour])')
     1099        PL.ylabel('Az [deg.]')
     1100        if tdel == 0.0:
     1101            PL.plot(th,az,'o',markersize=2, markeredgecolor='b',markerfacecolor='b')
     1102        else:
     1103            PL.plot_date(t,az,'o', markersize=2,markeredgecolor='b',markerfacecolor='b',tz=tz)
     1104            ax2.xaxis.set_major_formatter(timefmt)
     1105            ax2.xaxis.set_major_locator(majloc)
     1106            ax2.xaxis.set_minor_locator(minloc)
     1107        #ax2.grid(True)
     1108        ax2.set_ylim(0,360)
    9291109        ax2.yaxis.grid(True)
    930         # set this last as x axis is shared
    931         ax.xaxis.set_major_formatter(timefmt)
    932         ax.xaxis.set_major_locator(majloc)
    933         ax.xaxis.set_minor_locator(minloc)
     1110        #hfmt = DateFormatter('%H')
     1111        #hloc = HourLocator()
     1112        yloc = MultipleLocator(60)
     1113        ax2.yaxis.set_major_locator(yloc)
     1114        if tdel > 1.0:
     1115            labels = ax2.get_xticklabels()
     1116            PL.setp(labels, fontsize=10)
     1117            PL.xlabel('Time (UT [day])')
     1118        else:
     1119            PL.xlabel('Time (UT [hour])')
     1120
    9341121        PL.ion()
    9351122        PL.draw()
    936 
    937     def plotpointing(self):
     1123        if (self._outfile is not None):
     1124           PL.savefig(self._outfile)
     1125
     1126    def plotpointing(self, scan=None, outfile=None):
     1127    #def plotpointing(self):
    9381128        """
    9391129        plot telescope pointings
    9401130        """
    9411131        from matplotlib import pylab as PL
    942         from numpy import array
     1132        from numpy import array, pi
     1133        self._data = scan
     1134        self._outfile = outfile
    9431135        dir = array(self._data.get_directionval()).transpose()
    9441136        ra = dir[0]*180./pi
    9451137        dec = dir[1]*180./pi
    9461138        PL.cla()
    947         PL.ioff()
     1139        #PL.ioff()
    9481140        PL.clf()
    949         ax = PL.axes([0.1,0.1,0.8,0.8])
    950         ax = PL.axes([0.1,0.1,0.8,0.8])
     1141        # Adjust subplot layouts
     1142        if len(self._panellayout) !=6: self.set_panellayout(refresh=False)
     1143        lef, bot, rig, top, wsp, hsp = self._panellayout
     1144        PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top,
     1145                                 wspace=wsp,hspace=hsp)
     1146        ax = PL.gca()
     1147        #ax = PL.axes([0.1,0.1,0.8,0.8])
     1148        #ax = PL.axes([0.1,0.1,0.8,0.8])
    9511149        ax.set_aspect('equal')
    9521150        PL.plot(ra, dec, 'b,')
     
    9561154        [xmin,xmax,ymin,ymax] = PL.axis()
    9571155        PL.axis([xmax,xmin,ymin,ymax])
    958         PL.ion()
     1156        #PL.ion()
    9591157        PL.draw()
     1158        if (self._outfile is not None):
     1159           PL.savefig(self._outfile)
     1160
     1161    # plot total power data
     1162    # plotting in time is not yet implemented..
     1163    def plottp(self, scan=None, outfile=None):
     1164        if self._plotter.is_dead:
     1165            if hasattr(self._plotter.figmgr,'casabar'):
     1166                del self._plotter.figmgr.casabar
     1167            self._plotter = self._newplotter()
     1168            self._plotter.figmgr.casabar=self._newcasabar()
     1169        self._plotter.hold()
     1170        self._plotter.clear()
     1171        from asap import scantable
     1172        if not self._data and not scan:
     1173            msg = "Input is not a scantable"
     1174            if rcParams['verbose']:
     1175                #print msg
     1176                asaplog.push( msg )
     1177                print_log( 'ERROR' )
     1178                return
     1179            raise TypeError(msg)
     1180        if isinstance(scan, scantable):
     1181            if self._data is not None:
     1182                if scan != self._data:
     1183                    self._data = scan
     1184                    # reset
     1185                    self._reset()
     1186            else:
     1187                self._data = scan
     1188                self._reset()
     1189        # ranges become invalid when abcissa changes?
     1190        #if self._abcunit and self._abcunit != self._data.get_unit():
     1191        #    self._minmaxx = None
     1192        #    self._minmaxy = None
     1193        #    self._abcunit = self._data.get_unit()
     1194        #    self._datamask = None
     1195
     1196        # Adjust subplot layouts
     1197        if len(self._panellayout) !=6: self.set_panellayout(refresh=False)
     1198        lef, bot, rig, top, wsp, hsp = self._panellayout
     1199        self._plotter.figure.subplots_adjust(
     1200            left=lef,bottom=bot,right=rig,top=top,wspace=wsp,hspace=hsp)
     1201        if self._plotter.figmgr.casabar: self._plotter.figmgr.casabar.disable_button()
     1202        self._plottp(self._data)
     1203        if self._minmaxy is not None:
     1204            self._plotter.set_limits(ylim=self._minmaxy)
     1205        self._plotter.release()
     1206        self._plotter.tidy()
     1207        self._plotter.show(hardrefresh=False)
     1208        print_log()
     1209        return
     1210
     1211    def _plottp(self,scan):
     1212        """
     1213        private method for plotting total power data
     1214        """
     1215        from numpy import ma, array, arange, logical_not
     1216        r=0
     1217        nr = scan.nrow()
     1218        a0,b0 = -1,-1
     1219        allxlim = []
     1220        allylim = []
     1221        y=[]
     1222        self._plotter.set_panels()
     1223        self._plotter.palette(0)
     1224        #title
     1225        #xlab = self._abcissa and self._abcissa[panelcount] \
     1226        #       or scan._getabcissalabel()
     1227        #ylab = self._ordinate and self._ordinate[panelcount] \
     1228        #       or scan._get_ordinate_label()
     1229        xlab = self._abcissa or 'row number' #or Time
     1230        ylab = self._ordinate or scan._get_ordinate_label()
     1231        self._plotter.set_axes('xlabel',xlab)
     1232        self._plotter.set_axes('ylabel',ylab)
     1233        lbl = self._get_label(scan, r, 's', self._title)
     1234        if isinstance(lbl, list) or isinstance(lbl, tuple):
     1235        #    if 0 <= panelcount < len(lbl):
     1236        #        lbl = lbl[panelcount]
     1237        #    else:
     1238                # get default label
     1239             lbl = self._get_label(scan, r, self._panelling, None)
     1240        self._plotter.set_axes('title',lbl)
     1241        y=array(scan._get_column(scan._getspectrum,-1))
     1242        m = array(scan._get_column(scan._getmask,-1))
     1243        y = ma.masked_array(y,mask=logical_not(array(m,copy=False)))
     1244        x = arange(len(y))
     1245        # try to handle spectral data somewhat...
     1246        l,m = y.shape
     1247        if m > 1:
     1248            y=y.mean(axis=1)
     1249        plotit = self._plotter.plot
     1250        llbl = self._get_label(scan, r, self._stacking, None)
     1251        self._plotter.set_line(label=llbl)
     1252        if len(x) > 0:
     1253            plotit(x,y)
     1254
     1255
     1256    # forwards to matplotlib.Figure.text
     1257    def figtext(self, *args, **kwargs):
     1258        """
     1259        Add text to figure at location x,y (relative 0-1 coords).
     1260        This method forwards *args and **kwargs to a Matplotlib method,
     1261        matplotlib.Figure.text.
     1262        See the method help for detailed information.
     1263        """
     1264        self._plotter.text(*args, **kwargs)
     1265    # end matplotlib.Figure.text forwarding function
     1266
     1267
     1268    # printing header information
     1269    def print_header(self, plot=True, fontsize=9, logger=False, selstr='', extrastr=''):
     1270        """
     1271        print data (scantable) header on the plot and/or logger.
     1272        Parameters:
     1273            plot:      whether or not print header info on the plot.
     1274            fontsize:  header font size (valid only plot=True)
     1275            autoscale: whether or not autoscale the plot (valid only plot=True)
     1276            logger:    whether or not print header info on the logger.
     1277            selstr:    additional selection string (not verified)
     1278            extrastr:  additional string to print (not verified)
     1279        """
     1280        if not plot and not logger: return
     1281        if not self._data: raise RuntimeError("No scantable has been set yet.")
     1282        # Now header will be printed on plot and/or logger.
     1283        # Get header information and format it.
     1284        ssum=self._data.__str__()
     1285        # Print Observation header to the upper-left corner of plot
     1286        if plot:
     1287            headstr=[ssum[ssum.find('Observer:'):ssum.find('Flux Unit:')]]
     1288            headstr.append(ssum[ssum.find('Beams:'):ssum.find('Observer:')]
     1289                         +ssum[ssum.find('Rest Freqs:'):ssum.find('Abcissa:')])
     1290            if extrastr != '': headstr[0]=extrastr+'\n'+headstr[0]
     1291            #headstr[1]='Data File:     '+(filestr or 'unknown')+'\n'+headstr[1]
     1292            ssel='***Selections***\n'+(selstr+self._data.get_selection().__str__() or 'none')
     1293            headstr.append(ssel)
     1294            nstcol=len(headstr)
     1295           
     1296            self._plotter.hold()
     1297            for i in range(nstcol):
     1298                self._plotter.figure.text(0.03+float(i)/nstcol,0.98,
     1299                             headstr[i],
     1300                             horizontalalignment='left',
     1301                             verticalalignment='top',
     1302                             fontsize=fontsize)
     1303            import time
     1304            self._plotter.figure.text(0.99,0.0,
     1305                            time.strftime("%a %d %b %Y  %H:%M:%S %Z"),
     1306                            horizontalalignment='right',
     1307                            verticalalignment='bottom',fontsize=8)
     1308            self._plotter.release()
     1309            del headstr, ssel
     1310        if logger:
     1311            asaplog.push("----------------\n  Plot Summary\n----------------")
     1312            asaplog.push(extrastr)
     1313            asaplog.push(ssum[ssum.find('Beams:'):])
     1314            print_log()
     1315        del ssum
     1316
     1317
Note: See TracChangeset for help on using the changeset viewer.