source: trunk/python/__init__.py@ 707

Last change on this file since 707 was 706, checked in by mar637, 19 years ago

various changes to enable non-gui plotting

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 14.6 KB
Line 
1"""
2This is the ATNF Single Dish Analysis package.
3
4"""
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/.asaprc
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 '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
64 # scantable
65 'scantable.save' : ['ASAP', str],
66 'scantable.autoaverage' : [True, _validate_bool],
67 'scantable.freqframe' : ['LSRK', str], #default frequency frame
68 'scantable.allaxes' : [True, _validate_bool], # apply action to all axes
69 'scantable.plotter' : [True, _validate_bool], # use internal plotter
70 'scantable.verbosesummary' : [False, _validate_bool]
71
72 # fitter
73 }
74
75def list_rcparameters():
76
77 print """
78 # general
79 # print verbose output
80 verbose : True
81
82 # preload a default plotter
83 useplotter : True
84
85 # apply operations on the input scantable or return new one
86 insitu : True
87
88 # plotting
89
90 # do we want a GUI or plot to a file
91 plotter.gui : True
92
93 # default mode for colour stacking
94 plotter.stacking : Pol
95
96 # default mode for panelling
97 plotter.panelling : scan
98
99 # default colours/linestyles
100 plotter.colours :
101 plotter.linestyles :
102
103 # scantable
104 # default ouput format when saving
105 scantable.save : ASAP
106 # auto averaging on read
107 scantable.autoaverage : True
108
109 # default frequency frame to set when function
110 # scantable.set_freqfrmae is called
111 scantable.freqframe : LSRK
112
113 # apply action to all axes not just the cursor location
114 scantable.allaxes : True
115
116 # use internal plotter
117 scantable.plotter : True
118
119 # Control the level of information printed by summary
120 scantable.verbosesummary : False
121
122 # Fitter
123 """
124
125def rc_params():
126 'Return the default params updated from the values in the rc file'
127
128 fname = _asap_fname()
129
130 if fname is None or not os.path.exists(fname):
131 message = 'could not find rc file; returning defaults'
132 ret = dict([ (key, tup[0]) for key, tup in defaultParams.items()])
133 #print message
134 return ret
135
136 cnt = 0
137 for line in file(fname):
138 cnt +=1
139 line = line.strip()
140 if not len(line): continue
141 if line.startswith('#'): continue
142 tup = line.split(':',1)
143 if len(tup) !=2:
144 print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
145 continue
146
147 key, val = tup
148 key = key.strip()
149 if not defaultParams.has_key(key):
150 print ('Bad key "%s" on line %d in %s' % (key, cnt, fname))
151 continue
152
153 default, converter = defaultParams[key]
154
155 ind = val.find('#')
156 if ind>=0: val = val[:ind] # ignore trailing comments
157 val = val.strip()
158 try: cval = converter(val) # try to convert to proper type or raise
159 except Exception, msg:
160 print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg))
161 continue
162 else:
163 # Alles Klar, update dict
164 defaultParams[key][0] = cval
165
166 # strip the conveter funcs and return
167 ret = dict([ (key, tup[0]) for key, tup in defaultParams.items()])
168 print ('loaded rc file %s'%fname)
169
170 return ret
171
172
173# this is the instance used by the asap classes
174rcParams = rc_params()
175
176rcParamsDefault = dict(rcParams.items()) # a copy
177
178def rc(group, **kwargs):
179 """
180 Set the current rc params. Group is the grouping for the rc, eg
181 for scantable.save the group is 'scantable', for plotter.stacking, the
182 group is 'plotter', and so on. kwargs is a list of attribute
183 name/value pairs, eg
184
185 rc('scantable', save='SDFITS')
186
187 sets the current rc params and is equivalent to
188
189 rcParams['scantable.save'] = 'SDFITS'
190
191 Use rcdefaults to restore the default rc params after changes.
192 """
193
194 aliases = {}
195
196 for k,v in kwargs.items():
197 name = aliases.get(k) or k
198 key = '%s.%s' % (group, name)
199 if not rcParams.has_key(key):
200 raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % (key, group, name))
201
202 rcParams[key] = v
203
204
205def rcdefaults():
206 """
207 Restore the default rc params - the ones that were created at
208 asap load time
209 """
210 rcParams.update(rcParamsDefault)
211
212
213def _is_sequence_or_number(param, ptype=int):
214 if isinstance(param,tuple) or isinstance(param,list):
215 out = True
216 for p in param:
217 out &= isinstance(p,ptype)
218 return out
219 elif isinstance(param, ptype):
220 return True
221 return False
222
223from asapfitter import *
224from asapreader import reader
225from asapmath import *
226from scantable import *
227from asaplinefind import *
228from asapfit import *
229
230from numarray import logical_and as mask_and
231from numarray import logical_or as mask_or
232from numarray import logical_not as mask_not
233
234if rcParams['useplotter']:
235 from asapplotter import *
236 if rcParams['verbose']:
237 print "Initialising GUI asapplotter with the name 'plotter' ..."
238 gui = os.environ.has_key('DISPLAY') and rcParams['plotter.gui']
239 plotter = asapplotter(gui)
240
241__date__ = '$Date: 2005-11-02 02:17:39 +0000 (Wed, 02 Nov 2005) $'.split()[1]
242__version__ = '1.2'
243
244if rcParams['verbose']:
245 def list_scans(t = scantable):
246 import sys, types
247 globs = sys.modules['__main__'].__dict__.iteritems()
248 print "The user created scantables are:"
249 sts = map(lambda x: x[0], filter(lambda x: isinstance(x[1], t), globs))
250 print filter(lambda x: not x.startswith('_'), sts)
251 return
252else:
253 pass
254
255def commands():
256 x = """
257 [The scan container]
258 scantable - a container for integrations/scans
259 (can open asap/rpfits/sdfits and ms files)
260 copy - returns a copy of a scan
261 get_scan - gets a specific scan out of a scantable
262 summary - print info about the scantable contents
263 set_cursor - set a specific Beam/IF/Pol 'cursor' for
264 further use
265 get_cursor - print out the current cursor position
266 stats - get specified statistic of the spectra in
267 the scantable
268 stddev - get the standard deviation of the spectra
269 in the scantable
270 get_tsys - get the TSys
271 get_time - get the timestamps of the integrations
272 get_unit - get the currnt unit
273 set_unit - set the abcissa unit to be used from this
274 point on
275 get_abcissa - get the abcissa values and name for a given
276 row (time)
277 set_freqframe - set the frame info for the Spectral Axis
278 (e.g. 'LSRK')
279 set_doppler - set the doppler to be used from this point on
280 set_instrument - set the instrument name
281 get_fluxunit - get the brightness flux unit
282 set_fluxunit - set the brightness flux unit
283 create_mask - return an mask in the current unit
284 for the given region. The specified regions
285 are NOT masked
286 get_restfreqs - get the current list of rest frequencies
287 set_restfreqs - set a list of rest frequencies
288 lines - print list of known spectral lines
289 flag_spectrum - flag a whole Beam/IF/Pol
290 save - save the scantable to disk as either 'ASAP'
291 or 'SDFITS'
292 nbeam,nif,nchan,npol - the number of beams/IFs/Pols/Chans
293 history - print the history of the scantable
294 get_fit - get a fit which has been stored witnh the data
295 average_time - return the (weighted) time average of a scan
296 or a list of scans
297 average_pol - average the polarisations together.
298 The dimension won't be reduced and
299 all polarisations will contain the
300 averaged spectrum.
301 auto_quotient - return the on/off quotient with
302 automatic detection of the on/off scans
303 quotient - return the on/off quotient
304 scale - return a scan scaled by a given factor
305 add - return a scan with given value added
306 bin - return a scan with binned channels
307 resample - return a scan with resampled channels
308 smooth - return the spectrally smoothed scan
309 poly_baseline - fit a polynomial baseline to all Beams/IFs/Pols
310 auto_poly_baseline - automatically fit a polynomial baseline
311 gain_el - apply gain-elevation correction
312 opacity - apply opacity correction
313 convert_flux - convert to and from Jy and Kelvin brightness
314 units
315 freq_align - align spectra in frequency frame
316 rotate_xyphase - rotate XY phase of cross correlation
317 rotate_linpolphase - rotate the phase of the complex
318 polarization O=Q+iU correlation
319 [Math] Mainly functions which operate on more than one scantable
320
321 average_time - return the (weighted) time average
322 of a list of scans
323 quotient - return the on/off quotient
324 simple_math - simple mathematical operations on two scantables,
325 'add', 'sub', 'mul', 'div'
326 [Fitting]
327 fitter
328 auto_fit - return a scan where the function is
329 applied to all Beams/IFs/Pols.
330 commit - return a new scan where the fits have been
331 commited.
332 fit - execute the actual fitting process
333 store_fit - store the fit paramaters in the data (scantable)
334 get_chi2 - get the Chi^2
335 set_scan - set the scantable to be fit
336 set_function - set the fitting function
337 set_parameters - set the parameters for the function(s), and
338 set if they should be held fixed during fitting
339 set_gauss_parameters - same as above but specialised for individual
340 gaussian components
341 get_parameters - get the fitted parameters
342 plot - plot the resulting fit and/or components and
343 residual
344 [Plotter]
345 asapplotter - a plotter for asap, default plotter is
346 called 'plotter'
347 plot - plot a (list of) scantable
348 save - save the plot to a file ('png' ,'ps' or 'eps')
349 set_mode - set the state of the plotter, i.e.
350 what is to be plotted 'colour stacked'
351 and what 'panelled'
352 set_cursor - only plot a selected part of the data
353 set_range - set a 'zoom' window
354 set_legend - specify user labels for the legend indeces
355 set_title - specify user labels for the panel indeces
356 set_ordinate - specify a user label for the ordinate
357 set_abcissa - specify a user label for the abcissa
358 set_layout - specify the multi-panel layout (rows,cols)
359
360 [Reading files]
361 reader - access rpfits/sdfits files
362 read - read in integrations
363 summary - list info about all integrations
364
365 [General]
366 commands - this command
367 print - print details about a variable
368 list_scans - list all scantables created bt the user
369 del - delete the given variable from memory
370 range - create a list of values, e.g.
371 range(3) = [0,1,2], range(2,5) = [2,3,4]
372 help - print help for one of the listed functions
373 execfile - execute an asap script, e.g. execfile('myscript')
374 list_rcparameters - print out a list of possible values to be
375 put into $HOME/.asaprc
376 mask_and,mask_or,
377 mask_not - boolean operations on masks created with
378 scantable.create_mask
379
380 Note:
381 How to use this with help:
382 # function 'summary'
383 [xxx] is just a category
384 Every 'sub-level' in this list should be replaces by a '.' Period when
385 using help
386 Example:
387 ASAP> help scantable # to get info on ths scantable
388 ASAP> help scantable.summary # to get help on the scantable's
389 ASAP> help average_time
390
391 """
392 print x
393 return
394
395def welcome():
396 return """Welcome to ASAP v%s (%s) - the ATNF Spectral Analysis Package
397
398Please report any bugs to:
399asap@atnf.csiro.au
400
401[IMPORTANT: ASAP is 0-based]
402Type commands() to get a list of all available ASAP commands.""" % (__version__, __date__)
Note: See TracBrowser for help on using the repository browser.