Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/asapgrid.py

    r2373 r2450  
    88
    99class asapgrid:
     10    """
     11    The asapgrid class is defined to convolve data onto regular
     12    spatial grid. Typical usage is as follows:
     13
     14       # create asapgrid instance with two input data
     15       g = asapgrid( ['testimage1.asap','testimage2.asap'] )
     16       # set IFNO if necessary
     17       g.setIF( 0 )
     18       # set POLNOs if necessary
     19       g.setPolList( [0,1] )
     20       # set SCANNOs if necessary
     21       g.setScanList( [22,23,24] )
     22       # define image with full specification
     23       # you can skip some parameters (see help for defineImage)
     24       g.defineImage( nx=12, ny=12, cellx='10arcsec', celly='10arcsec',
     25                      center='J2000 10h10m10s -5d05m05s' )
     26       # set convolution function
     27       g.setFunc( func='sf', width=3 )
     28       # enable min/max clipping
     29       g.enableClip()
     30       # or, disable min/max clipping
     31       #g.disableClip()
     32       # actual gridding
     33       g.grid()
     34       # save result
     35       g.save( outfile='grid.asap' )
     36       # plot result
     37       g.plot( plotchan=1246, plotpol=-1, plotgrid=True, plotobs=True )
     38    """
    1039    def __init__( self, infile ):
    11         self.infile = infile
     40        """
     41        Create asapgrid instance.
     42
     43        infile -- input data as a string or string list if you want
     44                  to grid more than one data at once. 
     45        """
    1246        self.outfile = None
    13         self.gridder = stgrid( self.infile )
    1447        self.ifno = None
     48        self.gridder = stgrid()
     49        self.setData( infile )
    1550
    1651    def setData( self, infile ):
    17         self.gridder._setin( infile )
     52        """
     53        Set data to be processed.
     54
     55        infile -- input data as a string or string list if you want
     56                  to grid more than one data at once. 
     57        """
     58        if isinstance( infile, str ):
     59            self.gridder._setin( infile )
     60        else:
     61            self.gridder._setfiles( infile )
     62        self.infile = infile
    1863
    1964    def setIF( self, ifno ):
     65        """
     66        Set IFNO to be processed. Currently, asapgrid allows to process
     67        only one IFNO for one gridding run even if the data contains
     68        multiple IFs. If you didn't specify IFNO, default value, which
     69        is IFNO in the first spectrum, will be processed.
     70
     71        ifno -- IFNO to be processed.
     72        """
    2073        self.ifno = ifno
    2174        self.gridder._setif( self.ifno )
    2275
    2376    def setPolList( self, pollist ):
     77        """
     78        Set list of polarization components you want to process.
     79        If not specified, all POLNOs will be processed.
     80
     81        pollist -- list of POLNOs.
     82        """
    2483        self.gridder._setpollist( pollist )
    2584
    2685    def setScanList( self, scanlist ):
     86        """
     87        Set list of scans you want to process. If not specified, all
     88        scans will be processed.
     89
     90        scanlist -- list of SCANNOs.
     91        """
    2792        self.gridder._setscanlist( scanlist )
    2893
    2994    def defineImage( self, nx=-1, ny=-1, cellx='', celly='', center='' ):
     95        """
     96        Define spatial grid.
     97
     98        First two parameters, nx and ny, define number of pixels of
     99        the grid. If which of those is not specified, it will be set
     100        to the same value as the other. If none of them are specified,
     101        it will be determined from map extent and cell size.
     102
     103        Next two parameters, cellx and celly, define size of pixel.
     104        You should set those parameters as string, which is constructed
     105        numerical value and unit, e.g. '0.5arcmin', or numerical value.
     106        If those values are specified as numerical value, their units
     107        will be assumed to 'arcsec'. If which of those is not specified,
     108        it will be set to the same value as the other. If none of them
     109        are specified, it will be determined from map extent and number
     110        of pixels, or set to '1arcmin' if neither nx nor ny is set.
     111
     112        The last parameter, center, define the central coordinate of
     113        the grid. You should specify its value as a string, like,
     114
     115           'J2000 05h08m50s -16d23m30s'
     116
     117        or
     118
     119           'J2000 05:08:50 -16.23.30'
     120
     121        You can omit equinox when you specify center coordinate. In that
     122        case, J2000 is assumed. If center is not specified, it will be
     123        determined from the observed positions of input data.
     124
     125        nx -- number of pixels along x (R.A.) direction.
     126        ny -- number of pixels along y (Dec.) direction.
     127        cellx -- size of pixel in x (R.A.) direction.
     128        celly -- size of pixel in y (Dec.) direction.
     129        center -- central position of the grid.
     130        """
     131        if not isinstance( cellx, str ):
     132            cellx = '%sarcsec'%(cellx)
     133        if not isinstance( celly, str ):
     134            celly = '%sarcsec'%(celly)
    30135        self.gridder._defineimage( nx, ny, cellx, celly, center )
    31136
    32137    def setFunc( self, func='box', width=-1 ):
     138        """
     139        Set convolution function. Possible options are 'box' (Box-car,
     140        default), 'sf' (prolate spheroidal), and 'gauss' (Gaussian).
     141        Width of convolution function can be set using width parameter.
     142        By default (-1), width is automatically set depending on each
     143        convolution function. Default values for width are:
     144
     145           'box': 1 pixel
     146           'sf': 3 pixels
     147           'gauss': 1 pixel (width is used as HWHM)
     148
     149        func -- Function type ('box', 'sf', 'gauss').
     150        width -- Width of convolution function. Default (-1) is to
     151                 choose pre-defined value for each convolution function.
     152        """
    33153        self.gridder._setfunc( func, width )
    34154
    35155    def setWeight( self, weightType='uniform' ):
    36         self.gridder._setweight( weightType )
     156        """
     157        Set weight type. Possible options are 'uniform' (default),
     158        'tint' (weight by integration time), 'tsys' (weight by
     159        Tsys: 1/Tsys**2), and 'tintsys' (weight by integration time
     160        as well as Tsys: tint/Tsys**2).
     161
     162        weightType -- weight type ('uniform', 'tint', 'tsys', 'tintsys')
     163        """
     164        self.gridder._setweight( weightType )
     165
     166    def enableClip( self ):
     167        """
     168        Enable min/max clipping.
     169
     170        By default, min/max clipping is disabled so that you should
     171        call this method before actual gridding if you want to do
     172        clipping.
     173        """
     174        self.gridder._enableclip()
     175
     176    def disableClip( self ):
     177        """
     178        Disable min/max clipping.
     179        """
     180        self.gridder._disableclip()
    37181
    38182    def grid( self ):
     183        """
     184        Actual gridding which will be done based on several user inputs.
     185        """
    39186        self.gridder._grid()
    40187
    41188    def save( self, outfile='' ):
     189        """
     190        Save result. By default, output data name will be constructed
     191        from first element of input data name list (e.g. 'input.asap.grid').
     192
     193        outfile -- output data name.
     194        """
    42195        self.outfile = self.gridder._save( outfile )
    43196
    44     def plot( self, plotchan=-1, plotpol=-1 ):
     197    def plot( self, plotchan=-1, plotpol=-1, plotobs=False, plotgrid=False ):
     198        """
     199        Plot gridded data.
     200
     201        plotchan -- Which channel you want to plot. Default (-1) is
     202                    to average all the channels.
     203        plotpol -- Which polarization component you want to plot.
     204                   Default (-1) is to average all the polarization
     205                   components.
     206        plotobs -- Also plot observed position if True. Default
     207                   is False. Setting True for large amount of spectra
     208                   might be time consuming.
     209        plotgrid -- Also plot grid center if True. Default is False.
     210                    Setting True for large number of grids might be
     211                    time consuming.
     212        """
    45213        import time
    46214        t0=time.time()
     
    49217        rcParams['scantable.storage'] = 'disk'
    50218        plotter = _SDGridPlotter( self.infile, self.outfile, self.ifno )
    51         plotter.plot( chan=plotchan, pol=plotpol )
     219        plotter.plot( chan=plotchan, pol=plotpol, plotobs=plotobs, plotgrid=plotgrid )
    52220        # back to original setup
    53221        rcParams['scantable.storage'] = storg
     
    58226class _SDGridPlotter:
    59227    def __init__( self, infile, outfile=None, ifno=-1 ):
    60         self.infile = infile
     228        if isinstance( infile, str ):
     229            self.infile = [infile]
     230        else:
     231            self.infile = infile
    61232        self.outfile = outfile
    62233        if self.outfile is None:
    63             self.outfile = self.infile.rstrip('/')+'.grid'
     234            self.outfile = self.infile[0].rstrip('/')+'.grid'
    64235        self.nx = -1
    65236        self.ny = -1
     
    79250
    80251    def get( self ):
    81         self.tablein = scantable( self.infile, average=False )
    82         if self.ifno < 0:
    83             ifno = self.tablein.getif(0)
    84             print 'ifno=',ifno
    85         else:
    86             ifno = self.ifno
    87         sel = selector()
    88         sel.set_ifs( ifno )
    89         self.tablein.set_selection( sel )
    90         self.nchan = len(self.tablein._getspectrum(0))
    91         self.nrow = self.tablein.nrow()
    92         del sel
    93 
    94252        s = scantable( self.outfile, average=False )
     253        self.nchan = len(s._getspectrum(0))
    95254        nrow = s.nrow()
    96255        pols = numpy.ones( nrow, dtype=int )
     
    106265        idx = 0
    107266        d0 = s.get_direction( 0 ).split()[-1]
    108         while ( s.get_direction(self.npol*idx).split()[-1] == d0 ): 
     267        while ( s.get_direction(self.npol*idx) is not None \
     268                and s.get_direction(self.npol*idx).split()[-1] == d0 ):
    109269            idx += 1
    110270       
     
    117277        #print self.blc
    118278        #print self.trc
    119         incrx = s.get_directionval( self.npol )
    120         incry = s.get_directionval( self.nx*self.npol )
     279        if nrow > 1:
     280            incrx = s.get_directionval( self.npol )
     281            incry = s.get_directionval( self.nx*self.npol )
     282        else:
     283            incrx = [0.0,0.0]
     284            incry = [0.0,0.0]
    121285        self.cellx = abs( self.blc[0] - incrx[0] )
    122286        self.celly = abs( self.blc[1] - incry[1] )
    123287        #print 'cellx,celly=',self.cellx,self.celly
    124288
    125     def plot( self, chan=-1, pol=-1 ):
     289    def plot( self, chan=-1, pol=-1, plotobs=False, plotgrid=False ):
    126290        if pol < 0:
    127291            opt = 'averaged over pol'
    128292        else:
    129293            opt = 'pol %s'%(pol)
    130         if chan < 0:
     294        if type(chan) is list:
     295            opt += ', averaged over channel %s-%s'%(chan[0],chan[1])
     296        elif chan < 0:
    131297            opt += ', averaged over channel'
    132298        else:
    133299            opt += ', channel %s'%(chan)
    134         data = self.getData( chan, pol )
     300        data = self.getData( chan, pol )
     301        data = numpy.fliplr( data )
    135302        title = 'Gridded Image (%s)'%(opt)
    136303        pl.figure(10)
    137304        pl.clf()
    138305        # plot grid position
    139         x = numpy.arange(self.blc[0],self.trc[0]+0.5*self.cellx,self.cellx,dtype=float)
    140         #print 'len(x)=',len(x)
    141         #print 'x=',x
    142         ybase = numpy.ones(self.nx,dtype=float)*self.blc[1]
    143         #print 'len(ybase)=',len(ybase)
    144         incr = self.celly
    145         for iy in xrange(self.ny):
    146             y = ybase + iy * incr
    147             #print y
    148             pl.plot(x,y,',',color='blue')
     306        if plotgrid:
     307            x = numpy.arange(self.blc[0],self.trc[0]+0.5*self.cellx,self.cellx,dtype=float)
     308            #print 'len(x)=',len(x)
     309            #print 'x=',x
     310            ybase = numpy.ones(self.nx,dtype=float)*self.blc[1]
     311            #print 'len(ybase)=',len(ybase)
     312            incr = self.celly
     313            for iy in xrange(self.ny):
     314                y = ybase + iy * incr
     315                #print y
     316                pl.plot(x,y,',',color='blue')
    149317        # plot observed position
    150         irow = 0
    151         while ( irow < self.nrow ):
    152             chunk = self.getPointingChunk( irow )
    153             #print chunk
    154             pl.plot(chunk[0],chunk[1],',',color='green')
    155             irow += chunk.shape[1]
    156             #print irow
     318        if plotobs:
     319            for i in xrange(len(self.infile)):
     320                self.createTableIn( self.infile[i] )
     321                irow = 0
     322                while ( irow < self.nrow ):
     323                    chunk = self.getPointingChunk( irow )
     324                    #print chunk
     325                    pl.plot(chunk[0],chunk[1],',',color='green')
     326                    irow += chunk.shape[1]
     327                    #print irow
    157328        # show image
    158         extent=[self.blc[0]-0.5*self.cellx,
    159                 self.trc[0]+0.5*self.cellx,
     329        extent=[self.trc[0]+0.5*self.cellx,
     330                self.blc[0]-0.5*self.cellx,
    160331                self.blc[1]-0.5*self.celly,
    161332                self.trc[1]+0.5*self.celly]
     333        deccorr = 1.0/numpy.cos(0.5*(self.blc[1]+self.trc[1]))
    162334        pl.imshow(data,extent=extent,origin='lower',interpolation='nearest')
    163335        pl.colorbar()
    164336        pl.xlabel('R.A. [rad]')
    165337        pl.ylabel('Dec. [rad]')
     338        ax = pl.axes()
     339        ax.set_aspect(deccorr)
    166340        pl.title( title )
     341
     342    def createTableIn( self, tab ):
     343        del self.tablein
     344        self.tablein = scantable( tab, average=False )
     345        if self.ifno < 0:
     346            ifno = self.tablein.getif(0)
     347            print 'ifno=',ifno
     348        else:
     349            ifno = self.ifno
     350        sel = selector()
     351        sel.set_ifs( ifno )
     352        self.tablein.set_selection( sel )
     353        self.nchan = len(self.tablein._getspectrum(0))
     354        self.nrow = self.tablein.nrow()
     355        del sel
     356       
    167357
    168358    def getPointingChunk( self, irow ):
     
    180370
    181371    def getData( self, chan=-1, pol=-1 ):
    182         if chan == -1:
     372        if type(chan) == list:
     373            spectra = self.__chanAverage(start=chan[0],end=chan[1])
     374        elif chan == -1:
    183375            spectra = self.__chanAverage()
    184376        else:
     
    189381        else:
    190382            retval = data[pol]
    191         #retval[0][self.nx-1] = -1.0
    192383        return retval
    193384
    194     def __chanAverage( self ):
     385    def __chanAverage( self, start=-1, end=-1 ):
    195386        s = scantable( self.outfile, average=False )
    196387        nrow = s.nrow()
     
    198389        irow = 0
    199390        sp = [0 for i in xrange(self.nchan)]
     391        if start < 0:
     392            start = 0
     393        if end < 0:
     394            end = self.nchan
    200395        for i in xrange(nrow/self.npol):
    201396            for ip in xrange(self.npol):
    202                 sp = s._getspectrum( irow )
     397                sp = s._getspectrum( irow )[start:end]
    203398                spectra[ip,i] = numpy.mean( sp )
    204399                irow += 1
     400           
    205401        return spectra
    206402
Note: See TracChangeset for help on using the changeset viewer.