source: trunk/python/asapplotter.py @ 753

Last change on this file since 753 was 753, checked in by mar637, 18 years ago

Bug fix: plot_other with panelling==p didn't work with cursor selction. added use of asaplog

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 32.8 KB
Line 
1from asap import rcParams, print_log
2from numarray import logical_and
3
4class asapplotter:
5    """
6    The ASAP plotter.
7    By default the plotter is set up to plot polarisations
8    'colour stacked' and scantables across panels.
9    Note:
10        Currenly it only plots 'spectra' not Tsys or
11        other variables.
12    """
13    def __init__(self, visible=None):
14        self._visible = rcParams['plotter.gui']
15        if visible is not None:
16            self._visible = visible
17        self._plotter = self._newplotter()
18
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]
36        self._panelling = None
37        self._stacking = None
38        self.set_panelling()
39        self.set_stacking()
40        self._rows = None
41        self._cols = None
42        self._autoplot = False
43        self._minmaxx = None
44        self._minmaxy = None
45        self._datamask = None
46        self._data = None
47        self._lmap = None
48        self._title = None
49        self._ordinate = None
50        self._abcissa = None
51        self._abcunit = None
52        self._cursor = {'t':None, 'b':None,
53                        'i':None, 'p':None
54                        }
55        self._usermask = None
56        self._usermaskspectra = None
57
58    def _newplotter(self):
59        if self._visible:
60            from asap.asaplotgui import asaplotgui as asaplot
61        else:
62            from asap.asaplot import asaplot
63        return asaplot()
64
65
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
77        Note:
78            If a (list) of scantables was specified in a previous call
79            to plot, no argument has to be given to 'replot'
80            NO checking is done that the abcissas of the scantables
81            are consistent e.g. all 'channel' or all 'velocity' etc.
82        """
83        if self._plotter.is_dead:
84            self._plotter = self._newplotter()
85        self._plotter.hold()
86        self._plotter.clear()
87        if len(args) > 0:
88            if self._data is not None:
89                if list(args) != self._data:
90                    self._data = list(args)
91                    # reset
92                    self._reset()
93            else:
94                if isinstance(args[0], list):
95                    self._data = args[0]
96                else:
97                    self._data = list(args)
98                self._reset()
99        # ranges become invalid when unit changes
100        if self._abcunit != self._data[0].get_unit():
101            self._minmaxx = None
102            self._minmaxy = None
103            self._abcunit = self._data[0].get_unit()
104            self._datamask = None
105        if self._panelling == 't':
106            maxrows = 25
107            if self._data[0].nrow() > maxrows:
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)
121        if self._minmaxy is not None:
122            self._plotter.set_limits(ylim=self._minmaxy)
123        self._plotter.release()
124        print_log()
125        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        rows = self._cursor["t"]
151        self._plotter.palette(0)
152        for rowsel in rows:
153            i = self._cursor["t"].index(rowsel)
154            if n > 1:
155                self._plotter.palette(0)
156                self._plotter.subplot(i)
157            colvals = eval(cdict2.get(colmode))
158            for j in colvals:
159                polmode = "raw"
160                jj = colvals.index(j)
161                savej = j
162                for k in cdict.keys():
163                    sel = eval(cdict2.get(k))
164                    j = sel[0]
165                    if k == "p":
166                        which = self._cursor["p"].index(j)
167                        polmode = self._polmode[which]
168                        j = which
169                    eval(cdict.get(k))
170                j = savej
171                if colmode == "p":
172                    polmode = self._polmode[self._cursor["p"].index(j)]
173                    #j = jj
174                eval(cdict.get(colmode))
175                x = None
176                y = None
177                m = None
178                if self._title is None:
179                    tlab = scan._getsourcename(rowsel)
180                else:
181                    if len(self._title) >= n:
182                        tlab = self._title[rowsel]
183                    else:
184                        tlab = scan._getsourcename(rowsel)
185                x,xlab = scan.get_abcissa(rowsel)
186                if self._abcissa: xlab = self._abcissa
187                y = None
188                m = scan._getmask(rowsel)
189                if self._usermask and self._usermask.count(j):
190                    m  = logical_and(self._usermask, m)
191                if polmode == "stokes":
192                    y = scan._getstokesspectrum(rowsel)
193                elif polmode == "stokes2":
194                    y = scan._getstokesspectrum(rowsel,True)
195                elif polmode == "circular":
196                    y = scan._stokestopolspectrum(rowsel,False,-1)
197                else:
198                    y = scan._getspectrum(rowsel)
199                if self._ordinate:
200                    ylab = self._ordinate
201                else:
202                    ylab = scan._get_ordinate_label()
203                m = scan._getmask(rowsel)
204                if self._datamask is not None:
205                    if len(m) == len(self._datamask):
206                        m = logical_and(m,self._datamask)
207                if self._lmap and len(self._lmap) > 0:
208                    llab = self._lmap[jj]
209                else:
210                    if colmode == 'p':
211                        llab = self._get_pollabel(scan, polmode)
212                    else:
213                        llab = self._ldict.get(colmode)+' '+str(j)
214                self._plotter.set_line(label=llab)
215                if self._minmaxx is not None:
216                    s,e = self._slice_indeces(x)
217                    x = x[s:e]
218                    y = y[s:e]
219                    m = m[s:e]
220                if len(x) > 1024 and rcParams['plotter.decimate']:
221                    fac = len(x)/1024
222                    x = x[::fac]
223                    m = m[::fac]
224                    y = y[::fac]
225                self._plotter.plot(x,y,m)
226                xlim=[min(x),max(x)]
227                if self._minmaxx is not None:
228                    xlim = self._minmaxx
229                self._plotter.axes.set_xlim(xlim)
230            self._plotter.set_axes('xlabel',xlab)
231            self._plotter.set_axes('ylabel',ylab)
232            self._plotter.set_axes('title',tlab)
233        return
234
235    def _plot_scans(self, scans, colmode):
236        from asap import asaplog
237        msg = "Plotting mode is scans across panels. Can only plot one row per scan."
238        asaplog.push(msg)
239        if colmode == 's':
240            return
241        cdict = {'b':'scan.setbeam(j)',
242                 'i':'scan.setif(j)',
243                 'p':'scan.setpol(j)'}
244        cdict2 = {'b':'self._cursor["b"]',
245                  'i':'self._cursor["i"]',
246                  'p':'self._cursor["p"]'}
247
248        n = len(scans)
249        ncol = 1
250        if self._stacking is not None:
251            scan = scans[0]
252            ncol = eval(self._cdict.get(colmode))
253        if n > 1:
254            ganged = rcParams['plotter.ganged']
255            if self._rows and self._cols:
256                n = min(n,self._rows*self._cols)
257                self._plotter.set_panels(rows=self._rows,cols=self._cols,
258                                         nplots=n,ganged=ganged)
259            else:
260                self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged)
261        else:
262            self._plotter.set_panels()
263
264        for scan in scans:
265            self._plotter.palette(0)
266            if n > 1:
267                self._plotter.subplot(scans.index(scan))
268            colvals = eval(cdict2.get(colmode))
269            rowsel = self._cursor["t"][0]
270            for j in colvals:
271                polmode = "raw"
272                jj = colvals.index(j)
273                savej = j
274                for k in cdict.keys():
275                    sel = eval(cdict2.get(k))
276                    j = sel[0]
277                    eval(cdict.get(k))
278                    if k == "p":
279                        which = self._cursor["p"].index(j)
280                        polmode = self._polmode[which]
281                        j = which
282                j = savej
283                if colmode == "p":
284                    polmode = self._polmode[self._cursor["p"].index(j)]
285                    #j = jj
286                eval(cdict.get(colmode))
287                x = None
288                y = None
289                m = None
290                tlab = self._title
291                if not self._title:
292                    tlab = scan._getsourcename(rowsel)
293                x,xlab = scan.get_abcissa(rowsel)
294                if self._abcissa: xlab = self._abcissa
295                if polmode == "stokes":
296                    y = scan._getstokesspectrum(rowsel)
297                elif polmode == "stokes2":
298                    y = scan._getstokesspectrum(rowsel,True)
299                elif polmode == "circular":
300                    y = scan._stokestopolspectrum(rowsel,False,-1)
301                else:
302                    y = scan._getspectrum(rowsel)
303                if self._ordinate:
304                    ylab = self._ordinate
305                else:
306                    ylab = scan._get_ordinate_label()
307                m = scan._getmask(rowsel)
308                if self._usermask and self._usermask.count(j):
309                    m  = logical_and(self._usermask, m)
310                if self._lmap and len(self._lmap) > 0:
311                    llab = self._lmap[jj]
312                else:
313                    if colmode == 'p':
314                        llab = self._get_pollabel(scan, polmode)
315                    else:
316                        llab = self._ldict.get(colmode)+' '+str(j)
317                self._plotter.set_line(label=llab)
318                if self._minmaxx is not None:
319                    s,e = self._slice_indeces(x)
320                    x = x[s:e]
321                    y = y[s:e]
322                    m = m[s:e]
323                if len(x) > 1024 and rcParams['plotter.decimate']:
324                    fac = len(x)/1024
325                    x = x[::fac]
326                    m = m[::fac]
327                    y = y[::fac]
328                self._plotter.plot(x,y,m)
329                xlim=[min(x),max(x)]
330                if self._minmaxx is not None:
331                    xlim = self._minmaxx
332                self._plotter.axes.set_xlim(xlim)
333
334            self._plotter.set_axes('xlabel',xlab)
335            self._plotter.set_axes('ylabel',ylab)
336            self._plotter.set_axes('title',tlab)
337        print_log()
338        return
339
340    def _plot_other(self,scans,colmode):
341        if colmode == self._panelling:
342            return
343        cdict = {'b':'scan.setbeam(i)',
344                 'i':'scan.setif(i)',
345                 'p':'scan.setpol(i)'}
346        cdict2 = {'b':'self._cursor["b"]',
347                  'i':'self._cursor["i"]',
348                  'p':'self._cursor["p"]',
349                  's': 'scans',
350                  't': 'self._cursor["t"]'}
351        scan = scans[0]
352        n = eval(self._cdict.get(self._panelling))
353        ncol=1
354        if self._stacking is not None:
355            ncol = eval(self._cdict.get(colmode))
356        if n > 1:
357            ganged = rcParams['plotter.ganged']
358            if self._rows and self._cols:
359                n = min(n,self._rows*self._cols)
360                self._plotter.set_panels(rows=self._rows,cols=self._cols,
361                                         nplots=n,ganged=ganged)
362            else:
363                self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged)
364        else:
365            self._plotter.set_panels()
366        panels = self._cursor[self._panelling]
367        for i in panels:
368            self._plotter.palette(0)
369            polmode = "raw"
370            ii = self._cursor[self._panelling].index(i)
371            if n>1:
372                self._plotter.subplot(ii)
373            if self._panelling == "p":
374                polmode = self._polmode[ii]
375
376            eval(cdict.get(self._panelling))
377
378            colvals = eval(cdict2.get(colmode))
379            for j in colvals:
380                rowsel = self._cursor["t"][0]
381                jj = colvals.index(j)
382                savei = i
383                for k in cdict.keys():
384                    if k != self._panelling:
385                        sel = eval(cdict2.get(k))
386                        i = sel[0]
387                        if k == "p":
388                            which = self._cursor["p"].index(i)
389                            polmode = self._polmode[which]
390                            i = which
391                        eval(cdict.get(k))
392                i = savei
393                if colmode == 's':
394                    scan = j
395                elif colmode == 't':
396                    rowsel = j
397                else:
398                    savei = i
399                    if colmode == 'p':
400                        polmode = self._polmode[self._cursor["p"].index(j)]
401
402                    i = j
403                    eval(cdict.get(colmode))
404                    i = savei
405                if self._panelling == "p":
406                    eval(cdict.get(self._panelling))
407                x = None
408                y = None
409                m = None
410                x,xlab = scan.get_abcissa(rowsel)
411                if self._abcissa: xlab = self._abcissa
412                if polmode == "stokes":
413                    y = scan._getstokesspectrum(rowsel)
414                elif polmode == "stokes2":
415                    y = scan._getstokesspectrum(rowsel,True)
416                elif polmode == "circular":
417                    y = scan._stokestopolspectrum(rowsel,False,-1)
418                else:
419                    y = scan._getspectrum(rowsel)
420
421                if self._ordinate:
422                    ylab = self._ordinate
423                else:
424                    ylab = scan._get_ordinate_label()
425                m = scan._getmask(rowsel)
426                if self._usermask and self._usermask.count(j):
427                    m  = logical_and(self._usermask, m)
428
429                if colmode == 's' or colmode == 't':
430                    if self._title and len(self._title) > 0:
431                        tlab = self._title[ii]
432                    else:
433                        if self._panelling == 'p':
434                            tlab = self._get_pollabel(scan, polmode)
435                        else:
436                            tlab = self._ldict.get(self._panelling)+' '+str(i)
437                    if self._lmap and len(self._lmap) > 0:
438                        llab = self._lmap[jj]
439                    else:
440                        llab = scan._getsourcename(rowsel)
441                else:
442                    if self._title and len(self._title) > 0:
443                        tlab = self._title[ii]
444                    else:
445                        if self._panelling == 'p':
446                            tlab = self._get_pollabel(scan, polmode)
447                        else:
448                            tlab = self._ldict.get(self._panelling)+' '+str(i)
449                    if self._lmap and len(self._lmap) > 0:
450                        llab = self._lmap[jj]
451                    else:
452                        if colmode == 'p':
453                            llab = self._get_pollabel(scan, polmode)
454                        else:
455                            llab = self._ldict.get(colmode)+' '+str(j)
456                self._plotter.set_line(label=llab)
457                if self._minmaxx is not None:
458                    s,e = self._slice_indeces(x)
459                    x = x[s:e]
460                    y = y[s:e]
461                    m = m[s:e]
462                if len(x) > 1024 and rcParams['plotter.decimate']:
463                    fac = len(x)/1024
464                    x = x[::fac]
465                    m = m[::fac]
466                    y = y[::fac]
467                self._plotter.plot(x,y,m)
468                xlim=[min(x),max(x)]
469                if self._minmaxx is not None:
470                    xlim = self._minmaxx
471                self._plotter.axes.set_xlim(xlim)
472
473            self._plotter.set_axes('xlabel',xlab)
474            self._plotter.set_axes('ylabel',ylab)
475            self._plotter.set_axes('title',tlab)
476
477        return
478
479
480    def set_mode(self, stacking=None, panelling=None):
481        """
482        Set the plots look and feel, i.e. what you want to see on the plot.
483        Parameters:
484            stacking:     tell the plotter which variable to plot
485                          as line color overlays (default 'pol')
486            panelling:    tell the plotter which variable to plot
487                          across multiple panels (default 'scan'
488        Note:
489            Valid modes are:
490                 'beam' 'Beam' 'b':     Beams
491                 'if' 'IF' 'i':         IFs
492                 'pol' 'Pol' 'p':       Polarisations
493                 'scan' 'Scan' 's':     Scans
494                 'time' 'Time' 't':     Times
495        """
496        msg = "Invalid mode"
497        if not self.set_panelling(panelling) or \
498               not self.set_stacking(stacking):
499            if rcParams['verbose']:
500                print msg
501                return
502            else:
503                raise TypeError(msg)
504        if self._data: self.plot()
505        return
506
507    def set_panelling(self, what=None):
508        mode = what
509        if mode is None:
510             mode = rcParams['plotter.panelling']
511        md = self._translate(mode)
512        if md:
513            self._panelling = md
514            self._title = None
515            return True
516        return False
517
518    def set_layout(self,rows=None,cols=None):
519        """
520        Set the multi-panel layout, i.e. how many rows and columns plots
521        are visible.
522        Parameters:
523             rows:   The number of rows of plots
524             cols:   The number of columns of plots
525        Note:
526             If no argument is given, the potter reverts to its auto-plot
527             behaviour.
528        """
529        self._rows = rows
530        self._cols = cols
531        if self._data: self.plot()
532        return
533
534    def set_stacking(self, what=None):
535        mode = what
536        if mode is None:
537             mode = rcParams['plotter.stacking']
538        md = self._translate(mode)
539        if md:
540            self._stacking = md
541            self._lmap = None
542            return True
543        return False
544
545    def set_range(self,xstart=None,xend=None,ystart=None,yend=None):
546        """
547        Set the range of interest on the abcissa of the plot
548        Parameters:
549            [x,y]start,[x,y]end:  The start and end points of the 'zoom' window
550        Note:
551            These become non-sensical when the unit changes.
552            use plotter.set_range() without parameters to reset
553
554        """
555        if xstart is None and xend is None:
556            self._minmaxx = None
557        else:
558            self._minmaxx = [xstart,xend]
559        if ystart is None and yend is None:
560            self._minmaxy = None
561        else:
562            self._minmaxy = [ystart,yend]
563        if self._data: self.plot()
564        return
565
566    def set_legend(self, mp=None):
567        """
568        Specify a mapping for the legend instead of using the default
569        indices:
570        Parameters:
571             mp:    a list of 'strings'. This should have the same length
572                    as the number of elements on the legend and then maps
573                    to the indeces in order. It is possible to uses latex
574                    math expression. These have to be enclosed in r'', e.g. r'$x^{2}$'
575
576        Example:
577             If the data has two IFs/rest frequencies with index 0 and 1
578             for CO and SiO:
579             plotter.set_stacking('i')
580             plotter.set_legend(['CO','SiO'])
581             plotter.plot()
582             plotter.set_legend([r'$^{12}CO$', r'SiO'])
583        """
584        self._lmap = mp
585        if self._data: self.plot()
586        return
587
588    def set_title(self, title=None):
589        """
590        Set the title of the plot. If multiple panels are plotted,
591        multiple titles have to be specified.
592        Example:
593             # two panels are visible on the plotter
594             plotter.set_title(["First Panel","Second Panel"])
595        """
596        self._title = title
597        if self._data: self.plot()
598        return
599
600    def set_ordinate(self, ordinate=None):
601        """
602        Set the y-axis label of the plot. If multiple panels are plotted,
603        multiple labels have to be specified.
604        Example:
605             # two panels are visible on the plotter
606             plotter.set_ordinate(["First Y-Axis","Second Y-Axis"])
607        """
608        self._ordinate = ordinate
609        if self._data: self.plot()
610        return
611
612    def set_abcissa(self, abcissa=None):
613        """
614        Set the x-axis label of the plot. If multiple panels are plotted,
615        multiple labels have to be specified.
616        Example:
617             # two panels are visible on the plotter
618             plotter.set_ordinate(["First X-Axis","Second X-Axis"])
619        """
620        self._abcissa = abcissa
621        if self._data: self.plot()
622        return
623
624    def set_colors(self, colormap):
625        """
626        Set the colors to be used. The plotter will cycle through
627        these colors when lines are overlaid (stacking mode).
628        Example:
629             plotter.set_colors("red green blue")
630             # If for example four lines are overlaid e.g I Q U V
631             # 'I' will be 'red', 'Q' will be 'green', U will be 'blue'
632             # and 'V' will be 'red' again.
633        """
634        if isinstance(colormap,str):
635            colormap = colormap.split()
636        self._plotter.palette(0,colormap=colormap)
637        if self._data: self.plot()
638
639    def set_linestyles(self, linestyles):
640        """
641        Set the linestyles to be used. The plotter will cycle through
642        these linestyles when lines are overlaid (stacking mode) AND
643        only one color has been set.
644        Parameters:
645             linestyles:     a list of linestyles to use.
646                             'line', 'dashed', 'dotted', 'dashdot',
647                             'dashdotdot' and 'dashdashdot' are
648                             possible
649
650        Example:
651             plotter.set_colors("black")
652             plotter.set_linestyles("line dashed dotted dashdot")
653             # If for example four lines are overlaid e.g I Q U V
654             # 'I' will be 'solid', 'Q' will be 'dashed',
655             # U will be 'dotted' and 'V' will be 'dashdot'.
656        """
657        if isinstance(linestyles,str):
658            linestyles = linestyles.split()
659        self._plotter.palette(color=0,linestyle=0,linestyles=linestyles)
660        if self._data: self.plot()
661
662    def save(self, filename=None, orientation=None, dpi=None):
663        """
664        Save the plot to a file. The know formats are 'png', 'ps', 'eps'.
665        Parameters:
666             filename:    The name of the output file. This is optional
667                          and autodetects the image format from the file
668                          suffix. If non filename is specified a file
669                          called 'yyyymmdd_hhmmss.png' is created in the
670                          current directory.
671             orientation: optional parameter for postscript only (not eps).
672                          'landscape', 'portrait' or None (default) are valid.
673                          If None is choosen for 'ps' output, the plot is
674                          automatically oriented to fill the page.
675             dpi:         The dpi of the output non-ps plot
676        """
677        self._plotter.save(filename,orientation,dpi)
678        return
679
680    def set_cursor(self, row=None,beam=None,IF=None,pol=None, refresh=True):
681        """
682        Specify a 'cursor' for plotting selected spectra. Time (rows),
683        Beam, IF, Polarisation ranges can be specified.
684        Parameters:
685            Default for all paramaters is to select all available
686            row:    selects the rows (time stamps) to be plotted, this has
687                    to be a vector of row indices, e.g. row=[0,2,5] or row=[2]
688            beam:   select a range of beams
689            IF:     select a range of IFs
690            pol:    select Polarisations for plotting these can be by index
691                    (raw polarisations (default)) or by names any of:
692                    ["I", "Q", "U", "V"] or
693                    ["I", "Plinear", "Pangle", "V"] or
694                    ["XX", "YY", "Real(XY)", "Imag(XY)"] or
695                    ["RR", "LL"]
696        Example:
697            plotter.set_mode('pol','time')
698            plotter.plot(myscan) # plots all raw polarisations colour stacked
699            plotter.set_cursor(pol=["I"]) # plot "I" only for all rows
700            # plot "I" only for two time stamps row=0 and row=2
701            plotter.set_cursor(row=[0,2],pol=["I"])
702
703        Note:
704            Be careful to select only exisiting polarisations.
705        """
706        if not self._data:
707            msg = "Can only set cursor after a first call to plot()"
708            if rcParams['verbose']:
709                print msg
710                return
711            else:
712                raise RuntimeError(msg)
713
714        n = self._data[0].nrow()
715        if row is None:
716            self._cursor["t"] = range(n)
717        else:
718            for i in row:
719                if i < 0 or i >= n:
720                    msg = "Row index '%d' out of range" % i
721                    if rcParams['verbose']:
722                        print msg
723                        return       
724                    else:
725                        raise IndexError(msg)
726            self._cursor["t"] = row
727
728        n = self._data[0].nbeam()
729        if beam is None:
730            self._cursor["b"] = range(n)
731        else:
732            for i in beam:
733                if i < 0 or  i >= n:
734                    msg = "Beam index '%d' out of range" % i
735                    if rcParams['verbose']:
736                        print msg
737                        return       
738                    else:
739                        raise IndexError(msg)
740
741            self._cursor["b"] = beam
742
743        n = self._data[0].nif()
744        if IF is None:
745            self._cursor["i"] = range(n)
746        else:
747            for i in IF:
748                if i < 0 or i >= n:
749                    msg = "IF index '%d' out of range" %i
750                    if rcParams['verbose']:
751                        print msg
752                        return       
753                    else:
754                        raise IndexError(msg)
755            self._cursor["i"] = IF
756
757        n = self._data[0].npol()
758        dstokes = {"I":0,"Q":1,"U":2,"V":3}
759        dstokes2 = {"I":0,"Plinear":1,"Pangle":2,"V":3}
760        draw = {"XX":0, "YY":1,"Real(XY)":2, "Imag(XY)":3}
761        dcirc = { "RR":0,"LL":1}#,"Real(RL)":2,"Imag(RL)":3}
762
763        if pol is None:
764            self._cursor["p"] = range(n)
765            self._polmode = ["raw" for i in range(n)]
766        else:
767            if isinstance(pol,str):
768                pol = pol.split()
769            polmode = []
770            pols = []
771            for i in pol:
772                if isinstance(i,str):
773                    if draw.has_key(i):
774                        pols.append(draw.get(i))
775                        polmode.append("raw")
776                    elif dstokes.has_key(i):
777                        pols.append(dstokes.get(i))
778                        polmode.append("stokes")
779                    elif dstokes2.has_key(i):
780                        pols.append(dstokes2.get(i))
781                        polmode.append("stokes2")
782                    elif dcirc.has_key(i):
783                        pols.append(dcirc.get(i))
784                        polmode.append("circular")
785                    else:
786                        msg = "Pol type '%s' not valid" %i
787                        if rcParams['verbose']:
788                            print msg
789                            return       
790                        else:
791                            raise TypeError(msg)                       
792                elif 0 > i >= n:
793                    print "Pol index '%d' out of range" %i
794                    if rcParams['verbose']:
795                        print msg
796                        return       
797                    else:
798                        raise IndexError(msg)                   
799                else:
800                    pols.append(i)
801                    polmode.append("raw")
802            self._cursor["p"] = pols
803            self._polmode = polmode
804        if self._data and refresh: self.plot()
805
806    def set_mask(self, mask=None, pol=None):
807        """
808        Set a plotting mask for a specific polarization.
809        This is useful for masking out "noise" Pangle outside a source.
810        Parameters:
811             mask:     a mask from scantable.create_mask
812             pol:      the polarisation to apply the mask to, e.g
813                       "Pangle" or "XX" etc.
814        Example:
815        """
816        if not self._data:
817            msg = "Can only set cursor after a first call to plot()"
818            if rcParams['verbose']:
819                print msg
820                return       
821            else:
822                raise RuntimeError(msg)                       
823        if isinstance(mask, array):
824            self._usermask = mask
825        if isinstance(mask, list):
826            self._usermask = array(mask)
827        if mask is None and pol is None:
828            self._usermask = None
829            self._usermaskspectra = None
830
831        dstokes = {"I":0,"Q":1,"U":2,"V":3}
832        dstokes2 = {"I":0,"Plinear":1,"Pangle":2,"V":3}
833        draw = {"XX":0, "YY":1,"Real(XY)":2, "Imag(XY)":3}
834        dcirc = { "RR":0,"LL":1}#,"Real(RL)":2,"Imag(RL)":3}
835        if isinstance(pol, str):
836            pol = pol.split()
837        if isinstance(pol, list):
838            if isinstance(pol[0], str):
839                pass
840            else:
841                cpos = self._cursor[self._stacking]
842                self._usermaskspectra =filter(lambda i: filter(lambda j: j==i ,cpos),pol)
843        else:
844            return
845        self.plot()
846
847    def _get_pollabel(self, scan, polmode):
848        tlab = ""
849        if polmode == "stokes":
850            tlab = scan._getpolarizationlabel(0,1,0)
851        elif polmode == "stokes2":
852            tlab = scan._getpolarizationlabel(0,1,1)
853        elif polmode == "circular":
854            tlab = scan._getpolarizationlabel(0,0,0)
855        else:
856            tlab = scan._getpolarizationlabel(1,0,0)
857        return tlab
858
859    def _slice_indeces(self, data):
860        mn = self._minmaxx[0]
861        mx = self._minmaxx[1]
862        asc = data[0] < data[-1]
863        start=0
864        end = len(data)-1
865        inc = 1
866        if not asc:
867            start = len(data)-1
868            end = 0
869            inc = -1
870        # find min index
871        while data[start] < mn:
872            start+= inc
873        # find max index
874        while data[end] > mx:
875            end-=inc
876        end +=1
877        if start > end:
878            return end,start
879        return start,end
880
881    def _reset(self):
882        self._usermask = None
883        self._usermaskspectra = None
884        self.set_cursor(refresh=False)
Note: See TracBrowser for help on using the repository browser.