source: trunk/python/__init__.py@ 1576

Last change on this file since 1576 was 1560, checked in by Malte Marquarding, 16 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
Line 
1"""
2This is the ATNF Single Dish Analysis package.
3
4"""
5import os,sys,shutil, platform
6
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]
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"]
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"):
27 os.environ["AIPSPATH"] = "%s %s somwhere" % ( asapdata, plf)
28# set up user space
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")
34 shutil.copyfile(asapdata+"/data/ipy_user_conf.py",
35 userdir+"/ipy_user_conf.py")
36 f = file(userdir+"/asapuserfuncs.py", "w")
37 f.close()
38 f = file(userdir+"/ipythonrc", "w")
39 f.close()
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
46# remove from namespace
47del asapdata, userdir, shutil, platform
48
49def _validate_bool(b):
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
57def _validate_int(s):
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
63def _asap_fname():
64 """
65 Return the path to the rc file
66
67 Search order:
68
69 * current working dir
70 * environ var ASAPRC
71 * HOME/.asaprc
72
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
92
93defaultParams = {
94 # general
95 'verbose' : [True, _validate_bool],
96 'useplotter' : [True, _validate_bool],
97 'insitu' : [True, _validate_bool],
98
99 # plotting
100 'plotter.gui' : [True, _validate_bool],
101 'plotter.stacking' : ['p', str],
102 'plotter.panelling' : ['s', str],
103 'plotter.colours' : ['', str],
104 'plotter.linestyles' : ['', str],
105 'plotter.decimate' : [False, _validate_bool],
106 'plotter.ganged' : [True, _validate_bool],
107 'plotter.histogram' : [False, _validate_bool],
108 'plotter.papertype' : ['A4', str],
109 'plotter.axesformatting' : ['mpl', str],
110
111 # scantable
112 'scantable.save' : ['ASAP', str],
113 'scantable.autoaverage' : [True, _validate_bool],
114 'scantable.freqframe' : ['LSRK', str], #default frequency frame
115 'scantable.verbosesummary' : [False, _validate_bool],
116 'scantable.storage' : ['memory', str],
117 'scantable.history' : [True, _validate_bool],
118 'scantable.reference' : ['.*(e|w|_R)$', str]
119 # fitter
120 }
121
122def list_rcparameters():
123
124 print """
125# general
126# print verbose output
127verbose : True
128
129# preload a default plotter
130useplotter : True
131
132# apply operations on the input scantable or return new one
133insitu : True
134
135# plotting
136
137# do we want a GUI or plot to a file
138plotter.gui : True
139
140# default mode for colour stacking
141plotter.stacking : Pol
142
143# default mode for panelling
144plotter.panelling : scan
145
146# push panels together, to share axis labels
147plotter.ganged : True
148
149# decimate the number of points plotted by a factor of
150# nchan/1024
151plotter.decimate : False
152
153# default colours/linestyles
154plotter.colours :
155plotter.linestyles :
156
157# enable/disable histogram plotting
158plotter.histogram : False
159
160# ps paper type
161plotter.papertype : A4
162
163# The formatting style of the xaxis
164plotter.axesformatting : 'mpl' (default) or 'asap' (for old versions of matplotlib)
165
166# scantable
167
168# default storage of scantable ('memory'/'disk')
169scantable.storage : memory
170
171# write history of each call to scantable
172scantable.history : True
173
174# default ouput format when saving
175scantable.save : ASAP
176
177# auto averaging on read
178scantable.autoaverage : True
179
180# default frequency frame to set when function
181# scantable.set_freqframe is called
182scantable.freqframe : LSRK
183
184# Control the level of information printed by summary
185scantable.verbosesummary : False
186
187# Control the identification of reference (off) scans
188# This is has to be a regular expression
189scantable.reference : .*(e|w|_R)$
190
191# Fitter
192"""
193
194def rc_params():
195 'Return the default params updated from the values in the rc file'
196
197 fname = _asap_fname()
198
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
204
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
215
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
221
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
228 except ValueError, msg:
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()])
237 print ('loaded rc file %s'%fname)
238
239 return ret
240
241
242# this is the instance used by the asap classes
243rcParams = rc_params()
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
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
252 name/value pairs, eg
253
254 rc('scantable', save='SDFITS')
255
256 sets the current rc params and is equivalent to
257
258 rcParams['scantable.save'] = 'SDFITS'
259
260 Use rcdefaults to restore the default rc params after changes.
261 """
262
263 aliases = {}
264
265 for k,v in kwargs.items():
266 name = aliases.get(k) or k
267 if len(group):
268 key = '%s.%s' % (group, name)
269 else:
270 key = name
271 if not rcParams.has_key(key):
272 raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % (key, group, name))
273
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
284def _n_bools(n, val):
285 return [ val for i in xrange(n) ]
286
287def _is_sequence_or_number(param, ptype=int):
288 if isinstance(param,tuple) or isinstance(param,list):
289 if len(param) == 0: return True # empty list
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
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
305
306def unique(x):
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 """
316 return dict([ (val, 1) for val in x]).keys()
317
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
333 valid = "rpf rpf.1 rpf.2 sdf sdfits mbf asap".split()
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
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
346asaplog=_asaplog()
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
357def mask_and(a, b):
358 assert(len(a)==len(b))
359 return [ a[i] & b[i] for i in xrange(len(a)) ]
360
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
368from asapfitter import fitter
369from asapreader import reader
370from selector import selector
371
372from asapmath import *
373from scantable import scantable
374from asaplinefind import linefinder
375from linecatalog import linecatalog
376
377if rcParams['useplotter']:
378 try:
379 from asapplotter import asapplotter
380 gui = os.environ.has_key('DISPLAY') and rcParams['plotter.gui']
381 if gui:
382 import matplotlib
383 matplotlib.use("TkAgg")
384 import pylab
385 xyplotter = pylab
386 plotter = asapplotter(gui)
387 del gui
388 except ImportError:
389 print "Matplotlib not installed. No plotting available"
390
391__date__ = '$Date: 2009-03-31 01:13:51 +0000 (Tue, 31 Mar 2009) $'.split()[1]
392__version__ = '$Revision: 1560 $'
393
394def is_ipython():
395 return '__IP' in dir(sys.modules["__main__"])
396if is_ipython():
397 def version(): print "ASAP %s(%s)"% (__version__, __date__)
398
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
407
408 def commands():
409 x = """
410 [The scan container]
411 scantable - a container for integrations/scans
412 (can open asap/rpfits/sdfits and ms files)
413 copy - returns a copy of a scan
414 get_scan - gets a specific scan out of a scantable
415 (by name or number)
416 drop_scan - drops a specific scan out of a scantable
417 (by number)
418 set_selection - set a new subselection of the data
419 get_selection - get the current selection object
420 summary - print info about the scantable contents
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
425 get_tsys - get the TSys
426 get_time - get the timestamps of the integrations
427 get_inttime - get the integration time
428 get_sourcename - get the source names of the scans
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
432 get_unit - get the current unit
433 set_unit - set the abcissa unit to be used from this
434 point on
435 get_abcissa - get the abcissa values and name for a given
436 row (time)
437 get_column_names - get the names of the columns in the scantable
438 for use with selector.set_query
439 set_freqframe - set the frame info for the Spectral Axis
440 (e.g. 'LSRK')
441 set_doppler - set the doppler to be used from this point on
442 set_dirframe - set the frame for the direction on the sky
443 set_instrument - set the instrument name
444 set_feedtype - set the feed type
445 get_fluxunit - get the brightness flux unit
446 set_fluxunit - set the brightness flux unit
447 set_sourcetype - set the type of the source - source or reference
448 create_mask - return an mask in the current unit
449 for the given region. The specified regions
450 are NOT masked
451 get_restfreqs - get the current list of rest frequencies
452 set_restfreqs - set a list of rest frequencies
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
457 flag - flag selected channels in the data
458 lag_flag - flag specified frequency in the data
459 save - save the scantable to disk as either 'ASAP',
460 'SDFITS' or 'ASCII'
461 nbeam,nif,nchan,npol - the number of beams/IFs/Pols/Chans
462 nscan - the number of scans in the scantable
463 nrow - the number of spectra in the scantable
464 history - print the history of the scantable
465 get_fit - get a fit which has been stored witnh the data
466 average_time - return the (weighted) time average of a scan
467 or a list of scans
468 average_pol - average the polarisations together.
469 average_beam - average the beams together.
470 convert_pol - convert to a different polarisation type
471 auto_quotient - return the on/off quotient with
472 automatic detection of the on/off scans (closest
473 in time off is selected)
474 mx_quotient - Form a quotient using MX data (off beams)
475 scale, *, / - return a scan scaled by a given factor
476 add, + - return a scan with given value added
477 sub, - - return a scan with given value subtracted
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
482 auto_poly_baseline - automatically fit a polynomial baseline
483 recalc_azel - recalculate azimuth and elevation based on
484 the pointing
485 gain_el - apply gain-elevation correction
486 opacity - apply opacity correction
487 convert_flux - convert to and from Jy and Kelvin brightness
488 units
489 freq_align - align spectra in frequency frame
490 invert_phase - Invert the phase of the cross-correlation
491 swap_linears - Swap XX and YY (or RR LL)
492 rotate_xyphase - rotate XY phase of cross correlation
493 rotate_linpolphase - rotate the phase of the complex
494 polarization O=Q+iU correlation
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
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
510 set_query - set a selection by SQL-like query, e.g. BEAMNO==1
511 ( also get_ functions for all these )
512 reset - unset all selections
513 + - merge two selections
514
515 [Math] Mainly functions which operate on more than one scantable
516
517 average_time - return the (weighted) time average
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'
522 quotient - build quotient of the given on and off scans
523 (matched pairs and 1 off - n on are valid)
524 merge - merge a list of scantables
525
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
538 [Fitting]
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
545 store_fit - store the fit parameters in the data (scantable)
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
551 set_gauss_parameters - same as above but specialised for individual
552 gaussian components
553 get_parameters - get the fitted parameters
554 plot - plot the resulting fit and/or components and
555 residual
556 [Plotter]
557 asapplotter - a plotter for asap, default plotter is
558 called 'plotter'
559 plot - plot a scantable
560 plot_lines - plot a linecatalog overlay
561 save - save the plot to a file ('png' ,'ps' or 'eps')
562 set_mode - set the state of the plotter, i.e.
563 what is to be plotted 'colour stacked'
564 and what 'panelled'
565 set_selection - only plot a selected part of the data
566 set_range - set a 'zoom' window [xmin,xmax,ymin,ymax]
567 set_legend - specify user labels for the legend indeces
568 set_title - specify user labels for the panel indeces
569 set_abcissa - specify a user label for the abcissa
570 set_ordinate - specify a user label for the ordinate
571 set_layout - specify the multi-panel layout (rows,cols)
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
575 set_font - set general font properties, e.g. 'family'
576 set_histogram - plot in historam style
577 set_mask - set a plotting mask for a specific polarization
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
584 annotate - draw an arrow with label
585 create_mask - create a scnatble mask interactively
586
587 xyplotter - matplotlib/pylab plotting functions
588
589 [Reading files]
590 reader - access rpfits/sdfits files
591 open - attach reader to a file
592 close - detach reader from file
593 read - read in integrations
594 summary - list info about all integrations
595
596 [General]
597 commands - this command
598 print - print details about a variable
599 list_scans - list all scantables created by the user
600 list_files - list all files readable by asap (default rpf)
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')
606 list_rcparameters - print out a list of possible values to be
607 put into $HOME/.asaprc
608 rc - set rc parameters from within asap
609 mask_and,mask_or,
610 mask_not - boolean operations on masks created with
611 scantable.create_mask
612
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
618 using help
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
624 """
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
633 return
634
635def welcome():
636 return """Welcome to ASAP v%s (%s) - the ATNF Spectral Analysis Package
637
638Please report any bugs via:
639http://svn.atnf.csiro.au/trac/asap/simpleticket
640
641[IMPORTANT: ASAP is 0-based]
642Type commands() to get a list of all available ASAP commands.""" % (__version__, __date__)
Note: See TracBrowser for help on using the repository browser.