Ignore:
Timestamp:
06/09/10 19:03:06 (14 years ago)
Author:
Kana Sugimoto
Message:

New Development: Yes

JIRA Issue: Yes (CAS-2211)

Ready for Test: Yes

Interface Changes: Yes

What Interface Changed: ASAP 3.0.0 interface changes

Test Programs:

Put in Release Notes: Yes

Module(s): all the CASA sd tools and tasks are affected.

Description: Merged ATNF-ASAP 3.0.0 developments to CASA (alma) branch.

Note you also need to update casa/code/atnf.


Location:
branches/alma
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/alma

  • branches/alma/python/asapplotter.py

    r1732 r1757  
    1 from asap import rcParams, print_log, selector
     1from asap import rcParams, print_log, print_log_dec
     2from asap import selector, scantable
    23from asap import asaplog
    34import matplotlib.axes
     5from matplotlib.font_manager import FontProperties
     6from matplotlib.text import Text
     7
    48import re
    59
     
    1317        other variables.
    1418    """
    15     def __init__(self, visible=None):
     19    def __init__(self, visible=None , **kwargs):
    1620        self._visible = rcParams['plotter.gui']
    1721        if visible is not None:
    1822            self._visible = visible
    19         self._plotter = self._newplotter()
     23        self._plotter = self._newplotter(**kwargs)
    2024        if self._visible and matplotlib.get_backend() == "TkAgg":
    2125            from asap.casatoolbar import CustomToolbarTkAgg
     
    4246        self._selection = selector()
    4347        self._hist = rcParams['plotter.histogram']
     48        self._fp = FontProperties()
    4449        self._panellayout = self.set_panellayout(refresh=False)
    4550
     
    5257        return None
    5358
    54     def _newplotter(self):
     59    def _newplotter(self, **kwargs):
    5560        backend=matplotlib.get_backend()
    5661        if not self._visible:
     
    6469        else:
    6570            from asap.asaplot import asaplot
    66         return asaplot()
    67 
    68 
     71        return asaplot(**kwargs)
     72
     73    #@print_log_dec
    6974    def plot(self, scan=None):
    7075        """
     
    101106        return
    102107
     108    def gca(self):
     109        return self._plotter.figure.gca()
     110
     111    def refresh(self):
     112        """Do a soft refresh"""
     113        self._plotter.figure.show()
     114
     115    def create_mask(self, nwin=1, panel=0, color=None):
     116        """
     117        Interactively define a mask.It retruns a mask that is equivalent to
     118        the one created manually with scantable.create_mask.
     119        Parameters:
     120            nwin:       The number of mask windows to create interactively
     121                        default is 1.
     122            panel:      Which panel to use for mask selection. This is useful
     123                        if different IFs are spread over panels (default 0)
     124        """
     125        if self._data is None:
     126            return []
     127        outmask = []
     128        self._plotter.subplot(panel)
     129        xmin, xmax = self._plotter.axes.get_xlim()
     130        marg = 0.05*(xmax-xmin)
     131        self._plotter.axes.set_xlim(xmin-marg, xmax+marg)
     132        self.refresh()
     133
     134        def cleanup(lines=False, texts=False, refresh=False):
     135            if lines:
     136                del self._plotter.axes.lines[-1]
     137            if texts:
     138                del self._plotter.axes.texts[-1]
     139            if refresh:
     140                self.refresh()
     141
     142        for w in xrange(nwin):
     143            wpos = []
     144            self.text(0.05,1.0, "Add start boundary",
     145                      coords="relative", fontsize=10)
     146            point = self._plotter.get_point()
     147            cleanup(texts=True)
     148            if point is None:
     149                continue
     150            wpos.append(point[0])
     151            self.axvline(wpos[0], color=color)
     152            self.text(0.05,1.0, "Add end boundary", coords="relative", fontsize=10)
     153            point = self._plotter.get_point()
     154            cleanup(texts=True, lines=True)
     155            if point is None:
     156                self.refresh()
     157                continue
     158            wpos.append(point[0])
     159            self.axvspan(wpos[0], wpos[1], alpha=0.1,
     160                         edgecolor=color, facecolor=color)
     161            ymin, ymax = self._plotter.axes.get_ylim()
     162            outmask.append(wpos)
     163
     164        self._plotter.axes.set_xlim(xmin, xmax)
     165        self.refresh()
     166        if len(outmask) > 0:
     167            return self._data.create_mask(*outmask)
     168        return []
    103169
    104170    # forwards to matplotlib axes
    105171    def text(self, *args, **kwargs):
     172        if kwargs.has_key("interactive"):
     173            #if kwargs.pop("interactive"):
     174            #    pos = self._plotter.get_point()
     175            #    args = tuple(pos)+args
     176            kwargs.pop("interactive")
    106177        self._axes_callback("text", *args, **kwargs)
     178
    107179    text.__doc__ = matplotlib.axes.Axes.text.__doc__
     180
    108181    def arrow(self, *args, **kwargs):
     182        if kwargs.has_key("interactive"):
     183            #if kwargs.pop("interactive"):
     184            #    pos = self._plotter.get_region()
     185            #    dpos = (pos[0][0], pos[0][1],
     186            #            pos[1][0]-pos[0][0],
     187            #            pos[1][1] - pos[0][1])
     188            #    args = dpos + args
     189            kwargs.pop("interactive")
    109190        self._axes_callback("arrow", *args, **kwargs)
     191
    110192    arrow.__doc__ = matplotlib.axes.Axes.arrow.__doc__
     193
     194    def annotate(self, text, xy=None, xytext=None, **kwargs):
     195        if kwargs.has_key("interactive"):
     196            #if kwargs.pop("interactive"):
     197            #    xy = self._plotter.get_point()
     198            #    xytext = self._plotter.get_point()
     199            kwargs.pop("interactive")
     200        if not kwargs.has_key("arrowprops"):
     201            kwargs["arrowprops"] = dict(arrowstyle="->")
     202        self._axes_callback("annotate", text, xy, xytext, **kwargs)
     203
     204    annotate.__doc__ = matplotlib.axes.Axes.annotate.__doc__
     205
    111206    def axvline(self, *args, **kwargs):
     207        if kwargs.has_key("interactive"):
     208            #if kwargs.pop("interactive"):
     209            #    pos = self._plotter.get_point()
     210            #    args = (pos[0],)+args
     211            kwargs.pop("interactive")
    112212        self._axes_callback("axvline", *args, **kwargs)
     213
    113214    axvline.__doc__ = matplotlib.axes.Axes.axvline.__doc__
     215
    114216    def axhline(self, *args, **kwargs):
     217        if kwargs.has_key("interactive"):
     218            #if kwargs.pop("interactive"):
     219            #    pos = self._plotter.get_point()
     220            #    args = (pos[1],)+args
     221            kwargs.pop("interactive")
    115222        self._axes_callback("axhline", *args, **kwargs)
     223
    116224    axhline.__doc__ = matplotlib.axes.Axes.axhline.__doc__
     225
    117226    def axvspan(self, *args, **kwargs):
     227        if kwargs.has_key("interactive"):
     228            #if kwargs.pop("interactive"):
     229            #    pos = self._plotter.get_region()
     230            #    dpos = (pos[0][0], pos[1][0])
     231            #    args = dpos + args
     232            kwargs.pop("interactive")
    118233        self._axes_callback("axvspan", *args, **kwargs)
    119234        # hack to preventy mpl from redrawing the patch
    120235        # it seem to convert the patch into lines on every draw.
    121236        # This doesn't happen in a test script???
    122         del self._plotter.axes.patches[-1]
     237        #del self._plotter.axes.patches[-1]
     238
    123239    axvspan.__doc__ = matplotlib.axes.Axes.axvspan.__doc__
    124240
    125241    def axhspan(self, *args, **kwargs):
     242        if kwargs.has_key("interactive"):
     243            #if kwargs.pop("interactive"):
     244            #    pos = self._plotter.get_region()
     245            #    dpos = (pos[0][1], pos[1][1])
     246            #    args = dpos + args
     247            kwargs.pop("interactive")
    126248        self._axes_callback("axhspan", *args, **kwargs)
    127249        # hack to preventy mpl from redrawing the patch
    128250        # it seem to convert the patch into lines on every draw.
    129251        # This doesn't happen in a test script???
    130         del self._plotter.axes.patches[-1]
     252        #del self._plotter.axes.patches[-1]
     253
    131254    axhspan.__doc__ = matplotlib.axes.Axes.axhspan.__doc__
    132255
     
    465588        if refresh and self._data: self.plot(self._data)
    466589
    467     def set_font(self, family=None, style=None, weight=None, size=None, refresh=True):
     590    def set_font(self, refresh=True,**kwargs):
    468591        """
    469592        Set font properties.
     
    479602        """
    480603        from matplotlib import rc as rcp
    481         if isinstance(family, str):
    482             rcp('font', family=family)
    483         if isinstance(style, str):
    484             rcp('font', style=style)
    485         if isinstance(weight, str):
    486             rcp('font', weight=weight)
    487         if isinstance(size, float) or isinstance(size, int):
    488             rcp('font', size=size)
     604        fdict = {}
     605        for k,v in kwargs.iteritems():
     606            if v:
     607                fdict[k] = v
     608        self._fp = FontProperties(**fdict)
    489609        if refresh and self._data: self.plot(self._data)
    490610
     
    540660        if not self._data.get_unit().endswith("Hz"):
    541661            raise RuntimeError("Can only overlay linecatalogs when data is in frequency.")
    542         from matplotlib.numerix import ma
     662        from numpy import ma
    543663        for j in range(len(self._plotter.subplots)):
    544664            self._plotter.subplot(j)
     
    716836        if isinstance(nstack0, int): nstack = nstack0
    717837        else: nstack = len(nstack0)
    718         maxpanel, maxstack = 16,8
     838        maxpanel, maxstack = 16,16
    719839        if n > maxpanel or nstack > maxstack:
    720840            maxn = 0
     
    761881                ylab = self._ordinate and self._ordinate[panelcount] \
    762882                       or scan._get_ordinate_label()
    763                 self._plotter.set_axes('xlabel',xlab)
    764                 self._plotter.set_axes('ylabel',ylab)
     883                self._plotter.set_axes('xlabel', xlab)
     884                self._plotter.set_axes('ylabel', ylab)
    765885                lbl = self._get_label(scan, r, self._panelling, self._title)
    766886                if isinstance(lbl, list) or isinstance(lbl, tuple):
     
    781901                    y = scan._getspectrum(r)
    782902                m = scan._getmask(r)
    783                 from matplotlib.numerix import logical_not, logical_and
     903                from numpy import logical_not, logical_and
    784904                if self._maskselection and len(self._usermask) == len(m):
    785905                    if d[self._stacking](r) in self._maskselection[self._stacking]:
    786906                        m = logical_and(m, self._usermask)
    787907                x = scan._getabcissa(r)
    788                 from matplotlib.numerix import ma, array
     908                from numpy import ma, array
    789909                y = ma.masked_array(y,mask=logical_not(array(m,copy=False)))
    790910                if self._minmaxx is not None:
     
    839959        #reset the selector to the scantable's original
    840960        scan.set_selection(savesel)
    841 
    842     def set_selection(self, selection=None, refresh=True):
     961       
     962        #temporary switch-off for older matplotlib
     963        #if self._fp is not None:
     964        if self._fp is not None and getattr(self._plotter.figure,'findobj',False):
     965            for o in self._plotter.figure.findobj(Text):
     966                o.set_fontproperties(self._fp)
     967
     968    def set_selection(self, selection=None, refresh=True, **kw):
    843969        """
    844970        Parameters:
     
    848974                        Otherwise,the parameter(s) are set without replotting.
    849975        """
    850         self._selection = isinstance(selection,selector) and selection or selector()
     976        if selection is None:
     977            # reset
     978            if len(kw) == 0:
     979                self._selection = selector()
     980            else:
     981                # try keywords
     982                for k in kw:
     983                    if k not in selector.fields:
     984                        raise KeyError("Invalid selection key '%s', valid keys are %s" % (k, selector.fields))
     985                self._selection = selector(**kw)
     986        elif isinstance(selection, selector):
     987            self._selection = selection
     988        else:
     989            raise TypeError("'selection' is not of type selector")
     990
    851991        d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO',
    852992              'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME' }
     
    8851025
    8861026    def plotazel(self, scan=None, outfile=None):
    887         """
    888         plot azimuth and elevation  versus time of a scantable
    889         """
    890         import pylab as PL
    891         from matplotlib.dates import DateFormatter, timezone, HourLocator, MinuteLocator, DayLocator
     1027    #def plotazel(self):
     1028        """
     1029        plot azimuth and elevation versus time of a scantable
     1030        """
     1031        from matplotlib import pylab as PL
     1032        from matplotlib.dates import DateFormatter, timezone
     1033        from matplotlib.dates import HourLocator, MinuteLocator,SecondLocator, DayLocator
    8921034        from matplotlib.ticker import MultipleLocator
    893         from matplotlib.numerix import array, pi
     1035        from numpy import array, pi
    8941036        self._data = scan
    8951037        self._outfile = outfile
     
    8981040        tz = timezone('UTC')
    8991041        PL.cla()
    900         #PL.ioff()
     1042        PL.ioff()
    9011043        PL.clf()
    9021044        # Adjust subplot layouts
     
    9171059            minloc = HourLocator(range(0,23,12))
    9181060            timefmt = DateFormatter("%b%d")
     1061        elif tdel > 24./60.:
     1062            timefmt = DateFormatter('%H:%M')
     1063            majloc = HourLocator()
     1064            minloc = MinuteLocator(30)
    9191065        else:
    920             timefmt = DateFormatter('%H')
    921             majloc = HourLocator()
    922             minloc = MinuteLocator(20)
     1066            timefmt = DateFormatter('%H:%M')
     1067            majloc = MinuteLocator(interval=5)
     1068            minloc = SecondLocator(30)
     1069
    9231070        PL.title(dstr)
    924 
    9251071        if tdel == 0.0:
    9261072            th = (t - PL.floor(t))*24.0
     
    9471093                if az[irow] < 0: az[irow] += 360.0
    9481094
    949         ax = PL.subplot(2,1,2)
     1095        ax2 = PL.subplot(2,1,2)
    9501096        #PL.xlabel('Time (UT [hour])')
    9511097        PL.ylabel('Az [deg.]')
     
    9541100        else:
    9551101            PL.plot_date(t,az,'o', markersize=2,markeredgecolor='b',markerfacecolor='b',tz=tz)
    956             ax.xaxis.set_major_formatter(timefmt)
    957             ax.xaxis.set_major_locator(majloc)
    958             ax.xaxis.set_minor_locator(minloc)
    959         #ax.grid(True)
    960         ax.set_ylim(0,360)
    961         ax.yaxis.grid(True)
     1102            ax2.xaxis.set_major_formatter(timefmt)
     1103            ax2.xaxis.set_major_locator(majloc)
     1104            ax2.xaxis.set_minor_locator(minloc)
     1105        #ax2.grid(True)
     1106        ax2.set_ylim(0,360)
     1107        ax2.yaxis.grid(True)
    9621108        #hfmt = DateFormatter('%H')
    9631109        #hloc = HourLocator()
    9641110        yloc = MultipleLocator(60)
    965         ax.yaxis.set_major_locator(yloc)
     1111        ax2.yaxis.set_major_locator(yloc)
    9661112        if tdel > 1.0:
    967             labels = ax.get_xticklabels()
     1113            labels = ax2.get_xticklabels()
    9681114            PL.setp(labels, fontsize=10)
    9691115            PL.xlabel('Time (UT [day])')
     
    9711117            PL.xlabel('Time (UT [hour])')
    9721118
    973         #PL.ion()
     1119        PL.ion()
    9741120        PL.draw()
    9751121        if (self._outfile is not None):
     
    9771123
    9781124    def plotpointing(self, scan=None, outfile=None):
     1125    #def plotpointing(self):
    9791126        """
    9801127        plot telescope pointings
    9811128        """
    982         import pylab as PL
    983         from matplotlib.dates import DateFormatter, timezone
    984         from matplotlib.ticker import MultipleLocator
    985         from matplotlib.numerix import array, pi, zeros
     1129        from matplotlib import pylab as PL
     1130        from numpy import array, pi
    9861131        self._data = scan
    9871132        self._outfile = outfile
     
    10011146        #ax = PL.axes([0.1,0.1,0.8,0.8])
    10021147        ax.set_aspect('equal')
    1003         PL.plot(ra,dec, 'b,')
     1148        PL.plot(ra, dec, 'b,')
    10041149        PL.xlabel('RA [deg.]')
    10051150        PL.ylabel('Declination [deg.]')
     
    11351280        # Print Observation header to the upper-left corner of plot
    11361281        if plot:
    1137             srest=ssum[ssum.find('Rest Freqs:'):ssum.find('Abcissa:')]
    1138             shead=ssum[ssum.find('Beams:'):ssum.find('Flux Unit:')]
    1139             headstr=shead.split('\n\n')
    1140             if extrastr != '': headstr[1]=extrastr+'\n'+headstr[1]
     1282            headstr=[ssum[ssum.find('Observer:'):ssum.find('Flux Unit:')]]
     1283            headstr.append(ssum[ssum.find('Beams:'):ssum.find('Observer:')]
     1284                         +ssum[ssum.find('Rest Freqs:'):ssum.find('Abcissa:')])
     1285            if extrastr != '': headstr[0]=extrastr+'\n'+headstr[0]
    11411286            #headstr[1]='Data File:     '+(filestr or 'unknown')+'\n'+headstr[1]
    1142             headstr[0]=headstr[0]+'\n'+srest
    1143             headstr.reverse()
    11441287            ssel='***Selections***\n'+(selstr+self._data.get_selection().__str__() or 'none')
    11451288            headstr.append(ssel)
     
    11591302                            verticalalignment='bottom',fontsize=8)
    11601303            self._plotter.release()
    1161             del srest, shead, headstr, ssel
     1304            del headstr, ssel
    11621305        if logger:
    11631306            asaplog.push("----------------\n  Plot Summary\n----------------")
Note: See TracChangeset for help on using the changeset viewer.