source: trunk/python/__init__.py @ 715

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

updated logging

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