Changeset 876 for trunk/python


Ignore:
Timestamp:
03/06/06 11:51:04 (19 years ago)
Author:
mar637
Message:

move to asap2 container

Location:
trunk/python
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/__init__.py

    r796 r876  
    250250
    251251from asapfitter import *
    252 from asapreader import reader
     252#from asapreader import reader
    253253
    254254from asapmath import *
    255 from scantable import *
    256 from asaplinefind import *
    257 from asapfit import *
     255#from scantable import *
     256#from asaplinefind import *
     257#from asapfit import *
    258258
    259259from numarray import logical_and as mask_and
     
    261261from numarray import logical_not as mask_not
    262262
    263 if rcParams['useplotter']:
    264     from  asapplotter import *
    265     gui = os.environ.has_key('DISPLAY') and rcParams['plotter.gui']
    266     plotter = asapplotter(gui)
    267     del gui
     263# if rcParams['useplotter']:
     264#     from  asapplotter import *
     265#     gui = os.environ.has_key('DISPLAY') and rcParams['plotter.gui']
     266#     plotter = asapplotter(gui)
     267#     del gui
    268268
    269269__date__ = '$Date$'.split()[1]
     
    286286            copy            - returns a copy of a scan
    287287            get_scan        - gets a specific scan out of a scantable
    288                               (by name or number)
     288                              (by name or number) [deprecated]
    289289            summary         - print info about the scantable contents
    290             set_cursor      - set a specific Beam/IF/Pol 'cursor' for
    291                               further use
    292             get_cursor      - print out the current cursor position
    293290            stats           - get specified statistic of the spectra in
    294291                              the scantable
     
    301298            get_elevation   - get the elevation of the scans
    302299            get_parangle    - get the parallactic angle of the scans
    303             get_unit        - get the currnt unit
     300            get_unit        - get the current unit
    304301            set_unit        - set the abcissa unit to be used from this
    305302                              point on
  • trunk/python/asapfitter.py

    r794 r876  
    130130                from asap import asaplog
    131131                asaplog.push("Fitting:")
    132                 self.selection = self.data.get_cursor()
     132                out = "Scan[%d] Beam[%d] IF[%d] Pol[%d] Cycle[%d]" (self.data.getscan(i),self.data.getbeam(i),self.data.getif(i),self.data.getpol(i), self.data.getcycle(i))
     133                asaplog.push(out)
    133134        self.fitter.setdata(self.x, self.y, self.mask)
    134135        if self.fitfunc == 'gauss':
     
    432433        print_log()
    433434
    434     def auto_fit(self, insitu=None, allaxes=True):
     435    def auto_fit(self, insitu=None):
    435436        """
    436437        Return a scan where the function is applied to all rows for
     
    451452        else:
    452453            scan = self.data
    453         sel = scan.get_cursor()
    454454        rows = range(scan.nrow())
    455455        from asap import asaplog
    456         if allaxes:
    457             for i in range(scan.nbeam()):
    458                 scan.setbeam(i)
    459                 for j in range(scan.nif()):
    460                     scan.setif(j)
    461                     for k in range(scan.npol()):
    462                         scan.setpol(k)
    463                         asaplog.push("Fitting:")
    464                         out = 'Beam[%d], IF[%d], Pol[%d]' % (i,j,k)
    465                         asaplog.push(out)
    466                         for iRow in rows:
    467                             self.x = scan._getabcissa(iRow)
    468                             self.y = scan._getspectrum(iRow)
    469                             self.data = None
    470                             self.fit()
    471                             x = self.get_parameters()
    472                             scan._setspectrum(self.fitter.getresidual(),iRow)
    473         else:
    474             asaplog.push("Fitting:")
    475             out = 'Beam[%d], IF[%d], Pol[%d]' % sel
     456        asaplog.push("Fitting:")
     457        for r in rows:
     458            out = "Scan[%d] Beam[%d] IF[%d] Pol[%d] Cycle[%d]" %        (self.data.getscan(r),self.data.getbeam(r),self.data.getif(r),self.data.getpol(r), self.data.getcycle(r))
    476459            asaplog.push(out)
    477             for iRow in rows:
    478                 self.x = scan._getabcissa(iRow)
    479                 self.y = scan._getspectrum(iRow)
    480                 self.data = None
    481                 self.fit()
    482                 x = self.get_parameters()
    483                 scan._setspectrum(self.fitter.getresidual(),iRow)
    484 
    485         scan.set_cursor(sel[0],sel[1],sel[2])
     460            self.x = scan._getabcissa(r)
     461            self.y = scan._getspectrum(r)
     462            self.data = None
     463            self.fit()
     464            x = self.get_parameters()
     465            scan._setspectrum(self.fitter.getresidual(),iRow)
    486466        print_log()
    487         if not insitu:
    488             return scan
     467        return scan
     468
  • trunk/python/asapmath.py

    r720 r876  
    4545    # need special formatting her for history...
    4646
    47     from asap._asap import average as _av
     47    from asap._asap import stmath
     48    stm = stmath()
    4849    for s in lst:
    4950        if not isinstance(s,scantable):
     
    5455            else:
    5556                raise TypeError(msg)
    56     s = scantable(_av(lst, mask, scanAv, weight))
     57    if scanAv: scanAv = "SCAN"
     58    else: scanAv = "NONE"
     59    s = scantable(stm._average(lst, mask, weight, scanAv, False))
    5760    s._add_history("average_time",varlist)
    5861    print_log()
    5962    return s
    6063
    61 def quotient(source, reference, preserve=True):
    62     """
    63     Return the quotient of a 'source' (signal) scan and a 'reference' scan.
    64     The reference can have just one row, even if the signal has many. Otherwise
    65     they must have the same number of rows.
    66     The cursor of the output scan is set to 0
    67     Parameters:
    68         source:        the 'on' scan
    69         reference:     the 'off' scan
    70         preserve:      you can preserve (default) the continuum or
    71                        remove it.  The equations used are
    72                        preserve:  Output = Toff * (on/off) - Toff
    73                        remove:    Output = Toff * (on/off) - Ton
    74     """
    75     varlist = vars()
    76     from asap._asap import quotient as _quot
    77     s = scantable(_quot(source, reference, preserve))
    78     s._add_history("quotient",varlist)
    79     print_log()
    80     return s
     64# def quotient(source, reference, preserve=True):
     65#     """
     66#     Return the quotient of a 'source' (signal) scan and a 'reference' scan.
     67#     The reference can have just one row, even if the signal has many. Otherwise
     68#     they must have the same number of rows.
     69#     The cursor of the output scan is set to 0
     70#     Parameters:
     71#         source:        the 'on' scan
     72#         reference:     the 'off' scan
     73#         preserve:      you can preserve (default) the continuum or
     74#                        remove it.  The equations used are
     75#                        preserve:  Output = Toff * (on/off) - Toff
     76#                        remove:    Output = Toff * (on/off) - Ton
     77#     """
     78#     varlist = vars()
     79#     from asap._asap import quotient as _quot
     80#     s = scantable(_quot(source, reference, preserve))
     81#     s._add_history("quotient",varlist)
     82#     print_log()
     83#     return s
    8184
    8285def simple_math(left, right, op='add', tsys=True):
     
    9497    """
    9598    varlist = vars()
     99    print "Not yet available in asap"
     100    return
    96101    if not isinstance(left,scantable) and not isinstance(right,scantable):
    97102        msg = "Please provide two scantables as input"
  • trunk/python/scantable.py

    r794 r876  
    1 from asap._asap import sdtable
     1from asap._asap import Scantable
    22from asap import rcParams
    33from asap import print_log
     
    55import sys
    66
    7 class scantable(sdtable):
     7class scantable(Scantable):
    88    """
    99        The ASAP container for scans
     
    3333
    3434        varlist = vars()
    35         self._p = None
     35        from asap._asap import stmath
     36        self._math = stmath()
    3637        from asap import asaplog
    37         if isinstance(filename,sdtable):
    38             sdtable.__init__(self, filename)
     38        if isinstance(filename, Scantable):
     39            Scantable.__init__(self, filename)
    3940            if unit is not None:
    4041                self.set_fluxunit(unit)
     
    5253                # crude check if asap table
    5354                if os.path.exists(filename+'/table.info'):
    54                     sdtable.__init__(self, filename)
     55                    Scantable.__init__(self, filename, "memory")
    5556                    if unit is not None:
    5657                        self.set_fluxunit(unit)
     
    6364                        raise IOError(msg)
    6465            else:
    65                 from asap._asap import sdreader
     66                from asap._asap import stfiller
    6667                ifSel = -1
    6768                beamSel = -1
    68                 r = sdreader()
     69                r = stfiller()
    6970                r._open(filename,ifSel,beamSel)
    7071                asaplog.push('Importing data...')
    7172                print_log()
    72                 r._read([-1])
     73                r._read()
    7374                tbl = r._getdata()
    7475                if unit is not None:
    7576                    tbl.set_fluxunit(unit)
    7677                if average:
    77                     from asap._asap import average as _av
    7878                    asaplog.push('Auto averaging integrations...')
    7979                    print_log()
    80                     tbl2 = _av((tbl,),(),True,'none')
    81                     sdtable.__init__(self,tbl2)
     80                    tbl2 = self._math._average((tbl,),(),'NONE','SCAN', False)
     81                    Scantable.__init__(self,tbl2)
    8282                    del tbl2
    8383                else:
    84                     sdtable.__init__(self,tbl)
     84                    Scantable.__init__(self,tbl)
    8585                del r,tbl
    8686                self._add_history("scantable", varlist)
    8787        print_log()
    8888
    89     def save(self, name=None, format=None, stokes=False, overwrite=False):
     89    def save(self, name=None, format=None, overwrite=False):
    9090        """
    9191        Store the scantable on disk. This can be an asap (aips++) Table, SDFITS,
     
    104104                                       'MS2' (saves as an aips++
    105105                                              MeasurementSet V2)
    106             stokes:      Convert to Stokes parameters (only available
    107                          currently with FITS and ASCII formats.
    108                          Default is False.
    109106            overwrite:   If the file should be overwritten if it exists.
    110107                         The default False is to return with warning
     
    135132            self._save(name)
    136133        else:
    137             from asap._asap import sdwriter as _sw
    138             w = _sw(format2)
    139             w.write(self, name, stokes)
     134            print "NYI"
     135#             from asap._asap import sdwriter as _sw
     136#             w = _sw(format2)
     137#             w.write(self, name, stokes)
    140138
    141139        print_log()
     
    150148            copiedscan = scan.copy()
    151149        """
    152         sd = scantable(sdtable._copy(self))
     150        sd = scantable(Scantable._copy(self))
    153151        return sd
    154152
     
    177175
    178176        try:
     177            bsel = self._getselection()
     178            sel = asap._asap.Selector()
    179179            if type(scanid) is str:
    180                 s = sdtable._getsource(self,scanid)
    181                 return scantable(s)
     180                sel._setname()
     181                self._setselection(sel)
     182                scopy = self._copy()
     183                self._setselection(bsel)
     184                return scantable(scopy)
    182185            elif type(scanid) is int:
    183                 s = sdtable._getscan(self,[scanid])
    184                 return scantable(s)
     186                sel._setscans([scanid])
     187                self._setselection(sel)
     188                scopy = self._copy()
     189                self._setselection(bsel)
     190                return scantable(scopy)
    185191            elif type(scanid) is list:
    186                 s = sdtable._getscan(self,scanid)
    187                 return scantable(s)
     192                sel._setscans(scanid)
     193                self._setselection(sel)
     194                scopy = self._copy()
     195                self._setselection(bsel)
     196                return scantable(scopy)
    188197            else:
    189198                msg = "Illegal scanid type, use 'int' or 'list' if ints."
     
    197206
    198207    def __str__(self):
    199         return sdtable._summary(self,True)
    200 
    201     def summary(self,filename=None, verbose=None):
     208        return Scantable._summary(self,True)
     209
     210    def summary(self, filename=None, verbose=None):
    202211        """
    203212        Print a summary of the contents of this scantable.
     
    208217                         The default (False) is taken from .asaprc
    209218        """
    210         info = sdtable._summary(self, verbose)
     219        info = Scantable._summary(self, verbose)
    211220        if verbose is None: verbose = rcParams['scantable.verbosesummary']
    212221        if filename is not None:
     
    244253                                            # if=0, pol=1
    245254        """
    246         varlist = vars()
    247         self.setbeam(beam)
    248         self.setpol(pol)
    249         self.setif(IF)
    250         self._add_history("set_cursor",varlist)
     255        print "DEPRECATED"
     256        varlist = vars()
     257        sel = asap._asap.Selector()
     258        sel._setbeams([beam])
     259        sel._setpols([pol])
     260        sel._setifs([IF])
     261        self._add_history("set_cursor", varlist)
    251262        return
    252263
     
    261272            none
    262273        """
    263         i = self.getbeam()
    264         j = self.getif()
    265         k = self.getpol()
     274        print "DEPRECATED"
     275        sel = self._getselection()
     276        i = sel.getbeams()[0]
     277        j = sel.getifs()[0]
     278        k = sel.getpols()[0]
    266279        from asap import asaplog
    267280        out = "--------------------------------------------------\n"
     
    273286        return i,j,k
    274287
    275     def stats(self, stat='stddev', mask=None, allaxes=None):
     288    def stats(self, stat='stddev', mask=None):
    276289        """
    277290        Determine the specified statistic of the current beam/if/pol
     
    283296            mask:    an optional mask specifying where the statistic
    284297                     should be determined.
    285             allaxes: if True apply to all spectra. Otherwise
    286                      apply only to the selected (beam/pol/if)spectra only.
    287                      The default is taken from .asaprc (True if none)
    288298        Example:
    289299            scan.set_unit('channel')
     
    291301            scan.stats(stat='mean', mask=m)
    292302        """
    293         if allaxes is None: allaxes = rcParams['scantable.allaxes']
    294         from asap._asap import stats as _stats
    295303        from numarray import array,zeros,Float
    296304        if mask == None:
    297             mask = ones(self.nchan())
     305            mask = []
    298306        axes = ['Beam','IF','Pol','Time']
    299 
    300         beamSel,IFSel,polSel = (self.getbeam(),self.getif(),self.getpol())
    301         if allaxes:
    302             n = self.nbeam()*self.nif()*self.npol()*self.nrow()
    303             shp = [self.nbeam(),self.nif(),self.npol(),self.nrow()]
    304             arr = array(zeros(n),shape=shp,type=Float)
    305 
    306             for i in range(self.nbeam()):
    307                 self.setbeam(i)
    308                 for j in range(self.nif()):
    309                     self.setif(j)
    310                     for k in range(self.npol()):
    311                         self.setpol(k)
    312                         arr[i,j,k,:] = _stats(self,mask,stat,-1)
    313             retval = {'axes': axes, 'data': arr, 'cursor':None}
    314             tm = [self._gettime(val) for val in range(self.nrow())]
    315             if rcParams['verbose']:
    316                 self._print_values(retval,stat,tm)
    317             self.setbeam(beamSel)
    318             self.setif(IFSel)
    319             self.setpol(polSel)
    320             return retval
    321 
    322         else:
    323             statval = _stats(self,mask,stat,-1)
    324             out = ''
    325             for l in range(self.nrow()):
    326                 tm = self._gettime(l)
    327                 out += 'Time[%s]:\n' % (tm)
    328                 if self.nbeam() > 1: out +=  ' Beam[%d] ' % (beamSel)
    329                 if self.nif() > 1: out +=  ' IF[%d] ' % (IFSel)
    330                 if self.npol() > 1: out +=  ' Pol[%d] ' % (polSel)
    331                 out += '= %3.3f\n' % (statval[l])
    332                 out +=  "--------------------------------------------------\n"
    333 
    334             if rcParams['verbose']:
    335                 print "--------------------------------------------------"
    336                 print " ",stat
    337                 print "--------------------------------------------------"
    338                 print out
    339             retval = {'axes': axes, 'data': array(statval), 'cursor':(i,j,k)}
    340             return retval
    341 
    342     def stddev(self,mask=None, allaxes=None):
     307        if not self._check_ifs():
     308             raise ValueError("Cannot apply mask as the IFs have different number of channels"
     309                              "Please use setselection() to select individual IFs")
     310
     311        statvals = self._math._stats(self, mask, stat)
     312        out = ''
     313        axes = []
     314        for i in range(self.nrow()):
     315            axis = []
     316            axis.append(self.getscan(i))
     317            axis.append(self.getbeam(i))
     318            axis.append(self.getif(i))
     319            axis.append(self.getpol(i))
     320            axis.append(self.getcycle(i))
     321            axes.append(axis)
     322            tm = self._gettime(i)
     323            src = self._getsourcename(i)
     324            out += 'Scan[%d] (%s) ' % (axis[0], src)
     325            out += 'Time[%s]:\n' % (tm)
     326            if self.nbeam(-1) > 1: out +=  ' Beam[%d] ' % (axis[1])
     327            if self.nif(-1) > 1: out +=  ' IF[%d] ' % (axis[2])
     328            if self.npol(-1) > 1: out +=  ' Pol[%d] ' % (axis[3])
     329            out += '= %3.3f\n' % (statvals[i])
     330            out +=  "--------------------------------------------------\n"
     331
     332        if rcParams['verbose']:
     333            print "--------------------------------------------------"
     334            print " ",stat
     335            print "--------------------------------------------------"
     336            print out
     337        retval = { 'axesnames': ['scanno','beamno','ifno','polno','cycleno'],
     338                   'axes' : axes,
     339                   'data': statvals}
     340        return retval
     341
     342    def stddev(self,mask=None):
    343343        """
    344344        Determine the standard deviation of the current beam/if/pol
     
    348348            mask:    an optional mask specifying where the standard
    349349                     deviation should be determined.
    350             allaxes: optional flag to show all or a cursor selected
    351                      spectrum of Beam/IF/Pol. Default is all or taken
    352                      from .asaprc
    353350
    354351        Example:
     
    357354            scan.stddev(mask=m)
    358355        """
    359         if allaxes is None: allaxes = rcParams['scantable.allaxes']
    360         return self.stats(stat='stddev',mask=mask, allaxes=allaxes);
    361 
    362     def get_tsys(self, allaxes=None):
     356        return self.stats(stat='stddev',mask=mask);
     357
     358    def get_tsys(self):
    363359        """
    364360        Return the System temperatures.
    365361        Parameters:
    366            allaxes:     if True apply to all spectra. Otherwise
    367                         apply only to the selected (beam/pol/if)spectra only.
    368                         The default is taken from .asaprc (True if none)
     362
    369363        Returns:
    370             a list of Tsys values.
    371         """
    372         if allaxes is None: allaxes = rcParams['scantable.allaxes']
    373         from numarray import array,zeros,Float
    374         axes = ['Beam','IF','Pol','Time']
    375 
    376         if allaxes:
    377             n = self.nbeam()*self.nif()*self.npol()*self.nrow()
    378             shp = [self.nbeam(),self.nif(),self.npol(),self.nrow()]
    379             arr = array(zeros(n),shape=shp,type=Float)
    380 
    381             for i in range(self.nbeam()):
    382                 self.setbeam(i)
    383                 for j in range(self.nif()):
    384                     self.setif(j)
    385                     for k in range(self.npol()):
    386                         self.setpol(k)
    387                         arr[i,j,k,:] = self._gettsys()
    388             retval = {'axes': axes, 'data': arr, 'cursor':None}
    389             tm = [self._gettime(val) for val in range(self.nrow())]
    390             if rcParams['verbose']:
    391                 self._print_values(retval,'Tsys',tm)
    392             return retval
    393 
    394         else:
    395             i,j,k = (self.getbeam(),self.getif(),self.getpol())
    396             statval = self._gettsys()
    397             out = ''
    398             for l in range(self.nrow()):
    399                 tm = self._gettime(l)
    400                 out += 'Time[%s]:\n' % (tm)
    401                 if self.nbeam() > 1: out +=  ' Beam[%d] ' % (i)
    402                 if self.nif() > 1: out +=  ' IF[%d] ' % (j)
    403                 if self.npol() > 1: out +=  ' Pol[%d] ' % (k)
    404                 out += '= %3.3f\n' % (statval[l])
    405                 out +=  "--------------------------------------------------\n"
    406 
    407             if rcParams['verbose']:
    408                 print "--------------------------------------------------"
    409                 print " TSys"
    410                 print "--------------------------------------------------"
    411                 print out
    412             retval = {'axes': axes, 'data': array(statval), 'cursor':(i,j,k)}
    413             return retval
     364            a list of Tsys values for the current selection
     365        """
     366
     367        return self._row_callback(self._gettsys, "Tsys")
     368
     369    def _row_callback(self, callback, label):
     370        axes = []
     371        axesnames = ['scanno','beamno','ifno','polno','cycleno']
     372        out = ""
     373        outvec =[]
     374        for i in range(self.nrow()):
     375            axis = []
     376            axis.append(self.getscan(i))
     377            axis.append(self.getbeam(i))
     378            axis.append(self.getif(i))
     379            axis.append(self.getpol(i))
     380            axis.append(self.getcycle(i))
     381            axes.append(axis)
     382            tm = self._gettime(i)
     383            src = self._getsourcename(i)
     384            out += 'Scan[%d] (%s) ' % (axis[0], src)
     385            out += 'Time[%s]:\n' % (tm)
     386            if self.nbeam(-1) > 1: out +=  ' Beam[%d] ' % (axis[1])
     387            if self.nif(-1) > 1: out +=  ' IF[%d] ' % (axis[2])
     388            if self.npol(-1) > 1: out +=  ' Pol[%d] ' % (axis[3])
     389            outvec.append(callback(i))
     390            out += '= %3.3f\n' % (outvec[i])
     391            out +=  "--------------------------------------------------\n"
     392        if rcParams['verbose']:
     393            print "--------------------------------------------------"
     394            print " %s" % (label)
     395            print "--------------------------------------------------"
     396            print out
     397        retval = {'axesnames': axesnames, 'axes': axes, 'data': outvec}
     398        return retval
     399
    414400
    415401    def get_time(self, row=-1):
     
    508494        inf[0] = unit
    509495        self._setcoordinfo(inf)
    510         if self._p: self.plot()
    511496        self._add_history("set_unit",varlist)
    512497
     
    532517        inf[2] = doppler
    533518        self._setcoordinfo(inf)
    534         if self._p: self.plot()
    535519        self._add_history("set_doppler",vars())
    536520        print_log()
     
    551535                   'GEO','GALACTO','LGROUP','CMB']
    552536
    553         if frame in valid:
     537        if 1:#frame in valid:
    554538            inf = list(self._getcoordinfo())
    555539            inf[1] = frame
     
    629613            from asap import asaplog
    630614            msg = "The current mask window unit is %s" % u
     615            if not _check_ifs():
     616                msg += "\nThis mask is only valid for IF=%d" % (self.getif(i))
    631617            asaplog.push(msg)
    632618        n = self.nchan()
     
    659645        return list(self._getrestfreqs())
    660646
    661     def lines(self):
    662         """
    663         Print the list of known spectral lines
    664         """
    665         l = sdtable._lines(self)
    666         if rcParams['verbose']:
    667             print l
    668         else:
    669             return l
    670 
    671     def set_restfreqs(self, freqs=None, unit='Hz', lines=None, source=None,
    672                       theif=None):
    673         """
    674         Select the restfrequency for the specified source and IF OR
    675         replace for all IFs.  If the 'freqs' argument holds a scalar,
    676         then that rest frequency will be applied to the selected
    677         data (and added to the list of available rest frequencies).
    678         In this way, you can set a rest frequency for each
    679         source and IF combination.   If the 'freqs' argument holds
    680         a vector, then it MUST be of length the number of IFs
    681         (and the available restfrequencies will be replaced by
    682         this vector).  In this case, *all* data ('source' and
    683         'theif' are ignored) have the restfrequency set per IF according
    684         to the corresponding value you give in the 'freqs' vector.
    685         E.g. 'freqs=[1e9,2e9]'  would mean IF 0 gets restfreq 1e9 and
    686         IF 1 gets restfreq 2e9.
    687 
    688         You can also specify the frequencies via known line names
    689         in the argument 'lines'.  Use 'freqs' or 'lines'.  'freqs'
    690         takes precedence. See the list of known names via function
    691         scantable.lines()
    692         Parameters:
    693             freqs:   list of rest frequencies
    694             unit:    unit for rest frequency (default 'Hz')
    695             lines:   list of known spectral lines names (alternative to freqs).
    696                      See possible list via scantable.lines()
    697             source:  Source name (blank means all)
    698             theif:   IF (-1 means all)
    699         Example:
    700             scan.set_restfreqs(freqs=1.4e9, source='NGC253', theif=2)
    701             scan.set_restfreqs(freqs=[1.4e9,1.67e9])
    702         """
    703         varlist = vars()
    704         if source is None:
    705             source = ""
    706         if theif is None:
    707             theif = -1
    708         t = type(freqs)
    709         if t is int or t is float:
    710            freqs = [freqs]
    711         if freqs is None:
    712            freqs = []
    713         t = type(lines)
    714         if t is str:
    715            lines = [lines]
    716         if lines is None:
    717            lines = []
    718         sdtable._setrestfreqs(self, freqs, unit, lines, source, theif)
    719         self._add_history("set_restfreqs", varlist)
    720 
    721 
    722 
    723     def flag_spectrum(self, thebeam, theif, thepol):
    724         """
    725         This flags a selected spectrum in the scan 'for good'.
    726         USE WITH CARE - not reversible.
    727         Use masks for non-permanent exclusion of channels.
    728         Parameters:
    729             thebeam,theif,thepol:    all have to be explicitly
    730                                      specified
    731         Example:
    732             scan.flag_spectrum(0,0,1)
    733             flags the spectrum for Beam=0, IF=0, Pol=1
    734         """
    735         if (thebeam < self.nbeam() and
    736             theif < self.nif() and
    737             thepol < self.npol()):
    738             sdtable.setbeam(self, thebeam)
    739             sdtable.setif(self, theif)
    740             sdtable.setpol(self, thepol)
    741             sdtable._flag(self)
    742             self._add_history("flag_spectrum", vars())
    743         else:
    744             print "Please specify a valid (Beam/IF/Pol)"
    745         return
    746 
    747     def _print_values(self, dat, label='', timestamps=[]):
    748         d = dat['data']
    749         a = dat['axes']
    750         shp = d.getshape()
    751         out = ''
    752         for i in range(shp[3]):
    753             out += '%s [%s]:\n' % (a[3],timestamps[i])
    754             t = d[:,:,:,i]
    755             for j in range(shp[0]):
    756                 if shp[0] > 1: out +=  ' %s[%d] ' % (a[0],j)
    757                 for k in range(shp[1]):
    758                     if shp[1] > 1: out +=  ' %s[%d] ' % (a[1],k)
    759                     for l in range(shp[2]):
    760                         if shp[2] > 1: out +=  ' %s[%d] ' % (a[2],l)
    761                         out += '= %3.3f\n' % (t[j,k,l])
    762             out += "-"*80
    763             out += "\n"
    764         print "-"*80
    765         print " ", label
    766         print "-"*80
    767         print out
     647
     648#     def set_restfreqs(self, freqs=None, unit='Hz', lines=None, source=None,
     649#                       theif=None):
     650#         """
     651#         Select the restfrequency for the specified source and IF OR
     652#         replace for all IFs.  If the 'freqs' argument holds a scalar,
     653#         then that rest frequency will be applied to the selected
     654#         data (and added to the list of available rest frequencies).
     655#         In this way, you can set a rest frequency for each
     656#         source and IF combination.   If the 'freqs' argument holds
     657#         a vector, then it MUST be of length the number of IFs
     658#         (and the available restfrequencies will be replaced by
     659#         this vector).  In this case, *all* data ('source' and
     660#         'theif' are ignored) have the restfrequency set per IF according
     661#         to the corresponding value you give in the 'freqs' vector.
     662#         E.g. 'freqs=[1e9,2e9]'  would mean IF 0 gets restfreq 1e9 and
     663#         IF 1 gets restfreq 2e9.
     664#
     665#         You can also specify the frequencies via known line names
     666#         in the argument 'lines'.  Use 'freqs' or 'lines'.  'freqs'
     667#         takes precedence. See the list of known names via function
     668#         scantable.lines()
     669#         Parameters:
     670#             freqs:   list of rest frequencies
     671#             unit:    unit for rest frequency (default 'Hz')
     672#             lines:   list of known spectral lines names (alternative to freqs).
     673#                      See possible list via scantable.lines()
     674#             source:  Source name (blank means all)
     675#             theif:   IF (-1 means all)
     676#         Example:
     677#             scan.set_restfreqs(freqs=1.4e9, source='NGC253', theif=2)
     678#             scan.set_restfreqs(freqs=[1.4e9,1.67e9])
     679#         """
     680#         varlist = vars()
     681#         if source is None:
     682#             source = ""
     683#         if theif is None:
     684#             theif = -1
     685#         t = type(freqs)
     686#         if t is int or t is float:
     687#            freqs = [freqs]
     688#         if freqs is None:
     689#            freqs = []
     690#         t = type(lines)
     691#         if t is str:
     692#            lines = [lines]
     693#         if lines is None:
     694#            lines = []
     695#         self._setrestfreqs(freqs, unit, lines, source, theif)
     696#         self._add_history("set_restfreqs", varlist)
     697#
     698
    768699
    769700    def history(self):
     
    818749        if weight is None: weight = 'tint'
    819750        if mask is None: mask = ()
    820         from asap._asap import average as _av
    821         s = scantable(_av((self,), mask, scanav, weight))
     751        if scanav:
     752          scanav = "SCAN"
     753        else:
     754          scanav = "NONE"
     755        s = scantable(self._math._average((self,), mask, weight, scanav, False))
    822756        s._add_history("average_time",varlist)
    823757        print_log()
    824758        return s
    825759
    826     def convert_flux(self, jyperk=None, eta=None, d=None, insitu=None,
    827                      allaxes=None):
     760    def convert_flux(self, jyperk=None, eta=None, d=None, insitu=None):
    828761        """
    829762        Return a scan where all spectra are converted to either
     
    844777                         The default is taken from .asaprc (True if none)
    845778        """
    846         if allaxes is None: allaxes = rcParams['scantable.allaxes']
    847779        if insitu is None: insitu = rcParams['insitu']
     780        self._math._setinsitu(insitu)
    848781        varlist = vars()
    849782        if jyperk is None: jyperk = -1.0
    850783        if d is None: d = -1.0
    851784        if eta is None: eta = -1.0
    852         if not insitu:
    853             from asap._asap import convertflux as _convert
    854             s = scantable(_convert(self, d, eta, jyperk, allaxes))
    855             s._add_history("convert_flux", varlist)
    856             print_log()
    857             return s
    858         else:
    859             from asap._asap import convertflux_insitu as _convert
    860             _convert(self, d, eta, jyperk, allaxes)
    861             self._add_history("convert_flux", varlist)
    862             print_log()
    863             return
    864 
    865     def gain_el(self, poly=None, filename="", method="linear",
    866                 insitu=None, allaxes=None):
     785        s = scantable(self._math._convertflux(self, d, eta, jyperk))
     786        s._add_history("convert_flux", varlist)
     787        print_log()
     788        if insitu: self._assign(s)
     789        else: return s
     790
     791    def gain_el(self, poly=None, filename="", method="linear", insitu=None):
    867792        """
    868793        Return a scan after applying a gain-elevation correction.
     
    902827                         Otherwise, the scaling is done in-situ
    903828                         The default is taken from .asaprc (False)
    904             allaxes:     If True apply to all spectra. Otherwise
    905                          apply only to the selected (beam/pol/if) spectra only
    906                          The default is taken from .asaprc (True if none)
    907         """
    908 
    909         if allaxes is None: allaxes = rcParams['scantable.allaxes']
     829        """
     830
    910831        if insitu is None: insitu = rcParams['insitu']
     832        self._math._setinsitu(insitu)
    911833        varlist = vars()
    912834        if poly is None:
     
    914836        from os.path import expandvars
    915837        filename = expandvars(filename)
    916         if not insitu:
    917             from asap._asap import gainel as _gainEl
    918             s = scantable(_gainEl(self, poly, filename, method, allaxes))
    919             s._add_history("gain_el", varlist)
    920             print_log()
    921             return s
    922         else:
    923             from asap._asap import gainel_insitu as _gainEl
    924             _gainEl(self, poly, filename, method, allaxes)
    925             self._add_history("gain_el", varlist)
    926             print_log()
    927             return
     838        s = scantable(self._math._gainel(self, poly, filename, method))
     839        s._add_history("gain_el", varlist)
     840        print_log()
     841        if insitu: self._assign(s)
     842        else: return s
    928843
    929844    def freq_align(self, reftime=None, method='cubic', perif=False,
     
    945860                         The default is taken from .asaprc (False)
    946861        """
     862        print "Not yet implemented"
     863        return
    947864        if insitu is None: insitu = rcParams['insitu']
     865        self._math._setinsitu(insitu)
    948866        varlist = vars()
    949867        if reftime is None: reftime = ''
    950868        perfreqid = not perif
    951         if not insitu:
    952             from asap._asap import freq_align as _align
    953             s = scantable(_align(self, reftime, method, perfreqid))
    954             s._add_history("freq_align", varlist)
    955             print_log()
    956             return s
    957         else:
    958             from asap._asap import freq_align_insitu as _align
    959             _align(self, reftime, method, perfreqid)
    960             self._add_history("freq_align", varlist)
    961             print_log()
    962             return
    963 
    964     def opacity(self, tau, insitu=None, allaxes=None):
     869        s = scantable(self._math._freqalign(self, reftime, method, perfreqid))
     870        s._add_history("freq_align", varlist)
     871        print_log()
     872        if insitu: self._assign(s)
     873        else: return s
     874
     875    def opacity(self, tau, insitu=None):
    965876        """
    966877        Apply an opacity correction. The data
     
    973884                         Otherwise, the scaling is done in-situ
    974885                         The default is taken from .asaprc (False)
    975             allaxes:     if True apply to all spectra. Otherwise
    976                          apply only to the selected (beam/pol/if)spectra only
    977                          The default is taken from .asaprc (True if none)
    978         """
    979         if allaxes is None: allaxes = rcParams['scantable.allaxes']
     886        """
    980887        if insitu is None: insitu = rcParams['insitu']
    981         varlist = vars()
    982         if not insitu:
    983             from asap._asap import opacity as _opacity
    984             s = scantable(_opacity(self, tau, allaxes))
    985             s._add_history("opacity", varlist)
    986             print_log()
    987             return s
    988         else:
    989             from asap._asap import opacity_insitu as _opacity
    990             _opacity(self, tau, allaxes)
    991             self._add_history("opacity", varlist)
    992             print_log()
    993             return
     888        self._math._setinsitu(insitu)
     889        varlist = vars()
     890        s = scantable(self._math._opacity(self, tau))
     891        s._add_history("opacity", varlist)
     892        print_log()
     893        if insitu: self._assign(s)
     894        else: return s
    994895
    995896    def bin(self, width=5, insitu=None):
     
    1002903        """
    1003904        if insitu is None: insitu = rcParams['insitu']
    1004         varlist = vars()
    1005         if not insitu:
    1006             from asap._asap import bin as _bin
    1007             s = scantable(_bin(self, width))
    1008             s._add_history("bin",varlist)
    1009             print_log()
    1010             return s
    1011         else:
    1012             from asap._asap import bin_insitu as _bin
    1013             _bin(self, width)
    1014             self._add_history("bin",varlist)
    1015             print_log()
    1016             return
     905        self._math._setinsitu(insitu)
     906        varlist = vars()
     907        s = scantable(self._math._bin(self, width))
     908        s._add_history("bin",varlist)
     909        print_log()
     910        if insitu: self._assign(s)
     911        else: return s
    1017912
    1018913
     
    1029924        """
    1030925        if insitu is None: insitu = rcParams['insitu']
    1031         varlist = vars()
    1032         if not insitu:
    1033             from asap._asap import resample as _resample
    1034             s = scantable(_resample(self, method, width))
    1035             s._add_history("resample",varlist)
    1036             print_log()
    1037             return s
    1038         else:
    1039             from asap._asap import resample_insitu as _resample
    1040             _resample(self, method, width)
    1041             self._add_history("resample",varlist)
    1042             print_log()
    1043             return
    1044 
    1045     def average_pol(self, mask=None, weight='none', insitu=None):
    1046         """
    1047         Average the Polarisations together.
    1048         The polarisation cursor of the output scan is set to 0
    1049         Parameters:
    1050             mask:        An optional mask defining the region, where the
    1051                          averaging will be applied. The output will have all
    1052                          specified points masked.
    1053             weight:      Weighting scheme. 'none' (default), 'var' (1/var(spec)
    1054                          weighted), or 'tsys' (1/Tsys**2 weighted)
    1055             insitu:      if False a new scantable is returned.
    1056                          Otherwise, the scaling is done in-situ
    1057                          The default is taken from .asaprc (False)
    1058         """
    1059         if insitu is None: insitu = rcParams['insitu']
    1060         varlist = vars()
    1061 
    1062         if mask is None:
    1063             mask = ()
    1064         if not insitu:
    1065             from asap._asap import averagepol as _avpol
    1066             s = scantable(_avpol(self, mask, weight))
    1067             s._add_history("average_pol",varlist)
    1068             print_log()
    1069             return s
    1070         else:
    1071             from asap._asap import averagepol_insitu as _avpol
    1072             _avpol(self, mask, weight)
    1073             self._add_history("average_pol",varlist)
    1074             print_log()
    1075             return
    1076 
    1077     def smooth(self, kernel="hanning", width=5.0, insitu=None, allaxes=None):
     926        self._math._setinsitu(insitu)
     927        varlist = vars()
     928        s = scantable(self._math._resample(self, method, width))
     929        s._add_history("resample",varlist)
     930        print_log()
     931        if insitu: self._assign(s)
     932        else: return s
     933
     934
     935#     def average_pol(self, mask=None, weight='none', insitu=None):
     936#         """
     937#         Average the Polarisations together.
     938#         The polarisation cursor of the output scan is set to 0
     939#         Parameters:
     940#             mask:        An optional mask defining the region, where the
     941#                          averaging will be applied. The output will have all
     942#                          specified points masked.
     943#             weight:      Weighting scheme. 'none' (default), 'var' (1/var(spec)
     944#                          weighted), or 'tsys' (1/Tsys**2 weighted)
     945#             insitu:      if False a new scantable is returned.
     946#                          Otherwise, the scaling is done in-situ
     947#                          The default is taken from .asaprc (False)
     948#         """
     949#         if insitu is None: insitu = rcParams['insitu']
     950#         self._math._setinsitu(insitu)
     951#         varlist = vars()
     952#
     953#         if mask is None:
     954#         mask = ()
     955#         s = self._math._averagepol(self, mask, weight)
     956#         s._add_history("average_pol",varlist)
     957#         print_log()
     958#         if insitu: self._assign(s)
     959#         else: return scantable(s)
     960
     961    def smooth(self, kernel="hanning", width=5.0, insitu=None):
    1078962        """
    1079963        Smooth the spectrum by the specified kernel (conserving flux).
     
    1090974                        Otherwise, the scaling is done in-situ
    1091975                        The default is taken from .asaprc (False)
    1092             allaxes:    If True (default) apply to all spectra. Otherwise
    1093                         apply only to the selected (beam/pol/if)spectra only
    1094                         The default is taken from .asaprc (True if none)
    1095976        Example:
    1096977             none
    1097978        """
    1098         if allaxes is None: allaxes = rcParams['scantable.allaxes']
    1099979        if insitu is None: insitu = rcParams['insitu']
    1100         varlist = vars()
    1101         if not insitu:
    1102             from asap._asap import smooth as _smooth
    1103             s = scantable(_smooth(self,kernel,width,allaxes))
    1104             s._add_history("smooth", varlist)
    1105             print_log()
    1106             return s
    1107         else:
    1108             from asap._asap import smooth_insitu as _smooth
    1109             _smooth(self,kernel,width,allaxes)
    1110             self._add_history("smooth", varlist)
    1111             print_log()
    1112             return
    1113 
    1114     def poly_baseline(self, mask=None, order=0, insitu=None, allaxes=None):
     980        self._math._setinsitu(insitu)
     981        varlist = vars()
     982        s = scantable(self._math._smooth(self,kernel,width))
     983        s._add_history("smooth", varlist)
     984        print_log()
     985        if insitu: self._assign(s)
     986        else: return s
     987
     988
     989    def poly_baseline(self, mask=None, order=0, insitu=None):
    1115990        """
    1116991        Return a scan which has been baselined (all rows) by a polynomial.
     
    11301005            bscan = scan.poly_baseline(order=3)
    11311006        """
    1132         if allaxes is None: allaxes = rcParams['scantable.allaxes']
    11331007        if insitu is None: insitu = rcParams['insitu']
    11341008        varlist = vars()
    11351009        if mask is None:
    11361010            from numarray import ones
    1137             mask = list(ones(self.nchan()))
     1011            mask = list(ones(self.nchan(-1)))
    11381012        from asap.asapfitter import fitter
    11391013        f = fitter()
    11401014        f.set_scan(self, mask)
    11411015        f.set_function(poly=order)
    1142         sf = f.auto_fit(insitu,allaxes)
    1143         if insitu:
    1144             self._add_history("poly_baseline", varlist)
    1145             print_log()
    1146             return
    1147         else:
    1148             sf._add_history("poly_baseline", varlist)
    1149             print_log()
    1150             return sf
    1151 
    1152     def auto_poly_baseline(self, mask=None, edge=(0,0), order=0,
    1153                            threshold=3,insitu=None):
    1154         """
    1155         Return a scan which has been baselined (all rows) by a polynomial.
    1156         Spectral lines are detected first using linefinder and masked out
    1157         to avoid them affecting the baseline solution.
    1158 
    1159         Parameters:
    1160             mask:       an optional mask retreived from scantable
    1161             edge:       an optional number of channel to drop at
    1162                         the edge of spectrum. If only one value is
    1163                         specified, the same number will be dropped from
    1164                         both sides of the spectrum. Default is to keep
    1165                         all channels
    1166             order:      the order of the polynomial (default is 0)
    1167             threshold:  the threshold used by line finder. It is better to
    1168                         keep it large as only strong lines affect the
    1169                         baseline solution.
    1170             insitu:     if False a new scantable is returned.
    1171                         Otherwise, the scaling is done in-situ
    1172                         The default is taken from .asaprc (False)
    1173 
    1174         Example:
    1175             scan2=scan.auto_poly_baseline(order=7)
    1176         """
    1177         if insitu is None: insitu = rcParams['insitu']
    1178         varlist = vars()
    1179         from asap.asapfitter import fitter
    1180         from asap.asaplinefind import linefinder
    1181         from asap import _is_sequence_or_number as _is_valid
    1182 
    1183         if not _is_valid(edge, int):
    1184 
    1185             raise RuntimeError, "Parameter 'edge' has to be an integer or a \
    1186             pair of integers specified as a tuple"
    1187 
    1188         # setup fitter
    1189         f = fitter()
    1190         f.set_function(poly=order)
    1191 
    1192         # setup line finder
    1193         fl=linefinder()
    1194         fl.set_options(threshold=threshold)
    1195 
    1196         if not insitu:
    1197             workscan=self.copy()
    1198         else:
    1199             workscan=self
    1200 
    1201         sel=workscan.get_cursor()
    1202         rows=range(workscan.nrow())
    1203         from asap import asaplog
    1204         for i in range(workscan.nbeam()):
    1205             workscan.setbeam(i)
    1206             for j in range(workscan.nif()):
    1207                 workscan.setif(j)
    1208                 for k in range(workscan.npol()):
    1209                     workscan.setpol(k)
    1210                     asaplog.push("Processing:")
    1211                     msg = 'Beam[%d], IF[%d], Pol[%d]' % (i,j,k)
    1212                     asaplog.push(msg)
    1213                     for iRow in rows:
    1214                        fl.set_scan(workscan,mask,edge)
    1215                        fl.find_lines(iRow)
    1216                        f.set_scan(workscan, fl.get_mask())
    1217                        f.x=workscan._getabcissa(iRow)
    1218                        f.y=workscan._getspectrum(iRow)
    1219                        f.data=None
    1220                        f.fit()
    1221                        x=f.get_parameters()
    1222                        workscan._setspectrum(f.fitter.getresidual(),iRow)
    1223         workscan.set_cursor(sel[0],sel[1],sel[2])
    1224         if not insitu:
    1225             return workscan
    1226 
    1227     def rotate_linpolphase(self, angle, allaxes=None):
    1228         """
    1229         Rotate the phase of the complex polarization O=Q+iU correlation.
    1230         This is always done in situ in the raw data.  So if you call this
    1231         function more than once then each call rotates the phase further.
    1232         Parameters:
    1233             angle:   The angle (degrees) to rotate (add) by.
    1234             allaxes: If True apply to all spectra. Otherwise
    1235                      apply only to the selected (beam/pol/if)spectra only.
    1236                      The default is taken from .asaprc (True if none)
    1237         Examples:
    1238             scan.rotate_linpolphase(2.3)
    1239     """
    1240         if allaxes is None: allaxes = rcParams['scantable.allaxes']
    1241         varlist = vars()
    1242         from asap._asap import _rotate_linpolphase as _rotate
    1243         _rotate(self, angle, allaxes)
    1244         self._add_history("rotate_linpolphase", varlist)
    1245         print_log()
    1246         return
    1247 
    1248 
    1249     def rotate_xyphase(self, angle, allaxes=None):
    1250         """
    1251         Rotate the phase of the XY correlation.  This is always done in situ
    1252         in the data.  So if you call this function more than once
    1253         then each call rotates the phase further.
    1254         Parameters:
    1255             angle:   The angle (degrees) to rotate (add) by.
    1256             allaxes: If True apply to all spectra. Otherwise
    1257                      apply only to the selected (beam/pol/if)spectra only.
    1258                      The default is taken from .asaprc (True if none)
    1259         Examples:
    1260             scan.rotate_xyphase(2.3)
    1261         """
    1262         if allaxes is None: allaxes = rcParams['scantable.allaxes']
    1263         varlist = vars()
    1264         from asap._asap import _rotate_xyphase
    1265         _rotate_xyphase(self, angle, allaxes)
    1266         self._add_history("rotate_xyphase", varlist)
    1267         print_log()
    1268         return
    1269 
    1270 
    1271     def add(self, offset, insitu=None, allaxes=None):
     1016        s = f.auto_fit(insitu)
     1017        s._add_history("poly_baseline", varlist)
     1018        print_log()
     1019        if insitu: self._assign(s)
     1020        else: return s
     1021
     1022#     def auto_poly_baseline(self, mask=None, edge=(0,0), order=0,
     1023#                            threshold=3, insitu=None):
     1024#         """
     1025#         Return a scan which has been baselined (all rows) by a polynomial.
     1026#         Spectral lines are detected first using linefinder and masked out
     1027#         to avoid them affecting the baseline solution.
     1028#
     1029#         Parameters:
     1030#             mask:       an optional mask retreived from scantable
     1031#             edge:       an optional number of channel to drop at
     1032#                         the edge of spectrum. If only one value is
     1033#                         specified, the same number will be dropped from
     1034#                         both sides of the spectrum. Default is to keep
     1035#                         all channels
     1036#             order:      the order of the polynomial (default is 0)
     1037#             threshold:  the threshold used by line finder. It is better to
     1038#                         keep it large as only strong lines affect the
     1039#                         baseline solution.
     1040#             insitu:     if False a new scantable is returned.
     1041#                         Otherwise, the scaling is done in-situ
     1042#                         The default is taken from .asaprc (False)
     1043#
     1044#         Example:
     1045#             scan2=scan.auto_poly_baseline(order=7)
     1046#         """
     1047#         if insitu is None: insitu = rcParams['insitu']
     1048#         varlist = vars()
     1049#         from asap.asapfitter import fitter
     1050#         from asap.asaplinefind import linefinder
     1051#         from asap import _is_sequence_or_number as _is_valid
     1052#
     1053#         if not _is_valid(edge, int):
     1054#             raise RuntimeError, "Parameter 'edge' has to be an integer or a \
     1055#             pair of integers specified as a tuple"
     1056#
     1057#         # setup fitter
     1058#         f = fitter()
     1059#         f.set_function(poly=order)
     1060#
     1061#         # setup line finder
     1062#         fl=linefinder()
     1063#         fl.set_options(threshold=threshold)
     1064#
     1065#         if not insitu:
     1066#             workscan=self.copy()
     1067#         else:
     1068#             workscan=self
     1069#
     1070#         rows=range(workscan.nrow())
     1071#         from asap import asaplog
     1072#         for i in rows:
     1073#             asaplog.push("Processing:")
     1074#             asaplog.push(msg)
     1075#             fl.set_scan(workscan,mask,edge)
     1076#             fl.find_lines(i)
     1077#             f.set_scan(workscan, fl.get_mask())
     1078#             f.x = workscan._getabcissa(i)
     1079#             f.y = workscan._getspectrum(i)
     1080#             f.data = None
     1081#             f.fit()
     1082#             x = f.get_parameters()
     1083#             workscan._setspectrum(f.fitter.getresidual(), i)
     1084#         workscan._add_history("poly_baseline", varlist)
     1085#         if insitu:
     1086#             self._assign(workscan)
     1087#         else:
     1088#             return workscan
     1089#
     1090#     def rotate_linpolphase(self, angle):
     1091#         """
     1092#         Rotate the phase of the complex polarization O=Q+iU correlation.
     1093#         This is always done in situ in the raw data.  So if you call this
     1094#         function more than once then each call rotates the phase further.
     1095#         Parameters:
     1096#             angle:   The angle (degrees) to rotate (add) by.
     1097#         Examples:
     1098#             scan.rotate_linpolphase(2.3)
     1099#     """
     1100#         varlist = vars()
     1101#         from asap._asap import _rotate_linpolphase as _rotate
     1102#         _rotate(self, angle, allaxes)
     1103#         self._add_history("rotate_linpolphase", varlist)
     1104#         print_log()
     1105#         return
     1106#
     1107#
     1108#     def rotate_xyphase(self, angle):
     1109#         """
     1110#         Rotate the phase of the XY correlation.  This is always done in situ
     1111#         in the data.  So if you call this function more than once
     1112#         then each call rotates the phase further.
     1113#         Parameters:
     1114#             angle:   The angle (degrees) to rotate (add) by.
     1115#         Examples:
     1116#             scan.rotate_xyphase(2.3)
     1117#         """
     1118#         varlist = vars()
     1119#         from asap._asap import _rotate_xyphase
     1120#         _rotate_xyphase(self, angle, allaxes)
     1121#         self._add_history("rotate_xyphase", varlist)
     1122#         print_log()
     1123#         return
     1124
     1125
     1126    def add(self, offset, insitu=None):
    12721127        """
    12731128        Return a scan where all spectra have the offset added
     
    12771132                         Otherwise, the scaling is done in-situ
    12781133                         The default is taken from .asaprc (False)
    1279             allaxes:     if True apply to all spectra. Otherwise
    1280                          apply only to the selected (beam/pol/if)spectra only
    1281                          The default is taken from .asaprc (True if none)
    1282         """
    1283         if allaxes is None: allaxes = rcParams['scantable.allaxes']
     1134        """
    12841135        if insitu is None: insitu = rcParams['insitu']
    1285         varlist = vars()
    1286         if not insitu:
    1287             from asap._asap import add as _add
    1288             s = scantable(_add(self, offset, allaxes))
    1289             s._add_history("add",varlist)
    1290             print_log()
     1136        self._math._setinsitu(insitu)
     1137        varlist = vars()
     1138        s = scantable(self._math._unaryop(self, offset, "ADD", False))
     1139        s._add_history("add",varlist)
     1140        print_log()
     1141        if insitu:
     1142            self._assign(s)
     1143        else:
    12911144            return s
    1292         else:
    1293             from asap._asap import add_insitu as _add
    1294             _add(self, offset, allaxes)
    1295             self._add_history("add",varlist)
    1296             print_log()
    1297             return
    1298 
    1299     def scale(self, factor, insitu=None, allaxes=None, tsys=True):
     1145
     1146    def scale(self, factor, tsys=True, insitu=None,):
    13001147        """
    13011148        Return a scan where all spectra are scaled by the give 'factor'
     
    13051152                         Otherwise, the scaling is done in-situ
    13061153                         The default is taken from .asaprc (False)
    1307             allaxes:     if True apply to all spectra. Otherwise
    1308                          apply only to the selected (beam/pol/if)spectra only.
    1309                          The default is taken from .asaprc (True if none)
    13101154            tsys:        if True (default) then apply the operation to Tsys
    13111155                         as well as the data
    13121156        """
    1313         if allaxes is None: allaxes = rcParams['scantable.allaxes']
    13141157        if insitu is None: insitu = rcParams['insitu']
    1315         varlist = vars()
    1316         if not insitu:
    1317             from asap._asap import scale as _scale
    1318             s = scantable(_scale(self, factor, allaxes, tsys))
    1319             s._add_history("scale",varlist)
    1320             print_log()
     1158        self._math._setinsitu(insitu)
     1159        varlist = vars()
     1160        s = scantable(self._math._unaryop(self, factor, "MUL", tsys))
     1161        s._add_history("scale",varlist)
     1162        print_log()
     1163        if insitu:
     1164            self._assign(s)
     1165        else:
    13211166            return s
    1322         else:
    1323             from asap._asap import scale_insitu as _scale
    1324             _scale(self, factor, allaxes, tsys)
    1325             self._add_history("scale",varlist)
    1326             print_log()
    1327             return
    1328 
    1329     def auto_quotient(self, mode='suffix', preserve=True):
     1167
     1168    def auto_quotient(self, mode='time', preserve=True):
    13301169        """
    13311170        This function allows to build quotients automatically.
     
    13431182                            remove:   Output = Tref * (on/off) - Ton
    13441183        """
    1345         modes = ["suffix","time"]
     1184        modes = ["time"]
    13461185        if not mode in modes:
    1347             print "please provide valid mode. Valid modes are %s" % (modes)
    1348             return None
    1349         from asap._asap import quotient as _quot
    1350         if mode == "suffix":
    1351             srcs = self.get_scan("*[^_ewR]")
    1352             refs = self.get_scan("*[_ewR]")
    1353             if isinstance(srcs,scantable) and isinstance(refs,scantable):
    1354                 from asap import asaplog
    1355                 ns,nr = srcs.nrow(),refs.nrow()
    1356                 msg = "Found %i Off and %i On scans" % (ns,nr)
    1357                 asaplog.push(msg)
    1358                 if nr > ns:
    1359                     asaplog("Found more Off integrations than On scans - dropping excess Offs.")
    1360                     refs = refs.get_scan(range(ns))
    1361                 print_log()
    1362                 return scantable(_quot(srcs,refs, preserve))
    1363             else:
    1364                 msg = "Couldn't find any on/off pairs"
    1365                 if rcParams['verbose']:
    1366                     print msg
    1367                     return
    1368                 else:
    1369                     raise RuntimeError()
    1370         else:
    1371             if rcParams['verbose']: print "not yet implemented"
    1372             return None
    1373 
    1374     def quotient(self, other, isreference=True, preserve=True):
    1375         """
    1376         Return the quotient of a 'source' (on) scan and a 'reference' (off)
    1377         scan.
    1378         The reference can have just one row, even if the signal has many.
    1379         Otherwise they must have the same number of rows.
    1380         The cursor of the output scan is set to 0
    1381         Parameters:
    1382             other:          the 'other' scan
    1383             isreference:    if the 'other' scan is the reference (default)
    1384                             or source
    1385             preserve:       you can preserve (default) the continuum or
    1386                             remove it.  The equations used are
    1387                             preserve: Output = Toff * (on/off) - Toff
    1388                             remove:   Output = Tref * (on/off) - Ton
    1389         Example:
    1390             # src is a scantable for an 'on' scan, ref for an 'off' scantable
    1391             q1 = src.quotient(ref)
    1392             q2 = ref.quotient(src, isreference=False)
    1393             # gives the same result
    1394         """
    1395         from asap._asap import quotient as _quot
    1396         try:
    1397             s = None
    1398             if isreference:
    1399                 s = scantable(_quot(self, other, preserve))
    1400             else:
    1401                 s = scantable(_quot(other, self, preserve))
    1402             print_log()
    1403             return s
    1404         except RuntimeError,e:
    1405             if rcParams['verbose']:
    1406                 print e
    1407                 return
    1408             else: raise
     1186            msg = "please provide valid mode. Valid modes are %s" % (modes)
     1187            raise ValueError(msg)
     1188        varlist = vars()
     1189        s = scantable(self._math._quotient(self, mode, preserve))
     1190        s._add_history("auto_quotient",varlist)
     1191        print_log()
     1192        return s
     1193
     1194
     1195
    14091196
    14101197    def freq_switch(self, insitu=None):
     
    14191206        """
    14201207        if insitu is None: insitu = rcParams['insitu']
    1421         varlist = vars()
    1422         try:
    1423             if insitu:
    1424                 from asap._asap import _frequency_switch_insitu
    1425                 _frequency_switch_insitu(self)
    1426                 self._add_history("freq_switch", varlist)
    1427                 print_log()
    1428                 return
    1429             else:
    1430                 from asap._asap import _frequency_switch
    1431                 sf = scantable(_frequency_switch(self))
    1432                 sf._add_history("freq_switch", varlist)
    1433                 print_log()
    1434                 return sf
    1435         except RuntimeError,e:
    1436             if rcParams['verbose']: print e
    1437             else: raise
     1208        self._math._setinsitu(insitu)
     1209        varlist = vars()
     1210        s = scantable(self._math._freqswitch(self))
     1211        s._add_history("freq_switch",varlist)
     1212        print_log()
     1213        if insitu: self._assign(s)
     1214        else: return s
    14381215
    14391216    def recalc_azel(self):
     
    14451222        """
    14461223        varlist = vars()
    1447         self._recalc_azel()
     1224        self._recalcazel()
    14481225        self._add_history("recalc_azel", varlist)
    14491226        print_log()
     
    14541231        s = None
    14551232        if isinstance(other, scantable):
    1456             from asap._asap import b_operate as _bop
    1457             s = scantable(_bop(self, other, 'add', True))
     1233            print "scantable + scantable NYI"
     1234            return
    14581235        elif isinstance(other, float):
    1459             from asap._asap import add as _add
    1460             s = scantable(_add(self, other, True))
     1236            s = scantable(self._math._unaryop(self, other, "ADD", False))
    14611237        else:
    14621238            raise TypeError("Other input is not a scantable or float value")
     
    14721248        s = None
    14731249        if isinstance(other, scantable):
    1474             from asap._asap import b_operate as _bop
    1475             s = scantable(_bop(self, other, 'sub', True))
     1250            print "scantable - scantable NYI"
     1251            return
    14761252        elif isinstance(other, float):
    1477             from asap._asap import add as _add
    1478             s = scantable(_add(self, -other, True))
     1253            s = scantable(self._math._unaryop(self, other, "SUB", False))
    14791254        else:
    14801255            raise TypeError("Other input is not a scantable or float value")
     
    14901265        s = None
    14911266        if isinstance(other, scantable):
    1492             from asap._asap import b_operate as _bop
    1493             s = scantable(_bop(self, other, 'mul', True))
     1267            print "scantable * scantable NYI"
     1268            return
     1269        elif isinstance(other, float):
     1270            s = scantable(self._math._unaryop(self, other, "MUL", False))
     1271        else:
     1272            raise TypeError("Other input is not a scantable or float value")
     1273        s._add_history("operator *", varlist)
     1274        print_log()
     1275        return s
     1276
     1277
     1278    def __div__(self, other):
     1279        """
     1280        implicit on all axes and on Tsys
     1281        """
     1282        varlist = vars()
     1283        s = None
     1284        if isinstance(other, scantable):
     1285            print "scantable / scantable NYI"
     1286            return
    14941287        elif isinstance(other, float):
    14951288            if other == 0.0:
    14961289                raise ZeroDivisionError("Dividing by zero is not recommended")
    1497             from asap._asap import scale as _sca
    1498             s = scantable(_sca(self, other, True))
    1499         else:
    1500             raise TypeError("Other input is not a scantable or float value")
    1501         s._add_history("operator *", varlist)
    1502         print_log()
    1503         return s
    1504 
    1505 
    1506     def __div__(self, other):
    1507         """
    1508         implicit on all axes and on Tsys
    1509         """
    1510         varlist = vars()
    1511         s = None
    1512         if isinstance(other, scantable):
    1513             from asap._asap import b_operate as _bop
    1514             s = scantable(_bop(self, other, 'div', True))
    1515         elif isinstance(other, float):
    1516             if other == 0.0:
    1517                 raise ZeroDivisionError("Dividing by zero is not recommended")
    1518             from asap._asap import scale as _sca
    1519             s = scantable(_sca(self, 1.0/other, True))
     1290            s = scantable(self._math._unaryop(self, other, "DIV", False))
    15201291        else:
    15211292            raise TypeError("Other input is not a scantable or float value")
     
    16031374        return lbl
    16041375
     1376    def _check_ifs(self):
     1377        nchans = [self.nchan(i) for i in range(self.nif(-1))]
     1378        return (sum(nchans)/len(nchans) == nchans[0])
Note: See TracChangeset for help on using the changeset viewer.