Changeset 2576


Ignore:
Timestamp:
06/26/12 17:40:25 (12 years ago)
Author:
Kana Sugimoto
Message:

New Development: Yes

JIRA Issue: Yes (CAS-1814/ATNF Trac #271)

Ready for Test: Yes

Interface Changes: Yes

What Interface Changed: added a new method, asapplotter.plotgrid

Test Programs:

Put in Release Notes: No

Module(s): asapplotter, sdplot

Description:

Added a new method, plotgrid, in the asapplotter class.
The methods samples spectra in a scantable by sky position recorded in
the DIRECTION column and plot them. User can specify center and spacing in
sky position to sample spectra. The number of spectra to be sampled in
horizontal (R.A.) and vertical (Dec.) direction should be specified as well.
An example of usage is,

import asap as sd
scan = sd.scantable("SOME_NAME",average=False)
sd.asapplotter.plotgrid(scan,center=(-3.133363,-0.329469),spacing=(-0.000272,-0.000257),rows=8,cols=8)

This example will sample 8x8 spectra and plot them by sky position.
So far, center and spacing should be defined in the unit of DIRECTION column.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/asapplotter.py

    r2538 r2576  
    12761276            PL.gcf().canvas.switch_backends(FigureCanvasAgg)
    12771277        self._data = scan
    1278         self._outfile = outfile
    12791278        dates = self._data.get_time(asdatetime=True)
    12801279        t = PL.date2num(dates)
     
    12841283        PL.clf()
    12851284        # Adjust subplot margins
    1286         if len(self._margins) != 6:
     1285        if not self._margins or len(self._margins) != 6:
    12871286            self.set_margin(refresh=False)
    12881287        lef, bot, rig, top, wsp, hsp = self._margins
     
    13621361        PL.draw()
    13631362        if matplotlib.get_backend() == 'Qt4Agg': PL.gcf().show()
    1364         if (self._outfile is not None):
    1365            PL.savefig(self._outfile)
     1363        if (outfile is not None):
     1364           PL.savefig(outfile)
    13661365
    13671366    def plotpointing(self, scan=None, outfile=None):
     
    13771376            PL.gcf().canvas.switch_backends(FigureCanvasAgg)
    13781377        self._data = scan
    1379         self._outfile = outfile
    13801378        dir = array(self._data.get_directionval()).transpose()
    13811379        ra = dir[0]*180./pi
     
    13851383        PL.clf()
    13861384        # Adjust subplot margins
    1387         if len(self._margins) != 6:
     1385        if not self._margins or len(self._margins) != 6:
    13881386            self.set_margin(refresh=False)
    13891387        lef, bot, rig, top, wsp, hsp = self._margins
     
    14031401        PL.draw()
    14041402        if matplotlib.get_backend() == 'Qt4Agg': PL.gcf().show()
    1405         if (self._outfile is not None):
    1406            PL.savefig(self._outfile)
     1403        if (outfile is not None):
     1404           PL.savefig(outfile)
    14071405
    14081406    # plot total power data
    14091407    # plotting in time is not yet implemented..
    14101408    @asaplog_post_dec
    1411     def plottp(self, scan=None, outfile=None):
     1409    def plottp(self, scan=None):
    14121410        self._assert_plotter(action="reload")
    14131411        self._plotter.hold()
     
    14341432
    14351433        # Adjust subplot margins
    1436         if len(self._margins) !=6: self.set_margin(refresh=False)
     1434        if not self._margins or len(self._margins) !=6:
     1435            self.set_margin(refresh=False)
    14371436        lef, bot, rig, top, wsp, hsp = self._margins
    14381437        self._plotter.figure.subplots_adjust(
     
    15831582            self._plotter.release()
    15841583        self._reset_header()
     1584
     1585    # plot spectra by pointing
     1586    @asaplog_post_dec
     1587    def plotgrid(self, scan=None,center=None,spacing=None,rows=None,cols=None):
     1588        """
     1589        Plot spectra based on direction.
     1590       
     1591        Parameters:
     1592            scan:      a scantable to plot
     1593            center:    the grid center direction (a list) of plots in the
     1594                       unit of DIRECTION column.
     1595                       (default) the center of map region
     1596            spacing:   a list of horizontal (R.A.) and vertical (Dec.)
     1597                       spacing in the unit of DIRECTION column.
     1598                       (default) Calculated by the extent of map region and
     1599                       the number of rows and cols to cover
     1600            rows:      number of panels (grid points) in horizontal direction
     1601            cols:      number of panels (grid points) in vertical direction
     1602
     1603        Note:
     1604        - Only the first IFNO, POLNO, and BEAM in the scantable will be
     1605        plotted.
     1606        - This method doesn't re-grid and average spectra in scantable. Use
     1607        asapgrid module to re-grid spectra before plotting with this method.
     1608        Only the first spectrum is plotted in case there are multiple
     1609        spectra which belong to a grid.
     1610        """
     1611        from asap import scantable
     1612        from numpy import array, ma
     1613        if not self._data and not scan:
     1614            msg = "No scantable is specified to plot"
     1615            raise TypeError(msg)
     1616        if isinstance(scan, scantable):
     1617            if self._data is not None:
     1618                if scan != self._data:
     1619                    self._data = scan
     1620                    # reset
     1621                    self._reset()
     1622            else:
     1623                self._data = scan
     1624                self._reset()
     1625        elif not self._data:
     1626            msg = "Input is not a scantable"
     1627            raise TypeError(msg)
     1628       
     1629        # Rows and cols
     1630        if rows:
     1631            self._rows = int(rows)
     1632        else:
     1633            msg = "Number of rows to plot are not specified. "
     1634            if self._rows:
     1635                msg += "Using previous value = %d" % (self._rows)
     1636                asaplog.push(msg)
     1637            else:
     1638                self._rows = 1
     1639                msg += "Setting rows = %d" % (self._rows)
     1640                asaplog.post()
     1641                asaplog.push(msg)
     1642                asaplog.post("WARN")
     1643        if cols:
     1644            self._cols = int(cols)
     1645        else:
     1646            msg = "Number of cols to plot are not specified. "
     1647            if self._cols:
     1648                msg += "Using previous value = %d" % (self._cols)
     1649                asaplog.push(msg)
     1650            else:
     1651                self._cols = 1
     1652                msg += "Setting cols = %d" % (self._cols)
     1653                asaplog.post()
     1654                asaplog.push(msg)
     1655                asaplog.post("WARN")
     1656
     1657        # Center and spacing
     1658        if type(center) == list and len(center) > 1:
     1659            center = center[0:2]
     1660        else:
     1661            asaplog.post()
     1662            asaplog.push("Grid center is not specified. Automatically calculated from pointing center.")
     1663            asaplog.post("WARN")
     1664            dirarr = array(self._data.get_directionval()).transpose()
     1665            #center = [dirarr[0].mean(), dirarr[1].mean()]
     1666            center = [0.5*(dirarr[0].max() + dirarr[0].min()),
     1667                      0.5*(dirarr[1].max() + dirarr[1].min())]
     1668            del dirarr
     1669        asaplog.push("Grid center: (%f, %f) " % (center[0],center[1]))
     1670
     1671        if spacing is None:
     1672            asaplog.post()
     1673            asaplog.push("Grid spacing not specified. Automatically calculated from map coverage")
     1674            asaplog.post("WARN")
     1675            # automatically get spacing
     1676            dirarr = array(self._data.get_directionval()).transpose()
     1677            wx = 2. * max(abs(dirarr[0].max()-center[0]),
     1678                          abs(dirarr[0].min()-center[0]))
     1679            wy = 2. * max(abs(dirarr[1].max()-center[1]),
     1680                          abs(dirarr[1].min()-center[1]))
     1681            # slightly expand area to plot the edges
     1682            wx *= 1.01
     1683            wy *= 1.01
     1684            xgrid = wx/self._cols
     1685            ygrid = wy/self._rows
     1686            print "Pointing range: (x, y) = (%f - %f, %f - %f)" %\
     1687              (dirarr[0].min(),dirarr[0].max(),dirarr[1].min(),dirarr[1].max())
     1688            # identical R.A. and/or Dec. for all spectra.
     1689            if xgrid == 0:
     1690                xgrid = 1.
     1691            if ygrid == 0:
     1692                ygrid = 1.
     1693            # spacing should be negative to transpose plot
     1694            spacing = [- xgrid, - ygrid]
     1695            del dirarr, xgrid, ygrid
     1696        #elif isinstance(spacing, str):
     1697        #    # spacing is a quantity
     1698        elif isinstance(spacing,list) and len(spacing) > 1:
     1699            for val in spacing[0:2]:
     1700                if not isinstance(val, str):
     1701                    raise TypeError("spacing should be a list of float")
     1702            spacing = spacing[0:2]
     1703        else:
     1704            msg = "Invalid spacing."
     1705            raise TypeError(msg)
     1706        asaplog.push("Spacing: (%f, %f) " % (spacing[0],spacing[1]))
     1707
     1708        ntotpl = self._rows * self._cols
     1709        minpos = [center[0]-spacing[0]*self._cols/2.,
     1710                  center[1]-spacing[1]*self._rows/2.]
     1711        #xbound = [center[0]-spacing[0]*self._cols/2.,
     1712        #          center[0]+spacing[0]*self._cols/2.]
     1713        #ybound = [center[1]-spacing[1]*self._rows/2.,
     1714        #          center[1]+spacing[1]*self._rows/2.]
     1715        print "Plot range: (x, y) = (%f - %f, %f - %f)" %\
     1716              (minpos[0],minpos[0]+spacing[0]*self._cols,
     1717               minpos[1],minpos[1]+spacing[1]*self._rows)
     1718        #      (xbound[0],xbound[1],ybound[0],ybound[1])
     1719        ifs = self._data.getifnos()
     1720        if len(ifs) > 1:
     1721            msg = "Found multiple IFs in scantable. Only the first IF (IFNO=%d) will be plotted." % ifs[0]
     1722            asaplog.post()
     1723            asaplog.push(msg)
     1724            asaplog.post("WARN")
     1725        pols = self._data.getpolnos()
     1726        if len(pols) > 1:
     1727            msg = "Found multiple POLs in scantable. Only the first POL (POLNO=%d) will be plotted." % pols[0]
     1728            asaplog.post()
     1729            asaplog.push(msg)
     1730            asaplog.post("WARN")
     1731        beams = self._data.getbeamnos()
     1732        if len(beams) > 1:
     1733            msg = "Found multiple BEAMs in scantable. Only the first BEAM (BEAMNO=%d) will be plotted." % beams[0]
     1734            asaplog.post()
     1735            asaplog.push(msg)
     1736            asaplog.post("WARN")
     1737        self._data.set_selection(ifs=[ifs[0]],pols=[pols[0]],beams=[beams[0]])
     1738        if self._data.nrow() > ntotpl:
     1739            msg = "Scantable is finely sampled than plotting grids. "\
     1740                  + "Only the first spectrum is plotted in each grid."
     1741            asaplog.post()
     1742            asaplog.push(msg)
     1743            asaplog.post("WARN")
     1744       
     1745        self._assert_plotter(action="reload")
     1746        self._plotter.hold()
     1747        self._plotter.clear()
     1748       
     1749        # Adjust subplot margins
     1750        if not self._margins or len(self._margins) !=6:
     1751            self.set_margin(refresh=False)
     1752        self._plotter.set_panels(rows=self._rows,cols=self._cols,
     1753                                 nplots=ntotpl,margin=self._margins,ganged=True)
     1754        if self.casabar_exists(): self._plotter.figmgr.casabar.disable_button()
     1755        # Actual plot
     1756        npl = 0
     1757        for irow in range(self._data.nrow()):
     1758            pos = self._data.get_directionval(irow)
     1759            ix = int((pos[0] - minpos[0])/spacing[0])
     1760            #if pos[0] < xbound[0] or pos[0] > xbound[1]:
     1761            if ix < 0 or ix >= self._cols:
     1762                print "Row %d : Out of X-range (x = %f) ... skipped" % (irow, pos[0])
     1763                continue
     1764            #ix = min(int((pos[0] - xbound[0])/spacing[0]),self._cols)
     1765            iy = int((pos[1]- minpos[1])/spacing[1])
     1766            #if pos[1] < ybound[0] or pos[1] > ybound[1]:
     1767            if iy < 0 or iy >= self._cols:
     1768                print "Row %d : Out of Y-range (y = %f) ... skipped" % (irow,pos[1])
     1769                continue
     1770            #iy = min(int((pos[1]- ybound[0])/spacing[1]),self._rows)
     1771            ipanel = ix + iy*self._cols
     1772            if len(self._plotter.subplots[ipanel]['lines']) > 0:
     1773                print "Row %d : panel %d lready plotted ... skipped" % (irow,ipanel)
     1774                # a spectrum already plotted in the panel
     1775                continue
     1776            # Plotting this row
     1777            print "PLOTTING row %d (panel=%d)" % (irow, ipanel)
     1778            npl += 1
     1779            self._plotter.subplot(ipanel)
     1780            self._plotter.palette(0)
     1781            xlab = self._abcissa and self._abcissa[ipanel] \
     1782                   or scan._getabcissalabel(irow)
     1783            if self._offset and not self._abcissa:
     1784                xlab += " (relative)"
     1785            ylab = self._ordinate and self._ordinate[ipanel] \
     1786                   or scan._get_ordinate_label()
     1787            self._plotter.set_axes('xlabel', xlab)
     1788            self._plotter.set_axes('ylabel', ylab)
     1789            #from numpy import pi
     1790            #lbl = "(%f, %f)" % (self._data.get_directionval(irow)[0]*180/pi,self._data.get_directionval(irow)[1]*180./pi)
     1791            lbl = self._data.get_direction(irow)
     1792            self._plotter.set_axes('title',lbl)
     1793
     1794            y = scan._getspectrum(irow)
     1795            # flag application
     1796            mr = scan._getflagrow(irow)
     1797            if mr:  # FLAGROW=True
     1798                y = ma.masked_array(y,mask=mr)
     1799            else:
     1800                m = scan._getmask(irow)
     1801                from numpy import logical_not, logical_and
     1802                ### user mask is not available so far
     1803                #if self._maskselection and len(self._usermask) == len(m):
     1804                #    if d[self._stacking](irow) in self._maskselection[self._stacking]:
     1805                #            m = logical_and(m, self._usermask)
     1806                y = ma.masked_array(y,mask=logical_not(array(m,copy=False)))
     1807
     1808            x = array(scan._getabcissa(irow))
     1809            if self._offset:
     1810                x += self._offset
     1811            if self._minmaxx is not None:
     1812                s,e = self._slice_indeces(x)
     1813                x = x[s:e]
     1814                y = y[s:e]
     1815            if len(x) > 1024 and rcParams['plotter.decimate']:
     1816                fac = len(x)/1024
     1817                x = x[::fac]
     1818                y = y[::fac]
     1819            self._plotter.set_line(label=lbl)
     1820            plotit = self._plotter.plot
     1821            if self._hist: plotit = self._plotter.hist
     1822            if len(x) > 0 and not mr:
     1823                plotit(x,y)
     1824#                 xlim= self._minmaxx or [min(x),max(x)]
     1825#                 allxlim += xlim
     1826#                 ylim= self._minmaxy or [ma.minimum(y),ma.maximum(y)]
     1827#                 allylim += ylim
     1828#             else:
     1829#                 xlim = self._minmaxx or []
     1830#                 allxlim += xlim
     1831#                 ylim= self._minmaxy or []
     1832#                 allylim += ylim
     1833           
     1834            if npl >= ntotpl:
     1835                break
     1836           
     1837        #self._plottp(self._data)
     1838
     1839        if self._minmaxy is not None:
     1840            self._plotter.set_limits(ylim=self._minmaxy)
     1841        self._plotter.release()
     1842        self._plotter.tidy()
     1843        self._plotter.show(hardrefresh=False)
     1844        return
Note: See TracChangeset for help on using the changeset viewer.