Changeset 1824


Ignore:
Timestamp:
08/02/10 19:40:09 (14 years ago)
Author:
Malte Marquarding
Message:

Refactoring of init.py. Moved functionality into separate modules. Some minor fixes to make unit test work under 'standard asap'.

Location:
trunk
Files:
3 added
5 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/__init__.py

    r1819 r1824  
    33
    44"""
    5 import os,sys,shutil, platform
    6 try:
    7     from functools import wraps as wraps_dec
    8 except ImportError:
    9     from asap.compatibility import wraps as wraps_dec
     5import os
     6import sys
    107
    11 # Set up CASAPATH and first time use of asap i.e. ~/.asap/*
    12 plf = None
    13 if sys.platform == "linux2":
    14     if platform.architecture()[0] == '64bit':
    15         plf = 'linux_64b'
    16     else:
    17         plf = 'linux_gnu'
    18 elif sys.platform == 'darwin':
    19     plf = 'darwin'
    20 else:
    21     # Shouldn't happen - default to linux
    22     plf = 'linux'
    23 asapdata = __path__[-1]
    24 # Allow user defined data location
    25 if os.environ.has_key("ASAPDATA"):
    26     if os.path.exists(os.environ["ASAPDATA"]):
    27         asapdata = os.environ["ASAPDATA"]
    28 # use CASAPATH if defined and "data" dir present
    29 if not os.environ.has_key("CASAPATH") or \
    30         not os.path.exists(os.environ["CASAPATH"].split()[0]+"/data"):
    31     os.environ["CASAPATH"] = "%s %s somwhere" % ( asapdata, plf)
    32 # set up user space
    33 userdir = os.environ["HOME"]+"/.asap"
    34 if not os.path.exists(userdir):
    35     print 'First time ASAP use. Setting up ~/.asap'
    36     os.mkdir(userdir)
    37     #shutil.copyfile(asapdata+"/data/ipythonrc-asap", userdir+"/ipythonrc-asap")
    38     # commented out by TT on 2009.06.23 for casapy use
    39     ##shutil.copyfile(asapdata+"/data/ipy_user_conf.py",
    40     ##                userdir+"/ipy_user_conf.py")
    41     f = file(userdir+"/asapuserfuncs.py", "w")
    42     f.close()
    43     f = file(userdir+"/ipythonrc", "w")
    44     f.close()
    45 # commented out by TT on 2009.06.23 for casapy use
    46 ##else:
    47     # upgrade to support later ipython versions
    48     ##if not os.path.exists(userdir+"/ipy_user_conf.py"):
    49     ##    shutil.copyfile(asapdata+"/data/ipy_user_conf.py",
    50     ##                    userdir+"/ipy_user_conf.py")
    51 
    52 # remove from namespace
    53 del asapdata, userdir, shutil, platform
    54 
    55 def _validate_bool(b):
    56     'Convert b to a boolean or raise'
    57     bl = b.lower()
    58     if bl in ('f', 'no', 'false', '0', 0): return False
    59     elif bl in ('t', 'yes', 'true', '1', 1): return True
    60     else:
    61         raise ValueError('Could not convert "%s" to boolean' % b)
    62 
    63 def _validate_int(s):
    64     'convert s to int or raise'
    65     try: return int(s)
    66     except ValueError:
    67         raise ValueError('Could not convert "%s" to int' % s)
    68 
    69 def _asap_fname():
    70     """
    71     Return the path to the rc file
    72 
    73     Search order:
    74 
    75      * current working dir
    76      * environ var ASAPRC
    77      * HOME/.asaprc
    78 
    79     """
    80     fname = os.path.join( os.getcwd(), '.asaprc')
    81     if os.path.exists(fname): return fname
    82 
    83     if os.environ.has_key('ASAPRC'):
    84         path =  os.environ['ASAPRC']
    85         if os.path.exists(path):
    86             fname = os.path.join(path, '.asaprc')
    87             if os.path.exists(fname):
    88                 return fname
    89 
    90     if os.environ.has_key('HOME'):
    91         home =  os.environ['HOME']
    92         fname = os.path.join(home, '.asaprc')
    93         if os.path.exists(fname):
    94             return fname
    95     return None
     8# first import!
     9from asap.env import *
     10# second import!
     11from asap.logging import *
     12from asap.parameters import *
     13from asap.utils import *
     14# explicitly import 'hidden' functions
     15from asap.utils import _n_bools, _is_sequence_or_number, _to_list
    9616
    9717
    98 defaultParams = {
    99     # general
    100     'verbose'             : [True, _validate_bool],
    101     'useplotter'          : [True, _validate_bool],
    102     'insitu'              : [True, _validate_bool],
     18if is_ipython():
     19    from ipysupport import *
    10320
    104     # plotting
    105     'plotter.gui'         : [True, _validate_bool],
    106     'plotter.stacking'    : ['p', str],
    107     'plotter.panelling'   : ['s', str],
    108     'plotter.colours'     : ['', str],
    109     'plotter.linestyles'  : ['', str],
    110     'plotter.decimate'    : [False, _validate_bool],
    111     'plotter.ganged'      : [True, _validate_bool],
    112     'plotter.histogram'  : [False, _validate_bool],
    113     'plotter.papertype'  : ['A4', str],
    114     ## for older Matplotlib version
    115     #'plotter.axesformatting' : ['mpl', str],
    116     'plotter.axesformatting' : ['asap', str],
     21# use rc parameter to enable/disable logging
     22asaplog.enable(rcParams['verbose'])
    11723
    118     # scantable
    119     'scantable.save'      : ['ASAP', str],
    120     'scantable.autoaverage'      : [True, _validate_bool],
    121     'scantable.freqframe' : ['LSRK', str],  #default frequency frame
    122     'scantable.verbosesummary'   : [False, _validate_bool],
    123     'scantable.storage'   : ['memory', str],
    124     'scantable.history'   : [True, _validate_bool],
    125     'scantable.reference'      : ['.*(e|w|_R)$', str],
    126     'scantable.parallactify'   : [False, _validate_bool]
    127     # fitter
    128     }
     24setup_env()
    12925
    130 def list_rcparameters():
     26# anything which uses matplotlib has to be imported after this!!!
     27if rcParams['useplotter']:
     28    try:
     29        gui = os.environ.has_key('DISPLAY') and rcParams['plotter.gui']
     30        if gui:
     31            import matplotlib
     32            if 'matplotlib.backends' not in matplotlib.sys.modules:
     33                matplotlib.use("TkAgg")
     34        from asapplotter import asapplotter
     35        from matplotlib import pylab
     36        xyplotter = pylab
     37        plotter = asapplotter(gui)
     38    except ImportError:
     39        asaplog.post( "Matplotlib not installed. No plotting available")
     40        print_log('WARN')
    13141
    132     print """
    133 # general
    134 # print verbose output
    135 verbose                    : True
    136 
    137 # preload a default plotter
    138 useplotter                 : True
    139 
    140 # apply operations on the input scantable or return new one
    141 insitu                     : True
    142 
    143 # plotting
    144 
    145 # do we want a GUI or plot to a file
    146 plotter.gui                : True
    147 
    148 # default mode for colour stacking
    149 plotter.stacking           : Pol
    150 
    151 # default mode for panelling
    152 plotter.panelling          : scan
    153 
    154 # push panels together, to share axis labels
    155 plotter.ganged             : True
    156 
    157 # decimate the number of points plotted by a factor of
    158 # nchan/1024
    159 plotter.decimate           : False
    160 
    161 # default colours/linestyles
    162 plotter.colours            :
    163 plotter.linestyles         :
    164 
    165 # enable/disable histogram plotting
    166 plotter.histogram          : False
    167 
    168 # ps paper type
    169 plotter.papertype          : A4
    170 
    171 # The formatting style of the xaxis
    172 plotter.axesformatting    : 'mpl' (default) or 'asap' (for old versions of matplotlib)
    173 
    174 # scantable
    175 
    176 # default storage of scantable ('memory'/'disk')
    177 scantable.storage          : memory
    178 
    179 # write history of each call to scantable
    180 scantable.history          : True
    181 
    182 # default ouput format when saving
    183 scantable.save             : ASAP
    184 
    185 # auto averaging on read
    186 scantable.autoaverage      : True
    187 
    188 # default frequency frame to set when function
    189 # scantable.set_freqframe is called
    190 scantable.freqframe        : LSRK
    191 
    192 # Control the level of information printed by summary
    193 scantable.verbosesummary   : False
    194 
    195 # Control the identification of reference (off) scans
    196 # This is has to be a regular expression
    197 scantable.reference        : .*(e|w|_R)$
    198 
    199 # Indicate whether the data was parallactified (total phase offest == 0.0)
    200 scantable.parallactify     : False
    201 
    202 # Fitter
    203 """
    204 
    205 def rc_params():
    206     'Return the default params updated from the values in the rc file'
    207 
    208     fname = _asap_fname()
    209 
    210     if fname is None or not os.path.exists(fname):
    211         message = 'could not find rc file; returning defaults'
    212         ret =  dict([ (key, tup[0]) for key, tup in defaultParams.items()])
    213         #print message
    214         return ret
    215 
    216     cnt = 0
    217     for line in file(fname):
    218         cnt +=1
    219         line = line.strip()
    220         if not len(line): continue
    221         if line.startswith('#'): continue
    222         tup = line.split(':',1)
    223         if len(tup) !=2:
    224             #print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
    225             asaplog.push('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
    226             print_log('WARN')
    227             continue
    228 
    229         key, val = tup
    230         key = key.strip()
    231         if not defaultParams.has_key(key):
    232             #print ('Bad key "%s" on line %d in %s' % (key, cnt, fname))
    233             asaplog.push('Bad key "%s" on line %d in %s' % (key, cnt, fname))
    234             print_log('WARN')
    235             continue
    236 
    237         default, converter =  defaultParams[key]
    238 
    239         ind = val.find('#')
    240         if ind>=0: val = val[:ind]   # ignore trailing comments
    241         val = val.strip()
    242         try: cval = converter(val)   # try to convert to proper type or raise
    243         except ValueError, msg:
    244             #print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg))
    245             asaplog.push('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, str(msg)))
    246             print_log('WARN')
    247             continue
    248         else:
    249             # Alles Klar, update dict
    250             defaultParams[key][0] = cval
    251 
    252     # strip the conveter funcs and return
    253     ret =  dict([ (key, tup[0]) for key, tup in defaultParams.items()])
    254     print ('loaded rc file %s'%fname)
    255 
    256     return ret
    257 
    258 
    259 # this is the instance used by the asap classes
    260 rcParams = rc_params()
    261 
    262 rcParamsDefault = dict(rcParams.items()) # a copy
    263 
    264 def rc(group, **kwargs):
    265     """
    266     Set the current rc params.  Group is the grouping for the rc, eg
    267     for scantable.save the group is 'scantable', for plotter.stacking, the
    268     group is 'plotter', and so on.  kwargs is a list of attribute
    269     name/value pairs, eg
    270 
    271       rc('scantable', save='SDFITS')
    272 
    273     sets the current rc params and is equivalent to
    274 
    275       rcParams['scantable.save'] = 'SDFITS'
    276 
    277     Use rcdefaults to restore the default rc params after changes.
    278     """
    279 
    280     aliases = {}
    281 
    282     for k,v in kwargs.items():
    283         name = aliases.get(k) or k
    284         if len(group):
    285             key = '%s.%s' % (group, name)
    286         else:
    287             key = name
    288         if not rcParams.has_key(key):
    289             raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % (key, group, name))
    290 
    291         rcParams[key] = v
    292 
    293 
    294 def rcdefaults():
    295     """
    296     Restore the default rc params - the ones that were created at
    297     asap load time
    298     """
    299     rcParams.update(rcParamsDefault)
    300 
    301 def _n_bools(n, val):
    302     return [ val for i in xrange(n) ]
    303 
    304 def _is_sequence_or_number(param, ptype=int):
    305     if isinstance(param,tuple) or isinstance(param,list):
    306         if len(param) == 0: return True # empty list
    307         out = True
    308         for p in param:
    309             out &= isinstance(p,ptype)
    310         return out
    311     elif isinstance(param, ptype):
    312         return True
    313     return False
    314 
    315 def _to_list(param, ptype=int):
    316     if isinstance(param, ptype):
    317         if ptype is str: return param.split()
    318         else: return [param]
    319     if _is_sequence_or_number(param, ptype):
    320         return param
    321     return None
    322 
    323 def unique(x):
    324     """
    325     Return the unique values in a list
    326     Parameters:
    327         x:      the list to reduce
    328     Examples:
    329         x = [1,2,3,3,4]
    330         print unique(x)
    331         [1,2,3,4]
    332     """
    333     return dict([ (val, 1) for val in x]).keys()
    334 
    335 def list_files(path=".",suffix="rpf"):
    336     """
    337     Return a list files readable by asap, such as rpf, sdfits, mbf, asap
    338     Parameters:
    339         path:     The directory to list (default '.')
    340         suffix:   The file extension (default rpf)
    341     Example:
    342         files = list_files("data/","sdfits")
    343         print files
    344         ['data/2001-09-01_0332_P363.sdfits',
    345         'data/2003-04-04_131152_t0002.sdfits',
    346         'data/Sgr_86p262_best_SPC.sdfits']
    347     """
    348     if not os.path.isdir(path):
    349         return None
    350     valid = "rpf rpf.1 rpf.2 sdf sdfits mbf asap".split()
    351     if not suffix in valid:
    352         return None
    353     files = [os.path.expanduser(os.path.expandvars(path+"/"+f)) for f in os.listdir(path)]
    354     return filter(lambda x: x.endswith(suffix),files)
    355 
    356 # workaround for ipython, which redirects this if banner=0 in ipythonrc
    357 sys.stdout = sys.__stdout__
    358 sys.stderr = sys.__stderr__
    359 
    360 # Logging
    361 from asap._asap import Log as _asaplog
    362 global asaplog
    363 asaplog=_asaplog()
    364 if rcParams['verbose']:
    365     asaplog.enable()
    366 else:
    367     asaplog.disable()
    368 
    369 
    370 def print_log_dec(f):
    371     @wraps_dec(f)
    372     def wrap_it(*args, **kw):
    373         val = f(*args, **kw)
    374         print_log()
    375         return val
    376     return wrap_it
    377 
    378 def print_log(level='INFO'):
    379     from taskinit import casalog
    380     log = asaplog.pop()
    381     #if len(log) and rcParams['verbose']: print log
    382     if len(log) and rcParams['verbose']: casalog.post( log, priority=level )
    383     return
    384 
    385 def mask_and(a, b):
    386     assert(len(a)==len(b))
    387     return [ a[i] & b[i] for i in xrange(len(a)) ]
    388 
    389 def mask_or(a, b):
    390     assert(len(a)==len(b))
    391     return [ a[i] | b[i] for i in xrange(len(a)) ]
    392 
    393 def mask_not(a):
    394     return [ not i for i in a ]
    395 
    396 from asapfitter import fitter
    39742from asapreader import reader
    39843from selector import selector
    399 
    40044from asapmath import *
    40145from scantable import scantable
     46from linecatalog import linecatalog
    40247from asaplinefind import linefinder
    40348from simplelinefinder import simplelinefinder
    404 from linecatalog import linecatalog
    40549from interactivemask import interactivemask
     50from asapfitter import fitter
    40651from opacity import skydip
    40752from opacity import model as opacity_model
    40853
    409 if rcParams['useplotter']:
    410     try:
    411         from asapplotter import asapplotter
    412         gui = os.environ.has_key('DISPLAY') and rcParams['plotter.gui']
    413         if gui:
    414             import matplotlib
    415             if not matplotlib.sys.modules['matplotlib.backends']: matplotlib.use("TkAgg")
    416         from matplotlib import pylab
    417         xyplotter = pylab
    418         plotter = asapplotter(gui)
    419         del gui
    420     except ImportError:
    421         #print "Matplotlib not installed. No plotting available"
    422         asaplog.post( "Matplotlib not installed. No plotting available")
    423         print_log('WARN')
    424 
    42554__date__ = '$Date$'.split()[1]
    426 __version__  = '3.0.0 alma'
    427 # nrao casapy specific, get revision number
    428 #__revision__ = ' unknown '
    429 casapath=os.environ["CASAPATH"].split()
    430 #svninfo.txt path
    431 if os.path.isdir(casapath[0]+'/'+casapath[1]+'/python/2.5/asap'):
    432     # for casa developer environment (linux or darwin)
    433     revinfo=casapath[0]+'/'+casapath[1]+'/python/2.5/asap/svninfo.txt'
    434 else:
    435     # for end-user environments
    436     if casapath[1]=='darwin':
    437         revinfo=casapath[0]+'/Resources/python/asap/svninfo.txt'
    438     else:
    439         revinfo=casapath[0]+'/lib/python2.5/asap/svninfo.txt'
    440 if os.path.isfile(revinfo):
    441     f = file(revinfo)
    442     f.readline()
    443     revsionno=f.readline()
    444     f.close()
    445     del f
    446     __revision__ = revsionno.rstrip()
    447 else:
    448     __revision__ = ' unknown '
    449 
    450 def is_ipython():
    451     return 'IPython' in sys.modules.keys()
    452 if is_ipython():
    453     def version(): print  "ASAP %s(%s)"% (__version__, __date__)
    454 
    455     def list_scans(t = scantable):
    456         import inspect
    457         print "The user created scantables are: ",
    458         globs=inspect.currentframe().f_back.f_locals.copy()
    459         out = [ k for k,v in globs.iteritems() \
    460                      if isinstance(v, scantable) and not k.startswith("_") ]
    461         print out
    462         return out
    463 
    464     def commands():
    465         x = """
    466     [The scan container]
    467         scantable           - a container for integrations/scans
    468                               (can open asap/rpfits/sdfits and ms files)
    469             copy            - returns a copy of a scan
    470             get_scan        - gets a specific scan out of a scantable
    471                               (by name or number)
    472             drop_scan       - drops a specific scan out of a scantable
    473                               (by number)
    474             set_selection   - set a new subselection of the data
    475             get_selection   - get the current selection object
    476             summary         - print info about the scantable contents
    477             stats           - get specified statistic of the spectra in
    478                               the scantable
    479             stddev          - get the standard deviation of the spectra
    480                               in the scantable
    481             get_tsys        - get the TSys
    482             get_time        - get the timestamps of the integrations
    483             get_inttime     - get the integration time
    484             get_sourcename  - get the source names of the scans
    485             get_azimuth     - get the azimuth of the scans
    486             get_elevation   - get the elevation of the scans
    487             get_parangle    - get the parallactic angle of the scans
    488             get_coordinate  - get the spectral coordinate for the given row,
    489                               which can be used for coordinate conversions
    490             get_weather     - get the weather condition parameters
    491             get_unit        - get the current unit
    492             set_unit        - set the abcissa unit to be used from this
    493                               point on
    494             get_abcissa     - get the abcissa values and name for a given
    495                               row (time)
    496             get_column_names - get the names of the columns in the scantable
    497                                for use with selector.set_query
    498             set_freqframe   - set the frame info for the Spectral Axis
    499                               (e.g. 'LSRK')
    500             set_doppler     - set the doppler to be used from this point on
    501             set_dirframe    - set the frame for the direction on the sky
    502             set_instrument  - set the instrument name
    503             set_feedtype    - set the feed type
    504             get_fluxunit    - get the brightness flux unit
    505             set_fluxunit    - set the brightness flux unit
    506             set_sourcetype  - set the type of the source - source or reference
    507             create_mask     - return an mask in the current unit
    508                               for the given region. The specified regions
    509                               are NOT masked
    510             get_restfreqs   - get the current list of rest frequencies
    511             set_restfreqs   - set a list of rest frequencies
    512             shift_refpix    - shift the reference pixel of the IFs
    513             set_spectrum    - overwrite the spectrum for a given row
    514             get_spectrum    - retrieve the spectrum for a given
    515             get_mask        - retrieve the mask for a given
    516             flag            - flag selected channels in the data
    517             lag_flag        - flag specified frequency in the data
    518             save            - save the scantable to disk as either 'ASAP',
    519                               'SDFITS' or 'ASCII'
    520             nbeam,nif,nchan,npol - the number of beams/IFs/Pols/Chans
    521             nscan           - the number of scans in the scantable
    522             nrow            - the number of spectra in the scantable
    523             history         - print the history of the scantable
    524             get_fit         - get a fit which has been stored witnh the data
    525             average_time    - return the (weighted) time average of a scan
    526                               or a list of scans
    527             average_pol     - average the polarisations together.
    528             average_beam    - average the beams together.
    529             convert_pol     - convert to a different polarisation type
    530             auto_quotient   - return the on/off quotient with
    531                               automatic detection of the on/off scans (closest
    532                               in time off is selected)
    533             mx_quotient     - Form a quotient using MX data (off beams)
    534             scale, *, /     - return a scan scaled by a given factor
    535             add, +          - return a scan with given value added
    536             sub, -          - return a scan with given value subtracted
    537             bin             - return a scan with binned channels
    538             resample        - return a scan with resampled channels
    539             smooth          - return the spectrally smoothed scan
    540             poly_baseline   - fit a polynomial baseline to all Beams/IFs/Pols
    541             auto_poly_baseline - automatically fit a polynomial baseline
    542             recalc_azel     - recalculate azimuth and elevation based on
    543                               the pointing
    544             gain_el         - apply gain-elevation correction
    545             opacity         - apply opacity correction
    546             convert_flux    - convert to and from Jy and Kelvin brightness
    547                               units
    548             freq_align      - align spectra in frequency frame
    549             invert_phase    - Invert the phase of the cross-correlation
    550             swap_linears    - Swap XX and YY (or RR LL)
    551             rotate_xyphase  - rotate XY phase of cross correlation
    552             rotate_linpolphase - rotate the phase of the complex
    553                                  polarization O=Q+iU correlation
    554             freq_switch     - perform frequency switching on the data
    555             stats           - Determine the specified statistic, e.g. 'min'
    556                               'max', 'rms' etc.
    557             stddev          - Determine the standard deviation of the current
    558                               beam/if/pol
    559             get_row_selector - get the selection object for a specified row
    560                                number
    561      [Selection]
    562          selector              - a selection object to set a subset of a scantable
    563             set_scans          - set (a list of) scans by index
    564             set_cycles         - set (a list of) cycles by index
    565             set_beams          - set (a list of) beamss by index
    566             set_ifs            - set (a list of) ifs by index
    567             set_polarisations  - set (a list of) polarisations by name
    568                                  or by index
    569             set_names          - set a selection by name (wildcards allowed)
    570             set_tsys           - set a selection by tsys thresholds
    571             set_query          - set a selection by SQL-like query, e.g. BEAMNO==1
    572             ( also  get_ functions for all these )
    573             reset              - unset all selections
    574             +                  - merge two selections
    575 
    576      [Math] Mainly functions which operate on more than one scantable
    577 
    578             average_time    - return the (weighted) time average
    579                               of a list of scans
    580             quotient        - return the on/off quotient
    581             simple_math     - simple mathematical operations on two scantables,
    582                               'add', 'sub', 'mul', 'div'
    583             quotient        - build quotient of the given on and off scans
    584                               (matched pairs and 1 off - n on are valid)
    585             merge           - merge a list of scantables
    586 
    587      [Line Catalog]
    588         linecatalog              - a linecatalog wrapper, taking an ASCII or
    589                                    internal format table
    590             summary              - print a summary of the current selection
    591             set_name             - select a subset by name pattern, e.g. '*OH*'
    592             set_strength_limits  - select a subset by line strength limits
    593             set_frequency_limits - select a subset by frequency limits
    594             reset                - unset all selections
    595             save                 - save the current subset to a table (internal
    596                                    format)
    597             get_row              - get the name and frequency from a specific
    598                                    row in the table
    599      [Fitting]
    600         fitter
    601             auto_fit        - return a scan where the function is
    602                               applied to all Beams/IFs/Pols.
    603             commit          - return a new scan where the fits have been
    604                               commited.
    605             fit             - execute the actual fitting process
    606             store_fit       - store the fit parameters in the data (scantable)
    607             get_chi2        - get the Chi^2
    608             set_scan        - set the scantable to be fit
    609             set_function    - set the fitting function
    610             set_parameters  - set the parameters for the function(s), and
    611                               set if they should be held fixed during fitting
    612             set_gauss_parameters - same as above but specialised for individual
    613                                    gaussian components
    614             get_parameters  - get the fitted parameters
    615             plot            - plot the resulting fit and/or components and
    616                               residual
    617     [Plotter]
    618         asapplotter         - a plotter for asap, default plotter is
    619                               called 'plotter'
    620             plot            - plot a scantable
    621             plot_lines      - plot a linecatalog overlay
    622             plotazel        - plot azimuth and elevation versus time
    623             plotpointing    - plot telescope pointings
    624             save            - save the plot to a file ('png' ,'ps' or 'eps')
    625             set_mode        - set the state of the plotter, i.e.
    626                               what is to be plotted 'colour stacked'
    627                               and what 'panelled'
    628             set_selection   - only plot a selected part of the data
    629             set_range       - set a 'zoom' window [xmin,xmax,ymin,ymax]
    630             set_legend      - specify user labels for the legend indeces
    631             set_title       - specify user labels for the panel indeces
    632             set_abcissa     - specify a user label for the abcissa
    633             set_ordinate    - specify a user label for the ordinate
    634             set_layout      - specify the multi-panel layout (rows,cols)
    635             set_colors      - specify a set of colours to use
    636             set_linestyles  - specify a set of linestyles to use if only
    637                               using one color
    638             set_font        - set general font properties, e.g. 'family'
    639             set_histogram   - plot in historam style
    640             set_mask        - set a plotting mask for a specific polarization
    641             text            - draw text annotations either in data or relative
    642                               coordinates
    643             arrow           - draw arrow annotations either in data or relative
    644                               coordinates
    645             axhline,axvline - draw horizontal/vertical lines
    646             axhspan,axvspan - draw horizontal/vertical regions
    647             annotate        - draw an arrow with label
    648             create_mask     - create a scnatble mask interactively
    649 
    650         xyplotter           - matplotlib/pylab plotting functions
    651 
    652     [General]
    653         commands            - this command
    654         print               - print details about a variable
    655         list_scans          - list all scantables created by the user
    656         list_files          - list all files readable by asap (default rpf)
    657         del                 - delete the given variable from memory
    658         range               - create a list of values, e.g.
    659                               range(3) = [0,1,2], range(2,5) = [2,3,4]
    660         help                - print help for one of the listed functions
    661         execfile            - execute an asap script, e.g. execfile('myscript')
    662         list_rcparameters   - print out a list of possible values to be
    663                               put into $HOME/.asaprc
    664         rc                  - set rc parameters from within asap
    665         mask_and,mask_or,
    666         mask_not            - boolean operations on masks created with
    667                               scantable.create_mask
    668         skydip              - gain opacity values from a sky dip observation
    669         opacity_model       - compute opacities fro given frequencies based on
    670                               atmospheric model
    671 
    672     Note:
    673         How to use this with help:
    674                                          # function 'summary'
    675         [xxx] is just a category
    676         Every 'sub-level' in this list should be replaces by a '.' Period when
    677         using help
    678         Example:
    679             ASAP> help scantable # to get info on ths scantable
    680             ASAP> help scantable.summary # to get help on the scantable's
    681             ASAP> help average_time
    682 
    683             """
    684         if rcParams['verbose']:
    685             try:
    686                 from IPython.genutils import page as pager
    687             except ImportError:
    688                 from pydoc import pager
    689             pager(x)
    690         else:
    691             print x
    692         return
     55__version__  = 'trunk'
     56__revision__ = get_revision()
    69357
    69458def welcome():
     
    69963
    70064[IMPORTANT: ASAP is 0-based]
    701 Type commands() to get a list of all available ASAP commands.""" % (__version__, __date__)
     65Type commands() to get a list of all available ASAP commands.""" % (__version__,
     66                                                                    __date__)
  • trunk/python/asapplotter.py

    r1819 r1824  
    1 from asap import rcParams, print_log, print_log_dec
    2 from asap import selector, scantable
    3 from asap import asaplog
     1from asap.parameters import rcParams
     2from asap.selector import selector
     3from asap.scantable import scantable
     4from asap.logging import asaplog, print_log, print_log_dec
    45import matplotlib.axes
    56from matplotlib.font_manager import FontProperties
     
    276277    def set_data(self, scan, refresh=True):
    277278        """
    278         Set a scantable to plot. 
     279        Set a scantable to plot.
    279280        Parameters:
    280281            scan:      a scantable
    281282            refresh:   True (default) or False. If True, the plot is
    282                        replotted based on the new parameter setting(s). 
     283                       replotted based on the new parameter setting(s).
    283284                       Otherwise,the parameter(s) are set without replotting.
    284285        Note:
    285286           The user specified masks and data selections will be reset
    286287           if a new scantable is set. This method should be called before
    287            setting data selections (set_selection) and/or masks (set_mask). 
     288           setting data selections (set_selection) and/or masks (set_mask).
    288289        """
    289290        from asap import scantable
     
    316317            self._datamask = None
    317318        if refresh: self.plot()
    318        
     319
    319320
    320321    def set_mode(self, stacking=None, panelling=None, refresh=True):
     
    327328                          across multiple panels (default 'scan'
    328329            refresh:      True (default) or False. If True, the plot is
    329                           replotted based on the new parameter setting(s). 
     330                          replotted based on the new parameter setting(s).
    330331                          Otherwise,the parameter(s) are set without replotting.
    331332        Note:
     
    369370             cols:   The number of columns of plots
    370371             refresh:  True (default) or False. If True, the plot is
    371                        replotted based on the new parameter setting(s). 
     372                       replotted based on the new parameter setting(s).
    372373                       Otherwise,the parameter(s) are set without replotting.
    373374        Note:
     
    397398            [x,y]start,[x,y]end:  The start and end points of the 'zoom' window
    398399            refresh:  True (default) or False. If True, the plot is
    399                       replotted based on the new parameter setting(s). 
     400                      replotted based on the new parameter setting(s).
    400401                      Otherwise,the parameter(s) are set without replotting.
    401402        Note:
     
    440441                        10: center
    441442            refresh:    True (default) or False. If True, the plot is
    442                         replotted based on the new parameter setting(s). 
     443                        replotted based on the new parameter setting(s).
    443444                        Otherwise,the parameter(s) are set without replotting.
    444445
     
    465466        Parameters:
    466467            refresh:    True (default) or False. If True, the plot is
    467                         replotted based on the new parameter setting(s). 
     468                        replotted based on the new parameter setting(s).
    468469                        Otherwise,the parameter(s) are set without replotting.
    469470        Example:
     
    486487                         data determine the labels
    487488            refresh:     True (default) or False. If True, the plot is
    488                          replotted based on the new parameter setting(s). 
     489                         replotted based on the new parameter setting(s).
    489490                         Otherwise,the parameter(s) are set without replotting.
    490491        Example:
     
    508509                         data determine the labels
    509510            refresh:     True (default) or False. If True, the plot is
    510                          replotted based on the new parameter setting(s). 
     511                         replotted based on the new parameter setting(s).
    511512                         Otherwise,the parameter(s) are set without replotting.
    512513        Example:
     
    529530            colmap:     a list of colour names
    530531            refresh:    True (default) or False. If True, the plot is
    531                         replotted based on the new parameter setting(s). 
     532                        replotted based on the new parameter setting(s).
    532533                        Otherwise,the parameter(s) are set without replotting.
    533534        Example:
     
    553554                         plotter.histogram
    554555            refresh:     True (default) or False. If True, the plot is
    555                          replotted based on the new parameter setting(s). 
     556                         replotted based on the new parameter setting(s).
    556557                         Otherwise,the parameter(s) are set without replotting.
    557558        """
     
    573574                             possible
    574575            refresh:         True (default) or False. If True, the plot is
    575                              replotted based on the new parameter setting(s). 
     576                             replotted based on the new parameter setting(s).
    576577                             Otherwise,the parameter(s) are set without replotting.
    577578        Example:
     
    600601                       seperately
    601602            refresh:   True (default) or False. If True, the plot is
    602                        replotted based on the new parameter setting(s). 
     603                       replotted based on the new parameter setting(s).
    603604                       Otherwise,the parameter(s) are set without replotting.
    604605        """
     
    616617        Parameters:
    617618            layout:   a list of subplots layout in figure coordinate (0-1),
    618                       i.e., fraction of the figure width or height. 
     619                      i.e., fraction of the figure width or height.
    619620                      The order of elements should be:
    620621                      [left, bottom, right, top, horizontal space btw panels,
    621                       vertical space btw panels]. 
     622                      vertical space btw panels].
    622623            refresh:  True (default) or False. If True, the plot is
    623                       replotted based on the new parameter setting(s). 
     624                      replotted based on the new parameter setting(s).
    624625                      Otherwise,the parameter(s) are set without replotting.
    625626        Note
    626627        * When layout is not specified, the values are reset to the defaults
    627628          of matplotlib.
    628         * If any element is set to be None, the current value is adopted. 
     629        * If any element is set to be None, the current value is adopted.
    629630        """
    630631        if layout == []: self._panellayout=self._reset_panellayout()
    631         else: 
     632        else:
    632633            self._panellayout=[None]*6
    633634            self._panellayout[0:len(layout)]=layout
     
    744745             selection:      the spectra to apply the mask to.
    745746             refresh:        True (default) or False. If True, the plot is
    746                              replotted based on the new parameter setting(s). 
     747                             replotted based on the new parameter setting(s).
    747748                             Otherwise,the parameter(s) are set without replotting.
    748749        Example:
     
    961962        #reset the selector to the scantable's original
    962963        scan.set_selection(savesel)
    963        
     964
    964965        #temporary switch-off for older matplotlib
    965966        #if self._fp is not None:
     
    973974            selection:  a selector object (default unset the selection)
    974975            refresh:    True (default) or False. If True, the plot is
    975                         replotted based on the new parameter setting(s). 
     976                        replotted based on the new parameter setting(s).
    976977                        Otherwise,the parameter(s) are set without replotting.
    977978        """
     
    10491050        PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top,
    10501051                                 wspace=wsp,hspace=hsp)
    1051        
     1052
    10521053        tdel = max(t) - min(t)
    10531054        ax = PL.subplot(2,1,1)
     
    12711272        print data (scantable) header on the plot and/or logger.
    12721273        Parameters:
    1273             plot:      whether or not print header info on the plot. 
     1274            plot:      whether or not print header info on the plot.
    12741275            fontsize:  header font size (valid only plot=True)
    12751276            autoscale: whether or not autoscale the plot (valid only plot=True)
     
    12801281        if not plot and not logger: return
    12811282        if not self._data: raise RuntimeError("No scantable has been set yet.")
    1282         # Now header will be printed on plot and/or logger. 
    1283         # Get header information and format it. 
     1283        # Now header will be printed on plot and/or logger.
     1284        # Get header information and format it.
    12841285        ssum=self._data.__str__()
    12851286        # Print Observation header to the upper-left corner of plot
     
    12931294            headstr.append(ssel)
    12941295            nstcol=len(headstr)
    1295            
     1296
    12961297            self._plotter.hold()
    12971298            for i in range(nstcol):
     
    13141315            print_log()
    13151316        del ssum
    1316 
    1317 
  • trunk/python/logging.py

    r1819 r1824  
    2525        logs.
    2626        """
    27         if len(self._log) > 0:
    28             self.logger.post(self._log, priority=level)
     27        logs = self._log.strip()
     28        if len(logs) > 0:
     29           self.logger.post(logs, priority=level)
    2930        if isinstance(self.logger, LogSink):
    30             logs = self.logger.pop()
    31             if logs > 0:
     31            logs = self.logger.pop().strip()
     32            if len(logs) > 0:
    3233                print logs
    3334        self._log = ""
  • trunk/python/scantable.py

    r1819 r1824  
    55    from asap.compatibility import wraps as wraps_dec
    66
     7from asap.env import is_casapy
    78from asap._asap import Scantable
    8 from asap import rcParams
    9 from asap import print_log, print_log_dec
    10 from asap import asaplog
    11 from asap import selector
    12 from asap import linecatalog
     9from asap.parameters import rcParams
     10from asap.logging import asaplog, print_log, print_log_dec
     11from asap.selector import selector
     12from asap.linecatalog import linecatalog
    1313from asap.coordinate import coordinate
    14 from asap import _n_bools, mask_not, mask_and, mask_or
     14from asap.utils import _n_bools, mask_not, mask_and, mask_or
    1515
    1616
     
    3737
    3838    @print_log_dec
    39     def __init__(self, filename, average=None, unit=None, getpt=None, antenna=None, parallactify=None):
     39    def __init__(self, filename, average=None, unit=None, getpt=None,
     40                 antenna=None, parallactify=None):
    4041        """
    4142        Create a scantable from a saved one or make a reference
     
    23992400        if unit is not None:
    24002401            self.set_fluxunit(unit)
    2401         #self.set_freqframe(rcParams['scantable.freqframe'])
     2402        if not is_casapy():
     2403            self.set_freqframe(rcParams['scantable.freqframe'])
    24022404
    24032405    def __getitem__(self, key):
  • trunk/test/test_scantable.py

    r1725 r1824  
    11import unittest
    22import datetime
    3 from asap import scantable, selector, rcParams, mask_not
    4 rcParams["verbose"] = False
     3from asap import scantable, selector, rcParams, mask_not, asaplog
     4asaplog.disable()
    55
    66class ScantableTest(unittest.TestCase):
    77    def setUp(self):
    8 
    9         self.st = scantable("data/MOPS.rpf", average=True)
     8        s = scantable("data/MOPS.rpf", average=True)
     9        sel = selector()
     10        # make sure this order is always correct - in can be random
     11        sel.set_order(["SCANNO", "POLNO"])
     12        s.set_selection(sel)
     13        self.st = s.copy()
    1014        restfreqs = [86.243]     # 13CO-1/0, SiO the two IF
    1115        self.st.set_restfreqs(restfreqs,"GHz")
     
    7882    def test_get_column_names(self):
    7983        cnames = ['SCANNO', 'CYCLENO', 'BEAMNO', 'IFNO',
    80                   'POLNO', 'FREQ_ID', 'MOLECULE_ID', 'REFBEAMNO',
     84                  'POLNO', 'FREQ_ID', 'MOLECULE_ID', 'REFBEAMNO', 'FLAGROW',
    8185                  'TIME', 'INTERVAL', 'SRCNAME', 'SRCTYPE',
    8286                  'FIELDNAME', 'SPECTRA', 'FLAGTRA', 'TSYS',
     
    101105    def test_get_sourcename(self):
    102106        self.assertEqual(self.st.get_sourcename(0), 'Orion_SiO_R')
    103         self.assertEqual(self.st.get_sourcename()[:2], ['Orion_SiO_R', 'Orion_SiO'])
     107        self.assertEqual(self.st.get_sourcename(),
     108                         ['Orion_SiO_R', 'Orion_SiO_R',
     109                          'Orion_SiO', 'Orion_SiO'])
    104110
    105111    def test_get_azimuth(self):
     
    144150        msk = q0.create_mask([-10,20])
    145151        q0.flag(mask=mask_not(msk))
     152        q1.flag(mask=msk)
    146153        self.assertAlmostEqual(q0.stats(stat='max')[0], 95.62171936)
    147         q1.flag(mask=msk)
    148154        self.assertAlmostEqual(q1.stats(stat='max')[0], 2.66563416)
    149155
Note: See TracChangeset for help on using the changeset viewer.