Changeset 1603 for branches/alma/python


Ignore:
Timestamp:
07/18/09 06:35:47 (15 years ago)
Author:
TakTsutsumi
Message:

New Development: No, merge with asap2.3.1

JIRA Issue: Yes CAS-1450

Ready to Release: Yes/No?

Interface Changes: Yes/No?

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: Yes

Module(s): single dish

Description: Upgrade of alma branch based on ASAP2.2.0

(rev.1562) to ASAP2.3.1 (rev.1561)


Location:
branches/alma/python
Files:
7 edited

Legend:

Unmodified
Added
Removed
  • branches/alma/python/__init__.py

    r1494 r1603  
    3232    os.mkdir(userdir)
    3333    #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")
    3437    f = file(userdir+"/asapuserfuncs.py", "w")
    3538    f.close()
    3639    f = file(userdir+"/ipythonrc", "w")
    3740    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
    3848# remove from namespace
    3949del asapdata, userdir, shutil, platform
     
    99109    'plotter.histogram'  : [False, _validate_bool],
    100110    'plotter.papertype'  : ['A4', str],
     111    'plotter.xaxisformatting' : ['asap', str],
    101112
    102113    # scantable
     
    105116    'scantable.freqframe' : ['LSRK', str],  #default frequency frame
    106117    '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]
    108121    # fitter
    109122    }
     
    136149plotter.ganged             : True
    137150
    138 # decimate the number of points plotted bya afactor of
     151# decimate the number of points plotted by a factor of
    139152# nchan/1024
    140153plotter.decimate           : False
     
    150163plotter.papertype          : A4
    151164
     165# The formatting style of the xaxis
     166plotter.xaxisformatting    : 'asap' or 'mpl'
     167
    152168# scantable
    153169
    154170# default storage of scantable ('memory'/'disk')
    155171scantable.storage          : memory
     172
     173# write history of each call to scantable
     174scantable.history          : True
     175
    156176# default ouput format when saving
    157177scantable.save             : ASAP
     178
    158179# auto averaging on read
    159180scantable.autoaverage      : True
     
    166187scantable.verbosesummary   : False
    167188
     189# Control the identification of reference (off) scans
     190# This is has to be a regular expression
     191scantable.reference         : .*(e|w|_R)$
    168192# Fitter
    169193"""
     
    242266    for k,v in kwargs.items():
    243267        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
    245272        if not rcParams.has_key(key):
    246273            raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % (key, group, name))
     
    352379if rcParams['useplotter']:
    353380    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
    360390    except ImportError:
    361         print "Matplotlib not installed. No plotting available"
     391        print "Matplotlib not installed. No plotting available"
    362392
    363393__date__ = '$Date$'.split()[1]
    364 __version__  = '2.2.0 alma'
     394__version__  = '2.3.1 alma'
    365395# nrao casapy specific, get revision number
    366396#__revision__ = ' unknown '
     
    369399if os.path.isfile(revinfo):
    370400    f = file(revinfo)
    371     f.readline()
     401    #f.readline()
    372402    revsionno=f.readline()
    373403    f.close()
     
    427457            get_fluxunit    - get the brightness flux unit
    428458            set_fluxunit    - set the brightness flux unit
     459            set_sourcetype  - set the type of the source - source or reference
    429460            create_mask     - return an mask in the current unit
    430461                              for the given region. The specified regions
     
    432463            get_restfreqs   - get the current list of rest frequencies
    433464            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
    435469            flag            - flag selected channels in the data
    436470            lag_flag        - flag specified frequency in the data
     
    439473            nbeam,nif,nchan,npol - the number of beams/IFs/Pols/Chans
    440474            nscan           - the number of scans in the scantable
    441             nrow            - te number of spectra in the scantable
     475            nrow            - the number of spectra in the scantable
    442476            history         - print the history of the scantable
    443477            get_fit         - get a fit which has been stored witnh the data
  • branches/alma/python/asapfitter.py

    r1461 r1603  
    33from asap import print_log
    44from asap import _n_bools
     5from asap import mask_and
    56
    67class fitter:
     
    5354        Parameters:
    5455            thescan:     a scantable
    55             mask:        a msk retireved from the scantable
     56            mask:        a msk retrieved from the scantable
    5657        """
    5758        if not thescan:
     
    142143                self.x = self.data._getabcissa(row)
    143144                self.y = self.data._getspectrum(row)
     145                self.mask = mask_and(self.mask, self.data._getmask(row))
    144146                from asap import asaplog
    145147                asaplog.push("Fitting:")
    146148                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))
    148154                asaplog.push(out,False)
    149155        self.fitter.setdata(self.x, self.y, self.mask)
     
    245251
    246252    def set_gauss_parameters(self, peak, centre, fwhm,
    247                              peakfixed=0, centerfixed=0,
     253                             peakfixed=0, centrefixed=0,
    248254                             fwhmfixed=0,
    249255                             component=0):
     
    253259            peak, centre, fwhm:  The gaussian parameters
    254260            peakfixed,
    255             centerfixed,
     261            centrefixed,
    256262            fwhmfixed:           Optional parameters to indicate if
    257263                                 the paramters should be held fixed during
     
    270276        if 0 <= component < len(self.components):
    271277            d = {'params':[peak, centre, fwhm],
    272                  'fixed':[peakfixed, centerfixed, fwhmfixed]}
     278                 'fixed':[peakfixed, centrefixed, fwhmfixed]}
    273279            self.set_parameters(d, component)
    274280        else:
     
    604610        asaplog.push("Fitting:")
    605611        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))
    607617            asaplog.push(out, False)
    608618            self.x = scan._getabcissa(r)
    609619            self.y = scan._getspectrum(r)
     620            self.mask = mask_and(self.mask, scan._getmask(r))
    610621            self.data = None
    611622            self.fit()
     623            x = self.get_parameters()
    612624            fpar = self.get_parameters()
    613625            if plot:
  • branches/alma/python/asaplotbase.py

    r1446 r1603  
    1515from matplotlib.ticker import OldScalarFormatter
    1616from matplotlib.ticker import NullLocator
    17 from matplotlib.transforms import blend_xy_sep_transform
     17
     18# API change in mpl >= 0.98
     19try:
     20    from matplotlib.transforms import blended_transform_factory
     21except ImportError:
     22    from matplotlib.transforms import blend_xy_sep_transform  as blended_transform_factory
    1823
    1924if int(matplotlib.__version__.split(".")[1]) < 87:
     
    161166        y2 = range(l2)
    162167        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
    167177        for i in range(l2):
    168178            x2[i] = x[i/2]
     
    410420                if fname[-3:].lower() == ".ps":
    411421                    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()
    414424
    415425                    if orientation is None:
     
    428438                    ow = ds * w
    429439                    oh = ds * h
    430                     self.figure.set_figsize_inches((ow, oh))
     440                    self.figure.set_size_inches((ow, oh))
    431441                    self.figure.savefig(fname, orientation=orientation,
    432442                                        papertype=papertype.lower())
    433                     self.figure.set_figsize_inches((w, h))
     443                    self.figure.set_size_inches((w, h))
    434444                    print 'Written file %s' % (fname)
    435445                else:
     
    617627                    self.subplots[i]['axes'] = self.figure.add_subplot(rows,
    618628                                                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())
    620631                else:
    621632                    if i == 0:
    622633                        self.subplots[i]['axes'] = self.figure.add_subplot(rows,
    623634                                                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())
    625638                    else:
    626639                        self.subplots[i]['axes'] = self.figure.add_subplot(rows,
     
    709722            for sp in self.subplots:
    710723                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)
    714727                fp = FP(size=rcParams['axes.labelsize'])
    715728                setp(ax.get_xticklabels(), fontsize=xts)
     
    770783        if rotate > 0.0: lbloffset = 0.03*len(label)
    771784        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)
    775796        if location.lower() == 'top':
    776797            ymax = 1.0-lbloffset
     
    783804            valign = 'top'
    784805            ylbl = ymin-0.01
    785         trans = blend_xy_sep_transform(ax.transData, ax.transAxes)
     806        trans = blended_transform_factory(ax.transData, ax.transAxes)
    786807        l = ax.axvline(x, ymin, ymax, color='black', **kwargs)
    787808        t = ax.text(x, ylbl ,label, verticalalignment=valign,
  • branches/alma/python/asaplotgui.py

    r1153 r1603  
    55from asap.asaplotbase import *
    66import Tkinter as Tk
     7import matplotlib
    78from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, \
    89        FigureManagerTkAgg
    910# Force use of the newfangled toolbar.
    10 import matplotlib
    11 matplotlib.use("TkAgg")
    1211matplotlib.rcParams['toolbar'] = 'toolbar2'
    1312
  • branches/alma/python/linecatalog.py

    r1259 r1603  
    11"""
    2 A representation of a spectra line catalog.
     2A representation of a spectral line catalog.
    33
    44Author: Malte Marquarding
     
    3434            else:
    3535                raise IOError(msg)
     36
     37    def __repr__(self):
     38        return lcbase.summary(self, -1)
    3639
    3740    def summary(self):
  • branches/alma/python/scantable.py

    r1530 r1603  
    4545            Scantable.__init__(self, filename)
    4646        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):
    4850                import os.path
    4951                filename = os.path.expandvars(filename)
     
    9698                                       'MS2' (saves as an aips++
    9799                                              MeasurementSet V2)
     100                                       'FITS' (save as image FITS - not
     101                                               readable by class)
     102                                       'CLASS' (save as FITS readable by CLASS)
    98103            overwrite:   If the file should be overwritten if it exists.
    99104                         The default False is to return with warning
     
    279284            return info
    280285
     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)
    281308
    282309    def get_selection(self):
     
    518545        times = self._get_column(self._gettime, row)
    519546        if not asdatetime:
    520             return times 
     547            return times
    521548        format = "%Y/%m/%d/%H:%M:%S"
    522549        if isinstance(times, list):
     
    755782                          to remove
    756783            width:        the width of the frequency to remove, to remove a
    757                           range of frequencies aroung the centre.
     784                          range of frequencies around the centre.
    758785            unit:         the frequency unit (default "GHz")
    759786        Notes:
     
    964991        IF 1 gets restfreq 2e9.
    965992        ********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.
    967994
    968995        Parameters:
     
    16871714            return s
    16881715
     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
    16891752    def auto_quotient(self, preserve=True, mode='paired'):
    16901753        """
     
    17031766                            '_e'/'_w' (Tid) and matches
    17041767                            on/off pairs from the observing pattern
    1705                 'time'
    1706                    finds the closest off in time
     1768                            'time'
     1769                            finds the closest off in time
    17071770
    17081771        """
     
    18641927            return fit.as_dict()
    18651928
     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
    18661949    def _add_history(self, funcname, parameters):
     1950        if not rcParams['scantable.history']:
     1951            return
    18671952        # create date
    18681953        sep = "##"
     
    19542039            tbl = Scantable(stype)
    19552040            r = stfiller(tbl)
     2041            rx = rcParams['scantable.reference']
     2042            r._setreferenceexpr(rx)
    19562043            msg = "Importing %s..." % (name)
    19572044            asaplog.push(msg, False)
     
    19592046            r._open(name, -1, -1, getpt)
    19602047            r._read()
    1961             #tbl = r._getdata()
    19622048            if average:
    19632049                tbl = self._math._average((tbl, ), (), 'NONE', 'SCAN')
    1964                 #tbl = tbl2
    19652050            if not first:
    19662051                tbl = self._math._merge([self, tbl])
    1967                 #tbl = tbl2
    19682052            Scantable.__init__(self, tbl)
    19692053            r._close()
     
    19742058        #self.set_freqframe(rcParams['scantable.freqframe'])
    19752059
     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  
    4747   
    4848    # for the americans
    49     set_polarization = set_polarisations
     49    set_polarizations = set_polarisations
     50    # for the lazy
     51    set_pols = set_polarisations
    5052
    5153    def set_ifs(self, ifs=[]):
     
    163165        prefix = "SELECT FROM $1 WHERE "
    164166        return self._gettaql().replace(prefix, "")
     167
    165168    def get_name(self):
    166169        print "NYI"
Note: See TracChangeset for help on using the changeset viewer.