source: trunk/python/__init__.py@ 708

Last change on this file since 708 was 706, checked in by mar637, 19 years ago

various changes to enable non-gui plotting

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