Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/asapplotter.py

    r1949 r1824  
    22from asap.selector import selector
    33from asap.scantable import scantable
    4 from asap.logging import asaplog, asaplog_post_dec
     4from asap.logging import asaplog, print_log, print_log_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 
    17     .. note::
    18 
     16    Note:
    1917        Currenly it only plots 'spectra' not Tsys or
    2018        other variables.
    21 
    2219    """
    2320    def __init__(self, visible=None , **kwargs):
     
    5148        self._fp = FontProperties()
    5249        self._panellayout = self.set_panellayout(refresh=False)
    53         self._offset = None
    54         self._rowcount = 0
    55         self._panelcnt = 0
    5650
    5751    def _translate(self, instr):
    58         keys = "s b i p t r".split()
     52        keys = "s b i p t".split()
    5953        if isinstance(instr, str):
    6054            for key in keys:
     
    8478        else: return None
    8579
    86     @asaplog_post_dec
     80    @print_log_dec
    8781    def plot(self, scan=None):
    8882        """
     
    9690            are consistent e.g. all 'channel' or all 'velocity' etc.
    9791        """
    98         self._rowcount = self._panelcnt = 0
    9992        if self._plotter.is_dead:
    10093            if hasattr(self._plotter.figmgr,'casabar'):
     
    10396            self._plotter.figmgr.casabar=self._newcasabar()
    10497        self._plotter.hold()
    105         #self._plotter.clear()
     98        self._plotter.clear()
    10699        if not self._data and not scan:
    107100            msg = "Input is not a scantable"
     101            if rcParams['verbose']:
     102                #print msg
     103                asaplog.push( msg )
     104                print_log( 'ERROR' )
     105                return
    108106            raise TypeError(msg)
    109         if scan:
    110             self.set_data(scan, refresh=False)
     107        if scan: self.set_data(scan,refresh=False)
    111108        self._plot(self._data)
    112109        if self._minmaxy is not None:
     
    116113        self._plotter.tidy()
    117114        self._plotter.show(hardrefresh=False)
     115        print_log()
    118116        return
    119117
     
    127125    def create_mask(self, nwin=1, panel=0, color=None):
    128126        """
    129         Interactively define a mask. It retruns a mask that is equivalent to
     127        Interactively define a mask.It retruns a mask that is equivalent to
    130128        the one created manually with scantable.create_mask.
    131129        Parameters:
     
    277275    # end matplotlib.axes fowarding functions
    278276
    279     @asaplog_post_dec
    280277    def set_data(self, scan, refresh=True):
    281278        """
     
    298295                    # reset
    299296                    self._reset()
    300                     msg = "A new scantable is set to the plotter. "\
    301                           "The masks and data selections are reset."
     297                    msg = "A new scantable is set to the plotter. The masks and data selections are reset."
    302298                    asaplog.push( msg )
     299                    print_log( 'INFO' )
    303300            else:
    304301                self._data = scan
     
    306303        else:
    307304            msg = "Input is not a scantable"
     305            if rcParams['verbose']:
     306                #print msg
     307                asaplog.push( msg )
     308                print_log( 'ERROR' )
     309                return
    308310            raise TypeError(msg)
    309311
     
    316318        if refresh: self.plot()
    317319
    318     @asaplog_post_dec
     320
    319321    def set_mode(self, stacking=None, panelling=None, refresh=True):
    320322        """
     
    339341        if not self.set_panelling(panelling) or \
    340342               not self.set_stacking(stacking):
    341             raise TypeError(msg)
    342         if self._panelling == 'r':
    343             self._stacking = '_r'
    344         elif self._stacking == 'r':
    345             self._panelling = '_r'
     343            if rcParams['verbose']:
     344                #print msg
     345                asaplog.push( msg )
     346                print_log( 'ERROR' )
     347                return
     348            else:
     349                raise TypeError(msg)
    346350        if refresh and self._data: self.plot(self._data)
    347351        return
    348352
    349353    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'
    363361            return True
    364362        return False
     
    384382
    385383    def set_stacking(self, what=None):
    386         """Set the 'stacking' mode i.e. which type of spectra should be
    387         overlayed.
    388         """
    389384        mode = what
    390385        if mode is None:
     
    394389            self._stacking = md
    395390            self._lmap = None
    396             if md == 'r':
    397                 self._panelling = '_r'
    398391            return True
    399392        return False
    400393
    401     def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True, offset=None):
     394    def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True):
    402395        """
    403396        Set the range of interest on the abcissa of the plot
     
    407400                      replotted based on the new parameter setting(s).
    408401                      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.
    411402        Note:
    412403            These become non-sensical when the unit changes.
     
    414405
    415406        """
    416         self._offset = offset
    417407        if xstart is None and xend is None:
    418408            self._minmaxx = None
     
    660650            deltachan:    the number of channels to include each side of the
    661651                          line to determine a local maximum/minimum
    662             rotate:       the rotation (in degrees) for the text label (default 90.0)
     652            rotate:       the rotation (in degrees) )for the text label (default 90.0)
    663653            location:     the location of the line annotation from the 'top',
    664654                          'bottom' or alternate (None - the default)
     
    730720    def save(self, filename=None, orientation=None, dpi=None):
    731721        """
    732         Save the plot to a file. The known formats are 'png', 'ps', 'eps'.
     722        Save the plot to a file. The know formats are 'png', 'ps', 'eps'.
    733723        Parameters:
    734724             filename:    The name of the output file. This is optional
     
    746736        return
    747737
    748     @asaplog_post_dec
     738
    749739    def set_mask(self, mask=None, selection=None, refresh=True):
    750740        """
     
    764754        if not self._data:
    765755            msg = "Can only set mask after a first call to plot()"
    766             raise RuntimeError(msg)
     756            if rcParams['verbose']:
     757                #print msg
     758                asaplog.push( msg )
     759                print_log( 'ERROR' )
     760                return
     761            else:
     762                raise RuntimeError(msg)
    767763        if len(mask):
    768764            if isinstance(mask, list) or isinstance(mask, tuple):
     
    821817        self._usermask = []
    822818        self._usermaskspectra = None
    823         self._offset = None
    824819        self.set_selection(None, False)
    825820
     
    827822        savesel = scan.get_selection()
    828823        sel = savesel +  self._selection
    829         order = self._get_sortstring([self._panelling,self._stacking])
    830         if order:
    831             sel.set_order(order)
     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)
    832828        scan.set_selection(sel)
    833829        d = {'b': scan.getbeam, 's': scan.getscan,
    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}
     830             'i': scan.getif, 'p': scan.getpol, 't': scan._gettime }
    837831
    838832        polmodes = dict(zip(self._selection.get_pols(),
     
    845839        if isinstance(nstack0, int): nstack = nstack0
    846840        else: nstack = len(nstack0)
    847         nptot = n
    848841        maxpanel, maxstack = 16,16
    849         if nstack > maxstack:
    850             msg ="Scan to be overlayed contains more than %d selections.\n" \
    851                   "Selecting first %d selections..." % (maxstack, maxstack)
     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)
    852848            asaplog.push(msg)
    853             asaplog.post('WARN')
     849            print_log('WARN')
     850            n = min(n,maxpanel)
    854851            nstack = min(nstack,maxstack)
    855         n = min(n,maxpanel)
    856            
    857852        if n > 1:
    858853            ganged = rcParams['plotter.ganged']
     
    870865#            self._plotter.set_panels()
    871866            self._plotter.set_panels(layout=self._panellayout)
    872         #r = 0
    873         r = self._rowcount
     867        r=0
    874868        nr = scan.nrow()
    875869        a0,b0 = -1,-1
     
    888882                xlab = self._abcissa and self._abcissa[panelcount] \
    889883                       or scan._getabcissalabel()
    890                 if self._offset and not self._abcissa:
    891                     xlab += " (relative)"
    892884                ylab = self._ordinate and self._ordinate[panelcount] \
    893885                       or scan._get_ordinate_label()
     
    895887                self._plotter.set_axes('ylabel', ylab)
    896888                lbl = self._get_label(scan, r, self._panelling, self._title)
    897                 #if self._panelling == 'r': lbl = ''
    898889                if isinstance(lbl, list) or isinstance(lbl, tuple):
    899890                    if 0 <= panelcount < len(lbl):
     
    904895                self._plotter.set_axes('title',lbl)
    905896                newpanel = True
    906                 stackcount = 0
     897                stackcount =0
    907898                panelcount += 1
    908             #if (b > b0 or newpanel) and stackcount < nstack:
    909             if stackcount < nstack and (newpanel or (a == a0 and b > b0)):
     899            if (b > b0 or newpanel) and stackcount < nstack:
    910900                y = []
    911901                if len(polmodes):
     
    918908                    if d[self._stacking](r) in self._maskselection[self._stacking]:
    919909                        m = logical_and(m, self._usermask)
     910                x = scan._getabcissa(r)
    920911                from numpy import ma, array
    921                 x = array(scan._getabcissa(r))
    922                 if self._offset:
    923                     x += self._offset
    924912                y = ma.masked_array(y,mask=logical_not(array(m,copy=False)))
    925913                if self._minmaxx is not None:
     
    972960                break
    973961            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
    987962        #reset the selector to the scantable's original
    988963        scan.set_selection(savesel)
     
    993968            for o in self._plotter.figure.findobj(Text):
    994969                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
    1009970
    1010971    def set_selection(self, selection=None, refresh=True, **kw):
     
    1031992            raise TypeError("'selection' is not of type selector")
    1032993
    1033         order = self._get_sortstring([self._panelling,self._stacking])
    1034         if order:
    1035             self._selection.set_order(order)
     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)
    1036998        if refresh and self._data: self.plot(self._data)
    1037999
    10381000    def _get_selected_n(self, scan):
    10391001        d1 = {'b': scan.getbeamnos, 's': scan.getscannos,
    1040              'i': scan.getifnos, 'p': scan.getpolnos, 't': scan.ncycle,
    1041              'r': scan.nrow, '_r': False}
     1002             'i': scan.getifnos, 'p': scan.getpolnos, 't': scan.ncycle }
    10421003        d2 = { 'b': self._selection.get_beams(),
    10431004               's': self._selection.get_scans(),
    10441005               'i': self._selection.get_ifs(),
    10451006               'p': self._selection.get_pols(),
    1046                't': self._selection.get_cycles(),
    1047                'r': False, '_r': 1}
     1007               't': self._selection.get_cycles() }
    10481008        n =  d2[self._panelling] or d1[self._panelling]()
    10491009        nstack = d2[self._stacking] or d1[self._stacking]()
     
    10641024             'i': "IF"+str(scan.getif(row)),
    10651025             'p': poleval,
    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': "" }
     1026             't': str(scan.get_time(row)) }
    10701027        return userlabel or d[mode]
    10711028
    10721029    def plotazel(self, scan=None, outfile=None):
     1030    #def plotazel(self):
    10731031        """
    10741032        plot azimuth and elevation versus time of a scantable
    10751033        """
    1076         visible = rcParams['plotter.gui']
    10771034        from matplotlib import pylab as PL
    10781035        from matplotlib.dates import DateFormatter, timezone
     
    10801037        from matplotlib.ticker import MultipleLocator
    10811038        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)
    10861039        self._data = scan
    10871040        self._outfile = outfile
     
    10931046        PL.clf()
    10941047        # Adjust subplot layouts
    1095         if len(self._panellayout) != 6:
    1096             self.set_panellayout(refresh=False)
     1048        if len(self._panellayout) !=6: self.set_panellayout(refresh=False)
    10971049        lef, bot, rig, top, wsp, hsp = self._panellayout
    10981050        PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top,
     
    11741126
    11751127    def plotpointing(self, scan=None, outfile=None):
     1128    #def plotpointing(self):
    11761129        """
    11771130        plot telescope pointings
    11781131        """
    1179         visible = rcParams['plotter.gui']
    11801132        from matplotlib import pylab as PL
    11811133        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)
    11861134        self._data = scan
    11871135        self._outfile = outfile
     
    11931141        PL.clf()
    11941142        # Adjust subplot layouts
    1195         if len(self._panellayout) != 6:
    1196             self.set_panellayout(refresh=False)
     1143        if len(self._panellayout) !=6: self.set_panellayout(refresh=False)
    11971144        lef, bot, rig, top, wsp, hsp = self._panellayout
    11981145        PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top,
     
    12151162    # plot total power data
    12161163    # plotting in time is not yet implemented..
    1217     @asaplog_post_dec
    12181164    def plottp(self, scan=None, outfile=None):
    12191165        if self._plotter.is_dead:
     
    12271173        if not self._data and not scan:
    12281174            msg = "Input is not a scantable"
     1175            if rcParams['verbose']:
     1176                #print msg
     1177                asaplog.push( msg )
     1178                print_log( 'ERROR' )
     1179                return
    12291180            raise TypeError(msg)
    12301181        if isinstance(scan, scantable):
     
    12561207        self._plotter.tidy()
    12571208        self._plotter.show(hardrefresh=False)
     1209        print_log()
    12581210        return
    12591211
     
    13161268
    13171269    # printing header information
    1318     @asaplog_post_dec
    13191270    def print_header(self, plot=True, fontsize=9, logger=False, selstr='', extrastr=''):
    13201271        """
     
    13231274            plot:      whether or not print header info on the plot.
    13241275            fontsize:  header font size (valid only plot=True)
     1276            autoscale: whether or not autoscale the plot (valid only plot=True)
    13251277            logger:    whether or not print header info on the logger.
    13261278            selstr:    additional selection string (not verified)
    13271279            extrastr:  additional string to print (not verified)
    13281280        """
    1329         if not plot and not logger:
    1330             return
    1331         if not self._data:
    1332             raise RuntimeError("No scantable has been set yet.")
     1281        if not plot and not logger: return
     1282        if not self._data: raise RuntimeError("No scantable has been set yet.")
    13331283        # Now header will be printed on plot and/or logger.
    13341284        # Get header information and format it.
     
    13631313            asaplog.push(extrastr)
    13641314            asaplog.push(ssum[ssum.find('Beams:'):])
     1315            print_log()
    13651316        del ssum
Note: See TracChangeset for help on using the changeset viewer.