source: trunk/python/asapplotter.py @ 762

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

merge from Release12 branch

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