source: trunk/python/__init__.py@ 713

Last change on this file since 713 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
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
[710]228from asap._asap import LogSink as _asaplog
229# use null sink if verbose==False
230#asaplog=_asaplog(rcParams['verbose'])
231asaplog=_asaplog()
232global asaplog
[113]233from asapfitter import *
[100]234from asapreader import reader
[710]235
[100]236from asapmath import *
[710]237from asap._asap import _math_setlog
238_math_setlog(asaplog)
239
[100]240from scantable import *
[297]241from asaplinefind import *
[530]242from asapfit import *
[285]243
[466]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
[226]248if rcParams['useplotter']:
[706]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)
[285]254
[574]255__date__ = '$Date: 2005-11-10 23:01:49 +0000 (Thu, 10 Nov 2005) $'.split()[1]
[706]256__version__ = '1.2'
[100]257
[706]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
[100]268
[113]269def commands():
[706]270 x = """
[113]271 [The scan container]
272 scantable - a container for integrations/scans
[182]273 (can open asap/rpfits/sdfits and ms files)
[113]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
[255]277 set_cursor - set a specific Beam/IF/Pol 'cursor' for
278 further use
279 get_cursor - print out the current cursor position
[182]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
[113]284 get_tsys - get the TSys
285 get_time - get the timestamps of the integrations
[255]286 get_unit - get the currnt unit
[513]287 set_unit - set the abcissa unit to be used from this
288 point on
[255]289 get_abcissa - get the abcissa values and name for a given
290 row (time)
[113]291 set_freqframe - set the frame info for the Spectral Axis
292 (e.g. 'LSRK')
[276]293 set_doppler - set the doppler to be used from this point on
[240]294 set_instrument - set the instrument name
[255]295 get_fluxunit - get the brightness flux unit
[240]296 set_fluxunit - set the brightness flux unit
[188]297 create_mask - return an mask in the current unit
298 for the given region. The specified regions
299 are NOT masked
[255]300 get_restfreqs - get the current list of rest frequencies
301 set_restfreqs - set a list of rest frequencies
[403]302 lines - print list of known spectral lines
[113]303 flag_spectrum - flag a whole Beam/IF/Pol
[116]304 save - save the scantable to disk as either 'ASAP'
305 or 'SDFITS'
[486]306 nbeam,nif,nchan,npol - the number of beams/IFs/Pols/Chans
307 history - print the history of the scantable
[530]308 get_fit - get a fit which has been stored witnh the data
[706]309 average_time - return the (weighted) time average of a scan
[513]310 or a list of scans
311 average_pol - average the polarisations together.
[113]312 The dimension won't be reduced and
313 all polarisations will contain the
314 averaged spectrum.
[690]315 auto_quotient - return the on/off quotient with
316 automatic detection of the on/off scans
[513]317 quotient - return the on/off quotient
318 scale - return a scan scaled by a given factor
[706]319 add - return a scan with given value added
[513]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
[706]324 auto_poly_baseline - automatically fit a polynomial baseline
[513]325 gain_el - apply gain-elevation correction
326 opacity - apply opacity correction
327 convert_flux - convert to and from Jy and Kelvin brightness
[255]328 units
[513]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
[100]334
[706]335 average_time - return the (weighted) time average
[513]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]
[113]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
[530]347 store_fit - store the fit paramaters in the data (scantable)
[113]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
[513]353 set_gauss_parameters - same as above but specialised for individual
354 gaussian components
[113]355 get_parameters - get the fitted parameters
[513]356 plot - plot the resulting fit and/or components and
357 residual
[210]358 [Plotter]
359 asapplotter - a plotter for asap, default plotter is
360 called 'plotter'
361 plot - plot a (list of) scantable
[378]362 save - save the plot to a file ('png' ,'ps' or 'eps')
[210]363 set_mode - set the state of the plotter, i.e.
364 what is to be plotted 'colour stacked'
365 and what 'panelled'
[530]366 set_cursor - only plot a selected part of the data
367 set_range - set a 'zoom' window
[255]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
[378]372 set_layout - specify the multi-panel layout (rows,cols)
[706]373
[182]374 [Reading files]
375 reader - access rpfits/sdfits files
376 read - read in integrations
377 summary - list info about all integrations
378
[113]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')
[255]388 list_rcparameters - print out a list of possible values to be
[274]389 put into $HOME/.asaprc
[466]390 mask_and,mask_or,
391 mask_not - boolean operations on masks created with
392 scantable.create_mask
[706]393
[210]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
[706]399 using help
[210]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
[113]405 """
406 print x
407 return
408
[706]409def welcome():
410 return """Welcome to ASAP v%s (%s) - the ATNF Spectral Analysis Package
[100]411
412Please report any bugs to:
[555]413asap@atnf.csiro.au
[100]414
[378]415[IMPORTANT: ASAP is 0-based]
[706]416Type commands() to get a list of all available ASAP commands.""" % (__version__, __date__)
Note: See TracBrowser for help on using the repository browser.