source: branches/Release-2-fixes/python/__init__.py@ 1041

Last change on this file since 1041 was 694, checked in by mar637, 19 years ago

added user customisable colors and linestyles.

  • 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
[226]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
[513]53 'verbose' : [True, _validate_bool],
54 'useplotter' : [True, _validate_bool],
[542]55 'insitu' : [True, _validate_bool],
[466]56
[226]57 # plotting
58 'plotter.stacking' : ['p', str],
59 'plotter.panelling' : ['s', str],
[694]60 'plotter.colours' : ['', str],
61 'plotter.linestyles' : ['', str],
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():
75
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
[255]86
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
[694]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
[466]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
[381]116
[255]117 # Fitter
118 """
119
[226]120def rc_params():
121 'Return the default params updated from the values in the rc file'
122
[513]123 fname = _asap_fname()
[226]124
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
130
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
141
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
147
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
169rcParams = rc_params()
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
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 = {}
[226]190
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))
196
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' ..."
[285]232 import asapplotter
233 plotter = asapplotter.asapplotter()
234 else:
[378]235 print "No $DISPLAY set. Disabling plotter.\n"
[285]236
[274]237#from numarray ones,zeros
[100]238
[378]239
[574]240__date__ = '$Date: 2005-09-29 06:36:56 +0000 (Thu, 29 Sep 2005) $'.split()[1]
[660]241__version__ = '1.1'
[100]242
243def list_scans(t = scantable):
244 import sys, types
245 globs = sys.modules['__main__'].__dict__.iteritems()
[113]246 print "The user created scantables are:"
[585]247 sts = map(lambda x: x[0], filter(lambda x: isinstance(x[1], t), globs))
248 print filter(lambda x: not x.startswith('_'), sts)
[100]249
[113]250def commands():
[210]251 x = """
[113]252 [The scan container]
253 scantable - a container for integrations/scans
[182]254 (can open asap/rpfits/sdfits and ms files)
[113]255 copy - returns a copy of a scan
256 get_scan - gets a specific scan out of a scantable
257 summary - print info about the scantable contents
[255]258 set_cursor - set a specific Beam/IF/Pol 'cursor' for
259 further use
260 get_cursor - print out the current cursor position
[182]261 stats - get specified statistic of the spectra in
262 the scantable
263 stddev - get the standard deviation of the spectra
264 in the scantable
[113]265 get_tsys - get the TSys
266 get_time - get the timestamps of the integrations
[255]267 get_unit - get the currnt unit
[513]268 set_unit - set the abcissa unit to be used from this
269 point on
[255]270 get_abcissa - get the abcissa values and name for a given
271 row (time)
[113]272 set_freqframe - set the frame info for the Spectral Axis
273 (e.g. 'LSRK')
[276]274 set_doppler - set the doppler to be used from this point on
[240]275 set_instrument - set the instrument name
[255]276 get_fluxunit - get the brightness flux unit
[240]277 set_fluxunit - set the brightness flux unit
[188]278 create_mask - return an mask in the current unit
279 for the given region. The specified regions
280 are NOT masked
[255]281 get_restfreqs - get the current list of rest frequencies
282 set_restfreqs - set a list of rest frequencies
[403]283 lines - print list of known spectral lines
[113]284 flag_spectrum - flag a whole Beam/IF/Pol
[116]285 save - save the scantable to disk as either 'ASAP'
286 or 'SDFITS'
[486]287 nbeam,nif,nchan,npol - the number of beams/IFs/Pols/Chans
288 history - print the history of the scantable
[530]289 get_fit - get a fit which has been stored witnh the data
[513]290 average_time - return the (weighted) time average of a scan
291 or a list of scans
292 average_pol - average the polarisations together.
[113]293 The dimension won't be reduced and
294 all polarisations will contain the
295 averaged spectrum.
[676]296 auto_quotient - return the on/off quotient with
297 automatic detection of the on/off scans
[513]298 quotient - return the on/off quotient
299 scale - return a scan scaled by a given factor
300 add - return a scan with given value added
301 bin - return a scan with binned channels
302 resample - return a scan with resampled channels
303 smooth - return the spectrally smoothed scan
304 poly_baseline - fit a polynomial baseline to all Beams/IFs/Pols
[547]305 auto_poly_baseline - automatically fit a polynomial baseline
[513]306 gain_el - apply gain-elevation correction
307 opacity - apply opacity correction
308 convert_flux - convert to and from Jy and Kelvin brightness
[255]309 units
[513]310 freq_align - align spectra in frequency frame
311 rotate_xyphase - rotate XY phase of cross correlation
312 rotate_linpolphase - rotate the phase of the complex
313 polarization O=Q+iU correlation
314 [Math] Mainly functions which operate on more than one scantable
[100]315
[513]316 average_time - return the (weighted) time average
317 of a list of scans
318 quotient - return the on/off quotient
319 simple_math - simple mathematical operations on two scantables,
320 'add', 'sub', 'mul', 'div'
321 [Fitting]
[113]322 fitter
323 auto_fit - return a scan where the function is
324 applied to all Beams/IFs/Pols.
325 commit - return a new scan where the fits have been
326 commited.
327 fit - execute the actual fitting process
[530]328 store_fit - store the fit paramaters in the data (scantable)
[113]329 get_chi2 - get the Chi^2
330 set_scan - set the scantable to be fit
331 set_function - set the fitting function
332 set_parameters - set the parameters for the function(s), and
333 set if they should be held fixed during fitting
[513]334 set_gauss_parameters - same as above but specialised for individual
335 gaussian components
[113]336 get_parameters - get the fitted parameters
[513]337 plot - plot the resulting fit and/or components and
338 residual
[210]339 [Plotter]
340 asapplotter - a plotter for asap, default plotter is
341 called 'plotter'
342 plot - plot a (list of) scantable
[378]343 save - save the plot to a file ('png' ,'ps' or 'eps')
[210]344 set_mode - set the state of the plotter, i.e.
345 what is to be plotted 'colour stacked'
346 and what 'panelled'
[530]347 set_cursor - only plot a selected part of the data
348 set_range - set a 'zoom' window
[255]349 set_legend - specify user labels for the legend indeces
350 set_title - specify user labels for the panel indeces
351 set_ordinate - specify a user label for the ordinate
352 set_abcissa - specify a user label for the abcissa
[378]353 set_layout - specify the multi-panel layout (rows,cols)
[210]354
[182]355 [Reading files]
356 reader - access rpfits/sdfits files
357 read - read in integrations
358 summary - list info about all integrations
359
[113]360 [General]
361 commands - this command
362 print - print details about a variable
363 list_scans - list all scantables created bt the user
364 del - delete the given variable from memory
365 range - create a list of values, e.g.
366 range(3) = [0,1,2], range(2,5) = [2,3,4]
367 help - print help for one of the listed functions
368 execfile - execute an asap script, e.g. execfile('myscript')
[255]369 list_rcparameters - print out a list of possible values to be
[274]370 put into $HOME/.asaprc
[466]371 mask_and,mask_or,
372 mask_not - boolean operations on masks created with
373 scantable.create_mask
374
[210]375 Note:
376 How to use this with help:
377 # function 'summary'
378 [xxx] is just a category
379 Every 'sub-level' in this list should be replaces by a '.' Period when
380 using help
381 Example:
382 ASAP> help scantable # to get info on ths scantable
383 ASAP> help scantable.summary # to get help on the scantable's
384 ASAP> help average_time
385
[113]386 """
387 print x
388 return
389
[573]390print """Welcome to ASAP v%s (%s) - the ATNF Spectral Analysis Package
[100]391
392Please report any bugs to:
[555]393asap@atnf.csiro.au
[100]394
[378]395[IMPORTANT: ASAP is 0-based]
[113]396Type commands() to get a list of all available ASAP commands.
[573]397""" % (__version__, __date__)
Note: See TracBrowser for help on using the repository browser.