source: trunk/python/__init__.py@ 714

Last change on this file since 714 was 710, checked in by mar637, 19 years ago

create_mask now also handles args[0]=list. auto_quotient checks for conformance between # of ons and offs

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