source: trunk/python/__init__.py @ 1423

Last change on this file since 1423 was 1423, checked in by Malte Marquarding, 16 years ago

fixed wrong indentation

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