source: trunk/python/__init__.py@ 705

Last change on this file since 705 was 702, checked in by mar637, 19 years ago

merges from Release-2-fixes

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