source: trunk/python/__init__.py@ 1576

Last change on this file since 1576 was 1560, checked in by Malte Marquarding, 15 years ago

minor doc fixes; fixed list_scans, which seems brokrn in latest ipython; rc parameter xaxisformatting -> axesformatting; fixed font settings for matplotlib rc parameters

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