source: branches/alma/python/__init__.py @ 1614

Last change on this file since 1614 was 1614, checked in by Takeshi Nakazato, 15 years ago

New Development: No

JIRA Issue: Yes CAS-729, CAS-1147

Ready to Release: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: No

Module(s): Module Names change impacts.

Description: Describe your changes here...

  1. Added level parameter to print_log()
  2. Replaced casalog.post() to asaplog.push() + print_log().


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