source: branches/hpc34/python/parameters.py@ 2582

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

Got rid of redundant print_log. Use asaplog.post directly.

File size: 7.3 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# only valid in asap standard mode not in scripts or casapy
88# It will disable exceptions and just print the messages
89verbose : True
90
91# preload a default plotter
92useplotter : True
93
94# apply operations on the input scantable or return new one
95insitu : True
96
97# plotting
98
99# do we want a GUI or plot to a file
100plotter.gui : True
101
102# default mode for colour stacking
103plotter.stacking : Pol
104
105# default mode for panelling
106plotter.panelling : scan
107
108# push panels together, to share axis labels
109plotter.ganged : True
110
111# decimate the number of points plotted by a factor of
112# nchan/1024
113plotter.decimate : False
114
115# default colours/linestyles
116plotter.colours :
117plotter.linestyles :
118
119# enable/disable histogram plotting
120plotter.histogram : False
121
122# ps paper type
123plotter.papertype : A4
124
125# The formatting style of the xaxis
126plotter.axesformatting : 'mpl' (default) or 'asap' (for old versions of matplotlib)
127
128# scantable
129
130# default storage of scantable ('memory'/'disk')
131scantable.storage : memory
132
133# write history of each call to scantable
134scantable.history : True
135
136# default ouput format when saving
137scantable.save : ASAP
138
139# auto averaging on read
140scantable.autoaverage : True
141
142# default frequency frame to set when function
143# scantable.set_freqframe is called
144scantable.freqframe : LSRK
145
146# Control the level of information printed by summary
147scantable.verbosesummary : False
148
149# Control the identification of reference (off) scans
150# This is has to be a regular expression
151scantable.reference : .*(e|w|_R)$
152
153# Indicate whether the data was parallactified (total phase offest == 0.0)
154scantable.parallactify : False
155
156# Fitter
157"""
158
159def rc_params():
160 'Return the default params updated from the values in the rc file'
161 fname = _asap_fname()
162
163 if fname is None or not os.path.exists(fname):
164 ret = dict([ (key, tup[0]) for key, tup in defaultParams.items()])
165 #print message
166 #message = 'could not find rc file; returning defaults'
167 return ret
168
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 #asaplog.push('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
179 #asaplog.post('WARN')
180 continue
181
182 key, val = tup
183 key = key.strip()
184 if not defaultParams.has_key(key):
185 print ('Bad key "%s" on line %d in %s' % (key, cnt, fname))
186 #asaplog.push('Bad key "%s" on line %d in %s' % (key, cnt, fname))
187 #asaplog.post('WARN')
188 continue
189
190 default, converter = defaultParams[key]
191
192 ind = val.find('#')
193 if ind>=0: val = val[:ind] # ignore trailing comments
194 val = val.strip()
195 try: cval = converter(val) # try to convert to proper type or raise
196 except ValueError, msg:
197 print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg))
198 #asaplog.push('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, str(msg)))
199 #asaplog.post('WARN')
200 continue
201 else:
202 # Alles Klar, update dict
203 defaultParams[key][0] = cval
204
205 # strip the conveter funcs and return
206 ret = dict([ (key, tup[0]) for key, tup in defaultParams.items()])
207 print ('loaded rc file %s'%fname)
208
209 return ret
210
211
212# this is the instance used by the asap classes
213rcParams = rc_params()
214
215rcParamsDefault = dict(rcParams.items()) # a copy
216
217def rc(group, **kwargs):
218 """
219 Set the current rc params. Group is the grouping for the rc, eg
220 for scantable.save the group is 'scantable', for plotter.stacking, the
221 group is 'plotter', and so on. kwargs is a list of attribute
222 name/value pairs, eg
223
224 rc('scantable', save='SDFITS')
225
226 sets the current rc params and is equivalent to
227
228 rcParams['scantable.save'] = 'SDFITS'
229
230 Use rcdefaults to restore the default rc params after changes.
231 """
232
233 aliases = {}
234
235 for k,v in kwargs.items():
236 name = aliases.get(k) or k
237 if len(group):
238 key = '%s.%s' % (group, name)
239 else:
240 key = name
241 if not rcParams.has_key(key):
242 raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % (key, group, name))
243
244 rcParams[key] = v
245
246
247def rcdefaults():
248 """
249 Restore the default rc params - the ones that were created at
250 asap load time
251 """
252 rcParams.update(rcParamsDefault)
Note: See TracBrowser for help on using the repository browser.