source: trunk/python/__init__.py@ 238

Last change on this file since 238 was 226, checked in by mar637, 20 years ago

added rcParams to support rc style default parameters, read from .asaprc

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 10.5 KB
RevLine 
[100]1"""
2This is the ATNF Single Dish Analysis package.
3
4"""
[226]5import os,sys
6
7def validate_bool(b):
8 'Convert b to a boolean or raise'
9 bl = b.lower()
10 if bl in ('f', 'no', 'false', '0', 0): return False
11 elif bl in ('t', 'yes', 'true', '1', 1): return True
12 else:
13 raise ValueError('Could not convert "%s" to boolean' % b)
14
15def validate_int(s):
16 'convert s to int or raise'
17 try: return int(s)
18 except ValueError:
19 raise ValueError('Could not convert "%s" to int' % s)
20
21def asap_fname():
22 """
23 Return the path to the rc file
24
25 Search order:
26
27 * current working dir
28 * environ var ASAPRC
29 * HOME/.matplotlibrc
30
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
56 # plotting
57 'plotter.stacking' : ['p', str],
58 'plotter.panelling' : ['s', str],
59
60 # scantable
61 'scantable.save' : ['ASAP', str],
62 'scantable.autoaverage' : [True, validate_bool],
63 'scantable.freqframe' : ['LSRK', str], #default frequency frame
64 'scantable.allaxes' : [True, validate_bool], # apply action to all axes
65 'scantable.plotter' : [True, validate_bool], # use internal plotter
66
67 # math
68 'math.insitu' : [False, validate_bool],
69
70 # fitter
71 'fitter.polyorder' : [0, validate_int],
72 'fitter.ncomponents' : [1, validate_int]
73 }
74
75def rc_params():
76 'Return the default params updated from the values in the rc file'
77
78 fname = asap_fname()
79
80 if fname is None or not os.path.exists(fname):
81 message = 'could not find rc file; returning defaults'
82 ret = dict([ (key, tup[0]) for key, tup in defaultParams.items()])
83 #print message
84 return ret
85
86 cnt = 0
87 for line in file(fname):
88 cnt +=1
89 line = line.strip()
90 if not len(line): continue
91 if line.startswith('#'): continue
92 tup = line.split(':',1)
93 if len(tup) !=2:
94 print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
95 continue
96
97 key, val = tup
98 key = key.strip()
99 if not defaultParams.has_key(key):
100 print ('Bad key "%s" on line %d in %s' % (key, cnt, fname))
101 continue
102
103 default, converter = defaultParams[key]
104
105 ind = val.find('#')
106 if ind>=0: val = val[:ind] # ignore trailing comments
107 val = val.strip()
108 try: cval = converter(val) # try to convert to proper type or raise
109 except Exception, msg:
110 print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg))
111 continue
112 else:
113 # Alles Klar, update dict
114 defaultParams[key][0] = cval
115
116 # strip the conveter funcs and return
117 ret = dict([ (key, tup[0]) for key, tup in defaultParams.items()])
118 verbose.report('loaded rc file %s'%fname)
119
120 return ret
121
122
123# this is the instance used by the asap classes
124rcParams = rc_params()
125
126rcParamsDefault = dict(rcParams.items()) # a copy
127
128def rc(group, **kwargs):
129 """
130 Set the current rc params. Group is the grouping for the rc, eg
131 for lines.linewidth the group is 'lines', for axes.facecolor, the
132 group is 'axes', and so on. kwargs is a list of attribute
133 name/value pairs, eg
134
135 rc('lines', linewidth=2, color='r')
136
137 sets the current rc params and is equivalent to
138
139 rcParams['lines.linewidth'] = 2
140 rcParams['lines.color'] = 'r'
141
142
143 Note you can use python's kwargs dictionary facility to store
144 dictionaries of default parameters. Eg, you can customize the
145 font rc as follows
146
147 font = {'family' : 'monospace',
148 'weight' : 'bold',
149 'size' : 'larger',
150 }
151
152 rc('font', **font) # pass in the font dict as kwargs
153
154 This enables you to easily switch between several configurations.
155 Use rcdefaults to restore the default rc params after changes.
156 """
157
158 aliases = {
159 }
160
161 for k,v in kwargs.items():
162 name = aliases.get(k) or k
163 key = '%s.%s' % (group, name)
164 if not rcParams.has_key(key):
165 raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % (key, group, name))
166
167 rcParams[key] = v
168
169
170def rcdefaults():
171 """
172 Restore the default rc params - the ones that were created at
173 asap load time
174 """
175 rcParams.update(rcParamsDefault)
176
[113]177from asapfitter import *
[100]178from asapreader import reader
179from asapmath import *
180from scantable import *
[226]181if rcParams['useplotter']:
182 print "Initialising plotter..."
183 from asapplotter import *
184 plotter = asapplotter()
[100]185#from numarray ones,zeros
186
187__date__ = '$Date: 2005-01-19 07:24:16 +0000 (Wed, 19 Jan 2005) $'
188__version__ = '0.1a'
189
190def list_scans(t = scantable):
191 import sys, types
192 #meta_t = type(t)
193 #if meta_t == types.InstanceType:
194 # t = t.__class__
195 #elif meta_t not in [types.ClassType, types.TypeType]:
196 # t = meta_t
197 globs = sys.modules['__main__'].__dict__.iteritems()
[113]198 print "The user created scantables are:"
199 x = map(lambda x: x[0], filter(lambda x: isinstance(x[1], t), globs))
200 print x
[100]201
[113]202def commands():
[210]203 x = """
[113]204 [The scan container]
205 scantable - a container for integrations/scans
[182]206 (can open asap/rpfits/sdfits and ms files)
[113]207 copy - returns a copy of a scan
208 get_scan - gets a specific scan out of a scantable
209 summary - print info about the scantable contents
210 set_selection - set a specific Beam/IF/Pol for furthrt use
211 get_selection - print out the current selection
[182]212 stats - get specified statistic of the spectra in
213 the scantable
214 stddev - get the standard deviation of the spectra
215 in the scantable
[113]216 get_tsys - get the TSys
217 get_time - get the timestamps of the integrations
218 set_unit - set the units to be used from this point on
219 set_freqframe - set the frame info for the Spectral Axis
220 (e.g. 'LSRK')
[188]221 create_mask - return an mask in the current unit
222 for the given region. The specified regions
223 are NOT masked
[113]224 set_restfreqs - give a list of rest frequencies
225 flag_spectrum - flag a whole Beam/IF/Pol
[116]226 save - save the scantable to disk as either 'ASAP'
227 or 'SDFITS'
[113]228 nbeam,nif,nchan,npol - the number of beams/IFs/Pols/Chans
229 [Math]
[142]230 average_time - return the (weighted) time average of a scan
231 or a list of scans
[128]232 average_pol - average the polarisations together.
[113]233 The dimension won't be reduced and
234 all polarisations will contain the
235 averaged spectrum.
236 quotient - return the on/off quotient
237 scale - returns a scan scaled by a given factor
[149]238 add - returns a scan with given value added
[113]239 bin - return a scan with binned channels
[179]240 smooth - return the spectrally smoothed scan
[113]241 poly_baseline - fit a polynomial baseline to all Beams/IFs/Pols
[100]242
[113]243 fitter
244 auto_fit - return a scan where the function is
245 applied to all Beams/IFs/Pols.
246 commit - return a new scan where the fits have been
247 commited.
248 fit - execute the actual fitting process
249 get_chi2 - get the Chi^2
250 set_scan - set the scantable to be fit
251 set_function - set the fitting function
252 set_parameters - set the parameters for the function(s), and
253 set if they should be held fixed during fitting
254 get_parameters - get the fitted parameters
[210]255 [Plotter]
256 asapplotter - a plotter for asap, default plotter is
257 called 'plotter'
258 plot - plot a (list of) scantable
259 set_mode - set the state of the plotter, i.e.
260 what is to be plotted 'colour stacked'
261 and what 'panelled'
262 set_range - set the abcissa 'zoom' range
263 set_legend_map - specify user labels for the legend indeces
264
[182]265 [Reading files]
266 reader - access rpfits/sdfits files
267 read - read in integrations
268 summary - list info about all integrations
269
[113]270 [General]
271 commands - this command
272 print - print details about a variable
273 list_scans - list all scantables created bt the user
274 del - delete the given variable from memory
275 range - create a list of values, e.g.
276 range(3) = [0,1,2], range(2,5) = [2,3,4]
277 help - print help for one of the listed functions
278 execfile - execute an asap script, e.g. execfile('myscript')
[210]279 Note:
280 How to use this with help:
281 # function 'summary'
282 [xxx] is just a category
283 Every 'sub-level' in this list should be replaces by a '.' Period when
284 using help
285 Example:
286 ASAP> help scantable # to get info on ths scantable
287 ASAP> help scantable.summary # to get help on the scantable's
288 ASAP> help average_time
289
[113]290 """
291 print x
292 return
293
294print """Welcome to ASAP - the ATNF Single Dish Analysis Package
[100]295This is a testing pre-release v0.1a
296
297Please report any bugs to:
[128]298Malte.Marquarding@csiro.au
[100]299
[113]300[NOTE: ASAP is 0-based]
301Type commands() to get a list of all available ASAP commands.
[100]302"""
Note: See TracBrowser for help on using the repository browser.