source: trunk/python/__init__.py @ 379

Last change on this file since 379 was 379, checked in by mar637, 19 years ago

cleanup

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 12.5 KB
RevLine 
[100]1"""
2This is the ATNF Single Dish Analysis package.
3
4"""
[226]5import os,sys
6
7def validate_bool(b):
8    'Convert b to a boolean or raise'
9    bl = b.lower()
10    if bl in ('f', 'no', 'false', '0', 0): return False
11    elif bl in ('t', 'yes', 'true', '1', 1): return True
12    else:
13        raise ValueError('Could not convert "%s" to boolean' % b)
14
15def validate_int(s):
16    'convert s to int or raise'
17    try: return int(s)
18    except ValueError:
19        raise ValueError('Could not convert "%s" to int' % s)
20
21def asap_fname():
22    """
23    Return the path to the rc file
24
25    Search order:
26
27     * current working dir
28     * environ var ASAPRC
[274]29     * HOME/.asaprc
[226]30     
31    """
32
33    fname = os.path.join( os.getcwd(), '.asaprc')
34    if os.path.exists(fname): return fname
35
36    if os.environ.has_key('ASAPRC'):
37        path =  os.environ['ASAPRC']
38        if os.path.exists(path):
39            fname = os.path.join(path, '.asaprc')
40            if os.path.exists(fname):
41                return fname
42
43    if os.environ.has_key('HOME'):
44        home =  os.environ['HOME']
45        fname = os.path.join(home, '.asaprc')
46        if os.path.exists(fname):
47            return fname
48    return None
49       
50
51defaultParams = {
52    # general
53    'verbose'             : [True, validate_bool],
54    'useplotter'          : [True, validate_bool],
[255]55    'insitu'              : [False, validate_bool],
[226]56
57    # plotting
58    'plotter.stacking'    : ['p', str],
59    'plotter.panelling'   : ['s', str],
60
61    # scantable
62    'scantable.save'      : ['ASAP', str],
63    'scantable.autoaverage'      : [True, validate_bool],
64    'scantable.freqframe' : ['LSRK', str],  #default frequency frame
65    'scantable.allaxes'   : [True, validate_bool],  # apply action to all axes
66    'scantable.plotter'   : [True, validate_bool], # use internal plotter
67
68    # fitter
69    }
70
[255]71def list_rcparameters():
72   
73    print """
74    # general
75    # print verbose output
76    'verbose'                    : True
77
78    # preload a default plotter
79    'useplotter'                 : True
80
81    # apply operations on the input scantable or return new one
82    'insitu'                     : False
83   
84    # plotting
85    # default mode for colour stacking
86    'plotter.stacking'           : 'Pol'
87
88    # default mode for panelling
89    'plotter.panelling'          : 'scan'
90
91    # scantable
92    # default ouput format when saving
93    'scantable.save'             : 'ASAP'
94    # auto averaging on read
95    'scantable.autoaverage'      : True
96
97    # default frequency frame to set when function
98    # scantable.set_freqfrmae is called
99    'scantable.freqframe'        : 'LSRK'
100
101    # apply action to all axes not just the cursor location
102    'scantable.allaxes'          : True
103
104    # use internal plotter
105    'scantable.plotter'          : True
106
107    # Fitter   
108    """
109   
[226]110def rc_params():
111    'Return the default params updated from the values in the rc file'
112   
113    fname = asap_fname()
114   
115    if fname is None or not os.path.exists(fname):
116        message = 'could not find rc file; returning defaults'
117        ret =  dict([ (key, tup[0]) for key, tup in defaultParams.items()])
118        #print message
119        return ret
120       
121    cnt = 0
122    for line in file(fname):
123        cnt +=1
124        line = line.strip()
125        if not len(line): continue
126        if line.startswith('#'): continue
127        tup = line.split(':',1)
128        if len(tup) !=2:
129            print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
130            continue
131       
132        key, val = tup
133        key = key.strip()
134        if not defaultParams.has_key(key):
135            print ('Bad key "%s" on line %d in %s' % (key, cnt, fname))
136            continue
137       
138        default, converter =  defaultParams[key]
139
140        ind = val.find('#')
141        if ind>=0: val = val[:ind]   # ignore trailing comments
142        val = val.strip()
143        try: cval = converter(val)   # try to convert to proper type or raise
144        except Exception, msg:
145            print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg))
146            continue
147        else:
148            # Alles Klar, update dict
149            defaultParams[key][0] = cval
150
151    # strip the conveter funcs and return
152    ret =  dict([ (key, tup[0]) for key, tup in defaultParams.items()])
[274]153    verbose.report('loaded rc file %s'%fname)
[226]154
155    return ret
156
157
158# this is the instance used by the asap classes
159rcParams = rc_params()
160
161rcParamsDefault = dict(rcParams.items()) # a copy
162
163def rc(group, **kwargs):
164    """
165    Set the current rc params.  Group is the grouping for the rc, eg
[379]166    for scantable.save the group is 'scantable', for plotter.stacking, the
167    group is 'plotter', and so on.  kwargs is a list of attribute
[226]168    name/value pairs, eg
169
[379]170      rc('scantable', save='SDFITS')
[226]171
172    sets the current rc params and is equivalent to
173   
[379]174      rcParams['scantable.save'] = 'SDFITS'
[226]175
176    Use rcdefaults to restore the default rc params after changes.
177    """
178
[379]179    aliases = {}
[226]180   
181    for k,v in kwargs.items():
182        name = aliases.get(k) or k
183        key = '%s.%s' % (group, name)
184        if not rcParams.has_key(key):
185            raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % (key, group, name))
186       
187        rcParams[key] = v
188
189
190def rcdefaults():
191    """
192    Restore the default rc params - the ones that were created at
193    asap load time
194    """
195    rcParams.update(rcParamsDefault)
196
[113]197from asapfitter import *
[100]198from asapreader import reader
199from asapmath import *
200from scantable import *
[297]201from asaplinefind import *
[285]202
[226]203if rcParams['useplotter']:
[285]204    if os.environ.has_key('DISPLAY'):
[378]205        print "Initialising asapplotter with the name 'plotter' ..."
[285]206        import asapplotter
207        plotter = asapplotter.asapplotter()
208    else:
[378]209        print "No $DISPLAY set. Disabling plotter.\n"
[285]210
[274]211#from numarray ones,zeros
[100]212
[378]213
[100]214__date__ = '$Date: 2005-02-07 22:34:16 +0000 (Mon, 07 Feb 2005) $'
[278]215__version__  = '0.2'
[100]216
217def list_scans(t = scantable):
218    import sys, types
219    #meta_t = type(t)
220    #if meta_t == types.InstanceType:
221    #    t = t.__class__
222    #elif meta_t not in [types.ClassType, types.TypeType]:
223    #    t = meta_t
224    globs = sys.modules['__main__'].__dict__.iteritems()
[113]225    print "The user created scantables are:"
226    x = map(lambda x: x[0], filter(lambda x: isinstance(x[1], t), globs))
227    print x
[100]228
[113]229def commands():
[210]230    x = """   
[113]231    [The scan container]
232        scantable           - a container for integrations/scans
[182]233                              (can open asap/rpfits/sdfits and ms files)
[113]234            copy            - returns a copy of a scan
235            get_scan        - gets a specific scan out of a scantable
236            summary         - print info about the scantable contents
[255]237            set_cursor      - set a specific Beam/IF/Pol 'cursor' for
238                              further use
239            get_cursor      - print out the current cursor position
[182]240            stats           - get specified statistic of the spectra in
241                              the scantable
242            stddev          - get the standard deviation of the spectra
243                              in the scantable
[113]244            get_tsys        - get the TSys
245            get_time        - get the timestamps of the integrations
[255]246            get_unit        - get the currnt unit
[276]247            set_unit        - set the abcissa unit to be used from this point on
[255]248            get_abcissa     - get the abcissa values and name for a given
249                              row (time)
[113]250            set_freqframe   - set the frame info for the Spectral Axis
251                              (e.g. 'LSRK')
[276]252            set_doppler     - set the doppler to be used from this point on
[240]253            set_instrument  - set the instrument name
[255]254            get_fluxunit    - get the brightness flux unit
[240]255            set_fluxunit    - set the brightness flux unit
[188]256            create_mask     - return an mask in the current unit
257                              for the given region. The specified regions
258                              are NOT masked
[255]259            get_restfreqs   - get the current list of rest frequencies
260            set_restfreqs   - set a list of rest frequencies
[113]261            flag_spectrum   - flag a whole Beam/IF/Pol
[116]262            save            - save the scantable to disk as either 'ASAP'
263                              or 'SDFITS'
[113]264            nbeam,nif,nchan,npol - the number of beams/IFs/Pols/Chans
265    [Math]
[142]266        average_time       - return the (weighted) time average of a scan
267                             or a list of scans
[128]268        average_pol         - average the polarisations together.
[113]269                              The dimension won't be reduced and
270                              all polarisations will contain the
271                              averaged spectrum.
272        quotient            - return the on/off quotient
[255]273        simple_math         - simple mathematical operations on two scantables,
274                              'add', 'sub', 'mul', 'div'
[301]275        scale               - return a scan scaled by a given factor
276        add                 - return a scan with given value added
[113]277        bin                 - return a scan with binned channels
[301]278        resample            - return a scan with resampled channels
[179]279        smooth              - return the spectrally smoothed scan
[113]280        poly_baseline       - fit a polynomial baseline to all Beams/IFs/Pols
[240]281        gain_el             - apply gain-elevation correction
282        opacity             - apply opacity correction
[255]283        convert_flux        - convert to and from Jy and Kelvin brightness
284                              units
[100]285
[113]286        fitter
287            auto_fit        - return a scan where the function is
288                              applied to all Beams/IFs/Pols.
289            commit          - return a new scan where the fits have been
290                              commited.
291            fit             - execute the actual fitting process
292            get_chi2        - get the Chi^2
293            set_scan        - set the scantable to be fit
294            set_function    - set the fitting function
295            set_parameters  - set the parameters for the function(s), and
296                              set if they should be held fixed during fitting
297            get_parameters  - get the fitted parameters
[210]298    [Plotter]
299        asapplotter         - a plotter for asap, default plotter is
300                              called 'plotter'
301            plot            - plot a (list of) scantable
[378]302            save            - save the plot to a file ('png' ,'ps' or 'eps')
[210]303            set_mode        - set the state of the plotter, i.e.
304                              what is to be plotted 'colour stacked'
305                              and what 'panelled'
306            set_range       - set the abcissa 'zoom' range
[255]307            set_legend      - specify user labels for the legend indeces
308            set_title       - specify user labels for the panel indeces
309            set_ordinate    - specify a user label for the ordinate
310            set_abcissa     - specify a user label for the abcissa
[378]311            set_layout      - specify the multi-panel layout (rows,cols)
[210]312           
[182]313    [Reading files]
314        reader              - access rpfits/sdfits files
315            read            - read in integrations
316            summary         - list info about all integrations
317
[113]318    [General]
319        commands            - this command
320        print               - print details about a variable
321        list_scans          - list all scantables created bt the user
322        del                 - delete the given variable from memory
323        range               - create a list of values, e.g.
324                              range(3) = [0,1,2], range(2,5) = [2,3,4]
325        help                - print help for one of the listed functions
326        execfile            - execute an asap script, e.g. execfile('myscript')
[255]327        list_rcparameters   - print out a list of possible values to be
[274]328                              put into $HOME/.asaprc
[210]329    Note:
330        How to use this with help:
331                                         # function 'summary'
332        [xxx] is just a category
333        Every 'sub-level' in this list should be replaces by a '.' Period when
334        using help
335        Example:
336            ASAP> help scantable # to get info on ths scantable
337            ASAP> help scantable.summary # to get help on the scantable's
338            ASAP> help average_time
339
[113]340    """
341    print x
342    return
343
344print """Welcome to ASAP - the ATNF Single Dish Analysis Package
[378]345This is a testing pre-release %s
[100]346
347Please report any bugs to:
[128]348Malte.Marquarding@csiro.au
[100]349
[378]350[IMPORTANT: ASAP is 0-based]
[113]351Type commands() to get a list of all available ASAP commands.
[378]352""" % (__version__)
Note: See TracBrowser for help on using the repository browser.