- Timestamp:
- 08/02/10 19:40:09 (14 years ago)
- Location:
- trunk
- Files:
-
- 3 added
- 5 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/python/__init__.py
r1819 r1824 3 3 4 4 """ 5 import os,sys,shutil, platform 6 try: 7 from functools import wraps as wraps_dec 8 except ImportError: 9 from asap.compatibility import wraps as wraps_dec 5 import os 6 import sys 10 7 11 # Set up CASAPATH and first time use of asap i.e. ~/.asap/* 12 plf = None 13 if sys.platform == "linux2": 14 if platform.architecture()[0] == '64bit': 15 plf = 'linux_64b' 16 else: 17 plf = 'linux_gnu' 18 elif sys.platform == 'darwin': 19 plf = 'darwin' 20 else: 21 # Shouldn't happen - default to linux 22 plf = 'linux' 23 asapdata = __path__[-1] 24 # Allow user defined data location 25 if os.environ.has_key("ASAPDATA"): 26 if os.path.exists(os.environ["ASAPDATA"]): 27 asapdata = os.environ["ASAPDATA"] 28 # use CASAPATH if defined and "data" dir present 29 if not os.environ.has_key("CASAPATH") or \ 30 not os.path.exists(os.environ["CASAPATH"].split()[0]+"/data"): 31 os.environ["CASAPATH"] = "%s %s somwhere" % ( asapdata, plf) 32 # set up user space 33 userdir = os.environ["HOME"]+"/.asap" 34 if not os.path.exists(userdir): 35 print 'First time ASAP use. Setting up ~/.asap' 36 os.mkdir(userdir) 37 #shutil.copyfile(asapdata+"/data/ipythonrc-asap", userdir+"/ipythonrc-asap") 38 # commented out by TT on 2009.06.23 for casapy use 39 ##shutil.copyfile(asapdata+"/data/ipy_user_conf.py", 40 ## userdir+"/ipy_user_conf.py") 41 f = file(userdir+"/asapuserfuncs.py", "w") 42 f.close() 43 f = file(userdir+"/ipythonrc", "w") 44 f.close() 45 # commented out by TT on 2009.06.23 for casapy use 46 ##else: 47 # upgrade to support later ipython versions 48 ##if not os.path.exists(userdir+"/ipy_user_conf.py"): 49 ## shutil.copyfile(asapdata+"/data/ipy_user_conf.py", 50 ## userdir+"/ipy_user_conf.py") 51 52 # remove from namespace 53 del asapdata, userdir, shutil, platform 54 55 def _validate_bool(b): 56 'Convert b to a boolean or raise' 57 bl = b.lower() 58 if bl in ('f', 'no', 'false', '0', 0): return False 59 elif bl in ('t', 'yes', 'true', '1', 1): return True 60 else: 61 raise ValueError('Could not convert "%s" to boolean' % b) 62 63 def _validate_int(s): 64 'convert s to int or raise' 65 try: return int(s) 66 except ValueError: 67 raise ValueError('Could not convert "%s" to int' % s) 68 69 def _asap_fname(): 70 """ 71 Return the path to the rc file 72 73 Search order: 74 75 * current working dir 76 * environ var ASAPRC 77 * HOME/.asaprc 78 79 """ 80 fname = os.path.join( os.getcwd(), '.asaprc') 81 if os.path.exists(fname): return fname 82 83 if os.environ.has_key('ASAPRC'): 84 path = os.environ['ASAPRC'] 85 if os.path.exists(path): 86 fname = os.path.join(path, '.asaprc') 87 if os.path.exists(fname): 88 return fname 89 90 if os.environ.has_key('HOME'): 91 home = os.environ['HOME'] 92 fname = os.path.join(home, '.asaprc') 93 if os.path.exists(fname): 94 return fname 95 return None 8 # first import! 9 from asap.env import * 10 # second import! 11 from asap.logging import * 12 from asap.parameters import * 13 from asap.utils import * 14 # explicitly import 'hidden' functions 15 from asap.utils import _n_bools, _is_sequence_or_number, _to_list 96 16 97 17 98 defaultParams = { 99 # general 100 'verbose' : [True, _validate_bool], 101 'useplotter' : [True, _validate_bool], 102 'insitu' : [True, _validate_bool], 18 if is_ipython(): 19 from ipysupport import * 103 20 104 # plotting 105 'plotter.gui' : [True, _validate_bool], 106 'plotter.stacking' : ['p', str], 107 'plotter.panelling' : ['s', str], 108 'plotter.colours' : ['', str], 109 'plotter.linestyles' : ['', str], 110 'plotter.decimate' : [False, _validate_bool], 111 'plotter.ganged' : [True, _validate_bool], 112 'plotter.histogram' : [False, _validate_bool], 113 'plotter.papertype' : ['A4', str], 114 ## for older Matplotlib version 115 #'plotter.axesformatting' : ['mpl', str], 116 'plotter.axesformatting' : ['asap', str], 21 # use rc parameter to enable/disable logging 22 asaplog.enable(rcParams['verbose']) 117 23 118 # scantable 119 'scantable.save' : ['ASAP', str], 120 'scantable.autoaverage' : [True, _validate_bool], 121 'scantable.freqframe' : ['LSRK', str], #default frequency frame 122 'scantable.verbosesummary' : [False, _validate_bool], 123 'scantable.storage' : ['memory', str], 124 'scantable.history' : [True, _validate_bool], 125 'scantable.reference' : ['.*(e|w|_R)$', str], 126 'scantable.parallactify' : [False, _validate_bool] 127 # fitter 128 } 24 setup_env() 129 25 130 def list_rcparameters(): 26 # anything which uses matplotlib has to be imported after this!!! 27 if rcParams['useplotter']: 28 try: 29 gui = os.environ.has_key('DISPLAY') and rcParams['plotter.gui'] 30 if gui: 31 import matplotlib 32 if 'matplotlib.backends' not in matplotlib.sys.modules: 33 matplotlib.use("TkAgg") 34 from asapplotter import asapplotter 35 from matplotlib import pylab 36 xyplotter = pylab 37 plotter = asapplotter(gui) 38 except ImportError: 39 asaplog.post( "Matplotlib not installed. No plotting available") 40 print_log('WARN') 131 41 132 print """133 # general134 # print verbose output135 verbose : True136 137 # preload a default plotter138 useplotter : True139 140 # apply operations on the input scantable or return new one141 insitu : True142 143 # plotting144 145 # do we want a GUI or plot to a file146 plotter.gui : True147 148 # default mode for colour stacking149 plotter.stacking : Pol150 151 # default mode for panelling152 plotter.panelling : scan153 154 # push panels together, to share axis labels155 plotter.ganged : True156 157 # decimate the number of points plotted by a factor of158 # nchan/1024159 plotter.decimate : False160 161 # default colours/linestyles162 plotter.colours :163 plotter.linestyles :164 165 # enable/disable histogram plotting166 plotter.histogram : False167 168 # ps paper type169 plotter.papertype : A4170 171 # The formatting style of the xaxis172 plotter.axesformatting : 'mpl' (default) or 'asap' (for old versions of matplotlib)173 174 # scantable175 176 # default storage of scantable ('memory'/'disk')177 scantable.storage : memory178 179 # write history of each call to scantable180 scantable.history : True181 182 # default ouput format when saving183 scantable.save : ASAP184 185 # auto averaging on read186 scantable.autoaverage : True187 188 # default frequency frame to set when function189 # scantable.set_freqframe is called190 scantable.freqframe : LSRK191 192 # Control the level of information printed by summary193 scantable.verbosesummary : False194 195 # Control the identification of reference (off) scans196 # This is has to be a regular expression197 scantable.reference : .*(e|w|_R)$198 199 # Indicate whether the data was parallactified (total phase offest == 0.0)200 scantable.parallactify : False201 202 # Fitter203 """204 205 def rc_params():206 'Return the default params updated from the values in the rc file'207 208 fname = _asap_fname()209 210 if fname is None or not os.path.exists(fname):211 message = 'could not find rc file; returning defaults'212 ret = dict([ (key, tup[0]) for key, tup in defaultParams.items()])213 #print message214 return ret215 216 cnt = 0217 for line in file(fname):218 cnt +=1219 line = line.strip()220 if not len(line): continue221 if line.startswith('#'): continue222 tup = line.split(':',1)223 if len(tup) !=2:224 #print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))225 asaplog.push('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))226 print_log('WARN')227 continue228 229 key, val = tup230 key = key.strip()231 if not defaultParams.has_key(key):232 #print ('Bad key "%s" on line %d in %s' % (key, cnt, fname))233 asaplog.push('Bad key "%s" on line %d in %s' % (key, cnt, fname))234 print_log('WARN')235 continue236 237 default, converter = defaultParams[key]238 239 ind = val.find('#')240 if ind>=0: val = val[:ind] # ignore trailing comments241 val = val.strip()242 try: cval = converter(val) # try to convert to proper type or raise243 except ValueError, msg:244 #print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg))245 asaplog.push('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, str(msg)))246 print_log('WARN')247 continue248 else:249 # Alles Klar, update dict250 defaultParams[key][0] = cval251 252 # strip the conveter funcs and return253 ret = dict([ (key, tup[0]) for key, tup in defaultParams.items()])254 print ('loaded rc file %s'%fname)255 256 return ret257 258 259 # this is the instance used by the asap classes260 rcParams = rc_params()261 262 rcParamsDefault = dict(rcParams.items()) # a copy263 264 def rc(group, **kwargs):265 """266 Set the current rc params. Group is the grouping for the rc, eg267 for scantable.save the group is 'scantable', for plotter.stacking, the268 group is 'plotter', and so on. kwargs is a list of attribute269 name/value pairs, eg270 271 rc('scantable', save='SDFITS')272 273 sets the current rc params and is equivalent to274 275 rcParams['scantable.save'] = 'SDFITS'276 277 Use rcdefaults to restore the default rc params after changes.278 """279 280 aliases = {}281 282 for k,v in kwargs.items():283 name = aliases.get(k) or k284 if len(group):285 key = '%s.%s' % (group, name)286 else:287 key = name288 if not rcParams.has_key(key):289 raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % (key, group, name))290 291 rcParams[key] = v292 293 294 def rcdefaults():295 """296 Restore the default rc params - the ones that were created at297 asap load time298 """299 rcParams.update(rcParamsDefault)300 301 def _n_bools(n, val):302 return [ val for i in xrange(n) ]303 304 def _is_sequence_or_number(param, ptype=int):305 if isinstance(param,tuple) or isinstance(param,list):306 if len(param) == 0: return True # empty list307 out = True308 for p in param:309 out &= isinstance(p,ptype)310 return out311 elif isinstance(param, ptype):312 return True313 return False314 315 def _to_list(param, ptype=int):316 if isinstance(param, ptype):317 if ptype is str: return param.split()318 else: return [param]319 if _is_sequence_or_number(param, ptype):320 return param321 return None322 323 def unique(x):324 """325 Return the unique values in a list326 Parameters:327 x: the list to reduce328 Examples:329 x = [1,2,3,3,4]330 print unique(x)331 [1,2,3,4]332 """333 return dict([ (val, 1) for val in x]).keys()334 335 def list_files(path=".",suffix="rpf"):336 """337 Return a list files readable by asap, such as rpf, sdfits, mbf, asap338 Parameters:339 path: The directory to list (default '.')340 suffix: The file extension (default rpf)341 Example:342 files = list_files("data/","sdfits")343 print files344 ['data/2001-09-01_0332_P363.sdfits',345 'data/2003-04-04_131152_t0002.sdfits',346 'data/Sgr_86p262_best_SPC.sdfits']347 """348 if not os.path.isdir(path):349 return None350 valid = "rpf rpf.1 rpf.2 sdf sdfits mbf asap".split()351 if not suffix in valid:352 return None353 files = [os.path.expanduser(os.path.expandvars(path+"/"+f)) for f in os.listdir(path)]354 return filter(lambda x: x.endswith(suffix),files)355 356 # workaround for ipython, which redirects this if banner=0 in ipythonrc357 sys.stdout = sys.__stdout__358 sys.stderr = sys.__stderr__359 360 # Logging361 from asap._asap import Log as _asaplog362 global asaplog363 asaplog=_asaplog()364 if rcParams['verbose']:365 asaplog.enable()366 else:367 asaplog.disable()368 369 370 def print_log_dec(f):371 @wraps_dec(f)372 def wrap_it(*args, **kw):373 val = f(*args, **kw)374 print_log()375 return val376 return wrap_it377 378 def print_log(level='INFO'):379 from taskinit import casalog380 log = asaplog.pop()381 #if len(log) and rcParams['verbose']: print log382 if len(log) and rcParams['verbose']: casalog.post( log, priority=level )383 return384 385 def mask_and(a, b):386 assert(len(a)==len(b))387 return [ a[i] & b[i] for i in xrange(len(a)) ]388 389 def mask_or(a, b):390 assert(len(a)==len(b))391 return [ a[i] | b[i] for i in xrange(len(a)) ]392 393 def mask_not(a):394 return [ not i for i in a ]395 396 from asapfitter import fitter397 42 from asapreader import reader 398 43 from selector import selector 399 400 44 from asapmath import * 401 45 from scantable import scantable 46 from linecatalog import linecatalog 402 47 from asaplinefind import linefinder 403 48 from simplelinefinder import simplelinefinder 404 from linecatalog import linecatalog405 49 from interactivemask import interactivemask 50 from asapfitter import fitter 406 51 from opacity import skydip 407 52 from opacity import model as opacity_model 408 53 409 if rcParams['useplotter']:410 try:411 from asapplotter import asapplotter412 gui = os.environ.has_key('DISPLAY') and rcParams['plotter.gui']413 if gui:414 import matplotlib415 if not matplotlib.sys.modules['matplotlib.backends']: matplotlib.use("TkAgg")416 from matplotlib import pylab417 xyplotter = pylab418 plotter = asapplotter(gui)419 del gui420 except ImportError:421 #print "Matplotlib not installed. No plotting available"422 asaplog.post( "Matplotlib not installed. No plotting available")423 print_log('WARN')424 425 54 __date__ = '$Date$'.split()[1] 426 __version__ = '3.0.0 alma' 427 # nrao casapy specific, get revision number 428 #__revision__ = ' unknown ' 429 casapath=os.environ["CASAPATH"].split() 430 #svninfo.txt path 431 if os.path.isdir(casapath[0]+'/'+casapath[1]+'/python/2.5/asap'): 432 # for casa developer environment (linux or darwin) 433 revinfo=casapath[0]+'/'+casapath[1]+'/python/2.5/asap/svninfo.txt' 434 else: 435 # for end-user environments 436 if casapath[1]=='darwin': 437 revinfo=casapath[0]+'/Resources/python/asap/svninfo.txt' 438 else: 439 revinfo=casapath[0]+'/lib/python2.5/asap/svninfo.txt' 440 if os.path.isfile(revinfo): 441 f = file(revinfo) 442 f.readline() 443 revsionno=f.readline() 444 f.close() 445 del f 446 __revision__ = revsionno.rstrip() 447 else: 448 __revision__ = ' unknown ' 449 450 def is_ipython(): 451 return 'IPython' in sys.modules.keys() 452 if is_ipython(): 453 def version(): print "ASAP %s(%s)"% (__version__, __date__) 454 455 def list_scans(t = scantable): 456 import inspect 457 print "The user created scantables are: ", 458 globs=inspect.currentframe().f_back.f_locals.copy() 459 out = [ k for k,v in globs.iteritems() \ 460 if isinstance(v, scantable) and not k.startswith("_") ] 461 print out 462 return out 463 464 def commands(): 465 x = """ 466 [The scan container] 467 scantable - a container for integrations/scans 468 (can open asap/rpfits/sdfits and ms files) 469 copy - returns a copy of a scan 470 get_scan - gets a specific scan out of a scantable 471 (by name or number) 472 drop_scan - drops a specific scan out of a scantable 473 (by number) 474 set_selection - set a new subselection of the data 475 get_selection - get the current selection object 476 summary - print info about the scantable contents 477 stats - get specified statistic of the spectra in 478 the scantable 479 stddev - get the standard deviation of the spectra 480 in the scantable 481 get_tsys - get the TSys 482 get_time - get the timestamps of the integrations 483 get_inttime - get the integration time 484 get_sourcename - get the source names of the scans 485 get_azimuth - get the azimuth of the scans 486 get_elevation - get the elevation of the scans 487 get_parangle - get the parallactic angle of the scans 488 get_coordinate - get the spectral coordinate for the given row, 489 which can be used for coordinate conversions 490 get_weather - get the weather condition parameters 491 get_unit - get the current unit 492 set_unit - set the abcissa unit to be used from this 493 point on 494 get_abcissa - get the abcissa values and name for a given 495 row (time) 496 get_column_names - get the names of the columns in the scantable 497 for use with selector.set_query 498 set_freqframe - set the frame info for the Spectral Axis 499 (e.g. 'LSRK') 500 set_doppler - set the doppler to be used from this point on 501 set_dirframe - set the frame for the direction on the sky 502 set_instrument - set the instrument name 503 set_feedtype - set the feed type 504 get_fluxunit - get the brightness flux unit 505 set_fluxunit - set the brightness flux unit 506 set_sourcetype - set the type of the source - source or reference 507 create_mask - return an mask in the current unit 508 for the given region. The specified regions 509 are NOT masked 510 get_restfreqs - get the current list of rest frequencies 511 set_restfreqs - set a list of rest frequencies 512 shift_refpix - shift the reference pixel of the IFs 513 set_spectrum - overwrite the spectrum for a given row 514 get_spectrum - retrieve the spectrum for a given 515 get_mask - retrieve the mask for a given 516 flag - flag selected channels in the data 517 lag_flag - flag specified frequency in the data 518 save - save the scantable to disk as either 'ASAP', 519 'SDFITS' or 'ASCII' 520 nbeam,nif,nchan,npol - the number of beams/IFs/Pols/Chans 521 nscan - the number of scans in the scantable 522 nrow - the number of spectra in the scantable 523 history - print the history of the scantable 524 get_fit - get a fit which has been stored witnh the data 525 average_time - return the (weighted) time average of a scan 526 or a list of scans 527 average_pol - average the polarisations together. 528 average_beam - average the beams together. 529 convert_pol - convert to a different polarisation type 530 auto_quotient - return the on/off quotient with 531 automatic detection of the on/off scans (closest 532 in time off is selected) 533 mx_quotient - Form a quotient using MX data (off beams) 534 scale, *, / - return a scan scaled by a given factor 535 add, + - return a scan with given value added 536 sub, - - return a scan with given value subtracted 537 bin - return a scan with binned channels 538 resample - return a scan with resampled channels 539 smooth - return the spectrally smoothed scan 540 poly_baseline - fit a polynomial baseline to all Beams/IFs/Pols 541 auto_poly_baseline - automatically fit a polynomial baseline 542 recalc_azel - recalculate azimuth and elevation based on 543 the pointing 544 gain_el - apply gain-elevation correction 545 opacity - apply opacity correction 546 convert_flux - convert to and from Jy and Kelvin brightness 547 units 548 freq_align - align spectra in frequency frame 549 invert_phase - Invert the phase of the cross-correlation 550 swap_linears - Swap XX and YY (or RR LL) 551 rotate_xyphase - rotate XY phase of cross correlation 552 rotate_linpolphase - rotate the phase of the complex 553 polarization O=Q+iU correlation 554 freq_switch - perform frequency switching on the data 555 stats - Determine the specified statistic, e.g. 'min' 556 'max', 'rms' etc. 557 stddev - Determine the standard deviation of the current 558 beam/if/pol 559 get_row_selector - get the selection object for a specified row 560 number 561 [Selection] 562 selector - a selection object to set a subset of a scantable 563 set_scans - set (a list of) scans by index 564 set_cycles - set (a list of) cycles by index 565 set_beams - set (a list of) beamss by index 566 set_ifs - set (a list of) ifs by index 567 set_polarisations - set (a list of) polarisations by name 568 or by index 569 set_names - set a selection by name (wildcards allowed) 570 set_tsys - set a selection by tsys thresholds 571 set_query - set a selection by SQL-like query, e.g. BEAMNO==1 572 ( also get_ functions for all these ) 573 reset - unset all selections 574 + - merge two selections 575 576 [Math] Mainly functions which operate on more than one scantable 577 578 average_time - return the (weighted) time average 579 of a list of scans 580 quotient - return the on/off quotient 581 simple_math - simple mathematical operations on two scantables, 582 'add', 'sub', 'mul', 'div' 583 quotient - build quotient of the given on and off scans 584 (matched pairs and 1 off - n on are valid) 585 merge - merge a list of scantables 586 587 [Line Catalog] 588 linecatalog - a linecatalog wrapper, taking an ASCII or 589 internal format table 590 summary - print a summary of the current selection 591 set_name - select a subset by name pattern, e.g. '*OH*' 592 set_strength_limits - select a subset by line strength limits 593 set_frequency_limits - select a subset by frequency limits 594 reset - unset all selections 595 save - save the current subset to a table (internal 596 format) 597 get_row - get the name and frequency from a specific 598 row in the table 599 [Fitting] 600 fitter 601 auto_fit - return a scan where the function is 602 applied to all Beams/IFs/Pols. 603 commit - return a new scan where the fits have been 604 commited. 605 fit - execute the actual fitting process 606 store_fit - store the fit parameters in the data (scantable) 607 get_chi2 - get the Chi^2 608 set_scan - set the scantable to be fit 609 set_function - set the fitting function 610 set_parameters - set the parameters for the function(s), and 611 set if they should be held fixed during fitting 612 set_gauss_parameters - same as above but specialised for individual 613 gaussian components 614 get_parameters - get the fitted parameters 615 plot - plot the resulting fit and/or components and 616 residual 617 [Plotter] 618 asapplotter - a plotter for asap, default plotter is 619 called 'plotter' 620 plot - plot a scantable 621 plot_lines - plot a linecatalog overlay 622 plotazel - plot azimuth and elevation versus time 623 plotpointing - plot telescope pointings 624 save - save the plot to a file ('png' ,'ps' or 'eps') 625 set_mode - set the state of the plotter, i.e. 626 what is to be plotted 'colour stacked' 627 and what 'panelled' 628 set_selection - only plot a selected part of the data 629 set_range - set a 'zoom' window [xmin,xmax,ymin,ymax] 630 set_legend - specify user labels for the legend indeces 631 set_title - specify user labels for the panel indeces 632 set_abcissa - specify a user label for the abcissa 633 set_ordinate - specify a user label for the ordinate 634 set_layout - specify the multi-panel layout (rows,cols) 635 set_colors - specify a set of colours to use 636 set_linestyles - specify a set of linestyles to use if only 637 using one color 638 set_font - set general font properties, e.g. 'family' 639 set_histogram - plot in historam style 640 set_mask - set a plotting mask for a specific polarization 641 text - draw text annotations either in data or relative 642 coordinates 643 arrow - draw arrow annotations either in data or relative 644 coordinates 645 axhline,axvline - draw horizontal/vertical lines 646 axhspan,axvspan - draw horizontal/vertical regions 647 annotate - draw an arrow with label 648 create_mask - create a scnatble mask interactively 649 650 xyplotter - matplotlib/pylab plotting functions 651 652 [General] 653 commands - this command 654 print - print details about a variable 655 list_scans - list all scantables created by the user 656 list_files - list all files readable by asap (default rpf) 657 del - delete the given variable from memory 658 range - create a list of values, e.g. 659 range(3) = [0,1,2], range(2,5) = [2,3,4] 660 help - print help for one of the listed functions 661 execfile - execute an asap script, e.g. execfile('myscript') 662 list_rcparameters - print out a list of possible values to be 663 put into $HOME/.asaprc 664 rc - set rc parameters from within asap 665 mask_and,mask_or, 666 mask_not - boolean operations on masks created with 667 scantable.create_mask 668 skydip - gain opacity values from a sky dip observation 669 opacity_model - compute opacities fro given frequencies based on 670 atmospheric model 671 672 Note: 673 How to use this with help: 674 # function 'summary' 675 [xxx] is just a category 676 Every 'sub-level' in this list should be replaces by a '.' Period when 677 using help 678 Example: 679 ASAP> help scantable # to get info on ths scantable 680 ASAP> help scantable.summary # to get help on the scantable's 681 ASAP> help average_time 682 683 """ 684 if rcParams['verbose']: 685 try: 686 from IPython.genutils import page as pager 687 except ImportError: 688 from pydoc import pager 689 pager(x) 690 else: 691 print x 692 return 55 __version__ = 'trunk' 56 __revision__ = get_revision() 693 57 694 58 def welcome(): … … 699 63 700 64 [IMPORTANT: ASAP is 0-based] 701 Type commands() to get a list of all available ASAP commands.""" % (__version__, __date__) 65 Type commands() to get a list of all available ASAP commands.""" % (__version__, 66 __date__) -
trunk/python/asapplotter.py
r1819 r1824 1 from asap import rcParams, print_log, print_log_dec 2 from asap import selector, scantable 3 from asap import asaplog 1 from asap.parameters import rcParams 2 from asap.selector import selector 3 from asap.scantable import scantable 4 from asap.logging import asaplog, print_log, print_log_dec 4 5 import matplotlib.axes 5 6 from matplotlib.font_manager import FontProperties … … 276 277 def set_data(self, scan, refresh=True): 277 278 """ 278 Set a scantable to plot. 279 Set a scantable to plot. 279 280 Parameters: 280 281 scan: a scantable 281 282 refresh: True (default) or False. If True, the plot is 282 replotted based on the new parameter setting(s). 283 replotted based on the new parameter setting(s). 283 284 Otherwise,the parameter(s) are set without replotting. 284 285 Note: 285 286 The user specified masks and data selections will be reset 286 287 if a new scantable is set. This method should be called before 287 setting data selections (set_selection) and/or masks (set_mask). 288 setting data selections (set_selection) and/or masks (set_mask). 288 289 """ 289 290 from asap import scantable … … 316 317 self._datamask = None 317 318 if refresh: self.plot() 318 319 319 320 320 321 def set_mode(self, stacking=None, panelling=None, refresh=True): … … 327 328 across multiple panels (default 'scan' 328 329 refresh: True (default) or False. If True, the plot is 329 replotted based on the new parameter setting(s). 330 replotted based on the new parameter setting(s). 330 331 Otherwise,the parameter(s) are set without replotting. 331 332 Note: … … 369 370 cols: The number of columns of plots 370 371 refresh: True (default) or False. If True, the plot is 371 replotted based on the new parameter setting(s). 372 replotted based on the new parameter setting(s). 372 373 Otherwise,the parameter(s) are set without replotting. 373 374 Note: … … 397 398 [x,y]start,[x,y]end: The start and end points of the 'zoom' window 398 399 refresh: True (default) or False. If True, the plot is 399 replotted based on the new parameter setting(s). 400 replotted based on the new parameter setting(s). 400 401 Otherwise,the parameter(s) are set without replotting. 401 402 Note: … … 440 441 10: center 441 442 refresh: True (default) or False. If True, the plot is 442 replotted based on the new parameter setting(s). 443 replotted based on the new parameter setting(s). 443 444 Otherwise,the parameter(s) are set without replotting. 444 445 … … 465 466 Parameters: 466 467 refresh: True (default) or False. If True, the plot is 467 replotted based on the new parameter setting(s). 468 replotted based on the new parameter setting(s). 468 469 Otherwise,the parameter(s) are set without replotting. 469 470 Example: … … 486 487 data determine the labels 487 488 refresh: True (default) or False. If True, the plot is 488 replotted based on the new parameter setting(s). 489 replotted based on the new parameter setting(s). 489 490 Otherwise,the parameter(s) are set without replotting. 490 491 Example: … … 508 509 data determine the labels 509 510 refresh: True (default) or False. If True, the plot is 510 replotted based on the new parameter setting(s). 511 replotted based on the new parameter setting(s). 511 512 Otherwise,the parameter(s) are set without replotting. 512 513 Example: … … 529 530 colmap: a list of colour names 530 531 refresh: True (default) or False. If True, the plot is 531 replotted based on the new parameter setting(s). 532 replotted based on the new parameter setting(s). 532 533 Otherwise,the parameter(s) are set without replotting. 533 534 Example: … … 553 554 plotter.histogram 554 555 refresh: True (default) or False. If True, the plot is 555 replotted based on the new parameter setting(s). 556 replotted based on the new parameter setting(s). 556 557 Otherwise,the parameter(s) are set without replotting. 557 558 """ … … 573 574 possible 574 575 refresh: True (default) or False. If True, the plot is 575 replotted based on the new parameter setting(s). 576 replotted based on the new parameter setting(s). 576 577 Otherwise,the parameter(s) are set without replotting. 577 578 Example: … … 600 601 seperately 601 602 refresh: True (default) or False. If True, the plot is 602 replotted based on the new parameter setting(s). 603 replotted based on the new parameter setting(s). 603 604 Otherwise,the parameter(s) are set without replotting. 604 605 """ … … 616 617 Parameters: 617 618 layout: a list of subplots layout in figure coordinate (0-1), 618 i.e., fraction of the figure width or height. 619 i.e., fraction of the figure width or height. 619 620 The order of elements should be: 620 621 [left, bottom, right, top, horizontal space btw panels, 621 vertical space btw panels]. 622 vertical space btw panels]. 622 623 refresh: True (default) or False. If True, the plot is 623 replotted based on the new parameter setting(s). 624 replotted based on the new parameter setting(s). 624 625 Otherwise,the parameter(s) are set without replotting. 625 626 Note 626 627 * When layout is not specified, the values are reset to the defaults 627 628 of matplotlib. 628 * If any element is set to be None, the current value is adopted. 629 * If any element is set to be None, the current value is adopted. 629 630 """ 630 631 if layout == []: self._panellayout=self._reset_panellayout() 631 else: 632 else: 632 633 self._panellayout=[None]*6 633 634 self._panellayout[0:len(layout)]=layout … … 744 745 selection: the spectra to apply the mask to. 745 746 refresh: True (default) or False. If True, the plot is 746 replotted based on the new parameter setting(s). 747 replotted based on the new parameter setting(s). 747 748 Otherwise,the parameter(s) are set without replotting. 748 749 Example: … … 961 962 #reset the selector to the scantable's original 962 963 scan.set_selection(savesel) 963 964 964 965 #temporary switch-off for older matplotlib 965 966 #if self._fp is not None: … … 973 974 selection: a selector object (default unset the selection) 974 975 refresh: True (default) or False. If True, the plot is 975 replotted based on the new parameter setting(s). 976 replotted based on the new parameter setting(s). 976 977 Otherwise,the parameter(s) are set without replotting. 977 978 """ … … 1049 1050 PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top, 1050 1051 wspace=wsp,hspace=hsp) 1051 1052 1052 1053 tdel = max(t) - min(t) 1053 1054 ax = PL.subplot(2,1,1) … … 1271 1272 print data (scantable) header on the plot and/or logger. 1272 1273 Parameters: 1273 plot: whether or not print header info on the plot. 1274 plot: whether or not print header info on the plot. 1274 1275 fontsize: header font size (valid only plot=True) 1275 1276 autoscale: whether or not autoscale the plot (valid only plot=True) … … 1280 1281 if not plot and not logger: return 1281 1282 if not self._data: raise RuntimeError("No scantable has been set yet.") 1282 # Now header will be printed on plot and/or logger. 1283 # Get header information and format it. 1283 # Now header will be printed on plot and/or logger. 1284 # Get header information and format it. 1284 1285 ssum=self._data.__str__() 1285 1286 # Print Observation header to the upper-left corner of plot … … 1293 1294 headstr.append(ssel) 1294 1295 nstcol=len(headstr) 1295 1296 1296 1297 self._plotter.hold() 1297 1298 for i in range(nstcol): … … 1314 1315 print_log() 1315 1316 del ssum 1316 1317 -
trunk/python/logging.py
r1819 r1824 25 25 logs. 26 26 """ 27 if len(self._log) > 0: 28 self.logger.post(self._log, priority=level) 27 logs = self._log.strip() 28 if len(logs) > 0: 29 self.logger.post(logs, priority=level) 29 30 if isinstance(self.logger, LogSink): 30 logs = self.logger.pop() 31 if l ogs> 0:31 logs = self.logger.pop().strip() 32 if len(logs) > 0: 32 33 print logs 33 34 self._log = "" -
trunk/python/scantable.py
r1819 r1824 5 5 from asap.compatibility import wraps as wraps_dec 6 6 7 from asap.env import is_casapy 7 8 from asap._asap import Scantable 8 from asap import rcParams 9 from asap import print_log, print_log_dec 10 from asap import asaplog 11 from asap import selector 12 from asap import linecatalog 9 from asap.parameters import rcParams 10 from asap.logging import asaplog, print_log, print_log_dec 11 from asap.selector import selector 12 from asap.linecatalog import linecatalog 13 13 from asap.coordinate import coordinate 14 from asap import _n_bools, mask_not, mask_and, mask_or14 from asap.utils import _n_bools, mask_not, mask_and, mask_or 15 15 16 16 … … 37 37 38 38 @print_log_dec 39 def __init__(self, filename, average=None, unit=None, getpt=None, antenna=None, parallactify=None): 39 def __init__(self, filename, average=None, unit=None, getpt=None, 40 antenna=None, parallactify=None): 40 41 """ 41 42 Create a scantable from a saved one or make a reference … … 2399 2400 if unit is not None: 2400 2401 self.set_fluxunit(unit) 2401 #self.set_freqframe(rcParams['scantable.freqframe']) 2402 if not is_casapy(): 2403 self.set_freqframe(rcParams['scantable.freqframe']) 2402 2404 2403 2405 def __getitem__(self, key): -
trunk/test/test_scantable.py
r1725 r1824 1 1 import unittest 2 2 import datetime 3 from asap import scantable, selector, rcParams, mask_not 4 rcParams["verbose"] = False 3 from asap import scantable, selector, rcParams, mask_not, asaplog 4 asaplog.disable() 5 5 6 6 class ScantableTest(unittest.TestCase): 7 7 def setUp(self): 8 9 self.st = scantable("data/MOPS.rpf", average=True) 8 s = scantable("data/MOPS.rpf", average=True) 9 sel = selector() 10 # make sure this order is always correct - in can be random 11 sel.set_order(["SCANNO", "POLNO"]) 12 s.set_selection(sel) 13 self.st = s.copy() 10 14 restfreqs = [86.243] # 13CO-1/0, SiO the two IF 11 15 self.st.set_restfreqs(restfreqs,"GHz") … … 78 82 def test_get_column_names(self): 79 83 cnames = ['SCANNO', 'CYCLENO', 'BEAMNO', 'IFNO', 80 'POLNO', 'FREQ_ID', 'MOLECULE_ID', 'REFBEAMNO', 84 'POLNO', 'FREQ_ID', 'MOLECULE_ID', 'REFBEAMNO', 'FLAGROW', 81 85 'TIME', 'INTERVAL', 'SRCNAME', 'SRCTYPE', 82 86 'FIELDNAME', 'SPECTRA', 'FLAGTRA', 'TSYS', … … 101 105 def test_get_sourcename(self): 102 106 self.assertEqual(self.st.get_sourcename(0), 'Orion_SiO_R') 103 self.assertEqual(self.st.get_sourcename()[:2], ['Orion_SiO_R', 'Orion_SiO']) 107 self.assertEqual(self.st.get_sourcename(), 108 ['Orion_SiO_R', 'Orion_SiO_R', 109 'Orion_SiO', 'Orion_SiO']) 104 110 105 111 def test_get_azimuth(self): … … 144 150 msk = q0.create_mask([-10,20]) 145 151 q0.flag(mask=mask_not(msk)) 152 q1.flag(mask=msk) 146 153 self.assertAlmostEqual(q0.stats(stat='max')[0], 95.62171936) 147 q1.flag(mask=msk)148 154 self.assertAlmostEqual(q1.stats(stat='max')[0], 2.66563416) 149 155
Note:
See TracChangeset
for help on using the changeset viewer.