source: trunk/python/__init__.py@ 1101

Last change on this file since 1101 was 1097, checked in by mar637, 18 years ago

reduced number of * imports. added plotter.papertype to rcparams

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.9 KB
RevLine 
[100]1"""
2This is the ATNF Single Dish Analysis package.
3
4"""
[1080]5import os,sys,shutil, platform
[226]6
[1080]7# Set up AIPSPATH and first time use of asap i.e. ~/.asap/*
8plf = None
9if sys.platform == "linux2":
10 if platform.architecture()[0] == '64bit':
11 plf = 'linux_64b'
12 else:
13 plf = 'linux_gnu'
14elif sys.platform == 'darwin':
15 plf = 'darwin'
16else:
17 # Shouldn't happen - default to linux
18 plf = 'linux'
19asapdata = __path__[-1]
20os.environ["AIPSPATH"] = "%s %s somwhere" % ( asapdata, plf)
21userdir = os.environ["HOME"]+"/.asap"
22if not os.path.exists(userdir):
23 print 'First time ASAP use. Setting up ~/.asap'
24 os.mkdir(userdir)
25 shutil.copyfile(asapdata+"/data/ipythonrc-asap", userdir+"/ipythonrc-asap")
26 f = file(userdir+"/asapuserfuncs.py", "w")
27 f.close()
28 f = file(userdir+"/ipythonrc", "w")
29 f.close()
30del asapdata, userdir, shutil, platform
31
[513]32def _validate_bool(b):
[226]33 'Convert b to a boolean or raise'
34 bl = b.lower()
35 if bl in ('f', 'no', 'false', '0', 0): return False
36 elif bl in ('t', 'yes', 'true', '1', 1): return True
37 else:
38 raise ValueError('Could not convert "%s" to boolean' % b)
39
[513]40def _validate_int(s):
[226]41 'convert s to int or raise'
42 try: return int(s)
43 except ValueError:
44 raise ValueError('Could not convert "%s" to int' % s)
45
[513]46def _asap_fname():
[226]47 """
48 Return the path to the rc file
49
50 Search order:
51
52 * current working dir
53 * environ var ASAPRC
[274]54 * HOME/.asaprc
[706]55
[226]56 """
57
58 fname = os.path.join( os.getcwd(), '.asaprc')
59 if os.path.exists(fname): return fname
60
61 if os.environ.has_key('ASAPRC'):
62 path = os.environ['ASAPRC']
63 if os.path.exists(path):
64 fname = os.path.join(path, '.asaprc')
65 if os.path.exists(fname):
66 return fname
67
68 if os.environ.has_key('HOME'):
69 home = os.environ['HOME']
70 fname = os.path.join(home, '.asaprc')
71 if os.path.exists(fname):
72 return fname
73 return None
74
[706]75
[226]76defaultParams = {
77 # general
[513]78 'verbose' : [True, _validate_bool],
79 'useplotter' : [True, _validate_bool],
[542]80 'insitu' : [True, _validate_bool],
[706]81
[226]82 # plotting
[706]83 'plotter.gui' : [True, _validate_bool],
[226]84 'plotter.stacking' : ['p', str],
85 'plotter.panelling' : ['s', str],
[700]86 'plotter.colours' : ['', str],
87 'plotter.linestyles' : ['', str],
[710]88 'plotter.decimate' : [False, _validate_bool],
89 'plotter.ganged' : [True, _validate_bool],
[1022]90 'plotter.histogram' : [False, _validate_bool],
[1097]91 'plotter.papertype' : ['A4', str],
[710]92
[226]93 # scantable
94 'scantable.save' : ['ASAP', str],
[513]95 'scantable.autoaverage' : [True, _validate_bool],
[226]96 'scantable.freqframe' : ['LSRK', str], #default frequency frame
[1076]97 'scantable.verbosesummary' : [False, _validate_bool],
98 'scantable.storage' : ['memory', str]
[226]99 # fitter
100 }
101
[255]102def list_rcparameters():
[706]103
[255]104 print """
[737]105# general
106# print verbose output
107verbose : True
[255]108
[737]109# preload a default plotter
110useplotter : True
[255]111
[737]112# apply operations on the input scantable or return new one
113insitu : True
[706]114
[737]115# plotting
[710]116
[737]117# do we want a GUI or plot to a file
118plotter.gui : True
[710]119
[737]120# default mode for colour stacking
121plotter.stacking : Pol
[255]122
[737]123# default mode for panelling
124plotter.panelling : scan
[255]125
[737]126# push panels together, to share axislabels
127plotter.ganged : True
[710]128
[737]129# decimate the number of points plotted bya afactor of
130# nchan/1024
131plotter.decimate : False
[733]132
[737]133# default colours/linestyles
134plotter.colours :
135plotter.linestyles :
[700]136
[1022]137# enable/disable histogram plotting
138plotter.histogram : False
139
[1097]140# ps paper type
141plotter.papertype : A4
142
[737]143# scantable
[1076]144
145# default storage of scantable (memory/disk)
146scantable.storage : memory
[737]147# default ouput format when saving
148scantable.save : ASAP
149# auto averaging on read
150scantable.autoaverage : True
[255]151
[737]152# default frequency frame to set when function
[1097]153# scantable.set_freqframe is called
[737]154scantable.freqframe : LSRK
[255]155
[737]156# Control the level of information printed by summary
157scantable.verbosesummary : False
[706]158
[737]159# Fitter
160"""
[706]161
[226]162def rc_params():
163 'Return the default params updated from the values in the rc file'
[706]164
[513]165 fname = _asap_fname()
[706]166
[226]167 if fname is None or not os.path.exists(fname):
168 message = 'could not find rc file; returning defaults'
169 ret = dict([ (key, tup[0]) for key, tup in defaultParams.items()])
170 #print message
171 return ret
[706]172
[226]173 cnt = 0
174 for line in file(fname):
175 cnt +=1
176 line = line.strip()
177 if not len(line): continue
178 if line.startswith('#'): continue
179 tup = line.split(':',1)
180 if len(tup) !=2:
181 print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
182 continue
[706]183
[226]184 key, val = tup
185 key = key.strip()
186 if not defaultParams.has_key(key):
187 print ('Bad key "%s" on line %d in %s' % (key, cnt, fname))
188 continue
[706]189
[226]190 default, converter = defaultParams[key]
191
192 ind = val.find('#')
193 if ind>=0: val = val[:ind] # ignore trailing comments
194 val = val.strip()
195 try: cval = converter(val) # try to convert to proper type or raise
[1080]196 except ValueError, msg:
[226]197 print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg))
198 continue
199 else:
200 # Alles Klar, update dict
201 defaultParams[key][0] = cval
202
203 # strip the conveter funcs and return
204 ret = dict([ (key, tup[0]) for key, tup in defaultParams.items()])
[466]205 print ('loaded rc file %s'%fname)
[226]206
207 return ret
208
209
210# this is the instance used by the asap classes
[706]211rcParams = rc_params()
[226]212
213rcParamsDefault = dict(rcParams.items()) # a copy
214
215def rc(group, **kwargs):
216 """
217 Set the current rc params. Group is the grouping for the rc, eg
[379]218 for scantable.save the group is 'scantable', for plotter.stacking, the
219 group is 'plotter', and so on. kwargs is a list of attribute
[226]220 name/value pairs, eg
221
[379]222 rc('scantable', save='SDFITS')
[226]223
224 sets the current rc params and is equivalent to
[706]225
[379]226 rcParams['scantable.save'] = 'SDFITS'
[226]227
228 Use rcdefaults to restore the default rc params after changes.
229 """
230
[379]231 aliases = {}
[706]232
[226]233 for k,v in kwargs.items():
234 name = aliases.get(k) or k
235 key = '%s.%s' % (group, name)
236 if not rcParams.has_key(key):
237 raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % (key, group, name))
[706]238
[226]239 rcParams[key] = v
240
241
242def rcdefaults():
243 """
244 Restore the default rc params - the ones that were created at
245 asap load time
246 """
247 rcParams.update(rcParamsDefault)
248
[513]249
250def _is_sequence_or_number(param, ptype=int):
251 if isinstance(param,tuple) or isinstance(param,list):
[928]252 if len(param) == 0: return True # empty list
[513]253 out = True
254 for p in param:
255 out &= isinstance(p,ptype)
256 return out
257 elif isinstance(param, ptype):
258 return True
259 return False
260
[928]261def _to_list(param, ptype=int):
262 if isinstance(param, ptype):
263 if ptype is str: return param.split()
264 else: return [param]
265 if _is_sequence_or_number(param, ptype):
266 return param
267 return None
[715]268
[944]269def unique(x):
[992]270 """
271 Return the unique values in a list
272 Parameters:
273 x: the list to reduce
274 Examples:
275 x = [1,2,3,3,4]
276 print unique(x)
277 [1,2,3,4]
278 """
[944]279 return dict([ (val, 1) for val in x]).keys()
280
[992]281def list_files(path=".",suffix="rpf"):
282 """
283 Return a list files readable by asap, such as rpf, sdfits, mbf, asap
284 Parameters:
285 path: The directory to list (default '.')
286 suffix: The file extension (default rpf)
287 Example:
288 files = list_files("data/","sdfits")
289 print files
290 ['data/2001-09-01_0332_P363.sdfits',
291 'data/2003-04-04_131152_t0002.sdfits',
292 'data/Sgr_86p262_best_SPC.sdfits']
293 """
294 import os
295 if not os.path.isdir(path):
296 return None
297 valid = "rpf sdf sdfits mbf asap".split()
298 if not suffix in valid:
299 return None
300 files = [os.path.expanduser(os.path.expandvars(path+"/"+f)) for f in os.listdir(path)]
301 return filter(lambda x: x.endswith(suffix),files)
302
[715]303# workaround for ipython, which redirects this if banner=0 in ipythonrc
304sys.stdout = sys.__stdout__
305sys.stderr = sys.__stderr__
306
307# Logging
308from asap._asap import Log as _asaplog
309global asaplog
[710]310asaplog=_asaplog()
[715]311if rcParams['verbose']:
312 asaplog.enable()
313else:
314 asaplog.disable()
315
316def print_log():
317 log = asaplog.pop()
318 if len(log) and rcParams['verbose']: print log
319 return
320
[1097]321from asapfitter import fitter as asapfitter
[895]322from asapreader import reader
[944]323from selector import selector
[710]324
[100]325from asapmath import *
[1080]326from scantable import scantable
[1097]327from asaplinefind import linefinder
[876]328#from asapfit import *
[285]329
[466]330from numarray import logical_and as mask_and
331from numarray import logical_or as mask_or
332from numarray import logical_not as mask_not
333
[928]334if rcParams['useplotter']:
[1097]335 from asapplotter import asapplotter
[928]336 gui = os.environ.has_key('DISPLAY') and rcParams['plotter.gui']
337 plotter = asapplotter(gui)
338 del gui
[285]339
[1069]340
[574]341__date__ = '$Date: 2006-07-31 02:21:46 +0000 (Mon, 31 Jul 2006) $'.split()[1]
[1069]342__version__ = '2.1a'
[100]343
[706]344if rcParams['verbose']:
[1014]345 def version(): print "ASAP %s(%s)"% (__version__, __date__)
[706]346 def list_scans(t = scantable):
347 import sys, types
348 globs = sys.modules['__main__'].__dict__.iteritems()
349 print "The user created scantables are:"
350 sts = map(lambda x: x[0], filter(lambda x: isinstance(x[1], t), globs))
351 print filter(lambda x: not x.startswith('_'), sts)
352 return
[100]353
[715]354 def commands():
355 x = """
[113]356 [The scan container]
357 scantable - a container for integrations/scans
[182]358 (can open asap/rpfits/sdfits and ms files)
[113]359 copy - returns a copy of a scan
360 get_scan - gets a specific scan out of a scantable
[984]361 (by name or number)
[1093]362 drop_scan - drops a specific scan out of a scantable
363 (by number)
[984]364 set_selection - set a new subselection of the data
365 get_selection - get the current selection object
[113]366 summary - print info about the scantable contents
[182]367 stats - get specified statistic of the spectra in
368 the scantable
369 stddev - get the standard deviation of the spectra
370 in the scantable
[113]371 get_tsys - get the TSys
372 get_time - get the timestamps of the integrations
[733]373 get_sourcename - get the source names of the scans
[794]374 get_azimuth - get the azimuth of the scans
375 get_elevation - get the elevation of the scans
376 get_parangle - get the parallactic angle of the scans
[876]377 get_unit - get the current unit
[513]378 set_unit - set the abcissa unit to be used from this
379 point on
[255]380 get_abcissa - get the abcissa values and name for a given
381 row (time)
[113]382 set_freqframe - set the frame info for the Spectral Axis
383 (e.g. 'LSRK')
[276]384 set_doppler - set the doppler to be used from this point on
[984]385 set_dirframe - set the frame for the direction on the sky
[240]386 set_instrument - set the instrument name
[255]387 get_fluxunit - get the brightness flux unit
[240]388 set_fluxunit - set the brightness flux unit
[188]389 create_mask - return an mask in the current unit
390 for the given region. The specified regions
391 are NOT masked
[255]392 get_restfreqs - get the current list of rest frequencies
393 set_restfreqs - set a list of rest frequencies
[1012]394 flag - flag selected channels in the data
[116]395 save - save the scantable to disk as either 'ASAP'
396 or 'SDFITS'
[486]397 nbeam,nif,nchan,npol - the number of beams/IFs/Pols/Chans
[733]398 nscan - the number of scans in the scantable
[984]399 nrow - te number of spectra in the scantable
[486]400 history - print the history of the scantable
[530]401 get_fit - get a fit which has been stored witnh the data
[706]402 average_time - return the (weighted) time average of a scan
[513]403 or a list of scans
[1069]404 average_channel - return the (median) average of a scantable
[513]405 average_pol - average the polarisations together.
[113]406 The dimension won't be reduced and
407 all polarisations will contain the
408 averaged spectrum.
[992]409 convert_pol - convert to a different polarisation type
[690]410 auto_quotient - return the on/off quotient with
[1069]411 automatic detection of the on/off scans (closest
412 in time off is selected)
[1014]413 scale, *, / - return a scan scaled by a given factor
414 add, +, - - return a scan with given value added
[513]415 bin - return a scan with binned channels
416 resample - return a scan with resampled channels
417 smooth - return the spectrally smoothed scan
418 poly_baseline - fit a polynomial baseline to all Beams/IFs/Pols
[706]419 auto_poly_baseline - automatically fit a polynomial baseline
[780]420 recalc_azel - recalculate azimuth and elevation based on
421 the pointing
[513]422 gain_el - apply gain-elevation correction
423 opacity - apply opacity correction
424 convert_flux - convert to and from Jy and Kelvin brightness
[255]425 units
[513]426 freq_align - align spectra in frequency frame
[1014]427 invert_phase - Invert the phase of the cross-correlation
428 swap_linears - Swap XX and YY
[513]429 rotate_xyphase - rotate XY phase of cross correlation
430 rotate_linpolphase - rotate the phase of the complex
431 polarization O=Q+iU correlation
[733]432 freq_switch - perform frequency switching on the data
433 stats - Determine the specified statistic, e.g. 'min'
434 'max', 'rms' etc.
435 stddev - Determine the standard deviation of the current
436 beam/if/pol
[1014]437 [Selection]
438 selector - a selection object to set a subset of a scantable
439 set_scans - set (a list of) scans by index
440 set_cycles - set (a list of) cycles by index
441 set_beams - set (a list of) beamss by index
442 set_ifs - set (a list of) ifs by index
443 set_polarisations - set (a list of) polarisations by name
444 or by index
445 set_names - set a selection by name (wildcards allowed)
446 set_tsys - set a selection by tsys thresholds
447 reset - unset all selections
448 + - merge to selections
[733]449
[513]450 [Math] Mainly functions which operate on more than one scantable
[100]451
[706]452 average_time - return the (weighted) time average
[513]453 of a list of scans
454 quotient - return the on/off quotient
455 simple_math - simple mathematical operations on two scantables,
456 'add', 'sub', 'mul', 'div'
[1069]457 quotient - build quotient of the given on and off scans
458 (matched pairs and 1 off/n on are valid)
459
[513]460 [Fitting]
[113]461 fitter
462 auto_fit - return a scan where the function is
463 applied to all Beams/IFs/Pols.
464 commit - return a new scan where the fits have been
465 commited.
466 fit - execute the actual fitting process
[984]467 store_fit - store the fit parameters in the data (scantable)
[113]468 get_chi2 - get the Chi^2
469 set_scan - set the scantable to be fit
470 set_function - set the fitting function
471 set_parameters - set the parameters for the function(s), and
472 set if they should be held fixed during fitting
[513]473 set_gauss_parameters - same as above but specialised for individual
474 gaussian components
[113]475 get_parameters - get the fitted parameters
[513]476 plot - plot the resulting fit and/or components and
477 residual
[210]478 [Plotter]
479 asapplotter - a plotter for asap, default plotter is
480 called 'plotter'
[984]481 plot - plot a scantable
[378]482 save - save the plot to a file ('png' ,'ps' or 'eps')
[210]483 set_mode - set the state of the plotter, i.e.
484 what is to be plotted 'colour stacked'
485 and what 'panelled'
[984]486 set_selection - only plot a selected part of the data
[733]487 set_range - set a 'zoom' window [xmin,xmax,ymin,ymax]
[255]488 set_legend - specify user labels for the legend indeces
489 set_title - specify user labels for the panel indeces
[733]490 set_abcissa - specify a user label for the abcissa
[255]491 set_ordinate - specify a user label for the ordinate
[378]492 set_layout - specify the multi-panel layout (rows,cols)
[733]493 set_colors - specify a set of colours to use
494 set_linestyles - specify a set of linestyles to use if only
495 using one color
[1054]496 set_histogram - plot in historam style
[733]497 set_mask - set a plotting mask for a specific polarization
[706]498
[182]499 [Reading files]
500 reader - access rpfits/sdfits files
[984]501 open - attach reader to a file
502 close - detach reader from file
[182]503 read - read in integrations
504 summary - list info about all integrations
505
[113]506 [General]
507 commands - this command
508 print - print details about a variable
509 list_scans - list all scantables created bt the user
[992]510 list_files - list all files readable by asap (default rpf)
[113]511 del - delete the given variable from memory
512 range - create a list of values, e.g.
513 range(3) = [0,1,2], range(2,5) = [2,3,4]
514 help - print help for one of the listed functions
515 execfile - execute an asap script, e.g. execfile('myscript')
[255]516 list_rcparameters - print out a list of possible values to be
[274]517 put into $HOME/.asaprc
[466]518 mask_and,mask_or,
519 mask_not - boolean operations on masks created with
520 scantable.create_mask
[706]521
[210]522 Note:
523 How to use this with help:
524 # function 'summary'
525 [xxx] is just a category
526 Every 'sub-level' in this list should be replaces by a '.' Period when
[706]527 using help
[210]528 Example:
529 ASAP> help scantable # to get info on ths scantable
530 ASAP> help scantable.summary # to get help on the scantable's
531 ASAP> help average_time
532
[715]533 """
534 print x
535 return
[113]536
[706]537def welcome():
538 return """Welcome to ASAP v%s (%s) - the ATNF Spectral Analysis Package
[100]539
[1035]540Please report any bugs via:
541http://sourcecode.atnf.csiro.au/cgi-bin/trac_asap.cgi/newticket
[100]542
[378]543[IMPORTANT: ASAP is 0-based]
[706]544Type commands() to get a list of all available ASAP commands.""" % (__version__, __date__)
Note: See TracBrowser for help on using the repository browser.