source: trunk/python/__init__.py @ 513

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

*Moved most asapmath functions to scantable member functions. Only ones taking more than one scantable as input remain.

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