source: trunk/python/__init__.py @ 1193

Last change on this file since 1193 was 1193, checked in by mar637, 18 years ago

added ipython detection to set up ipython specific things

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