source: trunk/python/__init__.py@ 729

Last change on this file since 729 was 715, checked in by mar637, 19 years ago

updated logging

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