source: trunk/python/__init__.py@ 921

Last change on this file since 921 was 895, checked in by mar637, 19 years ago

added asapreader to asap2

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