Changeset 920 for trunk


Ignore:
Timestamp:
03/22/06 21:45:31 (18 years ago)
Author:
mar637
Message:

asap2 migration of plotter

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/asapplotter.py

    r794 r920  
    1717        self._plotter = self._newplotter()
    1818
    19         self._tdict = {'Time':'t','time':'t','t':'t','T':'t'}
    20         self._bdict = {'Beam':'b','beam':'b','b':'b','B':'b'}
    21         self._idict = {'IF':'i','if':'i','i':'i','I':'i'}
    22         self._pdict = {'Pol':'p','pol':'p','p':'p'}
    23         self._sdict = {'scan':'s','Scan':'s','s':'s','S':'s'}
    24         self._cdict = {'t':'len(self._cursor["t"])',
    25                        'b':'len(self._cursor["b"])',
    26                        'i':'len(self._cursor["i"])',
    27                        'p':'len(self._cursor["p"])',
    28                        's':'len(scans)'}
    29         self._ldict = {'b':'Beam',
    30                        'i':'IF',
    31                        'p':'Pol',
    32                        's':'Scan'}
    33         self._dicts = [self._tdict,self._bdict,
    34                        self._idict,self._pdict,
    35                        self._sdict]
     19
    3620        self._panelling = None
    3721        self._stacking = None
     
    5034        self._abcissa = None
    5135        self._abcunit = None
    52         self._cursor = {'t':None, 'b':None,
    53                         'i':None, 'p':None
    54                         }
    55         self._usermask = None
    56         self._usermaskspectra = None
     36        self._usermask = []
     37        self._maskselection = None
     38        from asap._asap import selector
     39        self._selection = selector()
     40
     41    def _translate(self, instr):
     42        keys = "s b i p t".split()
     43        if isinstance(instr, str):
     44            for key in keys:
     45                if instr.lower().startswith(key):
     46                    return key
     47        return None
    5748
    5849    def _newplotter(self):
     
    6455
    6556
    66     def _translate(self, name):
    67         for d in self._dicts:
    68             if d.has_key(name):
    69                 return d[name]
    70         return None
    71 
    72     def plot(self, *args):
    73         """
    74         Plot a (list of) scantables.
    75         Parameters:
    76             one or more comma separated scantables
     57    def plot(self, scan):
     58        """
     59        Plot a scantable.
     60        Parameters:
     61            scan:   a scantable
    7762        Note:
    78             If a (list) of scantables was specified in a previous call
     63            If a scantable was specified in a previous call
    7964            to plot, no argument has to be given to 'replot'
    80             NO checking is done that the abcissas of the scantables
     65            NO checking is done that the abcissas of the scantable
    8166            are consistent e.g. all 'channel' or all 'velocity' etc.
    8267        """
     
    8570        self._plotter.hold()
    8671        self._plotter.clear()
    87         if len(args) > 0:
     72        from asap import scantable
     73        if isinstance(scan, scantable):
    8874            if self._data is not None:
    89                 if list(args) != self._data:
    90                     self._data = list(args)
     75                if scan != self._data:
     76                    self._data = scan
    9177                    # reset
    9278                    self._reset()
    9379            else:
    94                 if isinstance(args[0], list):
    95                     self._data = args[0]
    96                 else:
    97                     self._data = list(args)
     80                self._data = scan
    9881                self._reset()
    9982        # ranges become invalid when unit changes
    100         if self._abcunit != self._data[0].get_unit():
     83        if self._abcunit != self._data.get_unit():
    10184            self._minmaxx = None
    10285            self._minmaxy = None
    103             self._abcunit = self._data[0].get_unit()
     86            self._abcunit = self._data.get_unit()
    10487            self._datamask = None
    105         if self._panelling == 't':
    106             maxrows = 25
    107             if self._data[0].nrow() > maxrows and not (self._rows and self._cols):
    108                 if self._cursor["t"] is None or \
    109                        (isinstance(self._cursor["t"],list) and \
    110                         len(self._cursor["t"]) > maxrows ):
    111                     from asap import asaplog
    112                     msg ="Scan to be plotted contains more than %d rows.\n" \
    113                           "Selecting first %d rows..." % (maxrows,maxrows)
    114                     asaplog.push(msg)
    115                     self._cursor["t"] = range(maxrows)
    116             self._plot_time(self._data[0], self._stacking)
    117         elif self._panelling == 's':
    118             self._plot_scans(self._data, self._stacking)
    119         else:
    120             self._plot_other(self._data, self._stacking)
     88        self._plot(self._data)
    12189        if self._minmaxy is not None:
    12290            self._plotter.set_limits(ylim=self._minmaxy)
     
    12492        print_log()
    12593        return
    126 
    127     def _plot_time(self, scan, colmode):
    128         if colmode == 't':
    129             return
    130         n = len(self._cursor["t"])
    131         cdict = {'b':'scan.setbeam(j)',
    132                  'i':'scan.setif(j)',
    133                  'p':'scan.setpol(j)'}
    134         cdict2 = {'b':'self._cursor["b"]',
    135                   'i':'self._cursor["i"]',
    136                   'p':'self._cursor["p"]'}
    137         ncol = 1
    138         if self._stacking is not None:
    139             ncol = eval(self._cdict.get(colmode))
    140         if n > 1:
    141             ganged = rcParams['plotter.ganged']
    142             if self._rows and self._cols:
    143                 n = min(n,self._rows*self._cols)
    144                 self._plotter.set_panels(rows=self._rows,cols=self._cols,
    145                                          nplots=n,ganged=ganged)
    146             else:
    147                 self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged)
    148         else:
    149             self._plotter.set_panels()
    150         allxlim=[]
    151         rows = self._cursor["t"]
    152         rows = rows[:n]
    153         self._plotter.palette(0)
    154         for rowsel in rows:
    155             i = self._cursor["t"].index(rowsel)
    156             if n > 1:
    157                 self._plotter.palette(0)
    158                 self._plotter.subplot(i)
    159             colvals = eval(cdict2.get(colmode))
    160             for j in colvals:
    161                 polmode = "raw"
    162                 jj = colvals.index(j)
    163                 savej = j
    164                 for k in cdict.keys():
    165                     sel = eval(cdict2.get(k))
    166                     j = sel[0]
    167                     if k == "p":
    168                         which = self._cursor["p"].index(j)
    169                         polmode = self._polmode[which]
    170                         j = which
    171                     eval(cdict.get(k))
    172                 j = savej
    173                 if colmode == "p":
    174                     polmode = self._polmode[self._cursor["p"].index(j)]
    175                     #j = jj
    176                 eval(cdict.get(colmode))
    177                 x = None
    178                 y = None
    179                 m = None
    180                 if self._title is None:
    181                     tlab = scan._getsourcename(rowsel)
    182                 else:
    183                     if len(self._title) >= n:
    184                         tlab = self._title[rowsel]
    185                     else:
    186                         tlab = scan._getsourcename(rowsel)
    187                 x,xlab = scan.get_abcissa(rowsel)
    188                 if self._abcissa: xlab = self._abcissa
    189                 y = None
    190                 m = scan._getmask(rowsel)
    191                 if self._usermask and self._usermask.count(j):
    192                     m  = logical_and(self._usermask, m)
    193                 if polmode == "stokes":
    194                     y = scan._getstokesspectrum(rowsel)
    195                 elif polmode == "stokes2":
    196                     y = scan._getstokesspectrum(rowsel,True)
    197                 elif polmode == "circular":
    198                     y = scan._stokestopolspectrum(rowsel,False,-1)
    199                 else:
    200                     y = scan._getspectrum(rowsel)
    201                 if self._ordinate:
    202                     ylab = self._ordinate
    203                 else:
    204                     ylab = scan._get_ordinate_label()
    205                 m = scan._getmask(rowsel)
    206                 if self._datamask is not None:
    207                     if len(m) == len(self._datamask):
    208                         m = logical_and(m,self._datamask)
    209                 if self._lmap and len(self._lmap) > 0:
    210                     llab = self._lmap[jj]
    211                 else:
    212                     if colmode == 'p':
    213                         llab = self._get_pollabel(scan, polmode)
    214                     else:
    215                         llab = self._ldict.get(colmode)+' '+str(j)
    216                 self._plotter.set_line(label=llab)
    217                 if self._minmaxx is not None:
    218                     s,e = self._slice_indeces(x)
    219                     x = x[s:e]
    220                     y = y[s:e]
    221                     m = m[s:e]
    222                 if len(x) > 1024 and rcParams['plotter.decimate']:
    223                     fac = len(x)/1024
    224                     x = x[::fac]
    225                     m = m[::fac]
    226                     y = y[::fac]
    227                 self._plotter.plot(x,y,m)
    228                 xlim=[min(x),max(x)]
    229                 if self._minmaxx is not None:
    230                     xlim = self._minmaxx
    231                 allxlim += xlim
    232             allxlim.sort()
    233             self._plotter.axes.set_xlim([allxlim[0],allxlim[-1]])
    234             self._plotter.set_axes('xlabel',xlab)
    235             self._plotter.set_axes('ylabel',ylab)
    236             self._plotter.set_axes('title',tlab)
    237 
    238         return
    239 
    240     def _plot_scans(self, scans, colmode):
    241         from asap import asaplog
    242         msg = "Plotting mode is scans across panels. Can only plot one row per scan."
    243         asaplog.push(msg)
    244         if colmode == 's':
    245             return
    246         cdict = {'b':'scan.setbeam(j)',
    247                  'i':'scan.setif(j)',
    248                  'p':'scan.setpol(j)'}
    249         cdict2 = {'b':'self._cursor["b"]',
    250                   'i':'self._cursor["i"]',
    251                   'p':'self._cursor["p"]'}
    252 
    253         n = len(scans)
    254         ncol = 1
    255         if self._stacking is not None:
    256             scan = scans[0]
    257             ncol = eval(self._cdict.get(colmode))
    258         if n > 1:
    259             ganged = rcParams['plotter.ganged']
    260             if self._rows and self._cols:
    261                 n = min(n,self._rows*self._cols)
    262                 self._plotter.set_panels(rows=self._rows,cols=self._cols,
    263                                          nplots=n,ganged=ganged)
    264             else:
    265                 self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged)
    266         else:
    267             self._plotter.set_panels()
    268 
    269         for scan in scans:
    270             self._plotter.palette(0)
    271             if n > 1:
    272                 self._plotter.subplot(scans.index(scan))
    273             colvals = eval(cdict2.get(colmode))
    274             rowsel = self._cursor["t"][0]
    275             allxlim=[]
    276             for j in colvals:
    277                 polmode = "raw"
    278                 jj = colvals.index(j)
    279                 savej = j
    280                 for k in cdict.keys():
    281                     sel = eval(cdict2.get(k))
    282                     j = sel[0]
    283                     eval(cdict.get(k))
    284                     if k == "p":
    285                         which = self._cursor["p"].index(j)
    286                         polmode = self._polmode[which]
    287                         j = which
    288                 j = savej
    289                 if colmode == "p":
    290                     polmode = self._polmode[self._cursor["p"].index(j)]
    291                     #j = jj
    292                 eval(cdict.get(colmode))
    293                 x = None
    294                 y = None
    295                 m = None
    296                 tlab = self._title
    297                 if not self._title:
    298                     tlab = scan._getsourcename(rowsel)
    299                 x,xlab = scan.get_abcissa(rowsel)
    300                 if self._abcissa: xlab = self._abcissa
    301                 if polmode == "stokes":
    302                     y = scan._getstokesspectrum(rowsel)
    303                 elif polmode == "stokes2":
    304                     y = scan._getstokesspectrum(rowsel,True)
    305                 elif polmode == "circular":
    306                     y = scan._stokestopolspectrum(rowsel,False,-1)
    307                 else:
    308                     y = scan._getspectrum(rowsel)
    309                 if self._ordinate:
    310                     ylab = self._ordinate
    311                 else:
    312                     ylab = scan._get_ordinate_label()
    313                 m = scan._getmask(rowsel)
    314                 if self._usermask and self._usermask.count(j):
    315                     m  = logical_and(self._usermask, m)
    316                 if self._lmap and len(self._lmap) > 0:
    317                     llab = self._lmap[jj]
    318                 else:
    319                     if colmode == 'p':
    320                         llab = self._get_pollabel(scan, polmode)
    321                     else:
    322                         llab = self._ldict.get(colmode)+' '+str(j)
    323                 self._plotter.set_line(label=llab)
    324                 if self._minmaxx is not None:
    325                     s,e = self._slice_indeces(x)
    326                     x = x[s:e]
    327                     y = y[s:e]
    328                     m = m[s:e]
    329                 if len(x) > 1024 and rcParams['plotter.decimate']:
    330                     fac = len(x)/1024
    331                     x = x[::fac]
    332                     m = m[::fac]
    333                     y = y[::fac]
    334                 self._plotter.plot(x,y,m)
    335                 xlim=[min(x),max(x)]
    336                 if self._minmaxx is not None:
    337                     xlim = self._minmaxx
    338                 allxlim += xlim
    339             allxlim.sort()
    340             self._plotter.axes.set_xlim([allxlim[0],allxlim[-1]])
    341             self._plotter.set_axes('xlabel',xlab)
    342             self._plotter.set_axes('ylabel',ylab)
    343             self._plotter.set_axes('title',tlab)
    344         print_log()
    345         return
    346 
    347     def _plot_other(self,scans,colmode):
    348         if colmode == self._panelling:
    349             return
    350         cdict = {'b':'scan.setbeam(i)',
    351                  'i':'scan.setif(i)',
    352                  'p':'scan.setpol(i)'}
    353         cdict2 = {'b':'self._cursor["b"]',
    354                   'i':'self._cursor["i"]',
    355                   'p':'self._cursor["p"]',
    356                   's': 'scans',
    357                   't': 'self._cursor["t"]'}
    358         scan = scans[0]
    359         n = eval(self._cdict.get(self._panelling))
    360         ncol=1
    361         if self._stacking is not None:
    362             ncol = eval(self._cdict.get(colmode))
    363         if n > 1:
    364             ganged = rcParams['plotter.ganged']
    365             if self._rows and self._cols:
    366                 n = min(n,self._rows*self._cols)
    367                 self._plotter.set_panels(rows=self._rows,cols=self._cols,
    368                                          nplots=n,ganged=ganged)
    369             else:
    370                 self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged)
    371         else:
    372             self._plotter.set_panels()
    373         panels = self._cursor[self._panelling]
    374         for i in panels:
    375             self._plotter.palette(0)
    376             polmode = "raw"
    377             ii = self._cursor[self._panelling].index(i)
    378             if n>1:
    379                 self._plotter.subplot(ii)
    380             if self._panelling == "p":
    381                 polmode = self._polmode[ii]
    382 
    383             eval(cdict.get(self._panelling))
    384 
    385             allxlim=[]
    386             colvals = eval(cdict2.get(colmode))
    387             for j in colvals:
    388                 rowsel = self._cursor["t"][0]
    389                 jj = colvals.index(j)
    390                 savei = i
    391                 for k in cdict.keys():
    392                     if k != self._panelling:
    393                         sel = eval(cdict2.get(k))
    394                         i = sel[0]
    395                         if k == "p":
    396                             which = self._cursor["p"].index(i)
    397                             polmode = self._polmode[which]
    398                             i = which
    399                         eval(cdict.get(k))
    400                 i = savei
    401                 if colmode == 's':
    402                     scan = j
    403                 elif colmode == 't':
    404                     rowsel = j
    405                 else:
    406                     savei = i
    407                     if colmode == 'p':
    408                         polmode = self._polmode[self._cursor["p"].index(j)]
    409 
    410                     i = j
    411                     eval(cdict.get(colmode))
    412                     i = savei
    413                 #if self._panelling == "p":
    414                 eval(cdict.get(self._panelling))
    415                 x = None
    416                 y = None
    417                 m = None
    418                 x,xlab = scan.get_abcissa(rowsel)
    419                 if self._abcissa: xlab = self._abcissa
    420                 if polmode == "stokes":
    421                     y = scan._getstokesspectrum(rowsel)
    422                 elif polmode == "stokes2":
    423                     y = scan._getstokesspectrum(rowsel,True)
    424                 elif polmode == "circular":
    425                     y = scan._stokestopolspectrum(rowsel,False,-1)
    426                 else:
    427                     y = scan._getspectrum(rowsel)
    428 
    429                 if self._ordinate:
    430                     ylab = self._ordinate
    431                 else:
    432                     ylab = scan._get_ordinate_label()
    433                 m = scan._getmask(rowsel)
    434                 if self._usermask and self._usermask.count(j):
    435                     m  = logical_and(self._usermask, m)
    436 
    437                 if colmode == 's' or colmode == 't':
    438                     if self._title and len(self._title) > 0:
    439                         tlab = self._title[ii]
    440                     else:
    441                         if self._panelling == 'p':
    442                             tlab = self._get_pollabel(scan, polmode)
    443                         else:
    444                             tlab = self._ldict.get(self._panelling)+' '+str(i)
    445                     if self._lmap and len(self._lmap) > 0:
    446                         llab = self._lmap[jj]
    447                     else:
    448                         llab = scan._getsourcename(rowsel)
    449                 else:
    450                     if self._title and len(self._title) > 0:
    451                         tlab = self._title[ii]
    452                     else:
    453                         if self._panelling == 'p':
    454                             tlab = self._get_pollabel(scan, polmode)
    455                         else:
    456                             tlab = self._ldict.get(self._panelling)+' '+str(i)
    457                     if self._lmap and len(self._lmap) > 0:
    458                         llab = self._lmap[jj]
    459                     else:
    460                         if colmode == 'p':
    461                             llab = self._get_pollabel(scan, polmode)
    462                         else:
    463                             llab = self._ldict.get(colmode)+' '+str(j)
    464                 self._plotter.set_line(label=llab)
    465                 if self._minmaxx is not None:
    466                     s,e = self._slice_indeces(x)
    467                     x = x[s:e]
    468                     y = y[s:e]
    469                     m = m[s:e]
    470                 if len(x) > 1024 and rcParams['plotter.decimate']:
    471                     fac = len(x)/1024
    472                     x = x[::fac]
    473                     m = m[::fac]
    474                     y = y[::fac]
    475                 self._plotter.plot(x,y,m)
    476                 xlim=[min(x),max(x)]
    477                 if self._minmaxx is not None:
    478                     xlim = self._minmaxx
    479                 allxlim += xlim
    480             allxlim.sort()
    481             self._plotter.axes.set_xlim([allxlim[0],allxlim[-1]])
    482 
    483             self._plotter.set_axes('xlabel',xlab)
    484             self._plotter.set_axes('ylabel',ylab)
    485             self._plotter.set_axes('title',tlab)
    486 
    487         return
    488 
    48994
    49095    def set_mode(self, stacking=None, panelling=None):
     
    512117            else:
    513118                raise TypeError(msg)
    514         if self._data: self.plot()
     119        if self._data: self.plot(self._data)
    515120        return
    516121
     
    539144        self._rows = rows
    540145        self._cols = cols
    541         if self._data: self.plot()
     146        if self._data: self.plot(self._data)
    542147        return
    543148
     
    571176        else:
    572177            self._minmaxy = [ystart,yend]
    573         if self._data: self.plot()
     178        if self._data: self.plot(self._data)
    574179        return
    575180
     
    593198        """
    594199        self._lmap = mp
    595         if self._data: self.plot()
     200        if self._data: self.plot(self._data)
    596201        return
    597202
     
    605210        """
    606211        self._title = title
    607         if self._data: self.plot()
     212        if self._data: self.plot(self._data)
    608213        return
    609214
     
    617222        """
    618223        self._ordinate = ordinate
    619         if self._data: self.plot()
     224        if self._data: self.plot(self._data)
    620225        return
    621226
     
    629234        """
    630235        self._abcissa = abcissa
    631         if self._data: self.plot()
     236        if self._data: self.plot(self._data)
    632237        return
    633238
     
    645250            colormap = colormap.split()
    646251        self._plotter.palette(0,colormap=colormap)
    647         if self._data: self.plot()
     252        if self._data: self.plot(self._data)
    648253
    649254    def set_linestyles(self, linestyles):
     
    668273            linestyles = linestyles.split()
    669274        self._plotter.palette(color=0,linestyle=0,linestyles=linestyles)
    670         if self._data: self.plot()
     275        if self._data: self.plot(self._data)
    671276
    672277    def save(self, filename=None, orientation=None, dpi=None):
     
    688293        return
    689294
    690     def set_cursor(self, row=None,beam=None,IF=None,pol=None, refresh=True):
    691         """
    692         Specify a 'cursor' for plotting selected spectra. Time (rows),
    693         Beam, IF, Polarisation ranges can be specified.
    694         Parameters:
    695             Default for all paramaters is to select all available
    696             row:    selects the rows (time stamps) to be plotted, this has
    697                     to be a vector of row indices, e.g. row=[0,2,5] or row=[2]
    698             beam:   select a range of beams
    699             IF:     select a range of IFs
    700             pol:    select Polarisations for plotting these can be by index
    701                     (raw polarisations (default)) or by names any of:
    702                     ["I", "Q", "U", "V"] or
    703                     ["I", "Plinear", "Pangle", "V"] or
    704                     ["XX", "YY", "Real(XY)", "Imag(XY)"] or
    705                     ["RR", "LL"]
    706         Example:
    707             plotter.set_mode('pol','time')
    708             plotter.plot(myscan) # plots all raw polarisations colour stacked
    709             plotter.set_cursor(pol=["I"]) # plot "I" only for all rows
    710             # plot "I" only for two time stamps row=0 and row=2
    711             plotter.set_cursor(row=[0,2],pol=["I"])
    712 
    713         Note:
    714             Be careful to select only exisiting polarisations.
     295
     296    def set_mask(self, mask=None, selection=None):
     297        """
     298        Set a plotting mask for a specific polarization.
     299        This is useful for masking out "noise" Pangle outside a source.
     300        Parameters:
     301             mask:           a mask from scantable.create_mask
     302             selection:      the spectra to apply the mask to.
     303        Example:
     304             select = selector()
     305             select.setpolstrings("Pangle")
     306             plotter.set_mask(mymask, select)
    715307        """
    716308        if not self._data:
    717             msg = "Can only set cursor after a first call to plot()"
     309            msg = "Can only set mask after a first call to plot()"
    718310            if rcParams['verbose']:
    719311                print msg
     
    721313            else:
    722314                raise RuntimeError(msg)
    723 
    724         n = self._data[0].nrow()
    725         if row is None:
    726             self._cursor["t"] = range(n)
     315        if len(mask):
     316            if isinstance(mask, list) or isinstance(mask, tuple):
     317                self._usermask = array(mask)
     318            else:
     319                self._usermask = mask
     320        if mask is None and selection is None:
     321            self._usermask = []
     322            self._maskselection = None
     323        from asap._asap import selector
     324        if isinstance(selection, selector):
     325            self._maskselection = {'b': selection._getbeams(),
     326                                   's': selection._getscans(),
     327                                   'i': selection._getifs(),
     328                                   'p': selection._getpols(),
     329                                   't': [] }
    727330        else:
    728             for i in row:
    729                 if i < 0 or i >= n:
    730                     msg = "Row index '%d' out of range" % i
    731                     if rcParams['verbose']:
    732                         print msg
    733                         return
    734                     else:
    735                         raise IndexError(msg)
    736             self._cursor["t"] = row
    737 
    738         n = self._data[0].nbeam()
    739         if beam is None:
    740             self._cursor["b"] = range(n)
    741         else:
    742             for i in beam:
    743                 if i < 0 or  i >= n:
    744                     msg = "Beam index '%d' out of range" % i
    745                     if rcParams['verbose']:
    746                         print msg
    747                         return
    748                     else:
    749                         raise IndexError(msg)
    750 
    751             self._cursor["b"] = beam
    752 
    753         n = self._data[0].nif()
    754         if IF is None:
    755             self._cursor["i"] = range(n)
    756         else:
    757             for i in IF:
    758                 if i < 0 or i >= n:
    759                     msg = "IF index '%d' out of range" %i
    760                     if rcParams['verbose']:
    761                         print msg
    762                         return
    763                     else:
    764                         raise IndexError(msg)
    765             self._cursor["i"] = IF
    766 
    767         n = self._data[0].npol()
    768         dstokes = {"I":0,"Q":1,"U":2,"V":3}
    769         dstokes2 = {"I":0,"Plinear":1,"Pangle":2,"V":3}
    770         draw = {"XX":0, "YY":1,"Real(XY)":2, "Imag(XY)":3}
    771         dcirc = { "RR":0,"LL":1}#,"Real(RL)":2,"Imag(RL)":3}
    772 
    773         if pol is None:
    774             self._cursor["p"] = range(n)
    775             self._polmode = ["raw" for i in range(n)]
    776         else:
    777             if isinstance(pol,str):
    778                 pol = pol.split()
    779             polmode = []
    780             pols = []
    781             for i in pol:
    782                 if isinstance(i,str):
    783                     if draw.has_key(i):
    784                         pols.append(draw.get(i))
    785                         polmode.append("raw")
    786                     elif dstokes.has_key(i):
    787                         pols.append(dstokes.get(i))
    788                         polmode.append("stokes")
    789                     elif dstokes2.has_key(i):
    790                         pols.append(dstokes2.get(i))
    791                         polmode.append("stokes2")
    792                     elif dcirc.has_key(i):
    793                         pols.append(dcirc.get(i))
    794                         polmode.append("circular")
    795                     else:
    796                         msg = "Pol type '%s' not valid" %i
    797                         if rcParams['verbose']:
    798                             print msg
    799                             return
    800                         else:
    801                             raise TypeError(msg)
    802                 elif 0 > i >= n:
    803                     print "Pol index '%d' out of range" %i
    804                     if rcParams['verbose']:
    805                         print msg
    806                         return
    807                     else:
    808                         raise IndexError(msg)
    809                 else:
    810                     pols.append(i)
    811                     polmode.append("raw")
    812             self._cursor["p"] = pols
    813             self._polmode = polmode
    814         if self._data and refresh: self.plot()
    815 
    816     def set_mask(self, mask=None, pol=None):
    817         """
    818         Set a plotting mask for a specific polarization.
    819         This is useful for masking out "noise" Pangle outside a source.
    820         Parameters:
    821              mask:     a mask from scantable.create_mask
    822              pol:      the polarisation to apply the mask to, e.g
    823                        "Pangle" or "XX" etc.
    824         Example:
    825         """
    826         if not self._data:
    827             msg = "Can only set cursor after a first call to plot()"
    828             if rcParams['verbose']:
    829                 print msg
    830                 return
    831             else:
    832                 raise RuntimeError(msg)
    833         if isinstance(mask, array):
    834             self._usermask = mask
    835         if isinstance(mask, list):
    836             self._usermask = array(mask)
    837         if mask is None and pol is None:
    838             self._usermask = None
    839             self._usermaskspectra = None
    840 
    841         dstokes = {"I":0,"Q":1,"U":2,"V":3}
    842         dstokes2 = {"I":0,"Plinear":1,"Pangle":2,"V":3}
    843         draw = {"XX":0, "YY":1,"Real(XY)":2, "Imag(XY)":3}
    844         dcirc = { "RR":0,"LL":1}#,"Real(RL)":2,"Imag(RL)":3}
    845         if isinstance(pol, str):
    846             pol = pol.split()
    847         if isinstance(pol, list):
    848             if isinstance(pol[0], str):
    849                 pass
    850             else:
    851                 cpos = self._cursor[self._stacking]
    852                 self._usermaskspectra =filter(lambda i: filter(lambda j: j==i ,cpos),pol)
    853         else:
    854             return
    855         self.plot()
    856 
    857     def _get_pollabel(self, scan, polmode):
    858         tlab = ""
    859         if polmode == "stokes":
    860             tlab = scan._getpolarizationlabel(0,1,0)
    861         elif polmode == "stokes2":
    862             tlab = scan._getpolarizationlabel(0,1,1)
    863         elif polmode == "circular":
    864             tlab = scan._getpolarizationlabel(0,0,0)
    865         else:
    866             tlab = scan._getpolarizationlabel(1,0,0)
    867         return tlab
     331            self._maskselection = None
     332        self.plot(self._data)
    868333
    869334    def _slice_indeces(self, data):
     
    890355
    891356    def _reset(self):
    892         self._usermask = None
     357        self._usermask = []
    893358        self._usermaskspectra = None
    894         self.set_cursor(refresh=False)
     359        self.set_selection(None, False)
     360
     361    def _plot(self, scan):
     362        savesel = scan._getselection()
     363        scan._setselection(self._selection)
     364        d = {'b': scan.getbeam, 's': scan.getscan,
     365             'i': scan.getif, 'p': scan.getpol, 't': scan._gettime }
     366
     367        polmodes = dict(zip(self._selection._getpols(),self._selection._getpoltypes()))
     368        n,nstack = self._get_selected_n(scan)
     369        maxpanel, maxstack = 9,4
     370        if n > maxpanel or nstack > maxstack:
     371            from asap import asaplog
     372            msg ="Scan to be plotted contains more than %d selections.\n" \
     373                  "Selecting first %d selections..." % (maxpanel,maxpanel)
     374            asaplog.push(msg)
     375            print_log()
     376            n = min(n,maxpanel)
     377            nstack = min(n,maxstack)
     378
     379        if n > 1:
     380            ganged = rcParams['plotter.ganged']
     381            if self._rows and self._cols:
     382                n = min(n,self._rows*self._cols)
     383                self._plotter.set_panels(rows=self._rows,cols=self._cols,
     384                                         nplots=n,ganged=ganged)
     385            else:
     386                self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged)
     387        else:
     388            self._plotter.set_panels()
     389        r=0
     390        nr = scan.nrow()
     391        a0,b0 = -1,-1
     392        allxlim = []
     393        newpanel=True
     394        panelcount,stackcount = 0,0
     395        while r < nr:
     396            a = d[self._panelling](r)
     397            b = d[self._stacking](r)
     398#             print r
     399#             print "  a: ",a,a0,panelcount,n
     400#             print "  b: ",b,b0,stackcount,nstack
     401            if a > a0 and panelcount < n:
     402                if n > 1:
     403                    self._plotter.subplot(panelcount)
     404                    #pindex += 1
     405                self._plotter.palette(0)
     406                #title
     407                xlab = self._abcissa and self._abcissa[panelcount] \
     408                       or scan._getabcissalabel()
     409                ylab = self._ordinate and self._ordinate[panelcount] \
     410                       or scan._get_ordinate_label()
     411                self._plotter.set_axes('xlabel',xlab)
     412                self._plotter.set_axes('ylabel',ylab)
     413                lbl = self._get_label(scan, r, self._panelling, self._title)
     414                if isinstance(lbl, list) or isinstance(lbl, tuple):
     415                    if 0 <= panelcount < len(lbl):
     416                        lbl = lbl[panelcount]
     417                    else:
     418                        # get default label
     419                        lbl = self._get_label(scan, r, self._panelling, None)
     420                self._plotter.set_axes('title',lbl)
     421                newpanel = True
     422                stackcount =0
     423                panelcount += 1
     424            if (b > b0 or newpanel) and stackcount < nstack:
     425                y = []
     426                if len(polmodes):
     427                    y = scan._getspectrum(r, polmodes[scan.getpol(r)])
     428                else:
     429                    y = scan._getspectrum(r)
     430                m = scan._getmask(r)
     431                if self._maskselection and len(self._usermask) == len(m):
     432                    if d[self._stacking](r) in self._maskselection[self._stacking]:
     433                        print "debug"
     434                        m = logical_and(m, self._usermask)
     435                x = scan._getabcissa(r)
     436                if self._minmaxx is not None:
     437                    s,e = self._slice_indeces(x)
     438                    x = x[s:e]
     439                    y = y[s:e]
     440                    m = m[s:e]
     441                if len(x) > 1024 and True:#rcParams['plotter.decimate']:
     442                    fac = len(x)/1024
     443                    x = x[::fac]
     444                    m = m[::fac]
     445                    y = y[::fac]
     446                llbl = self._get_label(scan, r, self._stacking, self._lmap)
     447                if isinstance(llbl, list) or isinstance(llbl, tuple):
     448                    if 0 <= stackcount < len(llbl):
     449                        # use user label
     450                        llbl = llbl[stackcount]
     451                    else:
     452                        # get default label
     453                        llbl = self._get_label(scan, r, self._stacking, None)
     454                self._plotter.set_line(label=llbl)
     455                self._plotter.plot(x,y,m)
     456                xlim= self._minmaxx or [min(x),max(x)]
     457                allxlim += xlim
     458                stackcount += 1
     459                # last in colour stack -> autoscale x
     460                if stackcount == nstack:
     461                    allxlim.sort()
     462                    self._plotter.axes.set_xlim([allxlim[0],allxlim[-1]])
     463                    # clear
     464                    allxlim =[]
     465
     466            newpanel = False
     467            a0=a
     468            b0=b
     469            # ignore following rows
     470            if (panelcount == n) and (stackcount == nstack):
     471                pass#break
     472            r+=1 # next row
     473
     474        scan._setselection(savesel)
     475
     476    def set_selection(self, selection=None, refresh=True):
     477        from asap._asap import selector
     478        self._selection = selection or selector()
     479        d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO',
     480              'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME' }
     481        order = [d0[self._panelling],d0[self._stacking]]
     482        self._selection._setorder(order)
     483        if self._data and refresh: self.plot(self._data)
     484
     485    def _get_selected_n(self, scan):
     486        d1 = {'b': scan.nbeam, 's': scan.nscan,
     487             'i': scan.nif, 'p': scan.npol, 't': scan.ncycle }
     488        d2 = { 'b': len(self._selection._getbeams()),
     489               's': len(self._selection._getscans()),
     490               'i': len(self._selection._getifs()),
     491               'p': len(self._selection._getpols()),
     492               't': len(self._selection._getcycles()) }
     493        n =  d2[self._panelling] or d1[self._panelling]()
     494        nstack = d2[self._stacking] or d1[self._stacking]()
     495        return n,nstack
     496
     497    def _get_label(self, scan, row, mode, userlabel=None):
     498        pms = dict(zip(self._selection._getpols(),self._selection._getpoltypes()))
     499        if len(pms):
     500            poleval = scan._getpollabel(scan.getpol(row),pms[scan.getpol(row)])
     501        else:
     502            poleval = scan._getpollabel(scan.getpol(row),scan.poltype())
     503        d = {'b': "Beam "+str(scan.getbeam(row)),
     504             's': scan._getsourcename(row),
     505             'i': "IF"+str(scan.getif(row)),
     506             'p': scan.poltype().capitalize()+" "+poleval,
     507             't': scan._gettime(row) }
     508        return userlabel or d[mode]
Note: See TracChangeset for help on using the changeset viewer.