Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/asapplotter.py

    r1824 r1949  
    22from asap.selector import selector
    33from asap.scantable import scantable
    4 from asap.logging import asaplog, print_log, print_log_dec
     4from asap.logging import asaplog, asaplog_post_dec
    55import matplotlib.axes
    66from matplotlib.font_manager import FontProperties
     
    1414    By default the plotter is set up to plot polarisations
    1515    'colour stacked' and scantables across panels.
    16     Note:
     16
     17    .. note::
     18
    1719        Currenly it only plots 'spectra' not Tsys or
    1820        other variables.
     21
    1922    """
    2023    def __init__(self, visible=None , **kwargs):
     
    4851        self._fp = FontProperties()
    4952        self._panellayout = self.set_panellayout(refresh=False)
     53        self._offset = None
     54        self._rowcount = 0
     55        self._panelcnt = 0
    5056
    5157    def _translate(self, instr):
    52         keys = "s b i p t".split()
     58        keys = "s b i p t r".split()
    5359        if isinstance(instr, str):
    5460            for key in keys:
     
    7884        else: return None
    7985
    80     @print_log_dec
     86    @asaplog_post_dec
    8187    def plot(self, scan=None):
    8288        """
     
    9096            are consistent e.g. all 'channel' or all 'velocity' etc.
    9197        """
     98        self._rowcount = self._panelcnt = 0
    9299        if self._plotter.is_dead:
    93100            if hasattr(self._plotter.figmgr,'casabar'):
     
    96103            self._plotter.figmgr.casabar=self._newcasabar()
    97104        self._plotter.hold()
    98         self._plotter.clear()
     105        #self._plotter.clear()
    99106        if not self._data and not scan:
    100107            msg = "Input is not a scantable"
    101             if rcParams['verbose']:
    102                 #print msg
    103                 asaplog.push( msg )
    104                 print_log( 'ERROR' )
    105                 return
    106108            raise TypeError(msg)
    107         if scan: self.set_data(scan,refresh=False)
     109        if scan:
     110            self.set_data(scan, refresh=False)
    108111        self._plot(self._data)
    109112        if self._minmaxy is not None:
     
    113116        self._plotter.tidy()
    114117        self._plotter.show(hardrefresh=False)
    115         print_log()
    116118        return
    117119
     
    125127    def create_mask(self, nwin=1, panel=0, color=None):
    126128        """
    127         Interactively define a mask.It retruns a mask that is equivalent to
     129        Interactively define a mask. It retruns a mask that is equivalent to
    128130        the one created manually with scantable.create_mask.
    129131        Parameters:
     
    275277    # end matplotlib.axes fowarding functions
    276278
     279    @asaplog_post_dec
    277280    def set_data(self, scan, refresh=True):
    278281        """
     
    295298                    # reset
    296299                    self._reset()
    297                     msg = "A new scantable is set to the plotter. The masks and data selections are reset."
     300                    msg = "A new scantable is set to the plotter. "\
     301                          "The masks and data selections are reset."
    298302                    asaplog.push( msg )
    299                     print_log( 'INFO' )
    300303            else:
    301304                self._data = scan
     
    303306        else:
    304307            msg = "Input is not a scantable"
    305             if rcParams['verbose']:
    306                 #print msg
    307                 asaplog.push( msg )
    308                 print_log( 'ERROR' )
    309                 return
    310308            raise TypeError(msg)
    311309
     
    318316        if refresh: self.plot()
    319317
    320 
     318    @asaplog_post_dec
    321319    def set_mode(self, stacking=None, panelling=None, refresh=True):
    322320        """
     
    341339        if not self.set_panelling(panelling) or \
    342340               not self.set_stacking(stacking):
    343             if rcParams['verbose']:
    344                 #print msg
    345                 asaplog.push( msg )
    346                 print_log( 'ERROR' )
    347                 return
    348             else:
    349                 raise TypeError(msg)
     341            raise TypeError(msg)
     342        if self._panelling == 'r':
     343            self._stacking = '_r'
     344        elif self._stacking == 'r':
     345            self._panelling = '_r'
    350346        if refresh and self._data: self.plot(self._data)
    351347        return
    352348
    353349    def set_panelling(self, what=None):
     350        """Set the 'panelling' mode i.e. which type of spectra should be
     351        spread across different panels.
     352        """
     353
    354354        mode = what
    355355        if mode is None:
     
    359359            self._panelling = md
    360360            self._title = None
     361            if md == 'r':
     362                self._stacking = '_r'
    361363            return True
    362364        return False
     
    382384
    383385    def set_stacking(self, what=None):
     386        """Set the 'stacking' mode i.e. which type of spectra should be
     387        overlayed.
     388        """
    384389        mode = what
    385390        if mode is None:
     
    389394            self._stacking = md
    390395            self._lmap = None
     396            if md == 'r':
     397                self._panelling = '_r'
    391398            return True
    392399        return False
    393400
    394     def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True):
     401    def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True, offset=None):
    395402        """
    396403        Set the range of interest on the abcissa of the plot
     
    400407                      replotted based on the new parameter setting(s).
    401408                      Otherwise,the parameter(s) are set without replotting.
     409            offset:   shift the abcissa by the given amount. The abcissa label will
     410                      have '(relative)' appended to it.
    402411        Note:
    403412            These become non-sensical when the unit changes.
     
    405414
    406415        """
     416        self._offset = offset
    407417        if xstart is None and xend is None:
    408418            self._minmaxx = None
     
    650660            deltachan:    the number of channels to include each side of the
    651661                          line to determine a local maximum/minimum
    652             rotate:       the rotation (in degrees) )for the text label (default 90.0)
     662            rotate:       the rotation (in degrees) for the text label (default 90.0)
    653663            location:     the location of the line annotation from the 'top',
    654664                          'bottom' or alternate (None - the default)
     
    720730    def save(self, filename=None, orientation=None, dpi=None):
    721731        """
    722         Save the plot to a file. The know formats are 'png', 'ps', 'eps'.
     732        Save the plot to a file. The known formats are 'png', 'ps', 'eps'.
    723733        Parameters:
    724734             filename:    The name of the output file. This is optional
     
    736746        return
    737747
    738 
     748    @asaplog_post_dec
    739749    def set_mask(self, mask=None, selection=None, refresh=True):
    740750        """
     
    754764        if not self._data:
    755765            msg = "Can only set mask after a first call to plot()"
    756             if rcParams['verbose']:
    757                 #print msg
    758                 asaplog.push( msg )
    759                 print_log( 'ERROR' )
    760                 return
    761             else:
    762                 raise RuntimeError(msg)
     766            raise RuntimeError(msg)
    763767        if len(mask):
    764768            if isinstance(mask, list) or isinstance(mask, tuple):
     
    817821        self._usermask = []
    818822        self._usermaskspectra = None
     823        self._offset = None
    819824        self.set_selection(None, False)
    820825
     
    822827        savesel = scan.get_selection()
    823828        sel = savesel +  self._selection
    824         d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO',
    825               'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME' }
    826         order = [d0[self._panelling],d0[self._stacking]]
    827         sel.set_order(order)
     829        order = self._get_sortstring([self._panelling,self._stacking])
     830        if order:
     831            sel.set_order(order)
    828832        scan.set_selection(sel)
    829833        d = {'b': scan.getbeam, 's': scan.getscan,
    830              'i': scan.getif, 'p': scan.getpol, 't': scan._gettime }
     834             #'i': scan.getif, 'p': scan.getpol, 't': scan._gettime,
     835             'i': scan.getif, 'p': scan.getpol, 't': scan.get_time,
     836             'r': int, '_r': int}
    831837
    832838        polmodes = dict(zip(self._selection.get_pols(),
     
    839845        if isinstance(nstack0, int): nstack = nstack0
    840846        else: nstack = len(nstack0)
     847        nptot = n
    841848        maxpanel, maxstack = 16,16
    842         if n > maxpanel or nstack > maxstack:
    843             maxn = 0
    844             if nstack > maxstack: maxn = maxstack
    845             if n > maxpanel: maxn = maxpanel
    846             msg ="Scan to be plotted contains more than %d selections.\n" \
    847                   "Selecting first %d selections..." % (maxn, maxn)
     849        if nstack > maxstack:
     850            msg ="Scan to be overlayed contains more than %d selections.\n" \
     851                  "Selecting first %d selections..." % (maxstack, maxstack)
    848852            asaplog.push(msg)
    849             print_log('WARN')
    850             n = min(n,maxpanel)
     853            asaplog.post('WARN')
    851854            nstack = min(nstack,maxstack)
     855        n = min(n,maxpanel)
     856           
    852857        if n > 1:
    853858            ganged = rcParams['plotter.ganged']
     
    865870#            self._plotter.set_panels()
    866871            self._plotter.set_panels(layout=self._panellayout)
    867         r=0
     872        #r = 0
     873        r = self._rowcount
    868874        nr = scan.nrow()
    869875        a0,b0 = -1,-1
     
    882888                xlab = self._abcissa and self._abcissa[panelcount] \
    883889                       or scan._getabcissalabel()
     890                if self._offset and not self._abcissa:
     891                    xlab += " (relative)"
    884892                ylab = self._ordinate and self._ordinate[panelcount] \
    885893                       or scan._get_ordinate_label()
     
    887895                self._plotter.set_axes('ylabel', ylab)
    888896                lbl = self._get_label(scan, r, self._panelling, self._title)
     897                #if self._panelling == 'r': lbl = ''
    889898                if isinstance(lbl, list) or isinstance(lbl, tuple):
    890899                    if 0 <= panelcount < len(lbl):
     
    895904                self._plotter.set_axes('title',lbl)
    896905                newpanel = True
    897                 stackcount =0
     906                stackcount = 0
    898907                panelcount += 1
    899             if (b > b0 or newpanel) and stackcount < nstack:
     908            #if (b > b0 or newpanel) and stackcount < nstack:
     909            if stackcount < nstack and (newpanel or (a == a0 and b > b0)):
    900910                y = []
    901911                if len(polmodes):
     
    908918                    if d[self._stacking](r) in self._maskselection[self._stacking]:
    909919                        m = logical_and(m, self._usermask)
    910                 x = scan._getabcissa(r)
    911920                from numpy import ma, array
     921                x = array(scan._getabcissa(r))
     922                if self._offset:
     923                    x += self._offset
    912924                y = ma.masked_array(y,mask=logical_not(array(m,copy=False)))
    913925                if self._minmaxx is not None:
     
    960972                break
    961973            r+=1 # next row
     974        ###-S
     975        self._rowcount = r+1
     976        self._panelcnt += panelcount
     977        if self._plotter.figmgr.casabar:
     978            if self._panelcnt >= nptot-1:
     979                self._plotter.figmgr.casabar.disable_next()
     980            else:
     981                self._plotter.figmgr.casabar.enable_next()
     982            #if self._panelcnt - panelcount > 0:
     983            #    self._plotter.figmgr.casabar.enable_prev()
     984            #else:
     985            #    self._plotter.figmgr.casabar.disable_prev()
     986        ###-E
    962987        #reset the selector to the scantable's original
    963988        scan.set_selection(savesel)
     
    968993            for o in self._plotter.figure.findobj(Text):
    969994                o.set_fontproperties(self._fp)
     995
     996    def _get_sortstring(self, lorders):
     997        d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO',
     998              'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME', 'r':None, '_r':None }
     999        if not (type(lorders) == list) and not (type(lorders) == tuple):
     1000            return None
     1001        if len(lorders) > 0:
     1002            lsorts = []
     1003            for order in lorders:
     1004                ssort = d0[order]
     1005                if ssort:
     1006                    lsorts.append(ssort)
     1007            return lsorts
     1008        return None
    9701009
    9711010    def set_selection(self, selection=None, refresh=True, **kw):
     
    9921031            raise TypeError("'selection' is not of type selector")
    9931032
    994         d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO',
    995               'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME' }
    996         order = [d0[self._panelling],d0[self._stacking]]
    997         self._selection.set_order(order)
     1033        order = self._get_sortstring([self._panelling,self._stacking])
     1034        if order:
     1035            self._selection.set_order(order)
    9981036        if refresh and self._data: self.plot(self._data)
    9991037
    10001038    def _get_selected_n(self, scan):
    10011039        d1 = {'b': scan.getbeamnos, 's': scan.getscannos,
    1002              'i': scan.getifnos, 'p': scan.getpolnos, 't': scan.ncycle }
     1040             'i': scan.getifnos, 'p': scan.getpolnos, 't': scan.ncycle,
     1041             'r': scan.nrow, '_r': False}
    10031042        d2 = { 'b': self._selection.get_beams(),
    10041043               's': self._selection.get_scans(),
    10051044               'i': self._selection.get_ifs(),
    10061045               'p': self._selection.get_pols(),
    1007                't': self._selection.get_cycles() }
     1046               't': self._selection.get_cycles(),
     1047               'r': False, '_r': 1}
    10081048        n =  d2[self._panelling] or d1[self._panelling]()
    10091049        nstack = d2[self._stacking] or d1[self._stacking]()
     
    10241064             'i': "IF"+str(scan.getif(row)),
    10251065             'p': poleval,
    1026              't': str(scan.get_time(row)) }
     1066             't': str(scan.get_time(row)),
     1067             'r': "row "+str(row),
     1068             #'_r': str(scan.get_time(row))+",\nIF"+str(scan.getif(row))+", "+poleval+", Beam"+str(scan.getbeam(row)) }
     1069             '_r': "" }
    10271070        return userlabel or d[mode]
    10281071
    10291072    def plotazel(self, scan=None, outfile=None):
    1030     #def plotazel(self):
    10311073        """
    10321074        plot azimuth and elevation versus time of a scantable
    10331075        """
     1076        visible = rcParams['plotter.gui']
    10341077        from matplotlib import pylab as PL
    10351078        from matplotlib.dates import DateFormatter, timezone
     
    10371080        from matplotlib.ticker import MultipleLocator
    10381081        from numpy import array, pi
     1082        if not visible or not self._visible:
     1083            PL.ioff()
     1084            from matplotlib.backends.backend_agg import FigureCanvasAgg
     1085            PL.gcf().canvas.switch_backends(FigureCanvasAgg)
    10391086        self._data = scan
    10401087        self._outfile = outfile
     
    10461093        PL.clf()
    10471094        # Adjust subplot layouts
    1048         if len(self._panellayout) !=6: self.set_panellayout(refresh=False)
     1095        if len(self._panellayout) != 6:
     1096            self.set_panellayout(refresh=False)
    10491097        lef, bot, rig, top, wsp, hsp = self._panellayout
    10501098        PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top,
     
    11261174
    11271175    def plotpointing(self, scan=None, outfile=None):
    1128     #def plotpointing(self):
    11291176        """
    11301177        plot telescope pointings
    11311178        """
     1179        visible = rcParams['plotter.gui']
    11321180        from matplotlib import pylab as PL
    11331181        from numpy import array, pi
     1182        if not visible or not self._visible:
     1183            PL.ioff()
     1184            from matplotlib.backends.backend_agg import FigureCanvasAgg
     1185            PL.gcf().canvas.switch_backends(FigureCanvasAgg)
    11341186        self._data = scan
    11351187        self._outfile = outfile
     
    11411193        PL.clf()
    11421194        # Adjust subplot layouts
    1143         if len(self._panellayout) !=6: self.set_panellayout(refresh=False)
     1195        if len(self._panellayout) != 6:
     1196            self.set_panellayout(refresh=False)
    11441197        lef, bot, rig, top, wsp, hsp = self._panellayout
    11451198        PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top,
     
    11621215    # plot total power data
    11631216    # plotting in time is not yet implemented..
     1217    @asaplog_post_dec
    11641218    def plottp(self, scan=None, outfile=None):
    11651219        if self._plotter.is_dead:
     
    11731227        if not self._data and not scan:
    11741228            msg = "Input is not a scantable"
    1175             if rcParams['verbose']:
    1176                 #print msg
    1177                 asaplog.push( msg )
    1178                 print_log( 'ERROR' )
    1179                 return
    11801229            raise TypeError(msg)
    11811230        if isinstance(scan, scantable):
     
    12071256        self._plotter.tidy()
    12081257        self._plotter.show(hardrefresh=False)
    1209         print_log()
    12101258        return
    12111259
     
    12681316
    12691317    # printing header information
     1318    @asaplog_post_dec
    12701319    def print_header(self, plot=True, fontsize=9, logger=False, selstr='', extrastr=''):
    12711320        """
     
    12741323            plot:      whether or not print header info on the plot.
    12751324            fontsize:  header font size (valid only plot=True)
    1276             autoscale: whether or not autoscale the plot (valid only plot=True)
    12771325            logger:    whether or not print header info on the logger.
    12781326            selstr:    additional selection string (not verified)
    12791327            extrastr:  additional string to print (not verified)
    12801328        """
    1281         if not plot and not logger: return
    1282         if not self._data: raise RuntimeError("No scantable has been set yet.")
     1329        if not plot and not logger:
     1330            return
     1331        if not self._data:
     1332            raise RuntimeError("No scantable has been set yet.")
    12831333        # Now header will be printed on plot and/or logger.
    12841334        # Get header information and format it.
     
    13131363            asaplog.push(extrastr)
    13141364            asaplog.push(ssum[ssum.find('Beams:'):])
    1315             print_log()
    13161365        del ssum
Note: See TracChangeset for help on using the changeset viewer.