source: trunk/python/parameters.py @ 1858

Last change on this file since 1858 was 1858, checked in by Malte Marquarding, 14 years ago

Adde more API documentation

File size: 7.2 KB
Line 
1"""This module provides functions to set up resource parameters (rc).
2These can be set in a file .asaprc or using functions.
3"""
4__all__ = ["rc", "list_rcparameters", "rcParams", "rcParamsDefault"]
5
6import os
7
8def _validate_bool(b):
9    'Convert b to a boolean or raise'
10    bl = b.lower()
11    if bl in ('f', 'no', 'false', '0', 0): return False
12    elif bl in ('t', 'yes', 'true', '1', 1): return True
13    else:
14        raise ValueError('Could not convert "%s" to boolean' % b)
15
16def _validate_int(s):
17    'convert s to int or raise'
18    try: return int(s)
19    except ValueError:
20        raise ValueError('Could not convert "%s" to int' % s)
21
22def _asap_fname():
23    """
24    Return the path to the rc file
25
26    Search order:
27
28     * current working dir
29     * environ var ASAPRC
30     * HOME/.asaprc
31
32    """
33    fname = os.path.join( os.getcwd(), '.asaprc')
34    if os.path.exists(fname): return fname
35
36    if os.environ.has_key('ASAPRC'):
37        path =  os.environ['ASAPRC']
38        if os.path.exists(path):
39            fname = os.path.join(path, '.asaprc')
40            if os.path.exists(fname):
41                return fname
42
43    if os.environ.has_key('HOME'):
44        home =  os.environ['HOME']
45        fname = os.path.join(home, '.asaprc')
46        if os.path.exists(fname):
47            return fname
48    return None
49
50
51defaultParams = {
52    # general
53    'verbose'             : [True, _validate_bool],
54    'useplotter'          : [True, _validate_bool],
55    'insitu'              : [True, _validate_bool],
56
57    # plotting
58    'plotter.gui'         : [True, _validate_bool],
59    'plotter.stacking'    : ['p', str],
60    'plotter.panelling'   : ['s', str],
61    'plotter.colours'     : ['', str],
62    'plotter.linestyles'  : ['', str],
63    'plotter.decimate'    : [False, _validate_bool],
64    'plotter.ganged'      : [True, _validate_bool],
65    'plotter.histogram'  : [False, _validate_bool],
66    'plotter.papertype'  : ['A4', str],
67    ## for older Matplotlib version
68    #'plotter.axesformatting' : ['mpl', str],
69    'plotter.axesformatting' : ['asap', str],
70
71    # scantable
72    'scantable.save'      : ['ASAP', str],
73    'scantable.autoaverage'      : [True, _validate_bool],
74    'scantable.freqframe' : ['LSRK', str],  #default frequency frame
75    'scantable.verbosesummary'   : [False, _validate_bool],
76    'scantable.storage'   : ['memory', str],
77    'scantable.history'   : [True, _validate_bool],
78    'scantable.reference'      : ['.*(e|w|_R)$', str],
79    'scantable.parallactify'   : [False, _validate_bool]
80    # fitter
81    }
82
83def list_rcparameters():
84
85    print """
86# general
87# print verbose output
88verbose                    : True
89
90# preload a default plotter
91useplotter                 : True
92
93# apply operations on the input scantable or return new one
94insitu                     : True
95
96# plotting
97
98# do we want a GUI or plot to a file
99plotter.gui                : True
100
101# default mode for colour stacking
102plotter.stacking           : Pol
103
104# default mode for panelling
105plotter.panelling          : scan
106
107# push panels together, to share axis labels
108plotter.ganged             : True
109
110# decimate the number of points plotted by a factor of
111# nchan/1024
112plotter.decimate           : False
113
114# default colours/linestyles
115plotter.colours            :
116plotter.linestyles         :
117
118# enable/disable histogram plotting
119plotter.histogram          : False
120
121# ps paper type
122plotter.papertype          : A4
123
124# The formatting style of the xaxis
125plotter.axesformatting    : 'mpl' (default) or 'asap' (for old versions of matplotlib)
126
127# scantable
128
129# default storage of scantable ('memory'/'disk')
130scantable.storage          : memory
131
132# write history of each call to scantable
133scantable.history          : True
134
135# default ouput format when saving
136scantable.save             : ASAP
137
138# auto averaging on read
139scantable.autoaverage      : True
140
141# default frequency frame to set when function
142# scantable.set_freqframe is called
143scantable.freqframe        : LSRK
144
145# Control the level of information printed by summary
146scantable.verbosesummary   : False
147
148# Control the identification of reference (off) scans
149# This is has to be a regular expression
150scantable.reference        : .*(e|w|_R)$
151
152# Indicate whether the data was parallactified (total phase offest == 0.0)
153scantable.parallactify     : False
154
155# Fitter
156"""
157
158def rc_params():
159    'Return the default params updated from the values in the rc file'
160    fname = _asap_fname()
161
162    if fname is None or not os.path.exists(fname):
163        ret =  dict([ (key, tup[0]) for key, tup in defaultParams.items()])
164        #print message
165        #message = 'could not find rc file; returning defaults'
166        return ret
167
168    cnt = 0
169    for line in file(fname):
170        cnt +=1
171        line = line.strip()
172        if not len(line): continue
173        if line.startswith('#'): continue
174        tup = line.split(':',1)
175        if len(tup) !=2:
176            print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
177            #asaplog.push('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
178            #print_log('WARN')
179            continue
180
181        key, val = tup
182        key = key.strip()
183        if not defaultParams.has_key(key):
184            print ('Bad key "%s" on line %d in %s' % (key, cnt, fname))
185            #asaplog.push('Bad key "%s" on line %d in %s' % (key, cnt, fname))
186            #print_log('WARN')
187            continue
188
189        default, converter =  defaultParams[key]
190
191        ind = val.find('#')
192        if ind>=0: val = val[:ind]   # ignore trailing comments
193        val = val.strip()
194        try: cval = converter(val)   # try to convert to proper type or raise
195        except ValueError, msg:
196            print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg))
197            #asaplog.push('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, str(msg)))
198            #print_log('WARN')
199            continue
200        else:
201            # Alles Klar, update dict
202            defaultParams[key][0] = cval
203
204    # strip the conveter funcs and return
205    ret =  dict([ (key, tup[0]) for key, tup in defaultParams.items()])
206    print ('loaded rc file %s'%fname)
207
208    return ret
209
210
211# this is the instance used by the asap classes
212rcParams = rc_params()
213
214rcParamsDefault = dict(rcParams.items()) # a copy
215
216def rc(group, **kwargs):
217    """
218    Set the current rc params.  Group is the grouping for the rc, eg
219    for scantable.save the group is 'scantable', for plotter.stacking, the
220    group is 'plotter', and so on.  kwargs is a list of attribute
221    name/value pairs, eg
222
223      rc('scantable', save='SDFITS')
224
225    sets the current rc params and is equivalent to
226
227      rcParams['scantable.save'] = 'SDFITS'
228
229    Use rcdefaults to restore the default rc params after changes.
230    """
231
232    aliases = {}
233
234    for k,v in kwargs.items():
235        name = aliases.get(k) or k
236        if len(group):
237            key = '%s.%s' % (group, name)
238        else:
239            key = name
240        if not rcParams.has_key(key):
241            raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % (key, group, name))
242
243        rcParams[key] = v
244
245
246def rcdefaults():
247    """
248    Restore the default rc params - the ones that were created at
249    asap load time
250    """
251    rcParams.update(rcParamsDefault)
Note: See TracBrowser for help on using the repository browser.