source: trunk/python/__init__.py@ 1524

Last change on this file since 1524 was 1523, checked in by Malte Marquarding, 16 years ago

change version for release

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