source: trunk/python/__init__.py @ 1093

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

removed FITS output, added drop_scan function

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