Changeset 1603 for branches/alma/python
- Timestamp:
- 07/18/09 06:35:47 (15 years ago)
- Location:
- branches/alma/python
- Files:
-
- 7 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/alma/python/__init__.py
r1494 r1603 32 32 os.mkdir(userdir) 33 33 #shutil.copyfile(asapdata+"/data/ipythonrc-asap", userdir+"/ipythonrc-asap") 34 # commented out by TT on 2009.06.23 for casapy use 35 ##shutil.copyfile(asapdata+"/data/ipy_user_conf.py", 36 ## userdir+"/ipy_user_conf.py") 34 37 f = file(userdir+"/asapuserfuncs.py", "w") 35 38 f.close() 36 39 f = file(userdir+"/ipythonrc", "w") 37 40 f.close() 41 # commented out by TT on 2009.06.23 for casapy use 42 ##else: 43 # upgrade to support later ipython versions 44 ##if not os.path.exists(userdir+"/ipy_user_conf.py"): 45 ## shutil.copyfile(asapdata+"/data/ipy_user_conf.py", 46 ## userdir+"/ipy_user_conf.py") 47 38 48 # remove from namespace 39 49 del asapdata, userdir, shutil, platform … … 99 109 'plotter.histogram' : [False, _validate_bool], 100 110 'plotter.papertype' : ['A4', str], 111 'plotter.xaxisformatting' : ['asap', str], 101 112 102 113 # scantable … … 105 116 'scantable.freqframe' : ['LSRK', str], #default frequency frame 106 117 'scantable.verbosesummary' : [False, _validate_bool], 107 'scantable.storage' : ['memory', str] 118 'scantable.storage' : ['memory', str], 119 'scantable.history' : [True, _validate_bool], 120 'scantable.reference' : ['.*(e|w|_R)$', str] 108 121 # fitter 109 122 } … … 136 149 plotter.ganged : True 137 150 138 # decimate the number of points plotted by a afactor of151 # decimate the number of points plotted by a factor of 139 152 # nchan/1024 140 153 plotter.decimate : False … … 150 163 plotter.papertype : A4 151 164 165 # The formatting style of the xaxis 166 plotter.xaxisformatting : 'asap' or 'mpl' 167 152 168 # scantable 153 169 154 170 # default storage of scantable ('memory'/'disk') 155 171 scantable.storage : memory 172 173 # write history of each call to scantable 174 scantable.history : True 175 156 176 # default ouput format when saving 157 177 scantable.save : ASAP 178 158 179 # auto averaging on read 159 180 scantable.autoaverage : True … … 166 187 scantable.verbosesummary : False 167 188 189 # Control the identification of reference (off) scans 190 # This is has to be a regular expression 191 scantable.reference : .*(e|w|_R)$ 168 192 # Fitter 169 193 """ … … 242 266 for k,v in kwargs.items(): 243 267 name = aliases.get(k) or k 244 key = '%s.%s' % (group, name) 268 if len(group): 269 key = '%s.%s' % (group, name) 270 else: 271 key = name 245 272 if not rcParams.has_key(key): 246 273 raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % (key, group, name)) … … 352 379 if rcParams['useplotter']: 353 380 try: 354 from asapplotter import asapplotter 355 gui = os.environ.has_key('DISPLAY') and rcParams['plotter.gui'] 356 if gui: 357 import pylab as xyplotter 358 plotter = asapplotter(gui) 359 del gui 381 from asapplotter import asapplotter 382 gui = os.environ.has_key('DISPLAY') and rcParams['plotter.gui'] 383 if gui: 384 import matplotlib 385 matplotlib.use("TkAgg") 386 import pylab 387 xyplotter = pylab 388 plotter = asapplotter(gui) 389 del gui 360 390 except ImportError: 361 391 print "Matplotlib not installed. No plotting available" 362 392 363 393 __date__ = '$Date$'.split()[1] 364 __version__ = '2. 2.0alma'394 __version__ = '2.3.1 alma' 365 395 # nrao casapy specific, get revision number 366 396 #__revision__ = ' unknown ' … … 369 399 if os.path.isfile(revinfo): 370 400 f = file(revinfo) 371 f.readline()401 #f.readline() 372 402 revsionno=f.readline() 373 403 f.close() … … 427 457 get_fluxunit - get the brightness flux unit 428 458 set_fluxunit - set the brightness flux unit 459 set_sourcetype - set the type of the source - source or reference 429 460 create_mask - return an mask in the current unit 430 461 for the given region. The specified regions … … 432 463 get_restfreqs - get the current list of rest frequencies 433 464 set_restfreqs - set a list of rest frequencies 434 shift_refpix - shift the reference pixel of the IFs 465 shift_refpix - shift the reference pixel of the IFs 466 set_spectrum - overwrite the spectrum for a given row 467 get_spectrum - retrieve the spectrum for a given 468 get_mask - retrieve the mask for a given 435 469 flag - flag selected channels in the data 436 470 lag_flag - flag specified frequency in the data … … 439 473 nbeam,nif,nchan,npol - the number of beams/IFs/Pols/Chans 440 474 nscan - the number of scans in the scantable 441 nrow - t e number of spectra in the scantable475 nrow - the number of spectra in the scantable 442 476 history - print the history of the scantable 443 477 get_fit - get a fit which has been stored witnh the data -
branches/alma/python/asapfitter.py
r1461 r1603 3 3 from asap import print_log 4 4 from asap import _n_bools 5 from asap import mask_and 5 6 6 7 class fitter: … … 53 54 Parameters: 54 55 thescan: a scantable 55 mask: a msk ret ireved from the scantable56 mask: a msk retrieved from the scantable 56 57 """ 57 58 if not thescan: … … 142 143 self.x = self.data._getabcissa(row) 143 144 self.y = self.data._getspectrum(row) 145 self.mask = mask_and(self.mask, self.data._getmask(row)) 144 146 from asap import asaplog 145 147 asaplog.push("Fitting:") 146 148 i = row 147 out = "Scan[%d] Beam[%d] IF[%d] Pol[%d] Cycle[%d]" % (self.data.getscan(i),self.data.getbeam(i),self.data.getif(i),self.data.getpol(i), self.data.getcycle(i)) 149 out = "Scan[%d] Beam[%d] IF[%d] Pol[%d] Cycle[%d]" % (self.data.getscan(i), 150 self.data.getbeam(i), 151 self.data.getif(i), 152 self.data.getpol(i), 153 self.data.getcycle(i)) 148 154 asaplog.push(out,False) 149 155 self.fitter.setdata(self.x, self.y, self.mask) … … 245 251 246 252 def set_gauss_parameters(self, peak, centre, fwhm, 247 peakfixed=0, cent erfixed=0,253 peakfixed=0, centrefixed=0, 248 254 fwhmfixed=0, 249 255 component=0): … … 253 259 peak, centre, fwhm: The gaussian parameters 254 260 peakfixed, 255 cent erfixed,261 centrefixed, 256 262 fwhmfixed: Optional parameters to indicate if 257 263 the paramters should be held fixed during … … 270 276 if 0 <= component < len(self.components): 271 277 d = {'params':[peak, centre, fwhm], 272 'fixed':[peakfixed, cent erfixed, fwhmfixed]}278 'fixed':[peakfixed, centrefixed, fwhmfixed]} 273 279 self.set_parameters(d, component) 274 280 else: … … 604 610 asaplog.push("Fitting:") 605 611 for r in rows: 606 out = " Scan[%d] Beam[%d] IF[%d] Pol[%d] Cycle[%d]" % (scan.getscan(r),scan.getbeam(r),scan.getif(r),scan.getpol(r), scan.getcycle(r)) 612 out = " Scan[%d] Beam[%d] IF[%d] Pol[%d] Cycle[%d]" % (scan.getscan(r), 613 scan.getbeam(r), 614 scan.getif(r), 615 scan.getpol(r), 616 scan.getcycle(r)) 607 617 asaplog.push(out, False) 608 618 self.x = scan._getabcissa(r) 609 619 self.y = scan._getspectrum(r) 620 self.mask = mask_and(self.mask, scan._getmask(r)) 610 621 self.data = None 611 622 self.fit() 623 x = self.get_parameters() 612 624 fpar = self.get_parameters() 613 625 if plot: -
branches/alma/python/asaplotbase.py
r1446 r1603 15 15 from matplotlib.ticker import OldScalarFormatter 16 16 from matplotlib.ticker import NullLocator 17 from matplotlib.transforms import blend_xy_sep_transform 17 18 # API change in mpl >= 0.98 19 try: 20 from matplotlib.transforms import blended_transform_factory 21 except ImportError: 22 from matplotlib.transforms import blend_xy_sep_transform as blended_transform_factory 18 23 19 24 if int(matplotlib.__version__.split(".")[1]) < 87: … … 161 166 y2 = range(l2) 162 167 m2 = range(l2) 163 #ymsk = y.raw_mask() 164 #ydat = y.raw_data() 165 ymsk = y.mask 166 ydat = y.data 168 ymsk = None 169 ydat = None 170 if hasattr(y, "raw_mask"): 171 # numpy < 1.1 172 ymsk = y.raw_mask() 173 ydat = y.raw_data() 174 else: 175 ymsk = y.mask 176 ydat = y.data 167 177 for i in range(l2): 168 178 x2[i] = x[i/2] … … 410 420 if fname[-3:].lower() == ".ps": 411 421 from matplotlib import __version__ as mv 412 w = self.figure. figwidth.get()413 h = self.figure. figheight.get()422 w = self.figure.get_figwidth() 423 h = self.figure.get_figheight() 414 424 415 425 if orientation is None: … … 428 438 ow = ds * w 429 439 oh = ds * h 430 self.figure.set_ figsize_inches((ow, oh))440 self.figure.set_size_inches((ow, oh)) 431 441 self.figure.savefig(fname, orientation=orientation, 432 442 papertype=papertype.lower()) 433 self.figure.set_ figsize_inches((w, h))443 self.figure.set_size_inches((w, h)) 434 444 print 'Written file %s' % (fname) 435 445 else: … … 617 627 self.subplots[i]['axes'] = self.figure.add_subplot(rows, 618 628 cols, i+1) 619 self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter()) 629 if asaprcParams['plotter.xaxisformatting'] == 'mpl': 630 self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter()) 620 631 else: 621 632 if i == 0: 622 633 self.subplots[i]['axes'] = self.figure.add_subplot(rows, 623 634 cols, i+1) 624 self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter()) 635 if asaprcParams['plotter.xaxisformatting'] != 'mpl': 636 637 self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter()) 625 638 else: 626 639 self.subplots[i]['axes'] = self.figure.add_subplot(rows, … … 709 722 for sp in self.subplots: 710 723 ax = sp['axes'] 711 s = rcParams['axes.titlesize']712 tsize = s-(self.cols+self.rows -1)713 ax.title.set_size( max(tsize,9))724 s = ax.title.get_size() 725 tsize = s-(self.cols+self.rows) 726 ax.title.set_size(tsize) 714 727 fp = FP(size=rcParams['axes.labelsize']) 715 728 setp(ax.get_xticklabels(), fontsize=xts) … … 770 783 if rotate > 0.0: lbloffset = 0.03*len(label) 771 784 peakoffset = 0.01 772 xy0 = ax.transData.xy_tup((x,y)) 773 # get relative coords 774 xy = ax.transAxes.inverse_xy_tup(xy0) 785 xy = None 786 xy0 = None 787 # matplotlib api change 0.98 is using transform now 788 if hasattr(ax.transData, "inverse_xy_tup"): 789 # get relative coords 790 xy0 = ax.transData.xy_tup((x,y)) 791 xy = ax.transAxes.inverse_xy_tup(xy0) 792 else: 793 xy0 = ax.transData.transform((x,y)) 794 # get relative coords 795 xy = ax.transAxes.inverted().transform(xy0) 775 796 if location.lower() == 'top': 776 797 ymax = 1.0-lbloffset … … 783 804 valign = 'top' 784 805 ylbl = ymin-0.01 785 trans = blend _xy_sep_transform(ax.transData, ax.transAxes)806 trans = blended_transform_factory(ax.transData, ax.transAxes) 786 807 l = ax.axvline(x, ymin, ymax, color='black', **kwargs) 787 808 t = ax.text(x, ylbl ,label, verticalalignment=valign, -
branches/alma/python/asaplotgui.py
r1153 r1603 5 5 from asap.asaplotbase import * 6 6 import Tkinter as Tk 7 import matplotlib 7 8 from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, \ 8 9 FigureManagerTkAgg 9 10 # Force use of the newfangled toolbar. 10 import matplotlib11 matplotlib.use("TkAgg")12 11 matplotlib.rcParams['toolbar'] = 'toolbar2' 13 12 -
branches/alma/python/linecatalog.py
r1259 r1603 1 1 """ 2 A representation of a spectra line catalog.2 A representation of a spectral line catalog. 3 3 4 4 Author: Malte Marquarding … … 34 34 else: 35 35 raise IOError(msg) 36 37 def __repr__(self): 38 return lcbase.summary(self, -1) 36 39 37 40 def summary(self): -
branches/alma/python/scantable.py
r1530 r1603 45 45 Scantable.__init__(self, filename) 46 46 else: 47 if isinstance(filename, str): 47 if isinstance(filename, str):# or \ 48 # (isinstance(filename, list) or isinstance(filename, tuple)) \ 49 # and isinstance(filename[-1], str): 48 50 import os.path 49 51 filename = os.path.expandvars(filename) … … 96 98 'MS2' (saves as an aips++ 97 99 MeasurementSet V2) 100 'FITS' (save as image FITS - not 101 readable by class) 102 'CLASS' (save as FITS readable by CLASS) 98 103 overwrite: If the file should be overwritten if it exists. 99 104 The default False is to return with warning … … 279 284 return info 280 285 286 def get_spectrum(self, rowno): 287 """Return the spectrum for the current row in the scantable as a list. 288 Parameters: 289 rowno: the row number to retrieve the spectrum from 290 """ 291 return self._getspectrum(rowno) 292 293 def get_mask(self, rowno): 294 """Return the mask for the current row in the scantable as a list. 295 Parameters: 296 rowno: the row number to retrieve the mask from 297 """ 298 return self._getmask(rowno) 299 300 def set_spectrum(self, spec, rowno): 301 """Return the spectrum for the current row in the scantable as a list. 302 Parameters: 303 spec: the spectrum 304 rowno: the row number to set the spectrum for 305 """ 306 assert(len(spec) == self.nchan()) 307 return self._setspectrum(spec, rowno) 281 308 282 309 def get_selection(self): … … 518 545 times = self._get_column(self._gettime, row) 519 546 if not asdatetime: 520 return times 547 return times 521 548 format = "%Y/%m/%d/%H:%M:%S" 522 549 if isinstance(times, list): … … 755 782 to remove 756 783 width: the width of the frequency to remove, to remove a 757 range of frequencies aroun gthe centre.784 range of frequencies around the centre. 758 785 unit: the frequency unit (default "GHz") 759 786 Notes: … … 964 991 IF 1 gets restfreq 2e9. 965 992 ********NEED TO BE UPDATED end************ 966 You can also specify the frequencies via a linecatalog /993 You can also specify the frequencies via a linecatalog. 967 994 968 995 Parameters: … … 1687 1714 return s 1688 1715 1716 def set_sourcetype(self, match, matchtype="pattern", 1717 sourcetype="reference"): 1718 """ 1719 Set the type of the source to be an source or reference scan 1720 using the provided pattern: 1721 Parameters: 1722 match: a Unix style pattern, regular expression or selector 1723 matchtype: 'pattern' (default) UNIX style pattern or 1724 'regex' regular expression 1725 sourcetype: the type of the source to use (source/reference) 1726 """ 1727 varlist = vars() 1728 basesel = self.get_selection() 1729 stype = -1 1730 if sourcetype.lower().startswith("r"): 1731 stype = 1 1732 elif sourcetype.lower().startswith("s"): 1733 stype = 0 1734 else: 1735 raise ValueError("Illegal sourcetype use s(ource) or r(eference)") 1736 if matchtype.lower().startswith("p"): 1737 matchtype = "pattern" 1738 elif matchtype.lower().startswith("r"): 1739 matchtype = "regex" 1740 else: 1741 raise ValueError("Illegal matchtype, use p(attern) or r(egex)") 1742 sel = selector() 1743 if isinstance(match, selector): 1744 sel = match 1745 else: 1746 sel.set_query("SRCNAME == %s('%s')" % (matchtype, match)) 1747 self.set_selection(basesel+sel) 1748 self._setsourcetype(stype) 1749 self.set_selection(basesel) 1750 s._add_history("set_sourcetype", varlist) 1751 1689 1752 def auto_quotient(self, preserve=True, mode='paired'): 1690 1753 """ … … 1703 1766 '_e'/'_w' (Tid) and matches 1704 1767 on/off pairs from the observing pattern 1705 'time'1706 finds the closest off in time1768 'time' 1769 finds the closest off in time 1707 1770 1708 1771 """ … … 1864 1927 return fit.as_dict() 1865 1928 1929 def flag_nans(self): 1930 """ 1931 Utility function to flag NaN values in the scantable. 1932 """ 1933 import numpy 1934 basesel = self.get_selection() 1935 for i in range(self.nrow()): 1936 sel = selector()+basesel 1937 sel.set_scans(self.getscan(i)) 1938 sel.set_beams(self.getbeam(i)) 1939 sel.set_ifs(self.getif(i)) 1940 sel.set_polarisations(self.getpol(i)) 1941 self.set_selection(sel) 1942 nans = numpy.isnan(self._getspectrum(0)) 1943 if numpy.any(nans): 1944 bnans = [ bool(v) for v in nans] 1945 self.flag(bnans) 1946 self.set_selection(basesel) 1947 1948 1866 1949 def _add_history(self, funcname, parameters): 1950 if not rcParams['scantable.history']: 1951 return 1867 1952 # create date 1868 1953 sep = "##" … … 1954 2039 tbl = Scantable(stype) 1955 2040 r = stfiller(tbl) 2041 rx = rcParams['scantable.reference'] 2042 r._setreferenceexpr(rx) 1956 2043 msg = "Importing %s..." % (name) 1957 2044 asaplog.push(msg, False) … … 1959 2046 r._open(name, -1, -1, getpt) 1960 2047 r._read() 1961 #tbl = r._getdata()1962 2048 if average: 1963 2049 tbl = self._math._average((tbl, ), (), 'NONE', 'SCAN') 1964 #tbl = tbl21965 2050 if not first: 1966 2051 tbl = self._math._merge([self, tbl]) 1967 #tbl = tbl21968 2052 Scantable.__init__(self, tbl) 1969 2053 r._close() … … 1974 2058 #self.set_freqframe(rcParams['scantable.freqframe']) 1975 2059 2060 def __getitem__(self, key): 2061 if key < 0: 2062 key += self.nrow() 2063 if key >= self.nrow(): 2064 raise IndexError("Row index out of range.") 2065 return self._getspectrum(key) 2066 2067 def __setitem__(self, key, value): 2068 if key < 0: 2069 key += self.nrow() 2070 if key >= self.nrow(): 2071 raise IndexError("Row index out of range.") 2072 if not hasattr(value, "__len__") or \ 2073 len(value) > self.nchan(self.getif(key)): 2074 raise ValueError("Spectrum length doesn't match.") 2075 return self._setspectrum(value, key) 2076 2077 def __len__(self): 2078 return self.nrow() 2079 2080 def __iter__(self): 2081 for i in range(len(self)): 2082 yield self[i] -
branches/alma/python/selector.py
r1349 r1603 47 47 48 48 # for the americans 49 set_polarization = set_polarisations 49 set_polarizations = set_polarisations 50 # for the lazy 51 set_pols = set_polarisations 50 52 51 53 def set_ifs(self, ifs=[]): … … 163 165 prefix = "SELECT FROM $1 WHERE " 164 166 return self._gettaql().replace(prefix, "") 167 165 168 def get_name(self): 166 169 print "NYI"
Note:
See TracChangeset
for help on using the changeset viewer.