source: trunk/python/__init__.py@ 908

Last change on this file since 908 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
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
[706]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
49
[706]50
[226]51defaultParams = {
52 # general
[513]53 'verbose' : [True, _validate_bool],
54 'useplotter' : [True, _validate_bool],
[542]55 'insitu' : [True, _validate_bool],
[706]56
[226]57 # plotting
[706]58 'plotter.gui' : [True, _validate_bool],
[226]59 'plotter.stacking' : ['p', str],
60 'plotter.panelling' : ['s', str],
[700]61 'plotter.colours' : ['', str],
62 'plotter.linestyles' : ['', str],
[710]63 'plotter.decimate' : [False, _validate_bool],
64 'plotter.ganged' : [True, _validate_bool],
65
[226]66 # scantable
67 'scantable.save' : ['ASAP', str],
[513]68 'scantable.autoaverage' : [True, _validate_bool],
[226]69 'scantable.freqframe' : ['LSRK', str], #default frequency frame
[513]70 'scantable.plotter' : [True, _validate_bool], # use internal plotter
71 'scantable.verbosesummary' : [False, _validate_bool]
[226]72
73 # fitter
74 }
75
[255]76def list_rcparameters():
[706]77
[255]78 print """
[737]79# general
80# print verbose output
81verbose : True
[255]82
[737]83# preload a default plotter
84useplotter : True
[255]85
[737]86# apply operations on the input scantable or return new one
87insitu : True
[706]88
[737]89# plotting
[710]90
[737]91# do we want a GUI or plot to a file
92plotter.gui : True
[710]93
[737]94# default mode for colour stacking
95plotter.stacking : Pol
[255]96
[737]97# default mode for panelling
98plotter.panelling : scan
[255]99
[737]100# push panels together, to share axislabels
101plotter.ganged : True
[710]102
[737]103# decimate the number of points plotted bya afactor of
104# nchan/1024
105plotter.decimate : False
[733]106
[737]107# default colours/linestyles
108plotter.colours :
109plotter.linestyles :
[700]110
[737]111# scantable
112# default ouput format when saving
113scantable.save : ASAP
114# auto averaging on read
115scantable.autoaverage : True
[255]116
[737]117# default frequency frame to set when function
118# scantable.set_freqfrmae is called
119scantable.freqframe : LSRK
[255]120
[737]121# Control the level of information printed by summary
122scantable.verbosesummary : False
[706]123
[737]124# Fitter
125"""
[706]126
[226]127def rc_params():
128 'Return the default params updated from the values in the rc file'
[706]129
[513]130 fname = _asap_fname()
[706]131
[226]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
[706]137
[226]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
[706]148
[226]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
[706]154
[226]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()])
[466]170 print ('loaded rc file %s'%fname)
[226]171
172 return ret
173
174
175# this is the instance used by the asap classes
[706]176rcParams = rc_params()
[226]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
[379]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
[226]185 name/value pairs, eg
186
[379]187 rc('scantable', save='SDFITS')
[226]188
189 sets the current rc params and is equivalent to
[706]190
[379]191 rcParams['scantable.save'] = 'SDFITS'
[226]192
193 Use rcdefaults to restore the default rc params after changes.
194 """
195
[379]196 aliases = {}
[706]197
[226]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))
[706]203
[226]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
[513]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
[715]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
[710]233asaplog=_asaplog()
[715]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
[113]244from asapfitter import *
[895]245from asapreader import reader
[710]246
[100]247from asapmath import *
[880]248from scantable import *
249from asaplinefind import *
[876]250#from asapfit import *
[285]251
[466]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
[876]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
[285]261
[574]262__date__ = '$Date: 2006-03-08 03:29:58 +0000 (Wed, 08 Mar 2006) $'.split()[1]
[796]263__version__ = '2.0a'
[100]264
[706]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
[100]273
[715]274 def commands():
275 x = """
[113]276 [The scan container]
277 scantable - a container for integrations/scans
[182]278 (can open asap/rpfits/sdfits and ms files)
[113]279 copy - returns a copy of a scan
280 get_scan - gets a specific scan out of a scantable
[876]281 (by name or number) [deprecated]
[113]282 summary - print info about the scantable contents
[182]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
[113]287 get_tsys - get the TSys
288 get_time - get the timestamps of the integrations
[733]289 get_sourcename - get the source names of the scans
[794]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
[876]293 get_unit - get the current unit
[513]294 set_unit - set the abcissa unit to be used from this
295 point on
[255]296 get_abcissa - get the abcissa values and name for a given
297 row (time)
[113]298 set_freqframe - set the frame info for the Spectral Axis
299 (e.g. 'LSRK')
[276]300 set_doppler - set the doppler to be used from this point on
[240]301 set_instrument - set the instrument name
[255]302 get_fluxunit - get the brightness flux unit
[240]303 set_fluxunit - set the brightness flux unit
[188]304 create_mask - return an mask in the current unit
305 for the given region. The specified regions
306 are NOT masked
[255]307 get_restfreqs - get the current list of rest frequencies
308 set_restfreqs - set a list of rest frequencies
[403]309 lines - print list of known spectral lines
[113]310 flag_spectrum - flag a whole Beam/IF/Pol
[116]311 save - save the scantable to disk as either 'ASAP'
312 or 'SDFITS'
[486]313 nbeam,nif,nchan,npol - the number of beams/IFs/Pols/Chans
[733]314 nscan - the number of scans in the scantable
315 nrow - te number of integrations in the scantable
[486]316 history - print the history of the scantable
[530]317 get_fit - get a fit which has been stored witnh the data
[706]318 average_time - return the (weighted) time average of a scan
[513]319 or a list of scans
320 average_pol - average the polarisations together.
[113]321 The dimension won't be reduced and
322 all polarisations will contain the
323 averaged spectrum.
[690]324 auto_quotient - return the on/off quotient with
325 automatic detection of the on/off scans
[733]326 (matched pairs and 1 off - n on)
[513]327 quotient - return the on/off quotient
328 scale - return a scan scaled by a given factor
[706]329 add - return a scan with given value added
[513]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
[706]334 auto_poly_baseline - automatically fit a polynomial baseline
[780]335 recalc_azel - recalculate azimuth and elevation based on
336 the pointing
[513]337 gain_el - apply gain-elevation correction
338 opacity - apply opacity correction
339 convert_flux - convert to and from Jy and Kelvin brightness
[255]340 units
[513]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
[733]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
[513]351 [Math] Mainly functions which operate on more than one scantable
[100]352
[706]353 average_time - return the (weighted) time average
[513]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]
[113]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
[530]365 store_fit - store the fit paramaters in the data (scantable)
[113]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
[513]371 set_gauss_parameters - same as above but specialised for individual
372 gaussian components
[113]373 get_parameters - get the fitted parameters
[513]374 plot - plot the resulting fit and/or components and
375 residual
[210]376 [Plotter]
377 asapplotter - a plotter for asap, default plotter is
378 called 'plotter'
379 plot - plot a (list of) scantable
[378]380 save - save the plot to a file ('png' ,'ps' or 'eps')
[210]381 set_mode - set the state of the plotter, i.e.
382 what is to be plotted 'colour stacked'
383 and what 'panelled'
[530]384 set_cursor - only plot a selected part of the data
[733]385 set_range - set a 'zoom' window [xmin,xmax,ymin,ymax]
[255]386 set_legend - specify user labels for the legend indeces
387 set_title - specify user labels for the panel indeces
[733]388 set_abcissa - specify a user label for the abcissa
[255]389 set_ordinate - specify a user label for the ordinate
[378]390 set_layout - specify the multi-panel layout (rows,cols)
[733]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
[706]395
[182]396 [Reading files]
397 reader - access rpfits/sdfits files
398 read - read in integrations
399 summary - list info about all integrations
400
[113]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')
[255]410 list_rcparameters - print out a list of possible values to be
[274]411 put into $HOME/.asaprc
[466]412 mask_and,mask_or,
413 mask_not - boolean operations on masks created with
414 scantable.create_mask
[706]415
[210]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
[706]421 using help
[210]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
[715]427 """
428 print x
429 return
[113]430
[706]431def welcome():
432 return """Welcome to ASAP v%s (%s) - the ATNF Spectral Analysis Package
[100]433
434Please report any bugs to:
[555]435asap@atnf.csiro.au
[100]436
[378]437[IMPORTANT: ASAP is 0-based]
[706]438Type commands() to get a list of all available ASAP commands.""" % (__version__, __date__)
Note: See TracBrowser for help on using the repository browser.