Changeset 226
- Timestamp:
- 01/19/05 18:24:16 (20 years ago)
- Location:
- trunk/python
- Files:
-
- 4 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/python/__init__.py
r210 r226 3 3 4 4 """ 5 #import _asap 6 #from asaplot import ASAPlot 5 import os,sys 6 7 def validate_bool(b): 8 'Convert b to a boolean or raise' 9 bl = b.lower() 10 if bl in ('f', 'no', 'false', '0', 0): return False 11 elif bl in ('t', 'yes', 'true', '1', 1): return True 12 else: 13 raise ValueError('Could not convert "%s" to boolean' % b) 14 15 def validate_int(s): 16 'convert s to int or raise' 17 try: return int(s) 18 except ValueError: 19 raise ValueError('Could not convert "%s" to int' % s) 20 21 def asap_fname(): 22 """ 23 Return the path to the rc file 24 25 Search order: 26 27 * current working dir 28 * environ var ASAPRC 29 * HOME/.matplotlibrc 30 31 """ 32 33 fname = os.path.join( os.getcwd(), '.asaprc') 34 if os.path.exists(fname): return fname 35 36 if os.environ.has_key('ASAPRC'): 37 path = os.environ['ASAPRC'] 38 if os.path.exists(path): 39 fname = os.path.join(path, '.asaprc') 40 if os.path.exists(fname): 41 return fname 42 43 if os.environ.has_key('HOME'): 44 home = os.environ['HOME'] 45 fname = os.path.join(home, '.asaprc') 46 if os.path.exists(fname): 47 return fname 48 return None 49 50 51 defaultParams = { 52 # general 53 'verbose' : [True, validate_bool], 54 'useplotter' : [True, validate_bool], 55 56 # plotting 57 'plotter.stacking' : ['p', str], 58 'plotter.panelling' : ['s', str], 59 60 # scantable 61 'scantable.save' : ['ASAP', str], 62 'scantable.autoaverage' : [True, validate_bool], 63 'scantable.freqframe' : ['LSRK', str], #default frequency frame 64 'scantable.allaxes' : [True, validate_bool], # apply action to all axes 65 'scantable.plotter' : [True, validate_bool], # use internal plotter 66 67 # math 68 'math.insitu' : [False, validate_bool], 69 70 # fitter 71 'fitter.polyorder' : [0, validate_int], 72 'fitter.ncomponents' : [1, validate_int] 73 } 74 75 def rc_params(): 76 'Return the default params updated from the values in the rc file' 77 78 fname = asap_fname() 79 80 if fname is None or not os.path.exists(fname): 81 message = 'could not find rc file; returning defaults' 82 ret = dict([ (key, tup[0]) for key, tup in defaultParams.items()]) 83 #print message 84 return ret 85 86 cnt = 0 87 for line in file(fname): 88 cnt +=1 89 line = line.strip() 90 if not len(line): continue 91 if line.startswith('#'): continue 92 tup = line.split(':',1) 93 if len(tup) !=2: 94 print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname)) 95 continue 96 97 key, val = tup 98 key = key.strip() 99 if not defaultParams.has_key(key): 100 print ('Bad key "%s" on line %d in %s' % (key, cnt, fname)) 101 continue 102 103 default, converter = defaultParams[key] 104 105 ind = val.find('#') 106 if ind>=0: val = val[:ind] # ignore trailing comments 107 val = val.strip() 108 try: cval = converter(val) # try to convert to proper type or raise 109 except Exception, msg: 110 print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg)) 111 continue 112 else: 113 # Alles Klar, update dict 114 defaultParams[key][0] = cval 115 116 # strip the conveter funcs and return 117 ret = dict([ (key, tup[0]) for key, tup in defaultParams.items()]) 118 verbose.report('loaded rc file %s'%fname) 119 120 return ret 121 122 123 # this is the instance used by the asap classes 124 rcParams = rc_params() 125 126 rcParamsDefault = dict(rcParams.items()) # a copy 127 128 def rc(group, **kwargs): 129 """ 130 Set the current rc params. Group is the grouping for the rc, eg 131 for lines.linewidth the group is 'lines', for axes.facecolor, the 132 group is 'axes', and so on. kwargs is a list of attribute 133 name/value pairs, eg 134 135 rc('lines', linewidth=2, color='r') 136 137 sets the current rc params and is equivalent to 138 139 rcParams['lines.linewidth'] = 2 140 rcParams['lines.color'] = 'r' 141 142 143 Note you can use python's kwargs dictionary facility to store 144 dictionaries of default parameters. Eg, you can customize the 145 font rc as follows 146 147 font = {'family' : 'monospace', 148 'weight' : 'bold', 149 'size' : 'larger', 150 } 151 152 rc('font', **font) # pass in the font dict as kwargs 153 154 This enables you to easily switch between several configurations. 155 Use rcdefaults to restore the default rc params after changes. 156 """ 157 158 aliases = { 159 } 160 161 for k,v in kwargs.items(): 162 name = aliases.get(k) or k 163 key = '%s.%s' % (group, name) 164 if not rcParams.has_key(key): 165 raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % (key, group, name)) 166 167 rcParams[key] = v 168 169 170 def rcdefaults(): 171 """ 172 Restore the default rc params - the ones that were created at 173 asap load time 174 """ 175 rcParams.update(rcParamsDefault) 176 7 177 from asapfitter import * 8 178 from asapreader import reader 9 179 from asapmath import * 10 180 from scantable import * 11 print "Initialising plotter..." 12 from asapplotter import * 13 plotter = asapplotter() 181 if rcParams['useplotter']: 182 print "Initialising plotter..." 183 from asapplotter import * 184 plotter = asapplotter() 14 185 #from numarray ones,zeros 15 186 -
trunk/python/asaplot.py
r202 r226 7 7 import Tkinter as Tk 8 8 9 print "Importing matplotlib with TkAgg backend."9 #print "Importing matplotlib with TkAgg backend." 10 10 import matplotlib 11 11 matplotlib.use("TkAgg") -
trunk/python/asapplotter.py
r203 r226 1 1 from asap.asaplot import ASAPlot 2 from asap import rcParams 2 3 3 4 class asapplotter: 5 """ 6 The ASAP plotter. 7 By default the plotter is set up to plot polarisations 8 'colour stacked' and scantables across panels. 9 The defaul plotter is called 'plotter'. 10 Note: 11 Currenly it only plots 'spectra' not Tsys or 12 other variables. 13 """ 4 14 def __init__(self): 5 """6 The ASAP plotter.7 By default the plotter is set up to plot polarisations8 'colour stacked' and scantables across panels.9 The defaul plotter is called 'plotter'.10 Note:11 Currenly it only plots 'spectra' not Tsys or12 other variables.13 14 """15 15 self._plotter = ASAPlot() 16 16 … … 33 33 self._sdict] 34 34 self._panels = 's' 35 self._stacking = 'p'35 self._stacking = rcParams['plotter.stacking'] 36 36 self._autoplot = False 37 37 self._minmax = None 38 38 self._data = None 39 39 self._lmap = [] 40 self._title = None 40 41 41 42 def _translate(self, name): … … 97 98 y = None 98 99 m = None 99 tlab = scan._getsourcename(i) 100 if not self._title: 101 tlab = scan._getsourcename(i) 102 else: 103 if len(self._title) == n: 104 tlab = self._title[i] 105 else: 106 tlab = scan._getsourcename(i) 100 107 x,xlab = scan.get_abcissa(i) 101 108 y = scan.getspectrum(i) 102 109 ylab = 'Flux ('+scan.get_fluxunit()+')' 103 110 m = scan.getmask(i) 104 if len(self._lmap) > 0:111 if self._lmap and len(self._lmap) > 0: 105 112 llab = self._lmap[j] 106 113 else: … … 138 145 y = None 139 146 m = None 140 tlab = scan._getsourcename() 147 tlab = self._title 148 if not self._title: 149 tlab = scan._getsourcename() 141 150 x,xlab = scan.get_abcissa() 142 151 y = scan.getspectrum() … … 194 203 m = scan.getmask(k) 195 204 if colmode == 's' or colmode == 't': 196 tlab = self._ldict.get(self._panels)+' '+str(i) 205 if not self._title: 206 tlab = self._ldict.get(self._panels)+' '+str(i) 207 else: 208 if len(self.title) == n: 209 tlab = self._title[i] 210 else: 211 tlab = self._ldict.get(self._panels)+' '+str(i) 197 212 llab = scan._getsourcename(k) 198 213 else: 199 tlab = scan._getsourcename(k) 200 if len(self._lmap) > 0: 214 if self._title and len(self._title) > 0: 215 tlab = self._title[k] 216 else: 217 tlab = scan._getsourcename(k) 218 if self._lmap and len(self._lmap) > 0: 201 219 llab = self._lmap[j] 202 220 else: … … 214 232 215 233 216 def set_mode(self, stacking= 'pol', panelling='scan'):234 def set_mode(self, stacking=None, panelling=None): 217 235 """ 218 236 Parameters: … … 231 249 if not self.set_panels(panelling): 232 250 print "Invalid mode" 251 return 233 252 if not self.set_stacking(stacking): 234 253 print "Invalid mode" 235 return 236 237 def set_panels(self, what='scan'): 254 return 255 if self._data: self.plot() 256 return 257 258 def set_panels(self, what=None): 259 if not what: 260 what = rcParams['plotter.panelling'] 238 261 md = self._translate(what) 239 262 if md: 240 self._panels = md 263 self._panels = md 264 self._title = None 241 265 return True 242 266 return False 243 267 244 def set_stacking(self, what='pol'): 268 def set_stacking(self, what=None): 269 if not what: 270 what = rcParams['plotter.stacking'] 245 271 md = self._translate(what) 246 272 if md: 247 273 self._stacking = md 274 self._lmap = None 248 275 return True 249 276 return False … … 261 288 if start is None and end is None: 262 289 self._minmax = None 263 if self._data is not None: 264 self.plot() 290 if self._data: self.plot() 265 291 else: 266 292 self._minmax = [start,end] 267 if self._data is not None: 268 self.plot() 293 if self._data: self.plot() 269 294 return 270 295 271 def set_legend_map(self, mp=[]):296 def set_legend_map(self, mp=[]): 272 297 """ 273 298 Specify a mapping for the legend instead of using the default … … 286 311 """ 287 312 self._lmap = mp 288 313 if self._data: self.plot() 314 return 315 316 def set_title(self, title=None): 317 self._title = title 318 if self._data: self.plot() 319 return 320 289 321 if __name__ == '__main__': 290 322 plotter = asapplotter() -
trunk/python/scantable.py
r200 r226 1 1 from asap._asap import sdtable 2 from asap import rcParams 2 3 from numarray import ones,zeros 3 4 import sys … … 21 22 scantable 22 23 """ 23 self._vb = True24 self._vb = rcParams['verbose'] 24 25 self._p = None 25 26 from os import stat as st … … 28 29 sdtable.__init__(self, filename) 29 30 else: 30 mode = st(filename)[stat.ST_MODE] 31 try: 32 mode = st(filename)[stat.ST_MODE] 33 except OSError: 34 print "File not found" 35 return 31 36 if stat.S_ISDIR(mode): 32 37 # crude check if asap table … … 35 40 else: 36 41 print 'The given file is not a valid asap table' 37 else: 42 return 43 else: 44 autoav = rcParams['scantable.autoaverage'] 45 38 46 from asap._asap import sdreader 39 47 r = sdreader(filename) … … 41 49 r.read([-1]) 42 50 tbl = r.getdata() 43 44 from asap._asap import average 45 tmp = tuple([tbl]) 46 print 'Auto averging integrations...' 47 tbl2 = average(tmp,(),True,'none') 48 sdtable.__init__(self,tbl2) 49 del r,tbl 50 51 def save(self, name="", format='ASAP'): 51 if autoav: 52 from asap._asap import average 53 tmp = tuple([tbl]) 54 print 'Auto averaging integrations...' 55 tbl2 = average(tmp,(),True,'none') 56 sdtable.__init__(self,tbl2) 57 del r,tbl 58 else: 59 sdtable.__init__(self,tbl) 60 61 def save(self, name="", format=None): 52 62 """ 53 63 Store the scantable on disk. This can be a asap file or SDFITS/MS2. … … 60 70 'FITS' (saves each row as a FITS Image) 61 71 'ASCII' (saves as ascii text file) 62 'MS2' (saves as an aips++ MeasurementSet V2) 72 'MS2' (saves as an aips++ 73 MeasurementSet V2) 63 74 Example: 64 75 scan.save('myscan.asap') 65 76 scan.save('myscan.sdfits','SDFITS') 66 77 """ 78 if format is None: format = rcParams['scantable.save'] 67 79 if format == 'ASAP': 68 80 self._save(name) … … 72 84 w.write(self, name) 73 85 return 74 75 def _verbose(self, *args):76 """77 Set the verbose level True or False, to indicate if output78 should be printed as well as returned.79 """80 if len(args) == 0:81 return self._vb82 elif type(args[0]) is bool:83 self._vb = args[0]84 return85 86 86 87 def copy(self): … … 166 167 print " Cursor selection" 167 168 print "--------------------------------------------------" 168 out = 'Beam=%d IF=%d Pol=%d ' % (i,j,k)169 out = 'Beam=%d IF=%d Pol=%d ' % (i,j,k) 169 170 print out 170 171 return i,j,k 171 172 172 def stats(self, stat='stddev', mask=None, all= True):173 def stats(self, stat='stddev', mask=None, all=None): 173 174 """ 174 175 Determine the specified statistic of the current beam/if/pol … … 180 181 mask: an optional mask specifying where the statistic 181 182 should be determined. 182 all: optional flag to show all (default ) or a selected183 spectrum of Beam/IF/Pol183 all: optional flag to show all (default or .asaprc) or a 184 cursor selected spectrum of Beam/IF/Pol 184 185 185 186 Example: … … 188 189 scan.stats(stat='mean', mask=m) 189 190 """ 191 if all is None: all = rcParams['scantable.allaxes'] 190 192 from asap._asap import stats as _stats 191 193 if mask == None: … … 210 212 out += '= %3.3f\n' % (statval[l]) 211 213 out += "--------------------------------------------------\n" 212 213 214 if self._vb: 214 215 print "--------------------------------------------------" … … 232 233 out += '= %3.3f\n' % (statval[l]) 233 234 out += "--------------------------------------------------\n" 235 234 236 if self._vb: 235 237 print "--------------------------------------------------" … … 239 241 return statval 240 242 241 def stddev(self,mask=None, all= True):243 def stddev(self,mask=None, all=None): 242 244 """ 243 245 Determine the standard deviation of the current beam/if/pol … … 247 249 mask: an optional mask specifying where the standard 248 250 deviation should be determined. 249 all: optional flag to show all or a selected 250 spectrum of Beam/IF/Pol 251 all: optional flag to show all or a cursor selected 252 spectrum of Beam/IF/Pol. Default is all or taken 253 from .asaprc 251 254 252 255 Example: … … 255 258 scan.stddev(mask=m) 256 259 """ 260 if all is None: all = rcParams['scantable.allaxes'] 257 261 return self.stats(stat='stddev',mask=mask, all=all); 258 262 259 def get_tsys(self, all= True):263 def get_tsys(self, all=None): 260 264 """ 261 265 Return the System temperatures. … … 268 272 a list of Tsys values. 269 273 """ 274 if all is None: all = rcParams['scantable.allaxes'] 270 275 if all: 271 276 out = '' … … 287 292 out += '= %3.3f\n' % (ts[l]) 288 293 out+= "--------------------------------------------------\n" 289 290 294 if self._vb: 291 295 print "--------------------------------------------------" … … 308 312 out += '= %3.3f\n' % (ts[l]) 309 313 out += "--------------------------------------------------\n" 310 311 314 if self._vb: 312 315 print "--------------------------------------------------" … … 345 348 if self._p: self.plot() 346 349 347 def set_freqframe(self, frame= 'LSRK'):350 def set_freqframe(self, frame=None): 348 351 """ 349 352 Set the frame type of the Spectral Axis. … … 353 356 scan.set_freqframe('BARY') 354 357 """ 358 if not frame: frame = rcParams['scantable.freqframe'] 355 359 valid = ['REST','TOPO','LSRD','LSRK','BARY', \ 356 360 'GEO','GALACTO','LGROUP','CMB'] … … 379 383 selected Beam/IF/Pol 380 384 Parameters: 381 none 385 rowno: an optional row number in the scantable. Default is the 386 first row, i.e. rowno=0 382 387 Returns: 383 388 The abcissa values and it's format string. … … 501 506 self._p.set_panels(rows=npan) 502 507 xlab,ylab,tlab = None,None,None 503 vb = self._verbose() 504 self._verbose(False) 505 sel = self.get_selection() 508 self._vb = False 509 sel = self.get_selection() 506 510 for i in range(npan): 507 self._p.subplot(i) 511 if npan > 1: 512 self._p.subplot(i) 508 513 for j in range(validcol[col]): 509 514 x = None … … 540 545 self._p.release() 541 546 self.set_selection(sel[0],sel[1],sel[2]) 542 self._v erbose(vb)547 self._vb = rcParams['verbose'] 543 548 return
Note:
See TracChangeset
for help on using the changeset viewer.