Changes in trunk [1949:1849]


Ignore:
Location:
trunk
Files:
2 added
11 deleted
73 edited

Legend:

Unmodified
Added
Removed
  • trunk/Makefile

    r1949 r1849  
    77#for linux
    88PREFIX := $(word 1, $(CASAPATH))/$(word 2,$(CASAPATH))
    9 PYTHONVER := $(shell $(shell make -s -f $(PREFIX)/makedefs VARS=PYTHONVER eval_vars) && echo $$PYTHONVER)
    10 PYDIR := $(PREFIX)/python/$(PYTHONVER)
     9PYDIR := $(PREFIX)/python/2.5
    1110
    1211ifndef ASAPROOT
    1312   ASAPROOT := $(shell pwd)
    1413endif
    15 ATNFD := external-alma
    16 PYRAPD := external/libpyrap
    1714
    1815#PY := $(wildcard python/*.py)
     
    3027module:
    3128        @if ( test -f getsvnrev.sh ) ; then /bin/bash getsvnrev.sh ; fi
    32         @cd $(ASAPROOT)/$(PYRAPD); make
    33         @cd $(ASAPROOT)/$(ATNFD); make
    3429        @cd $(ASAPROOT)/src; make
    3530        @cd $(ASAPROOT)/apps; make
     
    4338        @if ( test ! -d $(PYDIR)/asap ) ; then mkdir -p $(PYDIR)/asap ; fi
    4439        @if ( test ! -d $(PREFIX)/bin ) ; then mkdir -p $(PREFIX)/bin ; fi
    45         @cd $(ASAPROOT)/$(ATNFD); make install
    46         @cd $(ASAPROOT)/$(PYRAPD); make install
    4740        @for file in $(LIBS) ; do cp -f $$file $(PYDIR)/asap ; done
    4841        @for file in $(BINS) ; do cp -f $$file $(PREFIX)/bin ; done
    4942        @for file in $(PY) ; do cp -f $$file $(PYDIR)/asap ; done
     43        @for file in $(APPS) ; do cp -f $$file $(PREFIX)/bin ; done
    5044        @if ( test ! -d $(PREFIX)/share/asap ) ; then mkdir -p $(PREFIX)/share/asap ; fi
    5145        @cp -f share/ipythonrc-asap $(PREFIX)/share/asap/
    52         @for file in $(APPS) ; do cp -f $$file $(PREFIX)/bin ; done
    5346        @echo "Successfully installed asap module to" $(PYDIR)
    5447
    5548clean:
    5649        @cd $(ASAPROOT)/src; make clean
    57 #       @cd $(ASAPROOT)/doc; make clean
    58         @cd $(ASAPROOT)/$(ATNFD); make realclean
    59         @cd $(ASAPROOT)/apps; make clean
    60         @cd $(ASAPROOT)/$(PYRAPD); make clean
     50        @cd $(ASAPROOT)/doc; make clean
    6151
    6252datadist:
  • trunk/SConstruct

    r1949 r1849  
    44import platform
    55import SCons
    6 
    7 # try to autodetect numpy
    8 def get_numpy_incdir():
    9     try:
    10         # try to find an egg
    11         from pkg_resources import require
    12         tmp = require("numpy")
    13         import numpy
    14         return numpy.__path__[0]+"/core/include"
    15     except Exception:
    16         # now try standard package
    17         try:
    18             import numpy
    19             return numpy.__path__[0]+"/core/include"
    20         except ImportError:
    21             pass
    22     return ""
    236
    247moduledir = distutils.sysconfig.get_python_lib()
     
    7558                ("pyraproot", "The root directory where libpyrap is installed",
    7659                 None),
    77                 ("numpyincdir", "numpy header file directory",
    78                  get_numpy_incdir()),
    7960                ("pyraplib", "The name of the pyrap library", "pyrap"),
    8061                ("pyraplibdir", "The directory where libpyrap is installed",
     
    147128
    148129    conf.env.AddCustomPackage('pyrap')
    149     if conf.CheckLib(conf.env["pyraplib"], language='c++', autoadd=0):
    150         conf.env.Append(CPPFLAGS=['-DHAVE_LIBPYRAP'])
     130    if  conf.env.get("enable_pyrap") and conf.CheckLib(conf.env["pyraplib"],
     131                                                       language='c++',
     132                                                       autoadd=0):
     133        conf.env.Append(CPPFLAGS=['-DHAVE_PYRAP'])
    151134        conf.env.PrependUnique(LIBS=env['pyraplib'])
    152     else:
    153         conf.env.AppendUnique(CPPPATH=[conf.env["numpyincdir"]])
    154         # numpy 1.0 uses config.h; numpy >= 1.1 uses numpyconfig.h
    155         if conf.CheckHeader("numpy/config.h") or \
    156                conf.CheckHeader("numpy/numpyconfig.h"):
    157             conf.env.Append(CPPDEFINES=["-DAIPS_USENUMPY"])
    158         else:
    159             conf.env.Exit(1)
    160         conf.env.Append(CPPFLAGS=['-DHAVE_LIBPYRAP'])
    161         # compile in pyrap here...
    162         conf.env["pyrapint"] = "#/external/libpyrap/pyrap-0.3.2"
     135   
    163136    # test for cfitsio
    164137    if not conf.CheckLib("m"): Exit(1)
  • trunk/apps

  • trunk/apps/Makefile

    r1949 r1849  
    88CASAARCH  := $(word 2, $(CASAPATH))
    99
    10 CORELIB := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=CORELIB eval_vars) && echo $$CORELIB)
    1110COREINCD := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=COREINCD eval_vars) && echo $$COREINCD)
    1211CASALIB   := $(CASAROOT)/$(CASAARCH)/lib
     
    1817
    1918# compiler flags
    20 CXXFLAGS := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=CXXFLAGS eval_vars) && echo $$CXXFLAGS)
    21 CXXFLAGS += -fPIC -O3 -Xlinker -rpath -Xlinker $(CASALIB)
     19CXXFLAGS := -fPIC -O3 -g
     20CXXFLAGS += -ansi -Wno-long-long -Wall
     21CXXFLAGS := -Xlinker -rpath -Xlinker $(CASALIB)
    2222
    2323
    2424INCDIRS   := -I$(COREINCD)
    25 LIBS      := -L$(CASALIB) $(CORELIB)
     25LIBS      := -L$(CASALIB) -lcasa_tables -lcasa_casa
    2626
    2727OBJECTS := asap2to3
  • trunk/apps/asap2to3.cpp

    r1949 r1849  
    2929  Int verid=tab.rwKeywordSet().fieldNumber("VERSION");
    3030  tab.rwKeywordSet().define(verid,uInt(3));
    31   tab.tableInfo().setType("Scantable");
    3231  cout << "WARNING: This has invalidated the parallactic angle in the data. Reprocess the data in ASAP 3 "
    3332       << "if you need to handle polarisation conversions"
  • trunk/external-alma

  • trunk/external-alma/atnf/PKSIO/ASTEDataset.cc

    r1949 r1849  
    124124    + sizeof( char ) * 116                       // CDMY1
    125125    + sizeof( double ) * ASTE_ARYMAX ;           // DSBFC
    126 
    127   refFreq_.resize( ASTE_ARYMAX, 0.0 ) ;
    128126}
    129127
  • trunk/external-alma/atnf/PKSIO/ASTEFXDataset.cc

    r1949 r1849  
    124124    + sizeof( char ) * 116                          // CDMY1
    125125    + sizeof( double ) * ASTE_ARYMAX_FX ;           // DSBFC
    126 
    127   refFreq_.resize( ASTE_ARYMAX_FX, 0.0 ) ;
    128126}
    129127
  • trunk/external-alma/atnf/PKSIO/ASTEReader.cc

    r1949 r1849  
    8888  // Ref.: Ezawa, H. et al. 2004, Proc. SPIE, 5489, 763
    8989  //
    90   // double elon = -67. - 42. / 60. - 11. / 3600. ;
    91   // double nlat = -22. - 58. / 60. - 18. / 3600. ;
    92   // double alti = 2400. ;
    93   double elon = -67.7031 ;
    94   double nlat = -22.9717 ;
    95   double alti = 4800.0 ;
     90  double elon = -67. - 42. / 60. - 11. / 3600. ;
     91  double nlat = -22. - 58. / 60. - 18. / 3600. ;
     92  double alti = 2400. ;
    9693
    9794  // APEX value
     
    104101                           Quantity( nlat, "deg" ) ),
    105102               MPosition::Ref( MPosition::WGS84 ) ) ;
    106 
    107103  MeasFrame frame( p ) ;
    108104  MVPosition mvp ;
  • trunk/external-alma/atnf/PKSIO/MBFITSreader.cc

    r1949 r1849  
    146146  if (rpfitsin(jstat)) {
    147147    sprintf(cMsg, "Failed to open MBFITS file\n%s", rpname);
    148     //os << LogIO::SEVERE << cMsg << LogIO::POST ;
     148    os << LogIO::SEVERE << cMsg << LogIO::POST ;
    149149    return 1;
    150150  }
     
    165165    sprintf(cMsg, "Failed to read MBFITS header in file\n"
    166166                  "%s", rpname);
    167     //os << LogIO::SEVERE << cMsg << LogIO::POST ;
     167    os << LogIO::SEVERE << cMsg << LogIO::POST ;
    168168    close();
    169169    return 1;
  • trunk/external-alma/atnf/PKSIO/MBrecord.cc

    r1949 r1849  
    3737
    3838#include <atnf/PKSIO/MBrecord.h>
    39 #include <atnf/PKSIO/SrcType.h>
    4039
    4140#include <string.h>
     
    5958  decRate = 0.0f;
    6059  nIF     = 0;
    61 
    62   srcType = SrcType::NOTYPE ;
    63   srcVelocity = 0.0 ;
    6460}
    6561
     
    329325  srcVelocity = other.srcVelocity ;
    330326
    331   srcType = other.srcType ;
    332 
    333327  return *this;
    334328}
     
    448442  srcVelocity = other.srcVelocity ;
    449443
    450   srcType = other.srcType ;
    451 
    452444  return 0;
    453445}
  • trunk/external-alma/atnf/PKSIO/MBrecord.h

    r1949 r1849  
    167167                                // mode (added 1999/03/17).
    168168    int polNo ;                 // polarization ID
    169     double srcVelocity ;        // source velocity w.r.t. reference frame
    170 
    171     int srcType ;               // source type
     169    float srcVelocity ;         // source velocity w.r.t. reference frame
    172170
    173171  private:
  • trunk/external-alma/atnf/PKSIO/NRO45Reader.cc

    r1949 r1849  
    9393  // (conversion is done by http://vldb.gsi.go.jp/sokuchi/tky2jgd/)
    9494 
    95 //   double elon = 138. + 28. / 60. + 9.96444 / 3600. ;
    96 //   double nlat = 35. + 56. / 60. + 52.3314 / 3600. ;
    97 //   double alti = 1350. ;
     95  double elon = 138. + 28. / 60. + 9.96444 / 3600. ;
     96  double nlat = 35. + 56. / 60. + 52.3314 / 3600. ;
     97  double alti = 1350. ;
    9898
    99 //   Double elon = 138.4725 ;
    100 //   Double nlat = 35.9445 ;
    101 //   Double alti = 1412.599 ;
    102 
    103 //   MPosition p( MVPosition( Quantity( alti, "m" ),
    104 //                            Quantity( elon, "deg" ),
    105 //                            Quantity( nlat, "deg" ) ),
    106 //                MPosition::Ref( MPosition::WGS84 ) ) ;
    107 
    108   Double posx = -3.8710235e6 ;
    109   Double posy = 3.4281068e6 ;
    110   Double posz = 3.7240395e6 ;
    111   MPosition p( MVPosition( posx, posy, posz ),
    112                MPosition::ITRF ) ;
    113 
     99  MPosition p( MVPosition( Quantity( alti, "m" ),
     100                           Quantity( elon, "deg" ),
     101                           Quantity( nlat, "deg" ) ),
     102               MPosition::Ref( MPosition::WGS84 ) ) ;
    114103  MeasFrame frame( p ) ;
    115104  MVPosition mvp ;
  • trunk/external-alma/atnf/PKSIO/NRODataset.cc

    r1949 r1849  
    3434#include <casa/OS/Time.h>
    3535#include <scimath/Mathematics/InterpolateArray1D.h>
    36 
    37 #include <measures/Measures/MeasConvert.h>
    38 #include <measures/Measures/MCFrequency.h>
    39 #include <measures/Measures/MFrequency.h>
    40 #include <measures/Measures/MPosition.h>
    41 #include <measures/Measures/MEpoch.h>
    42 #include <measures/Measures/MDirection.h>
    4336
    4437#include <math.h>
     
    803796  }
    804797
    805   // conversion from TOPO to LSRK
    806   v[1] = toLSR( v[1], getStartIntTime( i ), record_->SCX, record_->SCY ) ;
    807 
    808   if ( refFreq_[ib] != 0.0 ) {
    809     v[1] = refFreq_[ib] ;
    810   }
    811   else {
    812     refFreq_[ib] = v[1] ;
    813   }
    814 
    815798  return v ;
    816799}
     
    837820
    838821}
    839 
    840 double NRODataset::toLSR( double v, double t, double x, double y )
    841 {
    842   double vlsr ;
    843 
    844   // get epoch
    845   double tcent = t + 0.5*getIPTIM()/86400.0 ;
    846   MEpoch me( Quantity( tcent, "d" ), MEpoch::UTC ) ;
    847 
    848   // get antenna position
    849   MPosition mp ;
    850   if ( SITE.find( "45" ) != string::npos ) {
    851     // 45m telescope
    852     Double posx = -3.8710235e6 ;
    853     Double posy = 3.4281068e6 ;
    854     Double posz = 3.7240395e6 ;
    855     mp = MPosition( MVPosition( posx, posy, posz ),
    856                     MPosition::ITRF ) ;
    857   }
    858   else {
    859     // ASTE
    860     Vector<Double> pos( 2 ) ;
    861     pos[0] = -67.7031 ;
    862     pos[1] = -22.9717 ;
    863     Double sitealt = 4800.0 ;
    864     mp = MPosition( MVPosition( Quantity( sitealt, "m" ),
    865                                 Quantum< Vector<Double> >( pos, "deg" ) ),
    866                     MPosition::WGS84 ) ;
    867   }
    868 
    869   // get direction
    870   MDirection md ;
    871   if ( SCNCD == 0 ) {
    872     // RADEC
    873     if ( EPOCH == "B1950" ) {
    874       md = MDirection( Quantity( Double(x), "rad" ), Quantity( Double(y), "rad" ),
    875                        MDirection::B1950 ) ;
    876     }
    877     else {
    878       md = MDirection( Quantity( Double(x), "rad" ), Quantity( Double(y), "rad" ),
    879                        MDirection::J2000 ) ;
    880     }
    881   }
    882   else if ( SCNCD == 1 ) {
    883     // LB
    884     md = MDirection( Quantity( Double(x), "rad" ), Quantity( Double(y), "rad" ),
    885                      MDirection::GALACTIC ) ;
    886   }
    887   else {
    888     // AZEL
    889     md = MDirection( Quantity( Double(x), "rad" ), Quantity( Double(y), "rad" ),
    890                      MDirection::AZEL ) ;
    891   }
    892    
    893   // to LSR
    894   MeasFrame mf( me, mp, md ) ;
    895   MFrequency::Convert tolsr( MFrequency::TOPO, MFrequency::Ref( MFrequency::LSRK, mf ) ) ;
    896   vlsr = (double)(tolsr( Double(v) ).get( "Hz" ).getValue()) ;
    897 
    898   return vlsr ;
    899 }
  • trunk/external-alma/atnf/PKSIO/NRODataset.h

    r1949 r1849  
    233233  void show() ;
    234234
    235   // convert frequency frame
    236   virtual double toLSR( double v, double t, double x, double y ) ;
    237 
    238235  // Type of file record
    239236  string LOFIL ;
     
    509506  // Logger
    510507  //LogIO os ;
    511 
    512   // reference frequency for each array
    513   vector<double> refFreq_ ;
    514508} ;
    515509
  • trunk/external-alma/atnf/PKSIO/NROFITSDataset.cc

    r1949 r1849  
    179179    + sizeof( double ) * ARYNM * 10 * 3    // FQCAL, CHCAL, CWCAL
    180180    + sizeof( char ) * 180 ;               // CDMY1
    181 
    182   refFreq_.resize( ARYNM, 0.0 ) ;
    183181}
    184182
     
    11671165  }
    11681166  else {
    1169     sprintf( record_->LAVST, "%4d%02d%02d%02d%02d%02d.000", itmp[0], itmp[1], itmp[2], itmp[3], itmp[4], itmp[5] ) ;
     1167    sprintf( record_->LAVST, "%d%d%d%d%d%d.000", itmp[0], itmp[1], itmp[2], itmp[3], itmp[4], itmp[5] ) ;
    11701168  }
    11711169  // DEBUG
     
    14621460//   //cout << endl ;
    14631461  //
    1464 
    1465 
    1466   // Update IPTIM since it depends on the row for NROFITS
    1467   int integ ;
    1468   status = readTable( integ, "INTEG", same_, i ) ;
    1469   if ( !status ) {
    1470     IPTIM = (double)integ ;
    1471   }
    1472 
    14731462  return status ;
    14741463}
     
    15241513    // debug
    15251514    //cout << "i=" << i << endl ;
    1526 //     if ( i == 16 ) {
    1527 //       ofstream ofs0( "spgrid0.dat" ) ;
    1528 //       for ( int ii = 0 ; ii < getNUMCH() ; ii++ )
    1529 //         ofs0 << xout[ii] << "," ;
    1530 //       ofs0 << endl ;
    1531 //       for ( int ii = 0 ; ii < getNUMCH() ; ii++ )
    1532 //         ofs0 << setprecision(16) << record->FREQ0+yout[ii] << "," ;
    1533 //       ofs0 << endl ;
    1534 //       ofs0.close() ;
    1535 //     }
     1515    if ( i == 16 ) {
     1516      ofstream ofs0( "spgrid0.dat" ) ;
     1517      for ( int ii = 0 ; ii < getNUMCH() ; ii++ )
     1518        ofs0 << xout[ii] << "," ;
     1519      ofs0 << endl ;
     1520      for ( int ii = 0 ; ii < getNUMCH() ; ii++ )
     1521        ofs0 << setprecision(16) << record->FREQ0+yout[ii] << "," ;
     1522      ofs0 << endl ;
     1523      ofs0.close() ;
     1524    }
    15361525    //
    15371526    Vector<Double> z( nchan ) ;
     
    27262715  return ib ;
    27272716}
    2728 
    2729 double NROFITSDataset::getStartIntTime( int i )
    2730 {
    2731   double v ;
    2732   readTable( v, "MJDST", same_, i ) ;
    2733   return v/86400.0 ;
    2734 }
    2735 
    2736 // double NROFITSDataset::toLSR( double v, double t, double x, double y )
    2737 // {
    2738 //   return v ;
    2739 // }
  • trunk/external-alma/atnf/PKSIO/NROFITSDataset.h

    r1949 r1849  
    9595  virtual int getPolarizationNum() ;
    9696  virtual uInt getArrayId( string type ) ;
    97   virtual double getStartIntTime( int i ) ;
    9897
    9998 protected:
     
    154153  int getOffset( char *name ) ;
    155154
    156   // convert frequency frame
    157 //   virtual double toLSR( double v, double t, double x, double y ) ;
    158 
    159155  // number of column for scan header
    160156  int numField_ ;
  • trunk/external-alma/atnf/PKSIO/NROOTFDataset.cc

    r1949 r1849  
    128128    + sizeof( double ) * NRO_ARYMAX * 10 * 3    // FQCAL, CHCAL, CWCAL
    129129    + sizeof( char ) * 180 ;                    // CDMY1
    130 
    131   refFreq_.resize( NRO_ARYMAX, 0.0 ) ;
    132130}
    133131
  • trunk/external-alma/atnf/PKSIO/NROReader.cc

    r1949 r1849  
    455455    }
    456456  }
    457   //freqref = vref ;
    458   freqref = "LSRK" ;
     457  freqref = vref ;
     458  // DEBUG
     459  freqref = "TOPO" ;
     460  //
    459461  //cout << "freqref = " << freqref << endl ;
    460462  NRODataRecord *record = dataset_->getRecord( 0 ) ;
  • trunk/external-alma/atnf/PKSIO/PKSFITSreader.cc

    r1949 r1849  
    3636#include <atnf/PKSIO/MBFITSreader.h>
    3737#include <atnf/PKSIO/SDFITSreader.h>
    38 #include <atnf/PKSIO/GBTFITSreader.h>
    3938#include <atnf/PKSIO/PKSFITSreader.h>
    4039#include <atnf/PKSIO/PKSrecord.h>
     
    5958  if (fitsType == "SDFITS") {
    6059    cReader = new SDFITSreader();
    61   } else if (fitsType == "GBTFITS") {
    62     cReader = new GBTFITSreader();
    6360  } else {
    6461    cReader = new MBFITSreader(retry, interpolate ? 1 : 0);
     
    432429    }
    433430  }
    434  
    435   pksrec.srcType = cMBrec.srcType ;
    436431
    437432  pksrec.srcDir.resize(2);
  • trunk/external-alma/atnf/PKSIO/PKSMS2reader.cc

    r1949 r1849  
    101101  if ( antenna.length() == 0 ) {
    102102    cAntId.resize( 1 ) ;
    103     //cAntId[0] = 0 ;
    104     ROScalarColumn<Int> ant1Col( cPKSMS, "ANTENNA1" ) ;
    105     cAntId[0] = ant1Col(0) ;
     103    cAntId[0] = 0 ;
    106104  }
    107105  else {
  • trunk/external-alma/atnf/PKSIO/PKSMS2writer.cc

    r1949 r1849  
    732732  // Extend the DATA_DESCRIPTION subtable.
    733733  while (Int(cDataDescription.nrow()) < IFno) {
    734     cDataDescription.addRow(1,True);
     734    cDataDescription.addRow();
    735735  }
    736736  Int n = IFno - 1;
     
    966966{
    967967  // Extend the POLARIZATION subtable.
    968   Int nr = cPolarization.nrow() ;
    969968  while (Int(cPolarization.nrow()) < IFno) {
    970     cPolarization.addRow(1,True);
     969    cPolarization.addRow();
    971970  }
    972971  Int n = IFno - 1;
     
    986985  corrType(1) = Stokes::YY;
    987986  }
    988   // initialization
    989   for ( Int i = nr ; i < n ; i++ )
    990     cPolarizationCols->corrType().put( i, corrType ) ;
    991987  cPolarizationCols->corrType().put(n, corrType);
    992988
     
    10961092{
    10971093  // Extend the SPECTRAL_WINDOW subtable.
    1098   Int nr = cSpectralWindow.nrow() ;
    10991094  while (Int(cSpectralWindow.nrow()) < IFno) {
    1100     cSpectralWindow.addRow(1,True);
     1095    cSpectralWindow.addRow();
    11011096  }
    11021097  Int n = IFno - 1;
     
    11161111    freqs(i) = refFreq + (i - refChan)*freqInc;
    11171112  }
    1118   // initialization
    1119   for ( Int i = nr ; i < n ; i++ )
    1120     cSpWindowCols->chanFreq().put( i, freqs ) ;
    11211113  cSpWindowCols->chanFreq().put(n, freqs);
    11221114
    11231115  Vector<Double> chanWidths(nChan, freqInc);
    1124   // initialization
    1125   for ( Int i = nr ; i < n ; i++ ) {
    1126     cSpWindowCols->chanWidth().put( i, chanWidths ) ;
    1127     cSpWindowCols->effectiveBW().put( i, chanWidths ) ;
    1128   }
    11291116  cSpWindowCols->chanWidth().put(n, chanWidths);
    11301117
     
    11331120
    11341121  Vector<Double> resolution(nChan, fabs(freqInc));
    1135   // initialization
    1136   for ( Int i = nr ; i < n ; i++ )
    1137     cSpWindowCols->resolution().put( i, resolution ) ;
    11381122  cSpWindowCols->resolution().put(n, resolution);
    11391123
  • trunk/external-alma/atnf/PKSIO/PKSreader.cc

    r1949 r1849  
    8181      buf[30] = '\0';
    8282      if (String(buf) == "SIMPLE  =                    T") {
    83         file.seek(560);
    84         file.read(26, buf, False);
    85         buf[26] = '\0' ;
    86         if ( String(buf) == "ORIGIN  = 'NRAO Green Bank" ) {
    87           // Looks like GBT SDFITS
    88           format = "GBTFITS" ;
    89           reader = new PKSFITSreader("GBTFITS") ;
    90         }
    91         else {
    92           // Looks like SDFITS.
    93           format = "SDFITS";
    94           reader = new PKSFITSreader("SDFITS");
    95         }
     83        // Looks like SDFITS.
     84        format = "SDFITS";
     85        reader = new PKSFITSreader("SDFITS");
     86
    9687       } else {
    9788         // Assume it's MBFITS.
     
    10293
    10394  } else if (inFile.isDirectory()) {
    104     Bool isMS = ( (File(name+"/table.info").exists())
    105                   && File(name+"/table.dat").exists() );
    106     if (isMS) {
    107       RegularFileIO ifs(name+"/table.info") ;
    108       char buf[128] ;
    109       ifs.read(sizeof(buf),buf,False) ;
    110       if ( strstr( buf, "Measurement Set" ) == NULL )
    111         isMS = False ;
    112     }
    113     //if (File(name + "/DATA_DESCRIPTION").exists()) {
    114     if (isMS) {
     95    if (File(name + "/DATA_DESCRIPTION").exists()) {
    11596      // MS version 2.
    11697      #ifdef NOPKSMS
  • trunk/external-alma/atnf/pks/pks_maths.cc

  • trunk/getsvnrev.sh

  • trunk/python

  • trunk/python/__init__.py

    r1949 r1849  
    1616from asap.utils import _n_bools, _is_sequence_or_number, _to_list
    1717
     18
    1819if is_ipython():
    1920    from ipysupport import *
    2021
    21 # Only use rcParams['verbose'] in standard asap cli mode
    22 # not in scripts or casapy
    23 if not is_asap_cli():
    24     rcParams['verbose'] = False
     22# use rc parameter to enable/disable logging
     23asaplog.enable(rcParams['verbose'])
    2524
    2625setup_env()
     
    3938        plotter = asapplotter(gui)
    4039    except ImportError:
    41         asaplog.push( "Matplotlib not installed. No plotting available")
    42         asaplog.post('WARN')
     40        asaplog.post( "Matplotlib not installed. No plotting available")
     41        print_log('WARN')
    4342
    4443from selector import selector
     
    5251from opacity import skydip
    5352from opacity import model as opacity_model
    54 from _asap import srctype
    5553
    5654__date__ = '$Date$'.split()[1]
  • trunk/python/asapfitter.py

    r1949 r1849  
    11import _asap
    22from asap.parameters import rcParams
    3 from asap.logging import asaplog, asaplog_post_dec
     3from asap.logging import asaplog, print_log, print_log_dec
    44from asap.utils import _n_bools, mask_and
    55
     
    99    The fitting class for ASAP.
    1010    """
     11
    1112    def __init__(self):
    1213        """
     
    4849        return
    4950
    50     @asaplog_post_dec
    5151    def set_scan(self, thescan=None, mask=None):
    5252        """
     
    5858        if not thescan:
    5959            msg = "Please give a correct scan"
    60             raise TypeError(msg)
     60            if rcParams['verbose']:
     61                #print msg
     62                asaplog.push(msg)
     63                print_log('ERROR')
     64                return
     65            else:
     66                raise TypeError(msg)
    6167        self.fitted = False
    6268        self.data = thescan
     
    6874        return
    6975
    70     @asaplog_post_dec
    7176    def set_function(self, **kwargs):
    7277        """
     
    8792        if kwargs.has_key('poly'):
    8893            self.fitfunc = 'poly'
    89             self.fitfuncs = ['poly']
    9094            n = kwargs.get('poly')
    91             self.components = [n+1]
     95            self.components = [n]
    9296            self.uselinear = False
    9397        elif kwargs.has_key('lpoly'):
    9498            self.fitfunc = 'poly'
    95             self.fitfuncs = ['lpoly']
    9699            n = kwargs.get('lpoly')
    97             self.components = [n+1]
     100            self.components = [n]
    98101            self.uselinear = True
    99102        elif kwargs.has_key('gauss'):
     
    111114        else:
    112115            msg = "Invalid function type."
    113             raise TypeError(msg)
     116            if rcParams['verbose']:
     117                #print msg
     118                asaplog.push(msg)
     119                print_log('ERROR')
     120                return
     121            else:
     122                raise TypeError(msg)
    114123
    115124        self.fitter.setexpression(self.fitfunc,n)
     
    117126        return
    118127
    119     @asaplog_post_dec
     128    @print_log_dec
    120129    def fit(self, row=0, estimate=False):
    121130        """
     
    137146               or self.fitfunc is None:
    138147            msg = "Fitter not yet initialised. Please set data & fit function"
    139             raise RuntimeError(msg)
     148            if rcParams['verbose']:
     149                #print msg
     150                asaplog.push(msg)
     151                print_log('ERROR')
     152                return
     153            else:
     154                raise RuntimeError(msg)
    140155
    141156        else:
     
    157172            if len(ps) == 0 or estimate:
    158173                self.fitter.estimate()
    159         fxdpar = list(self.fitter.getfixedparameters())
    160         if len(fxdpar) and fxdpar.count(0) == 0:
    161              raise RuntimeError,"No point fitting, if all parameters are fixed."
    162         if self.uselinear:
    163             converged = self.fitter.lfit()
    164         else:
    165             converged = self.fitter.fit()
    166         if not converged:
    167             raise RuntimeError,"Fit didn't converge."
     174        try:
     175            fxdpar = list(self.fitter.getfixedparameters())
     176            if len(fxdpar) and fxdpar.count(0) == 0:
     177                 raise RuntimeError,"No point fitting, if all parameters are fixed."
     178            if self.uselinear:
     179                converged = self.fitter.lfit()
     180            else:
     181                converged = self.fitter.fit()
     182            if not converged:
     183                raise RuntimeError,"Fit didn't converge."
     184        except RuntimeError, msg:
     185            if rcParams['verbose']:
     186                #print msg
     187                print_log()
     188                asaplog.push(str(msg))
     189                print_log('ERROR')
     190            else:
     191                raise
    168192        self._fittedrow = row
    169193        self.fitted = True
     194        print_log()
    170195        return
    171196
     
    196221                self.data._addfit(fit,self._fittedrow)
    197222
    198     @asaplog_post_dec
     223    @print_log_dec
    199224    def set_parameters(self,*args,**kwargs):
    200225        """
     
    204229              fixed:     a vector of which parameters are to be held fixed
    205230                         (default is none)
    206               component: in case of multiple gaussians/lorentzians,
    207                          the index of the component
     231              component: in case of multiple gaussians, the index of the
     232                         component
    208233        """
    209234        component = None
     
    219244        if self.fitfunc is None:
    220245            msg = "Please specify a fitting function first."
    221             raise RuntimeError(msg)
     246            if rcParams['verbose']:
     247                #print msg
     248                asaplog.push(msg)
     249                print_log('ERROR')
     250                return
     251            else:
     252                raise RuntimeError(msg)
    222253        if (self.fitfunc == "gauss" or self.fitfunc == 'lorentz') and component is not None:
    223254            if not self.fitted and sum(self.fitter.getparameters()) == 0:
     
    235266        if fixed is not None:
    236267            self.fitter.setfixedparameters(fixed)
     268        print_log()
    237269        return
    238270
    239     @asaplog_post_dec
    240271    def set_gauss_parameters(self, peak, centre, fwhm,
    241272                             peakfixed=0, centrefixed=0,
     
    257288        if self.fitfunc != "gauss":
    258289            msg = "Function only operates on Gaussian components."
    259             raise ValueError(msg)
     290            if rcParams['verbose']:
     291                #print msg
     292                asaplog.push(msg)
     293                print_log('ERROR')
     294                return
     295            else:
     296                raise ValueError(msg)
    260297        if 0 <= component < len(self.components):
    261298            d = {'params':[peak, centre, fwhm],
     
    264301        else:
    265302            msg = "Please select a valid  component."
    266             raise ValueError(msg)
    267 
    268     @asaplog_post_dec
     303            if rcParams['verbose']:
     304                #print msg
     305                asaplog.push(msg)
     306                print_log('ERROR')
     307                return
     308            else:
     309                raise ValueError(msg)
     310
    269311    def set_lorentz_parameters(self, peak, centre, fwhm,
    270312                             peakfixed=0, centrefixed=0,
     
    274316        Set the Parameters of a 'Lorentzian' component, set with set_function.
    275317        Parameters:
    276             peak, centre, fwhm:  The lorentzian parameters
     318            peak, centre, fwhm:  The gaussian parameters
    277319            peakfixed,
    278320            centrefixed,
     
    286328        if self.fitfunc != "lorentz":
    287329            msg = "Function only operates on Lorentzian components."
    288             raise ValueError(msg)
     330            if rcParams['verbose']:
     331                #print msg
     332                asaplog.push(msg)
     333                print_log('ERROR')
     334                return
     335            else:
     336                raise ValueError(msg)
    289337        if 0 <= component < len(self.components):
    290338            d = {'params':[peak, centre, fwhm],
     
    293341        else:
    294342            msg = "Please select a valid  component."
    295             raise ValueError(msg)
     343            if rcParams['verbose']:
     344                #print msg
     345                asaplog.push(msg)
     346                print_log('ERROR')
     347                return
     348            else:
     349                raise ValueError(msg)
    296350
    297351    def get_area(self, component=None):
     
    324378            return sum(areas)
    325379
    326     @asaplog_post_dec
    327380    def get_errors(self, component=None):
    328381        """
     
    334387        if not self.fitted:
    335388            msg = "Not yet fitted."
    336             raise RuntimeError(msg)
     389            if rcParams['verbose']:
     390                #print msg
     391                asaplog.push(msg)
     392                print_log('ERROR')
     393                return
     394            else:
     395                raise RuntimeError(msg)
    337396        errs = list(self.fitter.geterrors())
    338397        cerrs = errs
     
    344403        return cerrs
    345404
    346 
    347     @asaplog_post_dec
    348405    def get_parameters(self, component=None, errors=False):
    349406        """
     
    355412        if not self.fitted:
    356413            msg = "Not yet fitted."
    357             raise RuntimeError(msg)
     414            if rcParams['verbose']:
     415                #print msg
     416                asaplog.push(msg)
     417                print_log('ERROR')
     418                return
     419            else:
     420                raise RuntimeError(msg)
    358421        pars = list(self.fitter.getparameters())
    359422        fixed = list(self.fitter.getfixedparameters())
     
    381444                  area += [a for i in range(3)]
    382445        fpars = self._format_pars(cpars, cfixed, errors and cerrs, area)
    383         asaplog.push(fpars)
     446        if rcParams['verbose']:
     447            #print fpars
     448            asaplog.push(fpars)
     449            print_log()
    384450        return {'params':cpars, 'fixed':cfixed, 'formatted': fpars,
    385451                'errors':cerrs}
     
    415481        return out
    416482
    417 
    418     @asaplog_post_dec
    419483    def get_estimate(self):
    420484        """
     
    423487        pars = self.fitter.getestimate()
    424488        fixed = self.fitter.getfixedparameters()
    425         asaplog.push(self._format_pars(pars,fixed,None,None))
     489        if rcParams['verbose']:
     490            #print self._format_pars(pars,fixed,None)
     491            asaplog.push(self._format_pars(pars,fixed,None))
     492            print_log()
    426493        return pars
    427494
    428     @asaplog_post_dec
    429495    def get_residual(self):
    430496        """
     
    433499        if not self.fitted:
    434500            msg = "Not yet fitted."
    435             raise RuntimeError(msg)
     501            if rcParams['verbose']:
     502                #print msg
     503                asaplog.push(msg)
     504                print_log('ERROR')
     505                return
     506            else:
     507                raise RuntimeError(msg)
    436508        return self.fitter.getresidual()
    437509
    438     @asaplog_post_dec
    439510    def get_chi2(self):
    440511        """
     
    443514        if not self.fitted:
    444515            msg = "Not yet fitted."
    445             raise RuntimeError(msg)
     516            if rcParams['verbose']:
     517                #print msg
     518                asaplog.push(msg)
     519                print_log('ERROR')
     520                return
     521            else:
     522                raise RuntimeError(msg)
    446523        ch2 = self.fitter.getchi2()
    447         asaplog.push( 'Chi^2 = %3.3f' % (ch2) )
     524        if rcParams['verbose']:
     525            #print 'Chi^2 = %3.3f' % (ch2)
     526            asaplog.push( 'Chi^2 = %3.3f' % (ch2) )
     527            print_log()
    448528        return ch2
    449529
    450     @asaplog_post_dec
    451530    def get_fit(self):
    452531        """
     
    455534        if not self.fitted:
    456535            msg = "Not yet fitted."
    457             raise RuntimeError(msg)
     536            if rcParams['verbose']:
     537                #print msg
     538                asaplog.push(msg)
     539                print_log('ERROR')
     540                return
     541            else:
     542                raise RuntimeError(msg)
    458543        return self.fitter.getfit()
    459544
    460     @asaplog_post_dec
     545    @print_log_dec
    461546    def commit(self):
    462547        """
     
    465550        if not self.fitted:
    466551            msg = "Not yet fitted."
    467             raise RuntimeError(msg)
     552            if rcParams['verbose']:
     553                #print msg
     554                asaplog.push(msg)
     555                print_log('ERROR')
     556                return
     557            else:
     558                raise RuntimeError(msg)
    468559        from asap import scantable
    469560        if not isinstance(self.data, scantable):
    470561            msg = "Not a scantable"
    471             raise TypeError(msg)
     562            if rcParams['verbose']:
     563                #print msg
     564                asaplog.push(msg)
     565                print_log('ERROR')
     566                return
     567            else:
     568                raise TypeError(msg)
    472569        scan = self.data.copy()
    473570        scan._setspectrum(self.fitter.getresidual())
     571        print_log()
    474572        return scan
    475573
    476     @asaplog_post_dec
     574    @print_log_dec
    477575    def plot(self, residual=False, components=None, plotparms=False,
    478576             filename=None):
     
    573671        if (not rcParams['plotter.gui']):
    574672            self._p.save(filename)
    575 
    576     @asaplog_post_dec
     673        print_log()
     674
     675    @print_log_dec
    577676    def auto_fit(self, insitu=None, plot=False):
    578677        """
     
    584683        if not isinstance(self.data, scantable) :
    585684            msg = "Data is not a scantable"
    586             raise TypeError(msg)
     685            if rcParams['verbose']:
     686                #print msg
     687                asaplog.push(msg)
     688                print_log('ERROR')
     689                return
     690            else:
     691                raise TypeError(msg)
    587692        if insitu is None: insitu = rcParams['insitu']
    588693        if not insitu:
     
    620725            self._p.unmap()
    621726            self._p = None
     727        print_log()
    622728        return scan
  • trunk/python/asaplotbase.py

    r1949 r1849  
    1414
    1515from asap.parameters import rcParams as asaprcParams
    16 from asap.logging import asaplog
     16from asap.logging import asaplog, print_log
    1717
    1818# API change in mpl >= 0.98
     
    2525    #print "Warning: matplotlib version < 0.87. This might cause errors. Please upgrade."
    2626    asaplog.push( "matplotlib version < 0.99. This might cause errors. Please upgrade." )
    27     asaplog.post( 'WARN' )
     27    print_log( 'WARN' )
    2828
    2929class asaplotbase:
     
    417417            fname = 'asap'+dstr+'.png'
    418418
    419         d = ['png','.ps','eps', 'svg']
     419        d = ['png','.ps','eps']
    420420
    421421        from os.path import expandvars
     
    456456            except IOError, msg:
    457457                #print 'Failed to save %s: Error msg was\n\n%s' % (fname, err)
    458                 asaplog.post()
     458                print_log()
    459459                asaplog.push('Failed to save %s: Error msg was\n\n%s' % (fname, str(msg)))
    460                 asaplog.post( 'ERROR' )
     460                print_log( 'ERROR' )
    461461                return
    462462        else:
     
    464464            #print "'ps', 'eps', 'png'"
    465465            asaplog.push( "Invalid image type. Valid types are:" )
    466             asaplog.push( "'ps', 'eps', 'png', 'svg'" )
    467             asaplog.post('WARN')
     466            asaplog.push( "'ps', 'eps', 'png'" )
     467            print_log('WARN')
    468468
    469469
     
    669669                            for tick in self.subplots[i]['axes'].xaxis.majorTicks:
    670670                                tick.label1On = False
    671                             #self.subplots[i]['axes'].xaxis.label.set_visible(False)
     671                            self.subplots[i]['axes'].xaxis.label.set_visible(False)
    672672                    if i%cols:
    673673                        # Suppress y-labels for frames not in the left column.
    674674                        for tick in self.subplots[i]['axes'].yaxis.majorTicks:
    675675                            tick.label1On = False
    676                         #self.subplots[i]['axes'].yaxis.label.set_visible(False)
     676                        self.subplots[i]['axes'].yaxis.label.set_visible(False)
    677677                    # disable the first tick of [1:ncol-1] of the last row
    678678                    #if i+1 < nplots:
    679679                    #    self.subplots[i]['axes'].xaxis.majorTicks[0].label1On = False
    680                 # set axes label state for interior subplots.
    681                 if i%cols:
    682                     self.subplots[i]['axes'].yaxis.label.set_visible(False)
    683                 if (i <= (rows-1)*cols - 1) and (i+cols < nplots):
    684                     self.subplots[i]['axes'].xaxis.label.set_visible(False)
    685             self.rows = rows
    686             self.cols = cols
     680                self.rows = rows
     681                self.cols = cols
    687682            self.subplot(0)
    688683        del rows,cols,n,nplots,layout,ganged,i
    689 
    690684
    691685    def tidy(self):
     
    700694                if i != 0:
    701695                    ax.yaxis.majorTicks[-1].label1On = False
    702             ## set axes label state for interior subplots.
    703             #innerax=False
    704             #if i%self.cols:
    705             #    ax.yaxis.label.set_visible(innerax)
    706             #if (i <= (self.rows-1)*self.cols - 1) and (i+self.cols < nplots):
    707             #    ax.xaxis.label.set_visible(innerax)
    708            
     696
    709697
    710698    def set_title(self, title=None):
     
    745733                        sp['axes'].legend(tuple(lines), tuple(labels),
    746734                                          self.loc, prop=fp)
    747                     #else:
    748                     #    sp['axes'].legend((' '))
     735                    else:
     736                        sp['axes'].legend((' '))
    749737
    750738            from matplotlib.artist import setp
  • trunk/python/asapmath.py

    r1949 r1849  
    11from asap.scantable import scantable
    22from asap.parameters import rcParams
    3 from asap.logging import asaplog, asaplog_post_dec
     3from asap.logging import asaplog, print_log, print_log_dec
    44from asap.selector import selector
    55from asap import asaplotgui
    66
    7 @asaplog_post_dec
     7@print_log_dec
    88def average_time(*args, **kwargs):
    99    """
     
    6767        if not isinstance(s,scantable):
    6868            msg = "Please give a list of scantables"
    69             raise TypeError(msg)
     69            if rcParams['verbose']:
     70                #print msg
     71                asaplog.push(msg)
     72                print_log('ERROR')
     73                return
     74            else:
     75                raise TypeError(msg)
    7076    if scanav: scanav = "SCAN"
    7177    else: scanav = "NONE"
     
    9096        s = scantable(stm._new_average(alignedlst, compel, mask, weight.upper(), scanav))
    9197    s._add_history("average_time",varlist)
    92 
     98    print_log()
    9399    return s
    94100
    95 @asaplog_post_dec
    96101def quotient(source, reference, preserve=True):
    97102    """
     
    114119    s = scantable(stm._quotient(source, reference, preserve))
    115120    s._add_history("quotient",varlist)
     121    print_log()
    116122    return s
    117123
    118 @asaplog_post_dec
     124@print_log_dec
    119125def dototalpower(calon, caloff, tcalval=0.0):
    120126    """
     
    132138    s = scantable(stm._dototalpower(calon, caloff, tcalval))
    133139    s._add_history("dototalpower",varlist)
     140    print_log()
    134141    return s
    135142
    136 @asaplog_post_dec
     143@print_log_dec
    137144def dosigref(sig, ref, smooth, tsysval=0.0, tauval=0.0):
    138145    """
     
    152159    s = scantable(stm._dosigref(sig, ref, smooth, tsysval, tauval))
    153160    s._add_history("dosigref",varlist)
     161    print_log()
    154162    return s
    155163
    156 @asaplog_post_dec
     164@print_log_dec
    157165def calps(scantab, scannos, smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False):
    158166    """
    159167    Calibrate GBT position switched data
    160168    Adopted from GBTIDL getps
    161     Currently calps identify the scans as position switched data if source
    162     type enum is pson or psoff. The data must contains 'CAL' signal
    163     on/off in each integration. To identify 'CAL' on state, the source type
    164     enum of poncal and poffcal need to be present in the source name field.
     169    Currently calps identify the scans as position switched data if they
     170    contain '_ps' in the source name. The data must contains 'CAL' signal
     171    on/off in each integration. To identify 'CAL' on state, the word, 'calon'
     172    need to be present in the source name field.
    165173    (GBT MS data reading process to scantable automatically append these
    166174    id names to the source names)
     
    176184        tcalval:       optional user specified Tcal (default is 0.0,
    177185                       use Tcal value in the data)
    178         verify:        Verify calibration if true
    179186    """
    180187    varlist = vars()
     
    183190##     if s is None:
    184191##         msg = "The input data appear to contain no position-switch mode data."
    185 ##         raise TypeError(msg)
     192##         if rcParams['verbose']:
     193##             #print msg
     194##             asaplog.push(msg)
     195##             print_log('ERROR')
     196##             return
     197##         else:
     198##             raise TypeError(msg)
    186199    s = scantab.copy()
    187200    from asap._asap import srctype
     
    192205    except Exception, e:
    193206        msg = "The input data appear to contain no position-switch mode data."
    194         raise TypeError(msg)
     207        if rcParams['verbose']:
     208            #print msg
     209            asaplog.push(msg)
     210            print_log('ERROR')
     211            return
     212        else:
     213            raise TypeError(msg)
    195214    s.set_selection()
    196215    sel.reset()
     
    198217    if ssub is None:
    199218        msg = "No data was found with given scan numbers!"
    200         raise TypeError(msg)
     219        if rcParams['verbose']:
     220            #print msg
     221            asaplog.push(msg)
     222            print_log('ERROR')
     223            return
     224        else:
     225            raise TypeError(msg)
    201226    #ssubon = ssub.get_scan('*calon')
    202227    #ssuboff = ssub.get_scan('*[^calon]')
     
    213238    if ssubon.nrow() != ssuboff.nrow():
    214239        msg = "mismatch in numbers of CAL on/off scans. Cannot calibrate. Check the scan numbers."
    215         raise TypeError(msg)
     240        if rcParams['verbose']:
     241            #print msg
     242            asaplog.push(msg)
     243            print_log('ERROR')
     244            return
     245        else:
     246            raise TypeError(msg)
    216247    cals = dototalpower(ssubon, ssuboff, tcalval)
    217248    #sig = cals.get_scan('*ps')
     
    229260    if sig.nscan() != ref.nscan():
    230261        msg = "mismatch in numbers of on/off scans. Cannot calibrate. Check the scan numbers."
    231         raise TypeError(msg)
     262        if rcParams['verbose']:
     263            #print msg
     264            asaplog.push(msg)
     265            print_log('ERROR')
     266            return
     267        else:
     268            raise TypeError(msg)
    232269
    233270    #for user supplied Tsys
     
    235272        if tauval<=0.0:
    236273            msg = "Need to supply a valid tau to use the supplied Tsys"
    237             raise TypeError(msg)
     274            if rcParams['verbose']:
     275                #print msg
     276                asaplog.push(msg)
     277                print_log('ERROR')
     278                return
     279            else:
     280                raise TypeError(msg)
    238281        else:
    239282            sig.recalc_azel()
    240283            ref.recalc_azel()
    241284            #msg = "Use of user specified Tsys is not fully implemented yet."
    242             #raise TypeError(msg)
     285            #if rcParams['verbose']:
     286            #    print msg
     287            #    return
     288            #else:
     289            #    raise TypeError(msg)
    243290            # use get_elevation to get elevation and
    244291            # calculate a scaling factor using the formula
     
    308355        del sel
    309356        # plot
    310         asaplog.post()
     357        print_log()
    311358        asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.')
    312         asaplog.post('WARN')
     359        print_log('WARN')
    313360        p=asaplotgui.asaplotgui()
    314361        #nr=min(6,len(ifnos)*len(polnos))
     
    337384                btics.append(b)
    338385        else:
    339             asaplog.post()
     386            print_log()
    340387            asaplog.push('Only first 6 [if,pol] pairs are plotted.')
    341             asaplog.post('WARN')
     388            print_log('WARN')
    342389            nr=6
    343390            for i in range(2*nr):
     
    395442    ###
    396443    ress._add_history("calps", varlist)
     444    print_log()
    397445    return ress
    398446
    399 @asaplog_post_dec
     447@print_log_dec
    400448def calnod(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False):
    401449    """
     
    410458        tauval:      optional user specified tau value (not implemented yet)
    411459        tcalval:     optional user specified Tcal value
    412         verify:       Verify calibration if true
    413460    """
    414461    varlist = vars()
     
    422469##     if s is None:
    423470##         msg = "The input data appear to contain no Nod observing mode data."
    424 ##         raise TypeError(msg)
     471##         if rcParams['verbose']:
     472##             #print msg
     473##             asaplog.push(msg)
     474##             print_log('ERROR')
     475##             return
     476##         else:
     477##             raise TypeError(msg)
    425478    s = scantab.copy()
    426479    sel = selector()
     
    430483    except Exception, e:
    431484        msg = "The input data appear to contain no Nod observing mode data."
    432         raise TypeError(msg)
     485        if rcParams['verbose']:
     486            #print msg
     487            asaplog.push(msg)
     488            print_log('ERROR')
     489            return
     490        else:
     491            raise TypeError(msg)
    433492    sel.reset()
    434493    del sel
     
    452511        #if len(scannos)>2:
    453512        #    msg = "calnod can only process a pair of nod scans at time."
    454         #    raise TypeError(msg)
     513        #    if rcParams['verbose']:
     514        #        print msg
     515        #        return
     516        #    else:
     517        #        raise TypeError(msg)
    455518        #
    456519        #if len(scannos)==2:
     
    462525        if tauval<=0.0:
    463526            msg = "Need to supply a valid tau to use the supplied Tsys"
    464             raise TypeError(msg)
     527            if rcParams['verbose']:
     528                #print msg
     529                asaplog.push(msg)
     530                print_log('ERROR')
     531                return
     532            else:
     533                raise TypeError(msg)
    465534        else:
    466535            scantab.recalc_azel()
     
    527596        del sel
    528597        # plot
    529         asaplog.post()
     598        print_log()
    530599        asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.')
    531         asaplog.post('WARN')
     600        print_log('WARN')
    532601        p=asaplotgui.asaplotgui()
    533602        #nr=min(6,len(ifnos)*len(polnos))
     
    556625                btics.append(b)
    557626        else:
    558             asaplog.post()
     627            print_log()
    559628            asaplog.push('Only first 6 [if,pol] pairs are plotted.')
    560             asaplog.post('WARN')
     629            print_log('WARN')
    561630            nr=6
    562631            for i in range(2*nr):
     
    614683    ###
    615684    resspec._add_history("calnod",varlist)
     685    print_log()
    616686    return resspec
    617687
    618 @asaplog_post_dec
     688@print_log_dec
    619689def calfs(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False):
    620690    """
    621691    Calibrate GBT frequency switched data.
    622692    Adopted from GBTIDL getfs.
    623     Currently calfs identify the scans as frequency switched data if source
    624     type enum is fson and fsoff. The data must contains 'CAL' signal
    625     on/off in each integration. To identify 'CAL' on state, the source type
    626     enum of foncal and foffcal need to be present in the source name field.
     693    Currently calfs identify the scans as frequency switched data if they
     694    contain '_fs' in the source name. The data must contains 'CAL' signal
     695    on/off in each integration. To identify 'CAL' on state, the word, 'calon'
     696    need to be present in the source name field.
    627697    (GBT MS data reading via scantable automatically append these
    628698    id names to the source names)
     
    636706                       use Tsys in the data)
    637707        tauval:        optional user specified Tau
    638         verify:        Verify calibration if true
    639708    """
    640709    varlist = vars()
     
    647716#    if check is None:
    648717#        msg = "The input data appear to contain no Nod observing mode data."
    649 #        raise TypeError(msg)
     718#        if rcParams['verbose']:
     719#            print msg
     720#            return
     721#        else:
     722#            raise TypeError(msg)
    650723    s = scantab.get_scan(scannos)
    651724    del scantab
     
    739812        del sel
    740813        # plot
    741         asaplog.post()
     814        print_log()
    742815        asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.')
    743         asaplog.post('WARN')
     816        print_log('WARN')
    744817        p=asaplotgui.asaplotgui()
    745818        #nr=min(6,len(ifnos)*len(polnos))
     
    748821        btics=[]
    749822        if nr>3:
    750             asaplog.post()
     823            print_log()
    751824            asaplog.push('Only first 3 [if,pol] pairs are plotted.')
    752             asaplog.post('WARN')
     825            print_log('WARN')
    753826            nr=3
    754827        p.set_panels(rows=nr,cols=3,nplots=3*nr,ganged=False)
     
    818891    ###
    819892    resspec._add_history("calfs",varlist)
     893    print_log()
    820894    return resspec
    821895
    822 @asaplog_post_dec
     896@print_log_dec
    823897def merge(*args):
    824898    """
     
    847921        if not isinstance(s,scantable):
    848922            msg = "Please give a list of scantables"
    849             raise TypeError(msg)
     923            if rcParams['verbose']:
     924                #print msg
     925                asaplog.push(msg)
     926                print_log('ERROR')
     927                return
     928            else:
     929                raise TypeError(msg)
    850930    s = scantable(stm._merge(lst))
    851931    s._add_history("merge", varlist)
     932    print_log()
    852933    return s
    853934
    854 @asaplog_post_dec
    855935def calibrate( scantab, scannos=[], calmode='none', verify=None ):
    856936    """
     
    866946    if ( calmode == 'nod' ):
    867947        asaplog.push( 'Calibrating nod data.' )
     948        print_log()
    868949        scal = calnod( scantab, scannos=scannos, verify=verify )
    869950    elif ( calmode == 'quotient' ):
    870951        asaplog.push( 'Calibrating using quotient.' )
     952        print_log()
    871953        scal = scantab.auto_quotient( verify=verify )
    872954    elif ( calmode == 'ps' ):
    873955        asaplog.push( 'Calibrating %s position-switched data.' % antname )
     956        print_log()
    874957        if ( antname.find( 'APEX' ) != -1 ):
    875958            scal = apexcal( scantab, scannos, calmode, verify )
     
    880963    elif ( calmode == 'fs' or calmode == 'fsotf' ):
    881964        asaplog.push( 'Calibrating %s frequency-switched data.' % antname )
     965        print_log()
    882966        if ( antname.find( 'APEX' ) != -1 ):
    883967            scal = apexcal( scantab, scannos, calmode, verify )
     
    888972    elif ( calmode == 'otf' ):
    889973        asaplog.push( 'Calibrating %s On-The-Fly data.' % antname )
     974        print_log()
    890975        scal = almacal( scantab, scannos, calmode, verify )
    891976    else:
     
    9301015    return scal
    9311016
    932 @asaplog_post_dec
    9331017def splitant(filename, outprefix='',overwrite=False):
    9341018    """
     
    9481032    """
    9491033    # Import the table toolkit from CASA
    950     import casac
    951     from asap.scantable import is_ms
    952     tbtool = casac.homefinder.find_home_by_name('tableHome')
    953     tb = tbtool.create()
     1034    try:
     1035       import casac
     1036    except ImportError:
     1037       if rcParams['verbose']:
     1038           #print "failed to load casa"
     1039           print_log()
     1040           asaplog.push("failed to load casa")
     1041           print_log('ERROR')
     1042       else: raise
     1043       return False
     1044    try:
     1045       tbtool = casac.homefinder.find_home_by_name('tableHome')
     1046       tb = tbtool.create()
     1047       tb2 = tbtool.create()
     1048    except:
     1049       if rcParams['verbose']:
     1050           #print "failed to load a table tool:\n", e
     1051           print_log()
     1052           asaplog.push("failed to load table tool")
     1053           print_log('ERROR')
     1054       else: raise
     1055       return False
    9541056    # Check the input filename
    9551057    if isinstance(filename, str):
     
    9591061        if not os.path.exists(filename):
    9601062            s = "File '%s' not found." % (filename)
     1063            if rcParams['verbose']:
     1064                print_log()
     1065                asaplog.push(s)
     1066                print_log('ERROR')
     1067                return
    9611068            raise IOError(s)
    9621069        # check if input file is MS
    963         #if not os.path.isdir(filename) \
    964         #       or not os.path.exists(filename+'/ANTENNA') \
    965         #       or not os.path.exists(filename+'/table.f1'):
    966         if not is_ms(filename):
     1070        if not os.path.isdir(filename) \
     1071               or not os.path.exists(filename+'/ANTENNA') \
     1072               or not os.path.exists(filename+'/table.f1'):
    9671073            s = "File '%s' is not a Measurement set." % (filename)
     1074            if rcParams['verbose']:
     1075                print_log()
     1076                asaplog.push(s)
     1077                print_log('ERROR')
     1078                return
    9681079            raise IOError(s)
    9691080    else:
    9701081        s = "The filename should be string. "
     1082        if rcParams['verbose']:
     1083            print_log()
     1084            asaplog.push(s)
     1085            print_log('ERROR')
     1086            return
    9711087        raise TypeError(s)
    9721088    # Check out put file name
     
    9801096    nant=tb.nrows()
    9811097    antnames=tb.getcol('NAME',0,nant,1)
     1098    antpos=tb.getcol('POSITION',0,nant,1).transpose()
    9821099    tb.close()
    9831100    tb.open(tablename=filename,nomodify=True)
    9841101    ant1=tb.getcol('ANTENNA1',0,-1,1)
    9851102    tb.close()
    986     tmpname='asapmath.splitant.tmp'
    9871103    for antid in set(ant1):
    988         tb.open(tablename=filename,nomodify=True)
    989         tbsel=tb.query('ANTENNA1 == %s && ANTENNA2 == %s'%(antid,antid),tmpname)
    990         scan=scantable(tmpname,average=False,getpt=True,antenna=int(antid))
     1104        scan=scantable(filename,average=False,getpt=True,antenna=int(antid))
    9911105        outname=prefix+antnames[antid]+'.asap'
    9921106        scan.save(outname,format='ASAP',overwrite=overwrite)
    993         tbsel.close()
    994         tb.close()
    995         del tbsel
    9961107        del scan
    9971108        outfiles.append(outname)
    998         os.system('rm -rf '+tmpname)
    999     del tb
     1109    del tb, tb2
    10001110    return outfiles
    10011111
    1002 @asaplog_post_dec
    10031112def _array2dOp( scan, value, mode="ADD", tsys=False ):
    10041113    """
     
    10191128        del stm
    10201129    elif len( value ) != nrow:
    1021         raise ValueError( 'len(value) must be 1 or conform to scan.nrow()' )
     1130        asaplog.push( 'len(value) must be 1 or conform to scan.nrow()' )
     1131        print_log( 'ERROR' )
    10221132    else:
    10231133        from asap._asap import stmath
  • trunk/python/asapplotter.py

    r1949 r1849  
    22from asap.selector import selector
    33from asap.scantable import scantable
    4 from asap.logging import asaplog, asaplog_post_dec
     4from asap.logging import asaplog, print_log, print_log_dec
    55import matplotlib.axes
    66from matplotlib.font_manager import FontProperties
     
    1414    By default the plotter is set up to plot polarisations
    1515    'colour stacked' and scantables across panels.
    16 
    17     .. note::
    18 
     16    Note:
    1917        Currenly it only plots 'spectra' not Tsys or
    2018        other variables.
    21 
    2219    """
    2320    def __init__(self, visible=None , **kwargs):
     
    5148        self._fp = FontProperties()
    5249        self._panellayout = self.set_panellayout(refresh=False)
    53         self._offset = None
    54         self._rowcount = 0
    55         self._panelcnt = 0
    5650
    5751    def _translate(self, instr):
    58         keys = "s b i p t r".split()
     52        keys = "s b i p t".split()
    5953        if isinstance(instr, str):
    6054            for key in keys:
     
    8478        else: return None
    8579
    86     @asaplog_post_dec
     80    @print_log_dec
    8781    def plot(self, scan=None):
    8882        """
     
    9690            are consistent e.g. all 'channel' or all 'velocity' etc.
    9791        """
    98         self._rowcount = self._panelcnt = 0
    9992        if self._plotter.is_dead:
    10093            if hasattr(self._plotter.figmgr,'casabar'):
     
    10396            self._plotter.figmgr.casabar=self._newcasabar()
    10497        self._plotter.hold()
    105         #self._plotter.clear()
     98        self._plotter.clear()
    10699        if not self._data and not scan:
    107100            msg = "Input is not a scantable"
     101            if rcParams['verbose']:
     102                #print msg
     103                asaplog.push( msg )
     104                print_log( 'ERROR' )
     105                return
    108106            raise TypeError(msg)
    109         if scan:
    110             self.set_data(scan, refresh=False)
     107        if scan: self.set_data(scan,refresh=False)
    111108        self._plot(self._data)
    112109        if self._minmaxy is not None:
     
    116113        self._plotter.tidy()
    117114        self._plotter.show(hardrefresh=False)
     115        print_log()
    118116        return
    119117
     
    127125    def create_mask(self, nwin=1, panel=0, color=None):
    128126        """
    129         Interactively define a mask. It retruns a mask that is equivalent to
     127        Interactively define a mask.It retruns a mask that is equivalent to
    130128        the one created manually with scantable.create_mask.
    131129        Parameters:
     
    277275    # end matplotlib.axes fowarding functions
    278276
    279     @asaplog_post_dec
    280277    def set_data(self, scan, refresh=True):
    281278        """
     
    298295                    # reset
    299296                    self._reset()
    300                     msg = "A new scantable is set to the plotter. "\
    301                           "The masks and data selections are reset."
     297                    msg = "A new scantable is set to the plotter. The masks and data selections are reset."
    302298                    asaplog.push( msg )
     299                    print_log( 'INFO' )
    303300            else:
    304301                self._data = scan
     
    306303        else:
    307304            msg = "Input is not a scantable"
     305            if rcParams['verbose']:
     306                #print msg
     307                asaplog.push( msg )
     308                print_log( 'ERROR' )
     309                return
    308310            raise TypeError(msg)
    309311
     
    316318        if refresh: self.plot()
    317319
    318     @asaplog_post_dec
     320
    319321    def set_mode(self, stacking=None, panelling=None, refresh=True):
    320322        """
     
    339341        if not self.set_panelling(panelling) or \
    340342               not self.set_stacking(stacking):
    341             raise TypeError(msg)
    342         if self._panelling == 'r':
    343             self._stacking = '_r'
    344         elif self._stacking == 'r':
    345             self._panelling = '_r'
     343            if rcParams['verbose']:
     344                #print msg
     345                asaplog.push( msg )
     346                print_log( 'ERROR' )
     347                return
     348            else:
     349                raise TypeError(msg)
    346350        if refresh and self._data: self.plot(self._data)
    347351        return
    348352
    349353    def set_panelling(self, what=None):
    350         """Set the 'panelling' mode i.e. which type of spectra should be
    351         spread across different panels.
    352         """
    353 
    354354        mode = what
    355355        if mode is None:
     
    359359            self._panelling = md
    360360            self._title = None
    361             if md == 'r':
    362                 self._stacking = '_r'
    363361            return True
    364362        return False
     
    384382
    385383    def set_stacking(self, what=None):
    386         """Set the 'stacking' mode i.e. which type of spectra should be
    387         overlayed.
    388         """
    389384        mode = what
    390385        if mode is None:
     
    394389            self._stacking = md
    395390            self._lmap = None
    396             if md == 'r':
    397                 self._panelling = '_r'
    398391            return True
    399392        return False
    400393
    401     def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True, offset=None):
     394    def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True):
    402395        """
    403396        Set the range of interest on the abcissa of the plot
     
    407400                      replotted based on the new parameter setting(s).
    408401                      Otherwise,the parameter(s) are set without replotting.
    409             offset:   shift the abcissa by the given amount. The abcissa label will
    410                       have '(relative)' appended to it.
    411402        Note:
    412403            These become non-sensical when the unit changes.
     
    414405
    415406        """
    416         self._offset = offset
    417407        if xstart is None and xend is None:
    418408            self._minmaxx = None
     
    660650            deltachan:    the number of channels to include each side of the
    661651                          line to determine a local maximum/minimum
    662             rotate:       the rotation (in degrees) for the text label (default 90.0)
     652            rotate:       the rotation (in degrees) )for the text label (default 90.0)
    663653            location:     the location of the line annotation from the 'top',
    664654                          'bottom' or alternate (None - the default)
     
    730720    def save(self, filename=None, orientation=None, dpi=None):
    731721        """
    732         Save the plot to a file. The known formats are 'png', 'ps', 'eps'.
     722        Save the plot to a file. The know formats are 'png', 'ps', 'eps'.
    733723        Parameters:
    734724             filename:    The name of the output file. This is optional
     
    746736        return
    747737
    748     @asaplog_post_dec
     738
    749739    def set_mask(self, mask=None, selection=None, refresh=True):
    750740        """
     
    764754        if not self._data:
    765755            msg = "Can only set mask after a first call to plot()"
    766             raise RuntimeError(msg)
     756            if rcParams['verbose']:
     757                #print msg
     758                asaplog.push( msg )
     759                print_log( 'ERROR' )
     760                return
     761            else:
     762                raise RuntimeError(msg)
    767763        if len(mask):
    768764            if isinstance(mask, list) or isinstance(mask, tuple):
     
    821817        self._usermask = []
    822818        self._usermaskspectra = None
    823         self._offset = None
    824819        self.set_selection(None, False)
    825820
     
    827822        savesel = scan.get_selection()
    828823        sel = savesel +  self._selection
    829         order = self._get_sortstring([self._panelling,self._stacking])
    830         if order:
    831             sel.set_order(order)
     824        d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO',
     825              'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME' }
     826        order = [d0[self._panelling],d0[self._stacking]]
     827        sel.set_order(order)
    832828        scan.set_selection(sel)
    833829        d = {'b': scan.getbeam, 's': scan.getscan,
    834              #'i': scan.getif, 'p': scan.getpol, 't': scan._gettime,
    835              'i': scan.getif, 'p': scan.getpol, 't': scan.get_time,
    836              'r': int, '_r': int}
     830             'i': scan.getif, 'p': scan.getpol, 't': scan._gettime }
    837831
    838832        polmodes = dict(zip(self._selection.get_pols(),
     
    845839        if isinstance(nstack0, int): nstack = nstack0
    846840        else: nstack = len(nstack0)
    847         nptot = n
    848841        maxpanel, maxstack = 16,16
    849         if nstack > maxstack:
    850             msg ="Scan to be overlayed contains more than %d selections.\n" \
    851                   "Selecting first %d selections..." % (maxstack, maxstack)
     842        if n > maxpanel or nstack > maxstack:
     843            maxn = 0
     844            if nstack > maxstack: maxn = maxstack
     845            if n > maxpanel: maxn = maxpanel
     846            msg ="Scan to be plotted contains more than %d selections.\n" \
     847                  "Selecting first %d selections..." % (maxn, maxn)
    852848            asaplog.push(msg)
    853             asaplog.post('WARN')
     849            print_log('WARN')
     850            n = min(n,maxpanel)
    854851            nstack = min(nstack,maxstack)
    855         n = min(n,maxpanel)
    856            
    857852        if n > 1:
    858853            ganged = rcParams['plotter.ganged']
     
    870865#            self._plotter.set_panels()
    871866            self._plotter.set_panels(layout=self._panellayout)
    872         #r = 0
    873         r = self._rowcount
     867        r=0
    874868        nr = scan.nrow()
    875869        a0,b0 = -1,-1
     
    888882                xlab = self._abcissa and self._abcissa[panelcount] \
    889883                       or scan._getabcissalabel()
    890                 if self._offset and not self._abcissa:
    891                     xlab += " (relative)"
    892884                ylab = self._ordinate and self._ordinate[panelcount] \
    893885                       or scan._get_ordinate_label()
     
    895887                self._plotter.set_axes('ylabel', ylab)
    896888                lbl = self._get_label(scan, r, self._panelling, self._title)
    897                 #if self._panelling == 'r': lbl = ''
    898889                if isinstance(lbl, list) or isinstance(lbl, tuple):
    899890                    if 0 <= panelcount < len(lbl):
     
    904895                self._plotter.set_axes('title',lbl)
    905896                newpanel = True
    906                 stackcount = 0
     897                stackcount =0
    907898                panelcount += 1
    908             #if (b > b0 or newpanel) and stackcount < nstack:
    909             if stackcount < nstack and (newpanel or (a == a0 and b > b0)):
     899            if (b > b0 or newpanel) and stackcount < nstack:
    910900                y = []
    911901                if len(polmodes):
     
    918908                    if d[self._stacking](r) in self._maskselection[self._stacking]:
    919909                        m = logical_and(m, self._usermask)
     910                x = scan._getabcissa(r)
    920911                from numpy import ma, array
    921                 x = array(scan._getabcissa(r))
    922                 if self._offset:
    923                     x += self._offset
    924912                y = ma.masked_array(y,mask=logical_not(array(m,copy=False)))
    925913                if self._minmaxx is not None:
     
    972960                break
    973961            r+=1 # next row
    974         ###-S
    975         self._rowcount = r+1
    976         self._panelcnt += panelcount
    977         if self._plotter.figmgr.casabar:
    978             if self._panelcnt >= nptot-1:
    979                 self._plotter.figmgr.casabar.disable_next()
    980             else:
    981                 self._plotter.figmgr.casabar.enable_next()
    982             #if self._panelcnt - panelcount > 0:
    983             #    self._plotter.figmgr.casabar.enable_prev()
    984             #else:
    985             #    self._plotter.figmgr.casabar.disable_prev()
    986         ###-E
    987962        #reset the selector to the scantable's original
    988963        scan.set_selection(savesel)
     
    993968            for o in self._plotter.figure.findobj(Text):
    994969                o.set_fontproperties(self._fp)
    995 
    996     def _get_sortstring(self, lorders):
    997         d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO',
    998               'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME', 'r':None, '_r':None }
    999         if not (type(lorders) == list) and not (type(lorders) == tuple):
    1000             return None
    1001         if len(lorders) > 0:
    1002             lsorts = []
    1003             for order in lorders:
    1004                 ssort = d0[order]
    1005                 if ssort:
    1006                     lsorts.append(ssort)
    1007             return lsorts
    1008         return None
    1009970
    1010971    def set_selection(self, selection=None, refresh=True, **kw):
     
    1031992            raise TypeError("'selection' is not of type selector")
    1032993
    1033         order = self._get_sortstring([self._panelling,self._stacking])
    1034         if order:
    1035             self._selection.set_order(order)
     994        d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO',
     995              'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME' }
     996        order = [d0[self._panelling],d0[self._stacking]]
     997        self._selection.set_order(order)
    1036998        if refresh and self._data: self.plot(self._data)
    1037999
    10381000    def _get_selected_n(self, scan):
    10391001        d1 = {'b': scan.getbeamnos, 's': scan.getscannos,
    1040              'i': scan.getifnos, 'p': scan.getpolnos, 't': scan.ncycle,
    1041              'r': scan.nrow, '_r': False}
     1002             'i': scan.getifnos, 'p': scan.getpolnos, 't': scan.ncycle }
    10421003        d2 = { 'b': self._selection.get_beams(),
    10431004               's': self._selection.get_scans(),
    10441005               'i': self._selection.get_ifs(),
    10451006               'p': self._selection.get_pols(),
    1046                't': self._selection.get_cycles(),
    1047                'r': False, '_r': 1}
     1007               't': self._selection.get_cycles() }
    10481008        n =  d2[self._panelling] or d1[self._panelling]()
    10491009        nstack = d2[self._stacking] or d1[self._stacking]()
     
    10641024             'i': "IF"+str(scan.getif(row)),
    10651025             'p': poleval,
    1066              't': str(scan.get_time(row)),
    1067              'r': "row "+str(row),
    1068              #'_r': str(scan.get_time(row))+",\nIF"+str(scan.getif(row))+", "+poleval+", Beam"+str(scan.getbeam(row)) }
    1069              '_r': "" }
     1026             't': str(scan.get_time(row)) }
    10701027        return userlabel or d[mode]
    10711028
    10721029    def plotazel(self, scan=None, outfile=None):
     1030    #def plotazel(self):
    10731031        """
    10741032        plot azimuth and elevation versus time of a scantable
    10751033        """
    1076         visible = rcParams['plotter.gui']
    10771034        from matplotlib import pylab as PL
    10781035        from matplotlib.dates import DateFormatter, timezone
     
    10801037        from matplotlib.ticker import MultipleLocator
    10811038        from numpy import array, pi
    1082         if not visible or not self._visible:
    1083             PL.ioff()
    1084             from matplotlib.backends.backend_agg import FigureCanvasAgg
    1085             PL.gcf().canvas.switch_backends(FigureCanvasAgg)
    10861039        self._data = scan
    10871040        self._outfile = outfile
     
    10931046        PL.clf()
    10941047        # Adjust subplot layouts
    1095         if len(self._panellayout) != 6:
    1096             self.set_panellayout(refresh=False)
     1048        if len(self._panellayout) !=6: self.set_panellayout(refresh=False)
    10971049        lef, bot, rig, top, wsp, hsp = self._panellayout
    10981050        PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top,
     
    11741126
    11751127    def plotpointing(self, scan=None, outfile=None):
     1128    #def plotpointing(self):
    11761129        """
    11771130        plot telescope pointings
    11781131        """
    1179         visible = rcParams['plotter.gui']
    11801132        from matplotlib import pylab as PL
    11811133        from numpy import array, pi
    1182         if not visible or not self._visible:
    1183             PL.ioff()
    1184             from matplotlib.backends.backend_agg import FigureCanvasAgg
    1185             PL.gcf().canvas.switch_backends(FigureCanvasAgg)
    11861134        self._data = scan
    11871135        self._outfile = outfile
     
    11931141        PL.clf()
    11941142        # Adjust subplot layouts
    1195         if len(self._panellayout) != 6:
    1196             self.set_panellayout(refresh=False)
     1143        if len(self._panellayout) !=6: self.set_panellayout(refresh=False)
    11971144        lef, bot, rig, top, wsp, hsp = self._panellayout
    11981145        PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top,
     
    12151162    # plot total power data
    12161163    # plotting in time is not yet implemented..
    1217     @asaplog_post_dec
    12181164    def plottp(self, scan=None, outfile=None):
    12191165        if self._plotter.is_dead:
     
    12271173        if not self._data and not scan:
    12281174            msg = "Input is not a scantable"
     1175            if rcParams['verbose']:
     1176                #print msg
     1177                asaplog.push( msg )
     1178                print_log( 'ERROR' )
     1179                return
    12291180            raise TypeError(msg)
    12301181        if isinstance(scan, scantable):
     
    12561207        self._plotter.tidy()
    12571208        self._plotter.show(hardrefresh=False)
     1209        print_log()
    12581210        return
    12591211
     
    13161268
    13171269    # printing header information
    1318     @asaplog_post_dec
    13191270    def print_header(self, plot=True, fontsize=9, logger=False, selstr='', extrastr=''):
    13201271        """
     
    13231274            plot:      whether or not print header info on the plot.
    13241275            fontsize:  header font size (valid only plot=True)
     1276            autoscale: whether or not autoscale the plot (valid only plot=True)
    13251277            logger:    whether or not print header info on the logger.
    13261278            selstr:    additional selection string (not verified)
    13271279            extrastr:  additional string to print (not verified)
    13281280        """
    1329         if not plot and not logger:
    1330             return
    1331         if not self._data:
    1332             raise RuntimeError("No scantable has been set yet.")
     1281        if not plot and not logger: return
     1282        if not self._data: raise RuntimeError("No scantable has been set yet.")
    13331283        # Now header will be printed on plot and/or logger.
    13341284        # Get header information and format it.
     
    13631313            asaplog.push(extrastr)
    13641314            asaplog.push(ssum[ssum.find('Beams:'):])
     1315            print_log()
    13651316        del ssum
  • trunk/python/casatoolbar.py

    r1949 r1849  
    11import os
    22import matplotlib
    3 
    43######################################
    54##    Add CASA custom toolbar       ##
     
    145144        mymask.select_mask(once=True,showmask=False)
    146145
    147     def _mod_note(self,event):
    148         # Do not fire event when in zooming/panning mode
    149         if not self.figmgr.toolbar.mode == '':
    150             return
    151         if event.button ==1:
    152             self.notewin.load_textwindow(event)
    153         elif event.button == 3 and self._note_picked(event):
    154             self.notewin.load_modmenu(event)
    155         return
    156 
    157     def _note_picked(self,event):
    158         # just briefly check if any texts are picked
    159         for textobj in self.canvas.figure.texts:
    160             if textobj.contains(event)[0]:
    161                 return True
    162         for ax in self.canvas.figure.axes:
    163             for textobj in ax.texts:
    164                 if textobj.contains(event)[0]:
    165                     return True
    166         #print "No text picked"
    167         return False
    168 
    169     def _new_page(self,next=True):
    170         self.plotter._plotter.hold()
    171         #self.plotter._plotter.clear()
    172         self.plotter._plot(self.plotter._data)
    173         self.plotter._plotter.release()
    174         self.plotter._plotter.tidy()
    175         self.plotter._plotter.show(hardrefresh=False)
    176         pass
    177 
    178146#####################################
    179147##    Backend dependent Classes    ##
     
    182150if matplotlib.get_backend() == 'TkAgg':
    183151    import Tkinter as Tk
    184     from notationwindow import NotationWindowTkAgg
    185152
    186153class CustomToolbarTkAgg(CustomToolbarCommon, Tk.Frame):
     
    197164        self.button=True
    198165        self._add_custom_toolbar()
    199         self.notewin=NotationWindowTkAgg(master=self.canvas)
    200166        CustomToolbarCommon.__init__(self,parent)
    201167
     
    208174                                   text='statistics',
    209175                                   command=self.stat_cal)
    210         self.bNote=self._NewButton(master=self,
    211                                    text='notation',
    212                                    command=self.modify_note)
    213         #self.bPrev=self._NewButton(master=self,
    214         #                           text='- page',
    215         #                           command=self.prev_page)
    216         self.bNext=self._NewButton(master=self,
    217                                    text='+ page',
    218                                    command=self.next_page)
    219         if os.uname()[0] != 'Darwin':
    220             #self.bPrev.config(padx=5)
    221             self.bNext.config(padx=5)
    222176        self.bQuit=self._NewButton(master=self,
    223177                                   text='Quit',
     
    244198        self.bStat.config(relief='raised')
    245199        self.bSpec.config(relief='sunken')
    246         self.bNote.config(relief='raised')
    247200        self.mode='spec'
    248         self.notewin.close_widgets()
    249201        self.__disconnect_event()
    250202        #self.canvas.mpl_connect('button_press_event',self._select_spectrum)
     
    257209        self.bSpec.config(relief='raised')
    258210        self.bStat.config(relief='sunken')
    259         self.bNote.config(relief='raised')
    260211        self.mode='stat'
    261         self.notewin.close_widgets()
    262212        self.__disconnect_event()
    263213        self._p.register('button_press',self._single_mask)
    264 
    265     def modify_note(self):
    266         if not self.figmgr.toolbar.mode == '': return
    267         self.figmgr.toolbar.set_message('text: select a position/text')
    268         if self.mode == 'note': return
    269         self.bSpec.config(relief='raised')
    270         self.bStat.config(relief='raised')
    271         self.bNote.config(relief='sunken')
    272         self.mode='note'
    273         self.__disconnect_event()
    274         self._p.register('button_press',self._mod_note)
    275 
    276     def prev_page(self):
    277         self.figmgr.toolbar.set_message('plotting the previous page')
    278         self._new_page(next=False)
    279 
    280     def next_page(self):
    281         self.figmgr.toolbar.set_message('plotting the next page')
    282         self._new_page(next=True)
    283214
    284215    def quit(self):
     
    299230        self.bStat.config(relief='raised', state=Tk.DISABLED)
    300231        self.bSpec.config(relief='raised', state=Tk.DISABLED)
    301         #self.bPrev.config(state=Tk.DISABLED)
    302         #self.bNext.config(state=Tk.DISABLED)
    303232        self.button=False
    304233        self.mode=''
    305234        self.__disconnect_event()
    306 
    307     def enable_next(self):
    308         self.bNext.config(state=Tk.NORMAL)
    309 
    310     def disable_next(self):
    311         self.bNext.config(state=Tk.DISABLED)
    312 
    313     def enable_prev(self):
    314         #self.bPrev.config(state=Tk.NORMAL)
    315         pass
    316 
    317     def disable_prev(self):
    318         #self.bPrev.config(state=Tk.DISABLED)
    319         pass
    320235
    321236    def delete_bar(self):
  • trunk/python/env.py

    r1949 r1849  
    1 """This module has various functions for environment specific setings.
    2 """
    3 __all__ = ["is_casapy", "is_ipython", "setup_env", "get_revision",
    4            "is_asap_cli"]
     1__all__ = ["is_casapy", "is_ipython", "setup_env", "get_revision"]
    52
    63import sys
     
    107
    118def is_casapy():
    12     """Are we running inside casapy?"""
    139    try:
    1410        from taskinit import casalog
     
    1814
    1915def is_ipython():
    20     """Are we running inside IPython?"""
    2116    return 'IPython' in sys.modules.keys()
    2217
    23 def is_asap_cli():
    24     """Are we running inside asap ipython (but not casapy)"""
    25     return is_ipython() and not is_casapy()
    26 
    2718def setup_env():
    28     """Set-up environment variables for casa and initialise ~/.asap on first
    29     use.
    30     """
    3119    # Set up CASAPATH and first time use of asap i.e. ~/.asap/*
    3220    plf = None
     
    7159
    7260def get_revision():
    73     """Get the revision of the software. Only useful within casapy."""
    7461    if not is_casapy:
    7562        return ' unknown '
  • trunk/python/linecatalog.py

    r1949 r1849  
    1 """\
     1"""
    22A representation of a spectral line catalog.
     3
     4Author: Malte Marquarding
     5
    36"""
    47__revision__ = "$Revision$"
    58from asap._asap import linecatalog as lcbase
     9from asap.parameters import rcParams
    610from asap.logging import asaplog
    711import os
    812
    913class linecatalog(lcbase):
    10     """\
     14    """
    1115    This class is a warpper for line catalogs. These can be either ASCII tables
    1216    or the tables saved from this class.
    13 
    1417    ASCII tables have the following restrictions:
    15 
    16         * Comments can be present through lines starting with '#'.
    17 
    18         * The first column contains the name of the Molecule. This can't contain
    19           spaces, if it does it has to be wrapped in double-quotes.
    20 
    21         * The second column contains the frequency of the transition.
    22 
    23         * The third column contains the error in frequency.
    24 
    25         * The fourth column contains a value describing the intensity.
    26 
     18    Comments can be present through lines starting with '#'.
     19    The first column contains the name of the Molecule. This can't contain spaces,
     20    if it does it has to be wrapped in ""
     21    The second column contains the frequency of the transition.
     22    The third column contains the error in frequency.
     23    The fourth column contains a value describing the intensity
    2724    """
    2825
     
    3330        else:
    3431            msg = "File '%s' not found" % fpath
    35             raise IOError(msg)
     32            if rcParams['verbose']:
     33                #print msg
     34                asaplog.push( msg )
     35                print_log( 'ERROR' )
     36                return
     37            else:
     38                raise IOError(msg)
    3639
    3740    def __repr__(self):
     
    4952
    5053    def set_name(self, name, mode="pattern"):
    51         """\
     54        """
    5255        Set a name restriction on the table. This can be a standard unix-style
    5356        pattern or a regular expression.
    54 
    5557        Parameters:
    56 
    5758            name:       the name patterrn/regex
    58 
    5959            mode:       the matching mode, i.e. "pattern" (default) or "regex"
    60 
    6160        """
    6261        validmodes = "pattern regex".split()
     
    6665
    6766    def set_frequency_limits(self, fmin=1.0, fmax=120.0, unit="GHz"):
    68         """\
     67        """
    6968        Set frequency limits on the table.
    70 
    7169        Parameters:
    72 
    7370            fmin:       the lower bound
    74 
    7571            fmax:       the upper bound
    76 
    7772            unit:       the frequency unit (default "GHz")
    7873
    79         .. note:: The underlying table contains frequency values in MHz
     74        Note:
     75            The underlying table conatins frequency values in MHz
    8076        """
    8177        base = { "GHz": 1000.0, "MHz": 1.0 }
     
    8682
    8783    def set_strength_limits(self, smin, smax):
    88         """\
     84        """
    8985        Set line strength limits on the table (arbitrary units)
    90 
    9186        Parameters:
    92 
    9387            smin:       the lower bound
    94 
    9588            smax:       the upper bound
    96 
    9789        """
    9890        lcbase.set_strength_limits(self, smin, smax)
    9991
    10092    def save(self, name, overwrite=False):
    101         """\
     93        """
    10294        Save the subset of the table to disk. This uses an internal data format
    10395        and can be read in again.
     
    10799            if not overwrite:
    108100                msg = "File %s exists." % name
    109                 raise IOError(msg)
     101                if rcParams['verbose']:
     102                    #print msg
     103                    asaplog.push( msg )
     104                    print_log( 'ERROR' )
     105                    return
     106                else:
     107                    raise IOError(msg)
    110108        lcbase.save(self, name)
    111109
    112110    def reset(self):
    113         """\
    114         Reset the table to its initial state, i.e. undo all calls to ``set_``.
     111        """
     112        Reset the table to its initial state, i.e. undo all calls to set_
    115113        """
    116114        lcbase.reset(self)
    117115
    118116    def get_row(self, row=0):
    119         """\
     117        """
    120118        Get the values in a specified row of the table.
    121 
    122119        Parameters:
    123 
    124120              row:        the row to retrieve
    125 
    126121        """
    127         if row < 0 or row > len(self)-1:
    128             raise IndexError("Row index out of bounds.")
    129122        freq = lcbase.get_frequency(self, row)
    130123        name = lcbase.get_name(self, row)
     
    135128
    136129    def __getitem__(self, k):
    137         if k < 0:
    138             k = self.nrow()-k
     130        if k < 0: k = self.nrow()-k
    139131        return self.get_row(k)
  • trunk/python/logging.py

    r1949 r1849  
    1 """This module presents a logging abstraction layer on top of casa.
    2 """
    3 __all__ = ["asaplog", "asaplog_post_dec", "AsapLogger"]
     1__all__ = ["asaplog", "print_log", "print_log_dec"]
    42
    5 import inspect
    63from asap.env import is_casapy
    74from asap.parameters import rcParams
     
    1310
    1411
    15 class AsapLogger(object):
    16     """Wrapper object to allow for both casapy and asap logging.
    17 
    18     Inside casapy this will connect to `taskinit.casalog`. Otherwise it will
    19     create its own casa log sink.
    20 
    21     .. note:: Do instantiate a new one - use the :obj:`asaplog` instead.
    22 
    23     """
     12class _asaplog(object):
     13    """Wrapper object to allow for both casapy and asap logging"""
    2414    def __init__(self):
    25         self._enabled = True
     15        self._enabled = False
    2616        self._log = ""
    2717        if is_casapy():
     
    3222            set_global_sink(self.logger)
    3323
    34     def post(self, level='INFO', origin=""):
     24    def post(self, level):
    3525        """Post the messages to the logger. This will clear the buffered
    3626        logs.
    37 
    38         Parameters:
    39 
    40             level:  The log level (severity). One of INFO, WARN, ERROR.
    41 
    4227        """
    4328        if not self._enabled:
    4429            return
     30        if not rcParams['verbose']:
     31            return
    4532
    46         if not origin:
    47             origin = inspect.getframeinfo(inspect.currentframe().f_back)[2]
    4833        logs = self._log.strip()
    4934        if len(logs) > 0:
    50             if isinstance(self.logger, LogSink):
    51                 #can't handle unicode in boost signature
    52                 logs = str(logs)
    53             self.logger.post(logs, priority=level, origin=origin)
     35           self.logger.post(logs, priority=level)
    5436        if isinstance(self.logger, LogSink):
    5537            logs = self.logger.pop().strip()
     
    5941
    6042    def push(self, msg, newline=True):
    61         """Push logs into the buffer. post needs to be called to send them.
    62 
    63         Parameters:
    64 
    65             msg:        the log message (string)
    66 
    67             newline:    should we terminate with a newline (default yes)
    68 
    69         """
     43        """Push logs into the buffer. post needs to be called to send them."""
     44        from asap import rcParams
    7045        if self._enabled:
    71             sep = ""
    72             self._log = sep.join([self._log, msg])
    73             if newline:
    74                 self._log += "\n"
     46            if rcParams["verbose"]:
     47                sep = ""
     48                self._log = sep.join([self._log, msg])
     49                if newline:
     50                    self._log += "\n"
    7551
    7652    def enable(self, flag=True):
     
    8258        self._enabled = flag
    8359
    84     def is_enabled(self):
    85         return self._enabled
     60asaplog = _asaplog()
    8661
    87 asaplog = AsapLogger()
    88 """Default asap logger"""
    89 
    90 def asaplog_post_dec(f):
    91     """Decorator which posts log at completion of the wrapped method.
    92 
    93     Example::
    94 
    95         @asaplog_post_dec
    96         def test(self):
    97             do_stuff()
    98             asaplog.push('testing...', False)
    99             do_more_stuff()
    100             asaplog.push('finished')
    101     """
     62def print_log_dec(f, level='INFO'):
    10263    @wraps_dec(f)
    10364    def wrap_it(*args, **kw):
    104         level = "INFO"
    105         try:
    106             val = f(*args, **kw)
    107             return val
    108         except Exception, ex:
    109             level = "ERROR"
    110             asaplog.push(str(ex))
    111             if rcParams['verbose']:
    112                 pass
    113             else:
    114                 raise
    115         finally:
    116             asaplog.post(level, f.func_name)
    117             #asaplog.post(level, ".".join([f.__module__,f.func_name]))
     65        val = f(*args, **kw)
     66        print_log(level)
     67        return val
    11868    return wrap_it
    11969
     70def print_log(level='INFO'):
     71    """Alias for asaplog.post."""
     72    asaplog.post(level)
  • trunk/python/opacity.py

    r1949 r1849  
    66from asap.asapfitter import fitter
    77from asap.selector import selector
     8from asap.parameters import rcParams
    89from asap._asap import atmosphere
    910
     
    5051
    5152    def get_opacities(self, freq, elevation=None):
    52         """Get the opacity value(s) for the given frequency(ies).
     53        """Get the opacity value(s) for the fiven frequency(ies).
    5354        If no elevation is given the opacities for the zenith are returned.
    5455        If an elevation is specified refraction is also taken into account.
     
    147148                    is corrupted (Mopra). If set to 'False', an opacity value
    148149                    per polarisation is returned.
    149         tsky:       The sky temperature (default 300.0K). This might
     150        tksy:       The sky temperature (default 300.0K). This might
    150151                    be read from the data in the future.
    151152        plot:       Plot each fit (airmass vs. Tsys). Default is 'False'
    152153    """
     154    rcsave = rcParams['verbose']
     155    rcParams['verbose'] = False
    153156    if plot:
    154157        from matplotlib import pylab
     
    219222
    220223    scan.set_selection(basesel)
     224    rcParams['verbose'] = rcsave
    221225    if plot:
    222226        pylab.close()
  • trunk/python/parameters.py

    r1949 r1849  
    1 """This module provides functions to set up resource parameters (rc).
    2 These can be set in a file .asaprc or using functions.
    3 """
    41__all__ = ["rc", "list_rcparameters", "rcParams", "rcParamsDefault"]
    52
     
    8582    print """
    8683# general
    87 # only valid in asap standard mode not in scripts or casapy
    88 # It will disable exceptions and just print the messages
     84# print verbose output
    8985verbose                    : True
    9086
     
    177173            print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
    178174            #asaplog.push('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
    179             #asaplog.post('WARN')
     175            #print_log('WARN')
    180176            continue
    181177
     
    185181            print ('Bad key "%s" on line %d in %s' % (key, cnt, fname))
    186182            #asaplog.push('Bad key "%s" on line %d in %s' % (key, cnt, fname))
    187             #asaplog.post('WARN')
     183            #print_log('WARN')
    188184            continue
    189185
     
    197193            print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg))
    198194            #asaplog.push('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, str(msg)))
    199             #asaplog.post('WARN')
     195            #print_log('WARN')
    200196            continue
    201197        else:
  • trunk/python/scantable.py

    r1949 r1849  
    22
    33import os
    4 import numpy
    54try:
    65    from functools import wraps as wraps_dec
     
    1211from asap._asap import filler
    1312from asap.parameters import rcParams
    14 from asap.logging import asaplog, asaplog_post_dec
     13from asap.logging import asaplog, print_log, print_log_dec
    1514from asap.selector import selector
    1615from asap.linecatalog import linecatalog
    1716from asap.coordinate import coordinate
    18 from asap.utils import _n_bools, mask_not, mask_and, mask_or, page
    19 from asap.asapfitter import fitter
     17from asap.utils import _n_bools, mask_not, mask_and, mask_or
    2018
    2119
     
    2422    def wrap(obj, *args, **kw):
    2523        basesel = obj.get_selection()
    26         try:
    27             val = func(obj, *args, **kw)
    28         finally:
    29             obj.set_selection(basesel)
     24        val = func(obj, *args, **kw)
     25        obj.set_selection(basesel)
    3026        return val
    3127    return wrap
     
    3935
    4036    """
    41     if ( os.path.isdir(filename)
    42          and os.path.exists(filename+'/table.info')
    43          and os.path.exists(filename+'/table.dat') ):
    44         f=open(filename+'/table.info')
    45         l=f.readline()
    46         f.close()
    47         #if ( l.find('Scantable') != -1 ):
    48         if ( l.find('Measurement Set') == -1 ):
    49             return True
    50         else:
    51             return False
    52     else:
    53         return False
    54 ##     return (os.path.isdir(filename)
    55 ##             and not os.path.exists(filename+'/table.f1')
    56 ##             and os.path.exists(filename+'/table.info'))
    57 
    58 def is_ms(filename):
    59     """Is the given file a MeasurementSet?
    60 
    61     Parameters:
    62 
    63         filename: the name of the file/directory to test
    64 
    65     """
    66     if ( os.path.isdir(filename)
    67          and os.path.exists(filename+'/table.info')
    68          and os.path.exists(filename+'/table.dat') ):
    69         f=open(filename+'/table.info')
    70         l=f.readline()
    71         f.close()
    72         if ( l.find('Measurement Set') != -1 ):
    73             return True
    74         else:
    75             return False
    76     else:
    77         return False
    78    
     37    return (os.path.isdir(filename)
     38            and not os.path.exists(filename+'/table.f1')
     39            and os.path.exists(filename+'/table.info'))
     40
     41
    7942class scantable(Scantable):
    8043    """\
     
    8245    """
    8346
    84     @asaplog_post_dec
    85     #def __init__(self, filename, average=None, unit=None, getpt=None,
    86     #             antenna=None, parallactify=None):
    87     def __init__(self, filename, average=None, unit=None, parallactify=None, **args):
     47    @print_log_dec
     48    def __init__(self, filename, average=None, unit=None, getpt=None,
     49                 antenna=None, parallactify=None):
    8850        """\
    8951        Create a scantable from a saved one or make a reference
     
    11173                          the MS data faster in some cases.
    11274
    113             antenna:      for MeasurementSet input data only:
    114                           Antenna selection. integer (id) or string (name or id).
     75            antenna:      Antenna selection. integer (id) or string (name or id).
    11576
    11677            parallactify: Indicate that the data had been parallatified. Default
     
    12081        if average is None:
    12182            average = rcParams['scantable.autoaverage']
    122         #if getpt is None:
    123         #    getpt = True
    124         #if antenna is not None:
    125         #    asaplog.push("Antenna selection currently unsupported."
    126         #                 "Using ''")
    127         #    asaplog.post('WARN')
    128         #if antenna is None:
    129         #    antenna = ''
    130         #elif type(antenna) == int:
    131         #    antenna = '%s' % antenna
    132         #elif type(antenna) == list:
    133         #    tmpstr = ''
    134         #    for i in range( len(antenna) ):
    135         #        if type(antenna[i]) == int:
    136         #            tmpstr = tmpstr + ('%s,'%(antenna[i]))
    137         #        elif type(antenna[i]) == str:
    138         #            tmpstr=tmpstr+antenna[i]+','
    139         #        else:
    140         #            raise TypeError('Bad antenna selection.')
    141         #    antenna = tmpstr.rstrip(',')
     83        if getpt is None:
     84            getpt = True
     85        if antenna is not None:
     86            asaplog.push("Antenna selection currently unsupported."
     87                         "Using '0'")
     88            print_log('WARN')
     89        if antenna is None:
     90            antenna = ''
     91        elif type(antenna) == int:
     92            antenna = '%s' % antenna
     93        elif type(antenna) == list:
     94            tmpstr = ''
     95            for i in range( len(antenna) ):
     96                if type(antenna[i]) == int:
     97                    tmpstr = tmpstr + ('%s,'%(antenna[i]))
     98                elif type(antenna[i]) == str:
     99                    tmpstr=tmpstr+antenna[i]+','
     100                else:
     101                    asaplog.push('Bad antenna selection.')
     102                    print_log('ERROR')
     103                    return
     104            antenna = tmpstr.rstrip(',')
    142105        parallactify = parallactify or rcParams['scantable.parallactify']
    143106        varlist = vars()
     
    152115                if not os.path.exists(filename):
    153116                    s = "File '%s' not found." % (filename)
     117                    if rcParams['verbose']:
     118                        asaplog.push(s)
     119                        print_log('ERROR')
     120                        return
    154121                    raise IOError(s)
    155122                if is_scantable(filename):
     
    160127                    # do not reset to the default freqframe
    161128                    #self.set_freqframe(rcParams['scantable.freqframe'])
    162                 #elif os.path.isdir(filename) \
    163                 #         and not os.path.exists(filename+'/table.f1'):
    164                 elif is_ms(filename):
    165                     # Measurement Set
    166                     opts={'ms': {}}
    167                     mskeys=['getpt','antenna']
    168                     for key in mskeys:
    169                         if key in args.keys():
    170                             opts['ms'][key] = args[key]
    171                     #self._fill([filename], unit, average, getpt, antenna)
    172                     self._fill([filename], unit, average, opts)
    173                 elif os.path.isfile(filename):
    174                     #self._fill([filename], unit, average, getpt, antenna)
    175                     self._fill([filename], unit, average)
    176                 else:
     129                elif os.path.isdir(filename) \
     130                         and not os.path.exists(filename+'/table.f1'):
    177131                    msg = "The given file '%s'is not a valid " \
    178132                          "asap table." % (filename)
    179                     raise IOError(msg)
     133                    if rcParams['verbose']:
     134                        #print msg
     135                        asaplog.push( msg )
     136                        print_log( 'ERROR' )
     137                        return
     138                    else:
     139                        raise IOError(msg)
     140                else:
     141                    self._fill([filename], unit, average, getpt, antenna)
    180142            elif (isinstance(filename, list) or isinstance(filename, tuple)) \
    181143                  and isinstance(filename[-1], str):
    182                 #self._fill(filename, unit, average, getpt, antenna)
    183                 self._fill(filename, unit, average)
     144                self._fill(filename, unit, average, getpt, antenna)
    184145        self.parallactify(parallactify)
    185146        self._add_history("scantable", varlist)
    186 
    187     @asaplog_post_dec
     147        print_log()
     148
     149    @print_log_dec
    188150    def save(self, name=None, format=None, overwrite=False):
    189151        """\
     
    196158                         this is the root file name (data in 'name'.txt
    197159                         and header in 'name'_header.txt)
    198 
    199160            format:      an optional file format. Default is ASAP.
    200                          Allowed are:
    201 
    202                             * 'ASAP' (save as ASAP [aips++] Table),
    203                             * 'SDFITS' (save as SDFITS file)
    204                             * 'ASCII' (saves as ascii text file)
    205                             * 'MS2' (saves as an casacore MeasurementSet V2)
    206                             * 'FITS' (save as image FITS - not readable by class)
    207                             * 'CLASS' (save as FITS readable by CLASS)
    208 
     161                         Allowed are - 'ASAP' (save as ASAP [aips++] Table),
     162                                       'SDFITS' (save as SDFITS file)
     163                                       'ASCII' (saves as ascii text file)
     164                                       'MS2' (saves as an aips++
     165                                              MeasurementSet V2)
     166                                       'FITS' (save as image FITS - not
     167                                               readable by class)
     168                                       'CLASS' (save as FITS readable by CLASS)
    209169            overwrite:   If the file should be overwritten if it exists.
    210170                         The default False is to return with warning
    211171                         without writing the output. USE WITH CARE.
    212 
    213172        Example::
    214173
     
    228187            if not overwrite:
    229188                msg = "File %s exists." % name
    230                 raise IOError(msg)
     189                if rcParams['verbose']:
     190                    #print msg
     191                    asaplog.push( msg )
     192                    print_log( 'ERROR' )
     193                    return
     194                else:
     195                    raise IOError(msg)
    231196        format2 = format.upper()
    232197        if format2 == 'ASAP':
     
    236201            writer = stw(format2)
    237202            writer.write(self, name)
     203        print_log()
    238204        return
    239205
     
    267233        from asap import unique
    268234        if not _is_valid(scanid):
    269             raise RuntimeError( 'Please specify a scanno to drop from the scantable' )
    270         scanid = _to_list(scanid)
    271         allscans = unique([ self.getscan(i) for i in range(self.nrow())])
    272         for sid in scanid: allscans.remove(sid)
    273         if len(allscans) == 0:
    274             raise ValueError("Can't remove all scans")
    275         sel = selector(scans=allscans)
    276         return self._select_copy(sel)
     235            if rcParams['verbose']:
     236                #print "Please specify a scanno to drop from the scantable"
     237                asaplog.push( 'Please specify a scanno to drop from the scantable' )
     238                print_log( 'ERROR' )
     239                return
     240            else:
     241                raise RuntimeError("No scan given")
     242        try:
     243            scanid = _to_list(scanid)
     244            allscans = unique([ self.getscan(i) for i in range(self.nrow())])
     245            for sid in scanid: allscans.remove(sid)
     246            if len(allscans) == 0:
     247                raise ValueError("Can't remove all scans")
     248        except ValueError:
     249            if rcParams['verbose']:
     250                #print "Couldn't find any match."
     251                print_log()
     252                asaplog.push( "Couldn't find any match." )
     253                print_log( 'ERROR' )
     254                return
     255            else: raise
     256        try:
     257            sel = selector(scans=allscans)
     258            return self._select_copy(sel)
     259        except RuntimeError:
     260            if rcParams['verbose']:
     261                #print "Couldn't find any match."
     262                print_log()
     263                asaplog.push( "Couldn't find any match." )
     264                print_log( 'ERROR' )
     265            else:
     266                raise
    277267
    278268    def _select_copy(self, selection):
     
    284274
    285275    def get_scan(self, scanid=None):
    286         """\
     276        """
    287277        Return a specific scan (by scanno) or collection of scans (by
    288278        source name) in a new scantable.
     
    309299        """
    310300        if scanid is None:
    311             raise RuntimeError( 'Please specify a scan no or name to '
    312                                 'retrieve from the scantable' )
     301            if rcParams['verbose']:
     302                #print "Please specify a scan no or name to " \
     303                #      "retrieve from the scantable"
     304                asaplog.push( 'Please specify a scan no or name to retrieve'
     305                             ' from the scantable' )
     306                print_log( 'ERROR' )
     307                return
     308            else:
     309                raise RuntimeError("No scan given")
     310
    313311        try:
    314312            bsel = self.get_selection()
     
    325323            else:
    326324                msg = "Illegal scanid type, use 'int' or 'list' if ints."
    327                 raise TypeError(msg)
     325                if rcParams['verbose']:
     326                    #print msg
     327                    asaplog.push( msg )
     328                    print_log( 'ERROR' )
     329                else:
     330                    raise TypeError(msg)
    328331        except RuntimeError:
    329             raise
     332            if rcParams['verbose']:
     333                #print "Couldn't find any match."
     334                print_log()
     335                asaplog.push( "Couldn't find any match." )
     336                print_log( 'ERROR' )
     337            else: raise
    330338
    331339    def __str__(self):
     
    354362            else:
    355363                msg = "Illegal file name '%s'." % (filename)
    356                 raise IOError(msg)
    357         return page(info)
     364                if rcParams['verbose']:
     365                    #print msg
     366                    asaplog.push( msg )
     367                    print_log( 'ERROR' )
     368                else:
     369                    raise IOError(msg)
     370        if rcParams['verbose']:
     371            try:
     372                from IPython.genutils import page as pager
     373            except ImportError:
     374                from pydoc import pager
     375            pager(info)
     376        else:
     377            return info
    358378
    359379    def get_spectrum(self, rowno):
     
    378398
    379399    def set_spectrum(self, spec, rowno):
    380         """Set the spectrum for the current row in the scantable.
    381 
    382         Parameters:
    383 
    384              spec:   the new spectrum
    385 
    386              rowno:  the row number to set the spectrum for
     400        """Return the spectrum for the current row in the scantable as a list.
     401
     402        Parameters:
     403
     404             spec:   the spectrum
     405             rowno:    the row number to set the spectrum for
    387406
    388407        """
     
    498517            return workscan
    499518
    500     @asaplog_post_dec
    501     def stats(self, stat='stddev', mask=None, form='3.3f', row=None):
     519    #def stats(self, stat='stddev', mask=None):
     520    def stats(self, stat='stddev', mask=None, form='3.3f'):
    502521        """\
    503522        Determine the specified statistic of the current beam/if/pol
     
    509528            stat:    'min', 'max', 'min_abc', 'max_abc', 'sumsq', 'sum',
    510529                     'mean', 'var', 'stddev', 'avdev', 'rms', 'median'
    511 
    512530            mask:    an optional mask specifying where the statistic
    513531                     should be determined.
    514 
    515532            form:    format string to print statistic values
    516533
    517             row:     row number of spectrum to process.
    518                      (default is None: for all rows)
    519 
    520         Example:
     534        Example::
     535
    521536            scan.set_unit('channel')
    522537            msk = scan.create_mask([100, 200], [500, 600])
     
    536551            getchan = True
    537552            statvals = []
    538         if not rtnabc:
    539             if row == None:
    540                 statvals = self._math._stats(self, mask, stat)
    541             else:
    542                 statvals = self._math._statsrow(self, mask, stat, int(row))
     553        if not rtnabc: statvals = self._math._stats(self, mask, stat)
    543554
    544555        #def cb(i):
     
    552563        #outvec = []
    553564        sep = '-'*50
    554 
    555         if row == None:
    556             rows = xrange(self.nrow())
    557         elif isinstance(row, int):
    558             rows = [ row ]
    559 
    560         for i in rows:
     565        for i in range(self.nrow()):
    561566            refstr = ''
    562567            statunit= ''
     
    574579            out += 'Scan[%d] (%s) ' % (self.getscan(i), src)
    575580            out += 'Time[%s]:\n' % (tm)
    576             if self.nbeam(-1) > 1: out +=  ' Beam[%d] ' % (self.getbeam(i))
    577             if self.nif(-1) > 1:   out +=  ' IF[%d] ' % (self.getif(i))
    578             if self.npol(-1) > 1:  out +=  ' Pol[%d] ' % (self.getpol(i))
     581            if self.nbeam(-1) > 1:
     582                out +=  ' Beam[%d] ' % (self.getbeam(i))
     583            if self.nif(-1) > 1: out +=  ' IF[%d] ' % (self.getif(i))
     584            if self.npol(-1) > 1: out +=  ' Pol[%d] ' % (self.getpol(i))
    579585            #outvec.append(callback(i))
    580             if len(rows) > 1:
    581                 # out += ('= %'+form) % (outvec[i]) +'   '+refstr+'\n'
    582                 out += ('= %'+form) % (statvals[i]) +'   '+refstr+'\n'
     586            #out += ('= %'+form) % (outvec[i]) +'   '+refstr+'\n'
     587            out += ('= %'+form) % (statvals[i]) +'   '+refstr+'\n'
     588            out +=  sep+"\n"
     589
     590        if rcParams['verbose']:
     591            import os
     592            if os.environ.has_key( 'USER' ):
     593                usr=os.environ['USER']
    583594            else:
    584                 # out += ('= %'+form) % (outvec[0]) +'   '+refstr+'\n'
    585                 out += ('= %'+form) % (statvals[0]) +'   '+refstr+'\n'
    586             out +=  sep+"\n"
    587 
    588         import os
    589         if os.environ.has_key( 'USER' ):
    590             usr = os.environ['USER']
    591         else:
    592             import commands
    593             usr = commands.getoutput( 'whoami' )
    594         tmpfile = '/tmp/tmp_'+usr+'_casapy_asap_scantable_stats'
    595         f = open(tmpfile,'w')
    596         print >> f, sep
    597         print >> f, ' %s %s' % (label, statunit)
    598         print >> f, sep
    599         print >> f, out
    600         f.close()
    601         f = open(tmpfile,'r')
    602         x = f.readlines()
    603         f.close()
    604         asaplog.push(''.join(x), False)
    605 
     595                import commands
     596                usr=commands.getoutput( 'whoami' )
     597            tmpfile='/tmp/tmp_'+usr+'_casapy_asap_scantable_stats'
     598            f=open(tmpfile,'w')
     599            print >> f, sep
     600            print >> f, ' %s %s' % (label, statunit)
     601            print >> f, sep
     602            print >> f, out
     603            f.close()
     604            f=open(tmpfile,'r')
     605            x=f.readlines()
     606            f.close()
     607            blanc=''
     608            asaplog.push(blanc.join(x), False)
     609            #for xx in x:
     610            #    asaplog.push( xx, False )
     611            print_log()
    606612        return statvals
    607613
     
    615621            rowno:   a row number in the scantable. Default is the
    616622                     first row, i.e. rowno=0
    617 
    618623            chan:    a channel in the scantable. Default is the first
    619624                     channel, i.e. pos=0
     
    718723            out += '= %3.3f\n' % (outvec[i])
    719724            out +=  sep+'\n'
    720 
    721         asaplog.push(sep)
    722         asaplog.push(" %s" % (label))
    723         asaplog.push(sep)
    724         asaplog.push(out)
    725         asaplog.post()
     725        if rcParams['verbose']:
     726            asaplog.push(sep)
     727            asaplog.push(" %s" % (label))
     728            asaplog.push(sep)
     729            asaplog.push(out)
     730            print_log()
    726731        return outvec
    727732
    728     def _get_column(self, callback, row=-1, *args):
     733    def _get_column(self, callback, row=-1):
    729734        """
    730735        """
    731736        if row == -1:
    732             return [callback(i, *args) for i in range(self.nrow())]
     737            return [callback(i) for i in range(self.nrow())]
    733738        else:
    734739            if  0 <= row < self.nrow():
    735                 return callback(row, *args)
    736 
    737 
    738     def get_time(self, row=-1, asdatetime=False, prec=-1):
     740                return callback(row)
     741
     742
     743    def get_time(self, row=-1, asdatetime=False):
    739744        """\
    740745        Get a list of time stamps for the observations.
    741         Return a datetime object or a string (default) for each
    742         integration time stamp in the scantable.
     746        Return a datetime object for each integration time stamp in the scantable.
    743747
    744748        Parameters:
    745749
    746750            row:          row no of integration. Default -1 return all rows
    747 
    748751            asdatetime:   return values as datetime objects rather than strings
    749752
    750             prec:         number of digits shown. Default -1 to automatic calculation.
    751                           Note this number is equals to the digits of MVTime,
    752                           i.e., 0<prec<3: dates with hh:: only,
    753                           <5: with hh:mm:, <7 or 0: with hh:mm:ss,
    754                           and 6> : with hh:mm:ss.tt... (prec-6 t's added)
    755 
    756         """
     753        """
     754        from time import strptime
    757755        from datetime import datetime
    758         if prec < 0:
    759             # automagically set necessary precision +1
    760             prec = 7 - numpy.floor(numpy.log10(min(self.get_inttime())))
    761             prec = max(6, int(prec))
    762         else:
    763             prec = max(0, prec)
    764         if asdatetime:
    765             #precision can be 1 millisecond at max
    766             prec = min(12, prec)
    767 
    768         times = self._get_column(self._gettime, row, prec)
     756        times = self._get_column(self._gettime, row)
    769757        if not asdatetime:
    770758            return times
    771         format = "%Y/%m/%d/%H:%M:%S.%f"
    772         if prec < 7:
    773             nsub = 1 + (((6-prec)/2) % 3)
    774             substr = [".%f","%S","%M"]
    775             for i in range(nsub):
    776                 format = format.replace(substr[i],"")
     759        format = "%Y/%m/%d/%H:%M:%S"
    777760        if isinstance(times, list):
    778             return [datetime.strptime(i, format) for i in times]
    779         else:
    780             return datetime.strptime(times, format)
     761            return [datetime(*strptime(i, format)[:6]) for i in times]
     762        else:
     763            return datetime(*strptime(times, format)[:6])
    781764
    782765
     
    844827        Get a list of Positions on the sky (direction) for the observations.
    845828        Return a string for each integration in the scantable.
    846 
    847         Parameters:
    848 
     829        Parameters:
    849830            row:    row no of integration. Default -1 return all rows
    850 
     831        Example:
     832            none
    851833        """
    852834        return self._get_column(self._getdirection, row)
     
    864846        return self._get_column(self._getdirectionvec, row)
    865847
    866     @asaplog_post_dec
     848    @print_log_dec
    867849    def set_unit(self, unit='channel'):
    868850        """\
     
    883865        self._add_history("set_unit", varlist)
    884866
    885     @asaplog_post_dec
     867    @print_log_dec
    886868    def set_instrument(self, instr):
    887869        """\
     
    896878        self._setInstrument(instr)
    897879        self._add_history("set_instument", vars())
    898 
    899     @asaplog_post_dec
     880        print_log()
     881
     882    @print_log_dec
    900883    def set_feedtype(self, feedtype):
    901884        """\
     
    909892        self._setfeedtype(feedtype)
    910893        self._add_history("set_feedtype", vars())
    911 
    912     @asaplog_post_dec
     894        print_log()
     895
     896    @print_log_dec
    913897    def set_doppler(self, doppler='RADIO'):
    914898        """\
     
    925909        self._setcoordinfo(inf)
    926910        self._add_history("set_doppler", vars())
    927 
    928     @asaplog_post_dec
     911        print_log()
     912
     913    @print_log_dec
    929914    def set_freqframe(self, frame=None):
    930915        """\
     
    957942        else:
    958943            msg  = "Please specify a valid freq type. Valid types are:\n", valid
    959             raise TypeError(msg)
    960 
    961     @asaplog_post_dec
     944            if rcParams['verbose']:
     945                #print msg
     946                asaplog.push( msg )
     947                print_log( 'ERROR' )
     948            else:
     949                raise TypeError(msg)
     950        print_log()
     951
    962952    def set_dirframe(self, frame=""):
    963953        """\
     
    975965        """
    976966        varlist = vars()
    977         Scantable.set_dirframe(self, frame)
     967        try:
     968            Scantable.set_dirframe(self, frame)
     969        except RuntimeError, msg:
     970            if rcParams['verbose']:
     971                #print msg
     972                print_log()
     973                asaplog.push( str(msg) )
     974                print_log( 'ERROR' )
     975            else:
     976                raise
    978977        self._add_history("set_dirframe", varlist)
    979978
     
    992991        return unit
    993992
    994     @asaplog_post_dec
    995993    def get_abcissa(self, rowno=0):
    996994        """\
     
    10101008        abc = self._getabcissa(rowno)
    10111009        lbl = self._getabcissalabel(rowno)
     1010        print_log()
    10121011        return abc, lbl
    10131012
    1014     @asaplog_post_dec
    10151013    def flag(self, mask=None, unflag=False):
    10161014        """\
     
    10211019            mask:   an optional channel mask, created with create_mask. Default
    10221020                    (no mask) is all channels.
    1023 
    10241021            unflag:    if True, unflag the data
    10251022
     
    10271024        varlist = vars()
    10281025        mask = mask or []
    1029         self._flag(mask, unflag)
     1026        try:
     1027            self._flag(mask, unflag)
     1028        except RuntimeError, msg:
     1029            if rcParams['verbose']:
     1030                #print msg
     1031                print_log()
     1032                asaplog.push( str(msg) )
     1033                print_log( 'ERROR' )
     1034                return
     1035            else: raise
    10301036        self._add_history("flag", varlist)
    10311037
    1032     @asaplog_post_dec
    10331038    def flag_row(self, rows=[], unflag=False):
    10341039        """\
     
    10391044            rows:   list of row numbers to be flagged. Default is no row
    10401045                    (must be explicitly specified to execute row-based flagging).
    1041 
    10421046            unflag: if True, unflag the data.
    10431047
    10441048        """
    10451049        varlist = vars()
    1046         self._flag_row(rows, unflag)
     1050        try:
     1051            self._flag_row(rows, unflag)
     1052        except RuntimeError, msg:
     1053            if rcParams['verbose']:
     1054                print_log()
     1055                asaplog.push( str(msg) )
     1056                print_log('ERROR')
     1057                return
     1058            else: raise
    10471059        self._add_history("flag_row", varlist)
    10481060
    1049     @asaplog_post_dec
    10501061    def clip(self, uthres=None, dthres=None, clipoutside=True, unflag=False):
    10511062        """\
     
    10551066
    10561067            uthres:      upper threshold.
    1057 
    10581068            dthres:      lower threshold
    10591069
    10601070            clipoutside: True for flagging data outside the range [dthres:uthres].
    1061                          False for flagging data inside the range.
    1062 
     1071                         False for glagging data inside the range.
    10631072            unflag:      if True, unflag the data.
    10641073
    10651074        """
    10661075        varlist = vars()
    1067         self._clip(uthres, dthres, clipoutside, unflag)
     1076        try:
     1077            self._clip(uthres, dthres, clipoutside, unflag)
     1078        except RuntimeError, msg:
     1079            if rcParams['verbose']:
     1080                print_log()
     1081                asaplog.push(str(msg))
     1082                print_log('ERROR')
     1083                return
     1084            else: raise
    10681085        self._add_history("clip", varlist)
    10691086
    1070     @asaplog_post_dec
     1087    @print_log_dec
    10711088    def lag_flag(self, start, end, unit="MHz", insitu=None):
    10721089        """\
     
    10791096            start:    the start frequency (really a period within the
    10801097                      bandwidth)  or period to remove
    1081 
    10821098            end:      the end frequency or period to remove
    1083 
    10841099            unit:     the frequency unit (default "MHz") or "" for
    10851100                      explicit lag channels
     
    10971112        if not (unit == "" or base.has_key(unit)):
    10981113            raise ValueError("%s is not a valid unit." % unit)
    1099         if unit == "":
    1100             s = scantable(self._math._lag_flag(self, start, end, "lags"))
    1101         else:
    1102             s = scantable(self._math._lag_flag(self, start*base[unit],
    1103                                                end*base[unit], "frequency"))
     1114        try:
     1115            if unit == "":
     1116                s = scantable(self._math._lag_flag(self, start, end, "lags"))
     1117            else:
     1118                s = scantable(self._math._lag_flag(self, start*base[unit],
     1119                                                   end*base[unit], "frequency"))
     1120        except RuntimeError, msg:
     1121            if rcParams['verbose']:
     1122                #print msg
     1123                print_log()
     1124                asaplog.push( str(msg) )
     1125                print_log( 'ERROR' )
     1126                return
     1127            else: raise
    11041128        s._add_history("lag_flag", varlist)
     1129        print_log()
    11051130        if insitu:
    11061131            self._assign(s)
     
    11081133            return s
    11091134
    1110     @asaplog_post_dec
     1135    @print_log_dec
    11111136    def create_mask(self, *args, **kwargs):
    11121137        """\
     
    11201145                Pairs of start/end points (inclusive)specifying the regions
    11211146                to be masked
    1122 
    11231147            invert:     optional argument. If specified as True,
    11241148                        return an inverted mask, i.e. the regions
    11251149                        specified are EXCLUDED
    1126 
    11271150            row:        create the mask using the specified row for
    11281151                        unit conversions, default is row=0
     
    11501173        data = self._getabcissa(row)
    11511174        u = self._getcoordinfo()[0]
    1152         if u == "":
    1153             u = "channel"
    1154         msg = "The current mask window unit is %s" % u
    1155         i = self._check_ifs()
    1156         if not i:
    1157             msg += "\nThis mask is only valid for IF=%d" % (self.getif(i))
    1158         asaplog.push(msg)
     1175        if rcParams['verbose']:
     1176            if u == "": u = "channel"
     1177            msg = "The current mask window unit is %s" % u
     1178            i = self._check_ifs()
     1179            if not i:
     1180                msg += "\nThis mask is only valid for IF=%d" % (self.getif(i))
     1181            asaplog.push(msg)
    11591182        n = self.nchan()
    11601183        msk = _n_bools(n, False)
     
    11781201            if kwargs.get('invert'):
    11791202                msk = mask_not(msk)
     1203        print_log()
    11801204        return msk
    11811205
    1182     def get_masklist(self, mask=None, row=0, silent=False):
     1206    def get_masklist(self, mask=None, row=0):
    11831207        """\
    11841208        Compute and return a list of mask windows, [min, max].
     
    11871211
    11881212            mask:       channel mask, created with create_mask.
    1189 
    11901213            row:        calcutate the masklist using the specified row
    11911214                        for unit conversions, default is row=0
     
    12081231        data = self._getabcissa(row)
    12091232        u = self._getcoordinfo()[0]
    1210         if u == "":
    1211             u = "channel"
    1212         msg = "The current mask window unit is %s" % u
    1213         i = self._check_ifs()
    1214         if not i:
    1215             msg += "\nThis mask is only valid for IF=%d" % (self.getif(i))
    1216         if not silent:
     1233        if rcParams['verbose']:
     1234            if u == "": u = "channel"
     1235            msg = "The current mask window unit is %s" % u
     1236            i = self._check_ifs()
     1237            if not i:
     1238                msg += "\nThis mask is only valid for IF=%d" % (self.getif(i))
    12171239            asaplog.push(msg)
    12181240        masklist=[]
     
    12291251        """\
    12301252        Compute and Return lists of mask start indices and mask end indices.
    1231 
    1232         Parameters:
    1233 
     1253         Parameters:
    12341254            mask:       channel mask, created with create_mask.
    12351255
     
    13061326        """\
    13071327        Set or replace the restfrequency specified and
    1308         if the 'freqs' argument holds a scalar,
     1328        If the 'freqs' argument holds a scalar,
    13091329        then that rest frequency will be applied to all the selected
    13101330        data.  If the 'freqs' argument holds
     
    13221342
    13231343            freqs:   list of rest frequency values or string idenitfiers
    1324 
    13251344            unit:    unit for rest frequency (default 'Hz')
    13261345
     
    14331452        Scantable.shift_refpix(self, delta)
    14341453
    1435     @asaplog_post_dec
    14361454    def history(self, filename=None):
    14371455        """\
     
    14401458        Parameters:
    14411459
    1442             filename:    The name of the file to save the history to.
     1460            filename:    The name  of the file to save the history to.
    14431461
    14441462        """
     
    14471465        for h in hist:
    14481466            if h.startswith("---"):
    1449                 out = "\n".join([out, h])
     1467                out += "\n"+h
    14501468            else:
    14511469                items = h.split("##")
     
    14561474                out += "Function: %s\n  Parameters:" % (func)
    14571475                for i in items:
    1458                     if i == '':
    1459                         continue
    14601476                    s = i.split("=")
    14611477                    out += "\n   %s = %s" % (s[0], s[1])
    1462                 out = "\n".join([out, "-"*80])
     1478                out += "\n"+"-"*80
    14631479        if filename is not None:
    14641480            if filename is "":
     
    14721488            else:
    14731489                msg = "Illegal file name '%s'." % (filename)
    1474                 raise IOError(msg)
    1475         return page(out)
     1490                if rcParams['verbose']:
     1491                    #print msg
     1492                    asaplog.push( msg )
     1493                    print_log( 'ERROR' )
     1494                else:
     1495                    raise IOError(msg)
     1496        if rcParams['verbose']:
     1497            try:
     1498                from IPython.genutils import page as pager
     1499            except ImportError:
     1500                from pydoc import pager
     1501            pager(out)
     1502        else:
     1503            return out
     1504        return
    14761505    #
    14771506    # Maths business
    14781507    #
    1479     @asaplog_post_dec
     1508    @print_log_dec
    14801509    def average_time(self, mask=None, scanav=False, weight='tint', align=False):
    14811510        """\
     
    14901519            mask:     an optional mask (only used for 'var' and 'tsys'
    14911520                      weighting)
    1492 
    14931521            scanav:   True averages each scan separately
    14941522                      False (default) averages all scans together,
    1495 
    14961523            weight:   Weighting scheme.
    14971524                      'none'     (mean no weight)
     
    15021529                      'median'   ( median averaging)
    15031530                      The default is 'tint'
    1504 
    15051531            align:    align the spectra in velocity before averaging. It takes
    15061532                      the time of the first spectrum as reference time.
     
    15171543        scanav = (scanav and 'SCAN') or 'NONE'
    15181544        scan = (self, )
    1519 
    1520         if align:
    1521             scan = (self.freq_align(insitu=False), )
    1522         s = None
    1523         if weight.upper() == 'MEDIAN':
    1524             s = scantable(self._math._averagechannel(scan[0], 'MEDIAN',
    1525                                                      scanav))
    1526         else:
    1527             s = scantable(self._math._average(scan, mask, weight.upper(),
    1528                           scanav))
     1545        try:
     1546            if align:
     1547                scan = (self.freq_align(insitu=False), )
     1548            s = None
     1549            if weight.upper() == 'MEDIAN':
     1550                s = scantable(self._math._averagechannel(scan[0], 'MEDIAN',
     1551                                                         scanav))
     1552            else:
     1553                s = scantable(self._math._average(scan, mask, weight.upper(),
     1554                              scanav))
     1555        except RuntimeError, msg:
     1556            if rcParams['verbose']:
     1557                #print msg
     1558                print_log()
     1559                asaplog.push( str(msg) )
     1560                print_log( 'ERROR' )
     1561                return
     1562            else: raise
    15291563        s._add_history("average_time", varlist)
     1564        print_log()
    15301565        return s
    15311566
    1532     @asaplog_post_dec
     1567    @print_log_dec
    15331568    def convert_flux(self, jyperk=None, eta=None, d=None, insitu=None):
    15341569        """\
     
    15431578
    15441579            jyperk:      the Jy / K conversion factor
    1545 
    15461580            eta:         the aperture efficiency
    1547 
    1548             d:           the geometric diameter (metres)
    1549 
     1581            d:           the geomtric diameter (metres)
    15501582            insitu:      if False a new scantable is returned.
    15511583                         Otherwise, the scaling is done in-situ
     
    15611593        s = scantable(self._math._convertflux(self, d, eta, jyperk))
    15621594        s._add_history("convert_flux", varlist)
     1595        print_log()
    15631596        if insitu: self._assign(s)
    15641597        else: return s
    15651598
    1566     @asaplog_post_dec
     1599    @print_log_dec
    15671600    def gain_el(self, poly=None, filename="", method="linear", insitu=None):
    15681601        """\
     
    15811614                         gain-elevation correction as a function of
    15821615                         elevation (in degrees).
    1583 
    15841616            filename:    The name of an ascii file holding correction factors.
    15851617                         The first row of the ascii file must give the column
     
    16001632                         0.5 80 0.8
    16011633                         0.6 90 0.75
    1602 
    16031634            method:      Interpolation method when correcting from a table.
    16041635                         Values are  "nearest", "linear" (default), "cubic"
    16051636                         and "spline"
    1606 
    16071637            insitu:      if False a new scantable is returned.
    16081638                         Otherwise, the scaling is done in-situ
     
    16191649        s = scantable(self._math._gainel(self, poly, filename, method))
    16201650        s._add_history("gain_el", varlist)
     1651        print_log()
    16211652        if insitu:
    16221653            self._assign(s)
     
    16241655            return s
    16251656
    1626     @asaplog_post_dec
     1657    @print_log_dec
    16271658    def freq_align(self, reftime=None, method='cubic', insitu=None):
    16281659        """\
     
    16321663
    16331664        Parameters:
    1634 
    16351665            reftime:     reference time to align at. By default, the time of
    16361666                         the first row of data is used.
    1637 
    16381667            method:      Interpolation method for regridding the spectra.
    16391668                         Choose from "nearest", "linear", "cubic" (default)
    16401669                         and "spline"
    1641 
    16421670            insitu:      if False a new scantable is returned.
    16431671                         Otherwise, the scaling is done in-situ
     
    16511679        s = scantable(self._math._freq_align(self, reftime, method))
    16521680        s._add_history("freq_align", varlist)
     1681        print_log()
    16531682        if insitu: self._assign(s)
    16541683        else: return s
    16551684
    1656     @asaplog_post_dec
     1685    @print_log_dec
    16571686    def opacity(self, tau=None, insitu=None):
    16581687        """\
     
    16611690
    16621691        Parameters:
    1663 
    16641692            tau:         (list of) opacity from which the correction factor is
    16651693                         exp(tau*ZD)
     
    16701698                         if tau is `None` the opacities are determined from a
    16711699                         model.
    1672 
    16731700            insitu:      if False a new scantable is returned.
    16741701                         Otherwise, the scaling is done in-situ
     
    16831710        s = scantable(self._math._opacity(self, tau))
    16841711        s._add_history("opacity", varlist)
     1712        print_log()
    16851713        if insitu: self._assign(s)
    16861714        else: return s
    16871715
    1688     @asaplog_post_dec
     1716    @print_log_dec
    16891717    def bin(self, width=5, insitu=None):
    16901718        """\
     
    16941722
    16951723            width:       The bin width (default=5) in pixels
    1696 
    16971724            insitu:      if False a new scantable is returned.
    16981725                         Otherwise, the scaling is done in-situ
     
    17051732        s = scantable(self._math._bin(self, width))
    17061733        s._add_history("bin", varlist)
     1734        print_log()
    17071735        if insitu:
    17081736            self._assign(s)
     
    17101738            return s
    17111739
    1712     @asaplog_post_dec
     1740    @print_log_dec
    17131741    def resample(self, width=5, method='cubic', insitu=None):
    17141742        """\
     
    17181746
    17191747            width:       The bin width (default=5) in pixels
    1720 
    17211748            method:      Interpolation method when correcting from a table.
    17221749                         Values are  "nearest", "linear", "cubic" (default)
    17231750                         and "spline"
    1724 
    17251751            insitu:      if False a new scantable is returned.
    17261752                         Otherwise, the scaling is done in-situ
     
    17331759        s = scantable(self._math._resample(self, method, width))
    17341760        s._add_history("resample", varlist)
     1761        print_log()
    17351762        if insitu: self._assign(s)
    17361763        else: return s
    17371764
    1738     @asaplog_post_dec
     1765    @print_log_dec
    17391766    def average_pol(self, mask=None, weight='none'):
    17401767        """\
     
    17461773                         averaging will be applied. The output will have all
    17471774                         specified points masked.
    1748 
    17491775            weight:      Weighting scheme. 'none' (default), 'var' (1/var(spec)
    17501776                         weighted), or 'tsys' (1/Tsys**2 weighted)
     
    17551781        s = scantable(self._math._averagepol(self, mask, weight.upper()))
    17561782        s._add_history("average_pol", varlist)
     1783        print_log()
    17571784        return s
    17581785
    1759     @asaplog_post_dec
     1786    @print_log_dec
    17601787    def average_beam(self, mask=None, weight='none'):
    17611788        """\
     
    17661793                         averaging will be applied. The output will have all
    17671794                         specified points masked.
    1768 
    17691795            weight:      Weighting scheme. 'none' (default), 'var' (1/var(spec)
    17701796                         weighted), or 'tsys' (1/Tsys**2 weighted)
     
    17751801        s = scantable(self._math._averagebeams(self, mask, weight.upper()))
    17761802        s._add_history("average_beam", varlist)
     1803        print_log()
    17771804        return s
    17781805
     
    17831810
    17841811        Parameters:
    1785 
    17861812            pflag:  Bool indicating whether to turn this on (True) or
    17871813                    off (False)
     
    17921818        self._add_history("parallactify", varlist)
    17931819
    1794     @asaplog_post_dec
     1820    @print_log_dec
    17951821    def convert_pol(self, poltype=None):
    17961822        """\
     
    17991825
    18001826        Parameters:
    1801 
    18021827            poltype:    The new polarisation type. Valid types are:
    18031828                        "linear", "circular", "stokes" and "linpol"
     
    18051830        """
    18061831        varlist = vars()
    1807         s = scantable(self._math._convertpol(self, poltype))
     1832        try:
     1833            s = scantable(self._math._convertpol(self, poltype))
     1834        except RuntimeError, msg:
     1835            if rcParams['verbose']:
     1836                #print msg
     1837                print_log()
     1838                asaplog.push( str(msg) )
     1839                print_log( 'ERROR' )
     1840                return
     1841            else:
     1842                raise
    18081843        s._add_history("convert_pol", varlist)
     1844        print_log()
    18091845        return s
    18101846
    1811     @asaplog_post_dec
     1847    @print_log_dec
    18121848    def smooth(self, kernel="hanning", width=5.0, order=2, plot=False, insitu=None):
    18131849        """\
     
    18191855                        'hanning' (default), 'gaussian', 'boxcar', 'rmedian'
    18201856                        or 'poly'
    1821 
    18221857            width:      The width of the kernel in pixels. For hanning this is
    18231858                        ignored otherwise it defauls to 5 pixels.
     
    18251860                        Maximum. For 'boxcar' it is the full width.
    18261861                        For 'rmedian' and 'poly' it is the half width.
    1827 
    18281862            order:      Optional parameter for 'poly' kernel (default is 2), to
    18291863                        specify the order of the polnomial. Ignored by all other
    18301864                        kernels.
    1831 
    18321865            plot:       plot the original and the smoothed spectra.
    18331866                        In this each indivual fit has to be approved, by
    18341867                        typing 'y' or 'n'
    1835 
    18361868            insitu:     if False a new scantable is returned.
    18371869                        Otherwise, the scaling is done in-situ
     
    18841916            del orgscan
    18851917
     1918        print_log()
    18861919        if insitu: self._assign(s)
    18871920        else: return s
    18881921
    1889     @asaplog_post_dec
    1890     def old_poly_baseline(self, mask=None, order=0, plot=False, uselin=False, insitu=None, rows=None):
     1922    @print_log_dec
     1923    def poly_baseline(self, mask=None, order=0, plot=False, uselin=False,
     1924                      insitu=None):
    18911925        """\
    18921926        Return a scan which has been baselined (all rows) by a polynomial.
    1893        
     1927
    18941928        Parameters:
    18951929
    18961930            mask:       an optional mask
    1897 
    18981931            order:      the order of the polynomial (default is 0)
    1899 
    19001932            plot:       plot the fit and the residual. In this each
    19011933                        indivual fit has to be approved, by typing 'y'
    19021934                        or 'n'
    1903 
    19041935            uselin:     use linear polynomial fit
    1905 
    19061936            insitu:     if False a new scantable is returned.
    19071937                        Otherwise, the scaling is done in-situ
    19081938                        The default is taken from .asaprc (False)
    19091939
    1910             rows:       row numbers of spectra to be processed.
    1911                         (default is None: for all rows)
    1912        
    1913         Example:
     1940        Example::
     1941
    19141942            # return a scan baselined by a third order polynomial,
    19151943            # not using a mask
     
    19241952        varlist = vars()
    19251953        if mask is None:
    1926             mask = [True for i in xrange(self.nchan())]
    1927 
     1954            mask = [True for i in xrange(self.nchan(-1))]
     1955
     1956        from asap.asapfitter import fitter
    19281957        try:
    19291958            f = fitter()
     
    19331962                f.set_function(poly=order)
    19341963
    1935             if rows == None:
    1936                 rows = xrange(workscan.nrow())
    1937             elif isinstance(rows, int):
    1938                 rows = [ rows ]
    1939            
     1964            rows = range(workscan.nrow())
    19401965            if len(rows) > 0:
    19411966                self.blpars = []
    1942                 self.masklists = []
    1943                 self.actualmask = []
    1944            
     1967
    19451968            for r in rows:
     1969                # take into account flagtra info (CAS-1434)
     1970                flagtra = workscan._getmask(r)
     1971                actualmask = mask[:]
     1972                if len(actualmask) == 0:
     1973                    actualmask = list(flagtra[:])
     1974                else:
     1975                    if len(actualmask) != len(flagtra):
     1976                        raise RuntimeError, "Mask and flagtra have different length"
     1977                    else:
     1978                        for i in range(0, len(actualmask)):
     1979                            actualmask[i] = actualmask[i] and flagtra[i]
     1980                f.set_scan(workscan, actualmask)
    19461981                f.x = workscan._getabcissa(r)
    19471982                f.y = workscan._getspectrum(r)
    1948                 f.mask = mask_and(mask, workscan._getmask(r))    # (CAS-1434)
    19491983                f.data = None
    19501984                f.fit()
     
    19541988                    if x.upper() == 'N':
    19551989                        self.blpars.append(None)
    1956                         self.masklists.append(None)
    1957                         self.actualmask.append(None)
    19581990                        continue
    19591991                workscan._setspectrum(f.fitter.getresidual(), r)
    19601992                self.blpars.append(f.get_parameters())
    1961                 self.masklists.append(workscan.get_masklist(f.mask, row=r, silent=True))
    1962                 self.actualmask.append(f.mask)
    19631993
    19641994            if plot:
     
    19661996                f._p = None
    19671997            workscan._add_history("poly_baseline", varlist)
    1968             if insitu:
    1969                 self._assign(workscan)
    1970             else:
    1971                 return workscan
     1998            print_log()
     1999            if insitu: self._assign(workscan)
     2000            else: return workscan
    19722001        except RuntimeError:
    19732002            msg = "The fit failed, possibly because it didn't converge."
    1974             raise RuntimeError(msg)
    1975 
    1976     @asaplog_post_dec
    1977     def poly_baseline(self, mask=None, order=0, plot=False, batch=False, insitu=None, rows=None):
    1978         """\
    1979         Return a scan which has been baselined (all rows) by a polynomial.
    1980         Parameters:
    1981             mask:       an optional mask
    1982             order:      the order of the polynomial (default is 0)
    1983             plot:       plot the fit and the residual. In this each
    1984                         indivual fit has to be approved, by typing 'y'
    1985                         or 'n'. Ignored if batch = True.
    1986             batch:      if True a faster algorithm is used and logs
    1987                         including the fit results are not output
    1988                         (default is False)
    1989             insitu:     if False a new scantable is returned.
    1990                         Otherwise, the scaling is done in-situ
    1991                         The default is taken from .asaprc (False)
    1992             rows:       row numbers of spectra to be baselined.
    1993                         (default is None: for all rows)
    1994         Example:
    1995             # return a scan baselined by a third order polynomial,
    1996             # not using a mask
    1997             bscan = scan.poly_baseline(order=3)
    1998         """
    1999        
    2000         varlist = vars()
    2001        
    2002         if insitu is None: insitu = rcParams["insitu"]
    2003         if insitu:
    2004             workscan = self
    2005         else:
    2006             workscan = self.copy()
    2007 
    2008         nchan = workscan.nchan()
    2009        
    2010         if mask is None:
    2011             mask = [True for i in xrange(nchan)]
    2012 
    2013         try:
    2014             if rows == None:
    2015                 rows = xrange(workscan.nrow())
    2016             elif isinstance(rows, int):
    2017                 rows = [ rows ]
    2018            
    2019             if len(rows) > 0:
    2020                 workscan.blpars = []
    2021                 workscan.masklists = []
    2022                 workscan.actualmask = []
    2023 
    2024             if batch:
    2025                 workscan._poly_baseline_batch(mask, order)
    2026             elif plot:
    2027                 f = fitter()
    2028                 f.set_function(lpoly=order)
    2029                 for r in rows:
    2030                     f.x = workscan._getabcissa(r)
    2031                     f.y = workscan._getspectrum(r)
    2032                     f.mask = mask_and(mask, workscan._getmask(r))    # (CAS-1434)
    2033                     f.data = None
    2034                     f.fit()
    2035                    
    2036                     f.plot(residual=True)
    2037                     accept_fit = raw_input("Accept fit ( [y]/n ): ")
    2038                     if accept_fit.upper() == "N":
    2039                         self.blpars.append(None)
    2040                         self.masklists.append(None)
    2041                         self.actualmask.append(None)
    2042                         continue
    2043                     workscan._setspectrum(f.fitter.getresidual(), r)
    2044                     workscan.blpars.append(f.get_parameters())
    2045                     workscan.masklists.append(workscan.get_masklist(f.mask, row=r))
    2046                     workscan.actualmask.append(f.mask)
    2047                    
    2048                 f._p.unmap()
    2049                 f._p = None
    2050             else:
    2051                 for r in rows:
    2052                     fitparams = workscan._poly_baseline(mask, order, r)
    2053                     params = fitparams.getparameters()
    2054                     fmtd = ", ".join(["p%d = %3.6f" % (i, v) for i, v in enumerate(params)])
    2055                     errors = fitparams.geterrors()
    2056                     fmask = mask_and(mask, workscan._getmask(r))
    2057 
    2058                     workscan.blpars.append({"params":params,
    2059                                             "fixed": fitparams.getfixedparameters(),
    2060                                             "formatted":fmtd, "errors":errors})
    2061                     workscan.masklists.append(workscan.get_masklist(fmask, r, silent=True))
    2062                     workscan.actualmask.append(fmask)
    2063                    
    2064                     asaplog.push(fmtd)
    2065            
    2066             workscan._add_history("poly_baseline", varlist)
    2067            
    2068             if insitu:
    2069                 self._assign(workscan)
    2070             else:
    2071                 return workscan
    2072            
    2073         except RuntimeError, e:
    2074             msg = "The fit failed, possibly because it didn't converge."
    2075             if rcParams["verbose"]:
    2076                 asaplog.push(str(e))
    2077                 asaplog.push(str(msg))
     2003            if rcParams['verbose']:
     2004                #print msg
     2005                print_log()
     2006                asaplog.push( str(msg) )
     2007                print_log( 'ERROR' )
    20782008                return
    20792009            else:
    2080                 raise RuntimeError(str(e)+'\n'+msg)
    2081 
    2082 
    2083     def auto_poly_baseline(self, mask=None, edge=(0, 0), order=0,
     2010                raise RuntimeError(msg)
     2011
     2012
     2013    def auto_poly_baseline(self, mask=[], edge=(0, 0), order=0,
    20842014                           threshold=3, chan_avg_limit=1, plot=False,
    2085                            insitu=None, rows=None):
     2015                           insitu=None):
    20862016        """\
    20872017        Return a scan which has been baselined (all rows) by a polynomial.
     
    21242054                        Otherwise, the scaling is done in-situ
    21252055                        The default is taken from .asaprc (False)
    2126             rows:       row numbers of spectra to be processed.
    2127                         (default is None: for all rows)
    21282056
    21292057
     
    21352063        if insitu is None: insitu = rcParams['insitu']
    21362064        varlist = vars()
     2065        from asap.asapfitter import fitter
    21372066        from asap.asaplinefind import linefinder
    21382067        from asap import _is_sequence_or_number as _is_valid
     
    21582087            curedge = edge;
    21592088
    2160         if not insitu:
    2161             workscan = self.copy()
    2162         else:
    2163             workscan = self
    2164 
    21652089        # setup fitter
    21662090        f = fitter()
    2167         f.set_function(lpoly=order)
     2091        f.set_function(poly=order)
    21682092
    21692093        # setup line finder
     
    21712095        fl.set_options(threshold=threshold,avg_limit=chan_avg_limit)
    21722096
     2097        if not insitu:
     2098            workscan = self.copy()
     2099        else:
     2100            workscan = self
     2101
    21732102        fl.set_scan(workscan)
    21742103
    2175         if mask is None:
    2176             mask = _n_bools(workscan.nchan(), True)
    2177        
    2178         if rows is None:
    2179             rows = xrange(workscan.nrow())
    2180         elif isinstance(rows, int):
    2181             rows = [ rows ]
    2182        
     2104        rows = range(workscan.nrow())
    21832105        # Save parameters of baseline fits & masklists as a class attribute.
    21842106        # NOTICE: It does not reflect changes in scantable!
     
    21862108            self.blpars=[]
    21872109            self.masklists=[]
    2188             self.actualmask=[]
    21892110        asaplog.push("Processing:")
    21902111        for r in rows:
     
    22012122                    curedge = edge[workscan.getif(r)]
    22022123
    2203             actualmask = mask_and(mask, workscan._getmask(r))    # (CAS-1434)
     2124            # take into account flagtra info (CAS-1434)
     2125            flagtra = workscan._getmask(r)
     2126            actualmask = mask[:]
     2127            if len(actualmask) == 0:
     2128                actualmask = list(flagtra[:])
     2129            else:
     2130                if len(actualmask) != len(flagtra):
     2131                    raise RuntimeError, "Mask and flagtra have different length"
     2132                else:
     2133                    for i in range(0, len(actualmask)):
     2134                        actualmask[i] = actualmask[i] and flagtra[i]
    22042135
    22052136            # setup line finder
    22062137            fl.find_lines(r, actualmask, curedge)
    2207            
     2138            outmask=fl.get_mask()
     2139            f.set_scan(workscan, fl.get_mask())
    22082140            f.x = workscan._getabcissa(r)
    22092141            f.y = workscan._getspectrum(r)
    2210             f.mask = fl.get_mask()
    22112142            f.data = None
    22122143            f.fit()
    22132144
    22142145            # Show mask list
    2215             masklist=workscan.get_masklist(f.mask, row=r, silent=True)
     2146            masklist=workscan.get_masklist(fl.get_mask(),row=r)
    22162147            msg = "mask range: "+str(masklist)
    22172148            asaplog.push(msg, False)
     
    22232154                    self.blpars.append(None)
    22242155                    self.masklists.append(None)
    2225                     self.actualmask.append(None)
    22262156                    continue
    22272157
     
    22292159            self.blpars.append(f.get_parameters())
    22302160            self.masklists.append(masklist)
    2231             self.actualmask.append(f.mask)
    22322161        if plot:
    22332162            f._p.unmap()
     
    22392168            return workscan
    22402169
    2241     @asaplog_post_dec
     2170    @print_log_dec
    22422171    def rotate_linpolphase(self, angle):
    22432172        """\
     
    22582187        self._math._rotate_linpolphase(self, angle)
    22592188        self._add_history("rotate_linpolphase", varlist)
     2189        print_log()
    22602190        return
    22612191
    2262     @asaplog_post_dec
     2192    @print_log_dec
    22632193    def rotate_xyphase(self, angle):
    22642194        """\
     
    22792209        self._math._rotate_xyphase(self, angle)
    22802210        self._add_history("rotate_xyphase", varlist)
     2211        print_log()
    22812212        return
    22822213
    2283     @asaplog_post_dec
     2214    @print_log_dec
    22842215    def swap_linears(self):
    22852216        """\
     
    22902221        self._math._swap_linears(self)
    22912222        self._add_history("swap_linears", varlist)
     2223        print_log()
    22922224        return
    22932225
    2294     @asaplog_post_dec
     2226    @print_log_dec
    22952227    def invert_phase(self):
    22962228        """\
     
    23022234        return
    23032235
    2304     @asaplog_post_dec
     2236    @print_log_dec
    23052237    def add(self, offset, insitu=None):
    23062238        """\
     
    23102242
    23112243            offset:      the offset
    2312 
    23132244            insitu:      if False a new scantable is returned.
    23142245                         Otherwise, the scaling is done in-situ
     
    23262257            return s
    23272258
    2328     @asaplog_post_dec
     2259    @print_log_dec
    23292260    def scale(self, factor, tsys=True, insitu=None):
    23302261        """\
    23312262
    2332         Return a scan where all spectra are scaled by the given 'factor'
     2263        Return a scan where all spectra are scaled by the give 'factor'
    23332264
    23342265        Parameters:
    23352266
    23362267            factor:      the scaling factor (float or 1D float list)
    2337 
    23382268            insitu:      if False a new scantable is returned.
    23392269                         Otherwise, the scaling is done in-situ
    23402270                         The default is taken from .asaprc (False)
    2341 
    23422271            tsys:        if True (default) then apply the operation to Tsys
    23432272                         as well as the data
     
    23582287            s = scantable(self._math._unaryop(self.copy(), factor, "MUL", tsys))
    23592288        s._add_history("scale", varlist)
     2289        print_log()
    23602290        if insitu:
    23612291            self._assign(s)
     
    23722302
    23732303            match:          a Unix style pattern, regular expression or selector
    2374 
    23752304            matchtype:      'pattern' (default) UNIX style pattern or
    23762305                            'regex' regular expression
    2377 
    23782306            sourcetype:     the type of the source to use (source/reference)
    23792307
     
    24042332        self._add_history("set_sourcetype", varlist)
    24052333
    2406     @asaplog_post_dec
    2407     @preserve_selection
     2334    @print_log_dec
    24082335    def auto_quotient(self, preserve=True, mode='paired', verify=False):
    24092336        """\
     
    24162343            preserve:       you can preserve (default) the continuum or
    24172344                            remove it.  The equations used are
    2418 
    24192345                            preserve: Output = Toff * (on/off) - Toff
    2420 
    24212346                            remove:   Output = Toff * (on/off) - Ton
    2422 
    24232347            mode:           the on/off detection mode
    24242348                            'paired' (default)
     
    24302354                            finds the closest off in time
    24312355
    2432         .. todo:: verify argument is not implemented
    2433 
    2434         """
    2435         varlist = vars()
     2356        """
    24362357        modes = ["time", "paired"]
    24372358        if not mode in modes:
    24382359            msg = "please provide valid mode. Valid modes are %s" % (modes)
    24392360            raise ValueError(msg)
     2361        varlist = vars()
    24402362        s = None
    24412363        if mode.lower() == "paired":
    2442             sel = self.get_selection()
    2443             sel.set_query("SRCTYPE==psoff")
     2364            basesel = self.get_selection()
     2365            sel = selector()+basesel
     2366            sel.set_query("SRCTYPE==1")
    24442367            self.set_selection(sel)
    24452368            offs = self.copy()
    2446             sel.set_query("SRCTYPE==pson")
     2369            sel.set_query("SRCTYPE==0")
    24472370            self.set_selection(sel)
    24482371            ons = self.copy()
    24492372            s = scantable(self._math._quotient(ons, offs, preserve))
     2373            self.set_selection(basesel)
    24502374        elif mode.lower() == "time":
    24512375            s = scantable(self._math._auto_quotient(self, mode, preserve))
    24522376        s._add_history("auto_quotient", varlist)
     2377        print_log()
    24532378        return s
    24542379
    2455     @asaplog_post_dec
     2380    @print_log_dec
    24562381    def mx_quotient(self, mask = None, weight='median', preserve=True):
    24572382        """\
     
    24612386
    24622387            mask:           an optional mask to be used when weight == 'stddev'
    2463 
    24642388            weight:         How to average the off beams.  Default is 'median'.
    2465 
    24662389            preserve:       you can preserve (default) the continuum or
    2467                             remove it.  The equations used are:
    2468 
    2469                                 preserve: Output = Toff * (on/off) - Toff
    2470 
    2471                                 remove:   Output = Toff * (on/off) - Ton
     2390                            remove it.  The equations used are
     2391                            preserve: Output = Toff * (on/off) - Toff
     2392                            remove:   Output = Toff * (on/off) - Ton
    24722393
    24732394        """
     
    24802401        q = quotient(on, off, preserve)
    24812402        q._add_history("mx_quotient", varlist)
     2403        print_log()
    24822404        return q
    24832405
    2484     @asaplog_post_dec
     2406    @print_log_dec
    24852407    def freq_switch(self, insitu=None):
    24862408        """\
     
    24992421        s = scantable(self._math._freqswitch(self))
    25002422        s._add_history("freq_switch", varlist)
    2501         if insitu:
    2502             self._assign(s)
    2503         else:
    2504             return s
    2505 
    2506     @asaplog_post_dec
     2423        print_log()
     2424        if insitu: self._assign(s)
     2425        else: return s
     2426
     2427    @print_log_dec
    25072428    def recalc_azel(self):
    25082429        """Recalculate the azimuth and elevation for each position."""
     
    25102431        self._recalcazel()
    25112432        self._add_history("recalc_azel", varlist)
     2433        print_log()
    25122434        return
    25132435
    2514     @asaplog_post_dec
     2436    @print_log_dec
    25152437    def __add__(self, other):
    25162438        varlist = vars()
     
    25252447        return s
    25262448
    2527     @asaplog_post_dec
     2449    @print_log_dec
    25282450    def __sub__(self, other):
    25292451        """
     
    25412463        return s
    25422464
    2543     @asaplog_post_dec
     2465    @print_log_dec
    25442466    def __mul__(self, other):
    25452467        """
     
    25582480
    25592481
    2560     @asaplog_post_dec
     2482    @print_log_dec
    25612483    def __div__(self, other):
    25622484        """
     
    25762498        return s
    25772499
    2578     @asaplog_post_dec
    25792500    def get_fit(self, row=0):
    25802501        """\
     
    25902511        from asap.asapfit import asapfit
    25912512        fit = asapfit(self._getfit(row))
    2592         asaplog.push( '%s' %(fit) )
    2593         return fit.as_dict()
     2513        if rcParams['verbose']:
     2514            #print fit
     2515            asaplog.push( '%s' %(fit) )
     2516            print_log()
     2517            return
     2518        else:
     2519            return fit.as_dict()
    25942520
    25952521    def flag_nans(self):
     
    26852611        return (sum(nchans)/len(nchans) == nchans[0])
    26862612
    2687     @asaplog_post_dec
    2688     #def _fill(self, names, unit, average, getpt, antenna):
    2689     def _fill(self, names, unit, average, opts={}):
     2613    def _fill(self, names, unit, average, getpt, antenna):
    26902614        first = True
    26912615        fullnames = []
     
    26952619            if not os.path.exists(name):
    26962620                msg = "File '%s' does not exists" % (name)
     2621                if rcParams['verbose']:
     2622                    asaplog.push(msg)
     2623                    print_log( 'ERROR' )
     2624                    return
    26972625                raise IOError(msg)
    26982626            fullnames.append(name)
     
    27072635            msg = "Importing %s..." % (name)
    27082636            asaplog.push(msg, False)
    2709             #opts = {'ms': {'antenna' : antenna, 'getpt': getpt} }
    2710             r.open(name, opts)# antenna, -1, -1, getpt)
     2637            print_log()
     2638            r.open(name)# antenna, -1, -1, getpt)
    27112639            r.fill()
    27122640            if average:
     
    27182646            del r, tbl
    27192647            first = False
    2720             #flush log
    2721         asaplog.post()
    27222648        if unit is not None:
    27232649            self.set_fluxunit(unit)
  • trunk/python/selector.py

    r1949 r1849  
    1 import re
    2 from asap._asap import selector as _selector, srctype
     1from asap._asap import selector as _selector
    32from asap.utils import unique, _to_list
    43
     
    87    scantables to specific rows.
    98    """
    10     fields = ["pols", "ifs", "beams", "scans", "cycles", "name", "query", "types", "rows"]
     9    fields = ["pols", "ifs", "beams", "scans", "cycles", "name", "query"]
    1110
    1211    def __init__(self, *args, **kw):
     
    149148        Example:
    150149            # select all off scans with integration times over 60 seconds.
    151             selection.set_query("SRCTYPE == PSOFF AND INTERVAL > 60.0")
    152         """
    153         rx = re.compile("((SRCTYPE *[!=][=] *)([a-zA-Z.]+))", re.I)
    154         for r in rx.findall(query):
    155             sval = None
    156             stype = r[-1].lower()
    157             if stype.find('srctype.') == -1:
    158                 stype = ".".join(["srctype", stype])
    159             try:
    160                 sval = eval(stype)
    161                 sval = "%s%d" % (r[1], sval)
    162             except:
    163                 continue
    164             query = query.replace(r[0], sval)
     150            selection.set_query("SRCTYPE == 1 AND INTERVAL > 60.0")
     151        """
    165152        taql = "SELECT FROM $1 WHERE " + query
    166153        self._settaql(taql)
     
    216203    def get_types(self):
    217204        return list(self._gettypes())
    218     def get_rows(self):
    219         return list(self._getrows())
    220205    def get_query(self):
    221206        prefix = "SELECT FROM $1 WHERE "
     
    235220             "POLNO": self.get_pols(),
    236221             "QUERY": self.get_query(),
    237              "SRCTYPE": self.get_types(),
    238              "ROWS": self.get_rows(),
    239222             "Sort Order": self.get_order()
    240223             }
  • trunk/python/utils.py

    r1949 r1849  
    6161    if not os.path.isdir(path):
    6262        return None
    63     valid = "ms rpf rpf.1 rpf.2 sdf sdfits mbf asap".split()
     63    valid = "rpf rpf.1 rpf.2 sdf sdfits mbf asap".split()
    6464    if not suffix in valid:
    6565        return None
    6666    files = [os.path.expanduser(os.path.expandvars(path+"/"+f)) for f in os.listdir(path)]
    6767    return filter(lambda x: x.endswith(suffix),files)
    68 
    69 def page(message):
    70     """Run the input message through a pager. This is only done if
    71     ``rcParams["verbose"]`` is set.
    72     """
    73     verbose = False
    74     try:
    75         from asap.parameters import rcParams
    76         verbose = rcParams['verbose']
    77     except:
    78         pass
    79     if verbose:
    80         try:
    81             from IPython.genutils import page as pager
    82         except ImportError:
    83             from pydoc import pager
    84         pager(message)
    85         return None
    86     else:
    87         return message
  • trunk/src

  • trunk/src/AsapLogSink.cpp

    r1949 r1849  
    2121
    2222  void AsapLogSink::postMessage(const std::string& msg,
    23                                 const std::string& priority,
    24                                 const std::string& origin)
     23                                const std::string& location,
     24                                const std::string& priority)
    2525  {
    2626    LogMessage::Priority p;
     
    3232      p = LogMessage::SEVERE;
    3333    }
    34     LogMessage message(msg, LogOrigin(origin), p);
     34    LogMessage message(msg, LogOrigin(location), p);
    3535
    3636    MemoryLogSink::postLocally(message);
  • trunk/src/AsapLogSink.h

    r1949 r1849  
    3737
    3838  virtual void postMessage(const std::string& msg,
    39                            const std::string& priority="INFO",
    40                            const std::string& origin="");
     39                           const std::string& location="",
     40                           const std::string& priority="INFO");
    4141
    4242  std::string popMessages();
  • trunk/src/FillerBase.cpp

    r1949 r1849  
    3838  RecordFieldPtr< Array<Float> > tsysCol(row_.record(), "TSYS");
    3939
    40   //*specCol = spectrum;
    41   //*flagCol = flags;
    42   //*tsysCol = tsys;
    43   specCol.define(spectrum);
    44   flagCol.define(flags);
    45   tsysCol.define(tsys);
     40  *specCol = spectrum;
     41  *flagCol = flags;
     42  *tsysCol = tsys;
    4643}
    4744
  • trunk/src/FillerBase.h

    r1949 r1849  
    4343    virtual ~FillerBase() {;}
    4444
    45     virtual bool open(const std::string& filename, const casa::Record& rec) = 0;
    46     //    virtual bool open(const std::string& filename) = 0;
     45//    virtual bool open(const std::string& filename, const Record& rec) = 0;
     46    virtual bool open(const std::string& filename) = 0;
    4747    virtual void fill() = 0;
    4848    virtual void close() = 0;
  • trunk/src/FillerWrapper.h

    r1949 r1849  
    1616#include <casa/Exceptions.h>
    1717#include <casa/Utilities/CountedPtr.h>
    18 #include <casa/Containers/Record.h>
    1918#include <casa/OS/File.h>
    2019
     
    3938
    4039
    41   void open(const std::string& filename, const casa::Record& rec) {
    42     //  void open(const std::string& filename) {
     40//  void open(const std::string& filename, casa::Record rec) {
     41  void open(const std::string& filename) {
    4342    casa::File file(filename);
    4443    if ( !file.exists() ) {
     
    4645    }
    4746    filler_ = new PKSFiller(stable_);
    48     if (filler_->open(filename, rec)) {
    49       //    if (filler_->open(filename)) {
     47//    if (filler_->open(filename, rec)) {
     48    if (filler_->open(filename)) {
    5049      attached_ = true;
    5150      return;
    5251    }
    5352    filler_ = new NROFiller(stable_);
    54     if (filler_->open(filename, rec)) {
    55       //    if (filler_->open(filename)) {
     53//    if (filler_->open(filename, rec)) {
     54    if (filler_->open(filename)) {
    5655      attached_ = true;
    5756      return;
  • trunk/src/Makefile

    r1949 r1849  
    77###    3. Replase library names in G2CARCH '-lcasa_*' with '-l*'.
    88###    4. Comment-IN the definition of 'CXXOPTS'.
    9 TARGET   := /tmp/_asap.so
    10 
    11 ifndef ASAPROOT
    12         ASAPROOT := $(abspath ..)
    13 endif
    14 ATNFD := external-alma
     9#TARGET   := /tmp/_asap.so
     10TARGET   := /home/nakazato/tmp/_asap.so
    1511
    1612# the casa environment AIPSPATH has to be defined
    1713CASAROOT  := $(word 1, $(CASAPATH))
    1814CASAARCH  := $(word 2, $(CASAPATH))
    19 
    20 CXXFLAGS := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=CXXFLAGS eval_vars) && echo $$CXXFLAGS)
    21 CXXOPTS := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=COPTFLAGS eval_vars) && echo $$COPTFLAGS)
    22 LDFLAGS := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=LD_FLAGS eval_vars) && echo $$LD_FLAGS)
    2315
    2416COREINCD := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=COREINCD eval_vars) && echo $$COREINCD)
     
    3022PYTHONINCD := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=PYTHONINCD eval_vars) && echo $$PYTHONINCD)
    3123PYTHONLIB := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=PYTHONLIB eval_vars) && echo $$PYTHONLIB)
     24#PYTHONVER := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=PYTHONVER eval_vars) && echo $$PYTHONVER)
    3225BOOSTROOT := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=BOOSTROOT eval_vars) && echo $$BOOSTROOT)
    3326RPFITSLIBD := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=RPFITSLIBD eval_vars) && echo $$RPFITSLIBD)
    34 CFITSIOLIBD := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=CFITSIOLIBD eval_vars) && echo $$CFITSIOLIBD)
    35 CFITSIOINCD := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=CFITSIOINCD eval_vars) && echo $$CFITSIOINCD)
    3627
    3728CASAINC   := -I$(CASAROOT)/code/include -I$(COREINCD) -I$(CASAROOT)/$(CASAARCH)/include
    3829CASALIB   := $(CASAROOT)/$(CASAARCH)/lib
     30#USELIB := lib64
     31USELIB := lib
    3932
    4033# the compiler
     
    4437
    4538# compiler flags
    46 CXXFLAGS += -fPIC -DHAVE_LIBPYRAP
    47 
    48 PYRAPD := $(ASAPROOT)/external/libpyrap
    49 PYRAPLIBD := $(PYRAPD)
    50 PYRAPINCD := $(PYRAPD)/pyrap-0.3.2
    51 PYRAPLIB := -L$(PYRAPLIBD) -lpyrap
    52 
    53 
     39CXXFLAGS := -fPIC -O3 -g
     40CXXFLAGS += -ansi -Wno-long-long -Wall
     41#CXXOPTS := -DAIPS_64B
     42
     43# darwin specific flags
     44ifeq "$(CASAARCH)" "darwin"
     45   #CXXFLAGS +=-DAIPS_DARWIN -arch i386 #For 10.6
     46   CXXFLAGS +=-DAIPS_DARWIN
     47   #CXXFLAGS += -Wno-long-double
     48endif
     49
     50# cfitsio
     51CFITSIOROOT := /usr
     52CFITSIOINC := -I$(CFITSIOROOT)/include/cfitsio
    5453CFITSIOLIB := -lcfitsio
    5554
    5655#rpfits
     56RPFITSROOT := /usr
    5757RPFITSLIB := -lrpfits
    5858
     
    6060G2CLIB := -lgfortran
    6161
    62 # links to external libraries
    63 CASAPPLIB := -L$(ASAPROOT)/$(ATNFD) -latnf $(CORELIB) $(PYRAPLIB)\
     62# This assumes all casa libs are static only (*.a)
     63# if not than there might by symbol resolution errors.
     64CASAPPLIB := -L$(CASALIB) -latnf $(CORELIB) \
    6465             -L$(WCSLIBLIBD) $(WCSLIBLIB) \
    6566             -L$(RPFITSLIBD) $(RPFITSLIB) $(CFITSIOLIB) $(G2CLIB) -lstdc++
    6667
    6768# darwin specific CASA flags
    68 ifeq ($(shell uname), Darwin)
     69ifeq "$(CASAARCH)" "darwin"
    6970   CASAPPLIB += -framework vecLib
    7071else
     
    7273endif
    7374
     75# python
     76PYTHONINC := $(addprefix -I,$(PYTHONINCD))
     77PYTHONLIB := -L$(PYTHONLIBD) $(PYTHONLIB)
     78
     79# use python universal build
     80#ifeq "$(CASAARCH)" "darwin"
     81#   PYVERSION := 2.5
     82#   PYTHONROOT := /Library/Frameworks/Python.framework/Versions/$(PYVERSION)
     83#   PYTHONINC := -I$(PYTHONROOT)/include/python$(PYVERSION)
     84#   PYTHONLIB := -L$(PYTHONROOT)/lib -framework Python
     85#endif
     86
     87# the linker
    7488LD        := $(CXX)
    7589
     
    7892BOOSTINC  := -I$(BOOSTROOT)/include/boost -I$(BOOSTROOT)/include
    7993
    80 LDFLAGS   += -shared
     94LDFLAGS   := -shared -Wl$(TARGET) -s -Xlinker -rpath -Xlinker $(BOOSTROOT)/lib:$(PYTHONROOT)/lib:$(CASALIB)
     95ifeq "$(CASAARCH)" "darwin"
     96   LDFLAGS   := -bundle
     97endif
    8198
    8299
    83100# DO NOT MODIFY AFTER THIS
    84 INCDIRS   := -I. $(CASAINC)  -I$(CFITSIOINCD) $(BOOSTINC) $(addprefix -I, $(PYTHONINCD)) -I$(ASAPROOT)/$(ATNFD) -I$(PYRAPINCD)
     101INCDIRS   := -I. $(CASAINC)  $(CFITSIOINC) $(BOOSTINC) $(PYTHONINC)
    85102LIBS      := $(PYTHONLIB)  $(BOOSTLIB) $(CASAPPLIB)
    86103
  • trunk/src/NROFiller.cpp

    r1949 r1849  
    2020#include "NROFiller.h"
    2121#include "STHeader.h"
    22 #include <casa/Containers/Record.h>
    2322#include <atnf/PKSIO/SrcType.h>
    2423
     
    3736}
    3837
    39   bool NROFiller::open(const std::string& filename, const Record& rec)
     38bool NROFiller::open(const std::string& filename)
    4039{
    4140  bool status = true ;
  • trunk/src/NROFiller.h

    r1949 r1849  
    4545    virtual ~NROFiller();
    4646
    47     bool open(const std::string& filename, const casa::Record& rec) ;
     47    bool open(const std::string& filename) ;
    4848    void fill() ;
    4949    void close() ;
  • trunk/src/PKSFiller.cpp

    r1949 r1849  
    2020#include <casa/Arrays/ArrayLogical.h>
    2121#include <casa/Utilities/Regex.h>
    22 #include <casa/Utilities/DataType.h>
    2322#include <casa/Logging/LogIO.h>
    2423
    25 #include <casa/Containers/Record.h>
    2624#include <measures/Measures/MDirection.h>
    2725#include <measures/Measures/MeasConvert.h>
     
    3634
    3735#include <time.h>
    38 #include <sstream>
    3936
    4037#include "STDefs.h"
     
    6158}
    6259
    63 bool PKSFiller::open( const std::string& filename, const Record& rec)
     60bool PKSFiller::open( const std::string& filename)
    6461{
    6562  Bool haveBase, haveSpectra;
     
    7774  Vector<uInt> nchans,npols;
    7875
    79   String antenna("");
    80   Bool getPt = False;
    81 
    82   // parsing MS options
    83   if ( rec.isDefined( "ms" ) ) {
    84     Record msrec = rec.asRecord( "ms" ) ;
    85     //msrec.print( cout ) ;
    86     if ( msrec.isDefined( "getpt" ) ) {
    87       getPt = msrec.asBool( "getpt" ) ;
    88     }
    89     if ( msrec.isDefined( "antenna" ) ) {
    90       if ( msrec.type( msrec.fieldNumber( "antenna" ) ) == TpInt ) {
    91         Int antInt = msrec.asInt( "antenna" ) ;
    92         ostringstream oss ;
    93         oss << antInt ;
    94         antenna = String( oss ) ;
    95       }
    96       else {
    97         antenna = msrec.asString( "antenna" ) ;
    98       }
    99     }
    100   }
     76  String antenna("0");
    10177
    10278  reader_ = getPKSreader(inName, antenna, 0, 0, format, beams, ifs,
     
    170146  Vector<Int> start(nIF_, 1);
    171147  Vector<Int> end(nIF_, 0);
     148  Bool getPt = False;
    172149  reader_->select(beams, ifs, start, end, ref, True, haveXPol_[0], False, getPt);
    173150  setHeader(header);
     
    286263    Int match = pksrec.srcName.matches(rx);
    287264    std::string srcname;
    288     Int srctype = Int(SrcType::NOTYPE);
    289265    if (match) {
    290266      srcname = pksrec.srcName;
    291       srctype =  Int(SrcType::PSOFF);
    292267    } else {
    293268      srcname = pksrec.srcName.before(rx2);
    294       srctype =  Int(SrcType::PSON);
    295     }
    296     if ( pksrec.srcType != Int(SrcType::NOTYPE)) {
     269    }
     270    Int srctype = match;
     271    if ( pksrec.srcType != -1 ) {
    297272      srctype = pksrec.srcType ;
    298273    }
  • trunk/src/PKSFiller.h

    r1949 r1849  
    2020#include <casa/Arrays/Vector.h>
    2121
    22 
    2322#include "FillerBase.h"
    2423#include "Scantable.h"
    2524
    26 class casa::Record;
    2725class PKSreader;
    2826
     
    3634    virtual ~PKSFiller();
    3735
    38     bool open(const std::string& filename, const casa::Record& rec);
    39     //    bool open(const std::string& filename);
     36//    bool open(const std::string& filename, const Record& rec)=0;
     37    bool open(const std::string& filename);
    4038    void fill();
    4139    void close();
  • trunk/src/SConscript

    r1949 r1849  
    88cpps = env.SGlob("*.cpp")
    99pycpps = env.SGlob("python_*.cpp")
    10 for pf in pycpps:
    11     cpps.remove(pf)
     10for pf in pycpps: cpps.remove(pf)
    1211
    1312# location of libcasav.a
     
    1918myenv.Prepend( LIBS =  ['asap'] )
    2019
    21 shenv = myenv.Clone()
    22 pyrapdir = shenv.get("pyrapint", None)
    23 if pyrapdir:
    24     shenv.PrependUnique(CPPPATH=pyrapdir)   
    25     pycpps += shenv.Glob('%s/pyrap/*/*.cc' % pyrapdir)
    2620# Finally create the library for the module
    27 if not hasattr(shenv, "LoadableModule"):
    28     shenv.LoadableModule = shenv.SharedLibrary
    29 so = shenv.LoadableModule( target = "_asap.so", source = pycpps, SHLIBSUFFIX="" )
    30 #test = shenv.Program("test", cpps)
     21if not hasattr(myenv, "LoadableModule"):
     22    myenv.LoadableModule = myenv.SharedLibrary
     23so = myenv.LoadableModule( target = "_asap.so", source = pycpps, SHLIBSUFFIX="" )
     24#test = myenv.Program("test", cpps)
    3125Return("so")
    3226
  • trunk/src/STFit.cpp

    r1949 r1849  
    7070  table_.addColumn(ArrayColumnDesc<Int>("COMPONENTS"));
    7171  table_.addColumn(ArrayColumnDesc<Double>("PARAMETERS"));
    72   //  table_.addColumn(ArrayColumnDesc<Double>("ERRORS"));
    7372  table_.addColumn(ArrayColumnDesc<Bool>("PARMASKS"));
    7473  table_.addColumn(ArrayColumnDesc<String>("FRAMEINFO"));
     
    7877  compCol_.attach(table_,"COMPONENTS");
    7978  parCol_.attach(table_,"PARAMETERS");
    80   //  errCol_.attach(table_,"ERRORS");
    8179  maskCol_.attach(table_,"PARMASKS");
    8280  frameCol_.attach(table_,"FRAMEINFO");
     
    104102  // add new row if new id
    105103  if ( !foundentry ) table_.addRow();
    106 
    107104  funcCol_.put(rno, mathutil::toVectorString(fit.getFunctions()));
    108105  compCol_.put(rno, Vector<Int>(fit.getComponents()));
    109   const std::vector<float>& pvec = fit.getParameters();
    110   Vector<Double> dvec(pvec.size());
    111   for (size_t i=0; i < dvec.nelements(); ++i) {
    112     dvec[i] = Double(pvec[i]);
    113   }
    114   parCol_.put(rno, dvec);
    115   /*
    116   const std::vector<double>& evec = fit.getErrors();
    117   for (size_t i=0; i < dvec.nelements(); ++i) {
    118     dvec[i] = Double(evec[i]);
    119   }
    120   errCol_.put(rno, dvec);
    121   */
     106  parCol_.put(rno, Vector<Double>(fit.getParameters()));
    122107  maskCol_.put(rno, Vector<Bool>(fit.getParmasks()));
    123108  frameCol_.put(rno, mathutil::toVectorString(fit.getFrameinfo()));
    124109  idCol_.put(rno, resultid);
    125 
    126110  return resultid;
    127111}
     
    146130  fit.setComponents(istl);
    147131  Vector<Double> dvec;
     132  std::vector<double> dstl;
    148133  rec.get("PARAMETERS", dvec);
    149   std::vector<float> dstl(dvec.begin(), dvec.end());
    150   fit.setParameters(dstl);
    151   /*
    152134  dvec.tovector(dstl);
    153135  fit.setParameters(dstl);
    154   dvec.resize();
    155   rec.get("ERRORS", dvec);
    156   dvec.tovector(dstl);
    157   fit.setErrors(dstl);
    158   */
    159136  Vector<Bool> bvec;
    160137  std::vector<bool> bstl;
  • trunk/src/STFit.h

    r1949 r1849  
    4949  casa::ArrayColumn<casa::Int> compCol_;
    5050  casa::ArrayColumn<casa::Double> parCol_;
    51   //  casa::ArrayColumn<casa::Double> errCol_;
    5251  casa::ArrayColumn<casa::Bool> maskCol_;
    5352  casa::ArrayColumn<casa::String> frameCol_;
  • trunk/src/STFitEntry.cpp

    r1949 r1849  
    1111//
    1212#include "STFitEntry.h"
    13 #include <casa/iostream.h>
    1413
    15 using namespace casa;
    1614namespace asap {
    1715
    18   STFitEntry::STFitEntry()
    19   /* :
    20     functions_( std::vector<std::string>()),
    21     components_(std::vector<int>()),
    22     parameters_(std::vector<float>()),
    23     errors_(std::vector<float>()),
    24     parmasks_(std::vector<bool>()),
    25     frameinfo_(std::vector<std::string>())
    26   */
     16STFitEntry::STFitEntry()
    2717{
    2818}
     
    3020{
    3121  if ( this != &other ) {
    32     this->functions_ = std::vector<std::string>();
     22    this->functions_ = other.functions_;
    3323    this->components_ = other.components_;
    3424    this->parameters_ = other.parameters_;
    35     this->errors_ = other.errors_;
     25    this->parmasks_ = other.parmasks_;
    3626    this->frameinfo_ = other.frameinfo_;
    3727  }
    3828}
    3929
    40 STFitEntry& STFitEntry::operator=(const STFitEntry& other)
    41 {
    42   if ( this != &other ) {
    43     this->functions_ = other.functions_;
    44     this->components_ = other.components_;
    45     this->parameters_ = other.parameters_;
    46     this->errors_ = other.errors_;
    47     this->parmasks_ = other.parmasks_;
    48     this->frameinfo_ = other.frameinfo_;
    49   }
    50   return *this;
    51 }
    5230
    5331STFitEntry::~STFitEntry()
  • trunk/src/STFitEntry.h

    r1949 r1849  
    2828  STFitEntry(const STFitEntry& other);
    2929
    30   STFitEntry& operator=(const STFitEntry& other);
    31 
    3230  ~STFitEntry();
    3331
     
    3634  void setComponents(const std::vector<int>& c)
    3735    { components_ = c; }
    38   void setParameters(const std::vector<float>& p)
     36  void setParameters(const std::vector<double>& p)
    3937    { parameters_ = p; }
    40   void setErrors(const std::vector<float>& p)
    41     { errors_ = p; }
    4238  void setParmasks(const std::vector<bool>& m)
    4339    { parmasks_ = m; }
    4440  void setFrameinfo(const std::vector<std::string>& f)
    4541    { frameinfo_ = f; }
     42
    4643  std::vector<std::string> getFunctions() const { return functions_; }
    4744  std::vector<int> getComponents() const { return components_; }
    48   std::vector<float> getParameters() const { return parameters_; }
    49   std::vector<float> getErrors() const { return errors_; }
     45  std::vector<double> getParameters() const { return parameters_; }
    5046  std::vector<bool> getParmasks() const { return parmasks_; }
    5147  std::vector<std::string> getFrameinfo() const { return frameinfo_; }
    5248
    5349private:
    54 
    5550  std::vector<std::string> functions_;
    5651  std::vector<int> components_;
    57   std::vector<float> parameters_;
    58   std::vector<float> errors_;
     52  std::vector<double> parameters_;
    5953  std::vector<bool> parmasks_;
    6054  std::vector<std::string> frameinfo_;
  • trunk/src/STFitter.cpp

    r1949 r1849  
    142142    if (ncomp < 1) throw (AipsError("Need at least one gaussian to fit."));
    143143    funcs_.resize(ncomp);
    144     funcnames_.clear();
    145     funccomponents_.clear();
    146144    for (Int k=0; k<ncomp; ++k) {
    147145      funcs_[k] = new Gaussian1D<Float>();
    148       funcnames_.push_back(expr);
    149       funccomponents_.push_back(3);
    150146    }
    151147  } else if (expr == "poly") {
    152148    funcs_.resize(1);
    153     funcnames_.clear();
    154     funccomponents_.clear();
    155149    funcs_[0] = new Polynomial<Float>(ncomp);
    156       funcnames_.push_back(expr);
    157       funccomponents_.push_back(ncomp);
    158150  } else if (expr == "lorentz") {
    159151    if (ncomp < 1) throw (AipsError("Need at least one lorentzian to fit."));
    160152    funcs_.resize(ncomp);
    161     funcnames_.clear();
    162     funccomponents_.clear();
    163153    for (Int k=0; k<ncomp; ++k) {
    164154      funcs_[k] = new Lorentzian1D<Float>();
    165       funcnames_.push_back(expr);
    166       funccomponents_.push_back(3);
    167155    }
    168156  } else {
     
    421409}
    422410
    423 STFitEntry Fitter::getFitEntry() const
    424 {
    425   STFitEntry fit;
    426   fit.setParameters(getParameters());
    427   fit.setErrors(getErrors());
    428   fit.setComponents(funccomponents_);
    429   fit.setFunctions(funcnames_);
    430   fit.setParmasks(getFixedParameters());
    431   return fit;
    432 }
  • trunk/src/STFitter.h

    r1949 r1849  
    4040#include <scimath/Functionals/CompoundFunction.h>
    4141
    42 #include "STFitEntry.h"
    43 
    4442namespace asap {
    4543
     
    7169
    7270  std::vector<float> evaluate(int whichComp) const;
    73 
    74   STFitEntry getFitEntry() const;
    75 
    7671private:
    7772  void clear();
     
    8075  casa::Vector<casa::Bool> m_;
    8176  casa::PtrBlock<casa::Function<casa::Float>* > funcs_;
    82   std::vector<std::string> funcnames_;
    83   std::vector<int> funccomponents_;
    84  
    8577  //Bool estimateSet_;
    8678  casa::Float chisquared_;
  • trunk/src/STMath.cpp

    r1949 r1849  
    17961796    out.push_back(outstat);
    17971797  }
    1798   return out;
    1799 }
    1800 
    1801 std::vector< float > STMath::statisticRow( const CountedPtr< Scantable > & in,
    1802                                         const std::vector< bool > & mask,
    1803                                         const std::string& which,
    1804                                         int row )
    1805 {
    1806 
    1807   Vector<Bool> m(mask);
    1808   const Table& tab = in->table();
    1809   ROArrayColumn<Float> specCol(tab, "SPECTRA");
    1810   ROArrayColumn<uChar> flagCol(tab, "FLAGTRA");
    1811   std::vector<float> out;
    1812 
    1813   Vector<Float> spec; specCol.get(row, spec);
    1814   Vector<uChar> flag; flagCol.get(row, flag);
    1815   MaskedArray<Float> ma  = maskedArray(spec, flag);
    1816   float outstat = 0.0;
    1817   if ( spec.nelements() == m.nelements() ) {
    1818     outstat = mathutil::statistics(which, ma(m));
    1819   } else {
    1820     outstat = mathutil::statistics(which, ma);
    1821   }
    1822   out.push_back(outstat);
    1823 
    18241798  return out;
    18251799}
  • trunk/src/STMath.h

    r1949 r1849  
    262262                                      const casa::CountedPtr<Scantable> &ref,
    263263                                      casa::Double choffset,
    264                                       casa::Double choffset2 = 0.0 );
     264                                      casa::Double choffset = 0.0 );
    265265
    266266  /**
     
    277277                               const std::vector<bool>& mask,
    278278                               const std::string& which);
    279 
    280   std::vector<float> statisticRow(const casa::CountedPtr<Scantable>& in,
    281                                const std::vector<bool>& mask,
    282                                const std::string& which,
    283                                int row);
    284279
    285280  std::vector< int > minMaxChan(const casa::CountedPtr<Scantable>& in,
  • trunk/src/STMathWrapper.h

    r1949 r1849  
    132132  { return STMath::statistic(in.getCP(), mask, which); }
    133133
    134   std::vector<float> statisticRow(const ScantableWrapper& in,
    135                                const std::vector<bool>& mask,
    136                                const std::string& which,
    137                                int row)
    138   { return STMath::statisticRow(in.getCP(), mask, which, row); }
    139 
    140134  std::vector<int> minMaxChan(const ScantableWrapper& in,
    141135                               const std::vector<bool>& mask,
  • trunk/src/STSelector.cpp

    r1949 r1849  
    270270}
    271271
    272 std::vector< int > asap::STSelector::getRows( ) const
    273 {
    274   return rowselection_ ;
    275 }
    276 
    277272std::string asap::STSelector::print( )
    278273{
  • trunk/src/STSelector.h

    r1949 r1849  
    5757  std::vector<int> getCycles() const;
    5858  std::vector<int> getTypes() const;
    59   std::vector<int> getRows() const;
    6059  std::vector<std::string> getPolTypes() const;
    6160  std::string getTaQL() const { return taql_; }
  • trunk/src/Scantable.cpp

    r1949 r1849  
    101101  fitTable_ = STFit(*this);
    102102  table_.rwKeywordSet().defineTable("FIT", fitTable_.table());
    103   table_.tableInfo().setType( "Scantable" ) ;
    104103  originalTable_ = table_;
    105104  attach();
     
    121120    table_ = tab;
    122121  }
    123   table_.tableInfo().setType( "Scantable" ) ;
    124122
    125123  attachSubtables();
     
    167165      table_.markForDelete();
    168166  }
    169   table_.tableInfo().setType( "Scantable" ) ;
    170167  /// @todo reindex SCANNO, recompute nbeam, nif, npol
    171168  if ( clear ) copySubtables(other);
     
    684681std::string Scantable::formatTime(const MEpoch& me, bool showdate) const
    685682{
    686   return formatTime(me, showdate, 0);
    687 }
    688 
    689 std::string Scantable::formatTime(const MEpoch& me, bool showdate, uInt prec) const
    690 {
    691683  MVTime mvt(me.getValue());
    692684  if (showdate)
    693     //mvt.setFormat(MVTime::YMD);
    694     mvt.setFormat(MVTime::YMD, prec);
     685    mvt.setFormat(MVTime::YMD);
    695686  else
    696     //mvt.setFormat(MVTime::TIME);
    697     mvt.setFormat(MVTime::TIME, prec);
     687    mvt.setFormat(MVTime::TIME);
    698688  ostringstream oss;
    699689  oss << mvt;
     
    10421032}
    10431033
    1044 // std::string Scantable::getTime(int whichrow, bool showdate) const
    1045 // {
    1046 //   MEpoch::ROScalarColumn timeCol(table_, "TIME");
    1047 //   MEpoch me;
    1048 //   if (whichrow > -1) {
    1049 //     me = timeCol(uInt(whichrow));
    1050 //   } else {
    1051 //     Double tm;
    1052 //     table_.keywordSet().get("UTC",tm);
    1053 //     me = MEpoch(MVEpoch(tm));
    1054 //   }
    1055 //   return formatTime(me, showdate);
    1056 // }
    1057 
    1058 std::string Scantable::getTime(int whichrow, bool showdate, uInt prec) const
    1059 {
     1034std::string Scantable::getTime(int whichrow, bool showdate) const
     1035{
     1036  MEpoch::ROScalarColumn timeCol(table_, "TIME");
    10601037  MEpoch me;
    1061   me = getEpoch(whichrow);
    1062   return formatTime(me, showdate, prec);
     1038  if (whichrow > -1) {
     1039    me = timeCol(uInt(whichrow));
     1040  } else {
     1041    Double tm;
     1042    table_.keywordSet().get("UTC",tm);
     1043    me = MEpoch(MVEpoch(tm));
     1044  }
     1045  return formatTime(me, showdate);
    10631046}
    10641047
     
    17261709}
    17271710
    1728 bool Scantable::getFlagtraFast(int whichrow)
    1729 {
    1730   uChar flag;
    1731   Vector<uChar> flags;
    1732   flagsCol_.get(uInt(whichrow), flags);
    1733   for (int i = 0; i < flags.size(); i++) {
    1734     if (i==0) {
    1735       flag = flags[i];
    1736     }
    1737     else {
    1738       flag &= flags[i];
    1739     }
    1740     return ((flag >> 7) == 1);
    1741    }
    1742 }
    1743 
    1744 void Scantable::doPolyBaseline(const std::vector<bool>& mask, int order, int rowno, Fitter& fitter)
    1745 {
    1746   fitter.setExpression("poly", order);
    1747 
    1748   std::vector<double> abcsd = getAbcissa(rowno);
    1749   std::vector<float> abcs;
    1750   for (int i = 0; i < abcsd.size(); i++) {
    1751     abcs.push_back((float)abcsd[i]);
    1752   }
    1753   std::vector<float> spec = getSpectrum(rowno);
    1754   std::vector<bool> fmask = getMask(rowno);
    1755   if (fmask.size() != mask.size()) {
    1756     throw(AipsError("different mask sizes"));
    1757   }
    1758   for (int i = 0; i < fmask.size(); i++) {
    1759     fmask[i] = fmask[i] && mask[i];
    1760   }
    1761   fitter.setData(abcs, spec, fmask);
    1762 
    1763   fitter.lfit();
    1764 }
    1765 
    1766 void Scantable::polyBaselineBatch(const std::vector<bool>& mask, int order)
    1767 {
    1768   Fitter fitter = Fitter();
    1769   for (uInt rowno=0; rowno < nrow(); ++rowno) {
    1770     doPolyBaseline(mask, order, rowno, fitter);
    1771     setSpectrum(fitter.getResidual(), rowno);
    1772   }
    1773 }
    1774 
    1775 STFitEntry Scantable::polyBaseline(const std::vector<bool>& mask, int order, int rowno)
    1776 {
    1777   Fitter fitter = Fitter();
    1778   doPolyBaseline(mask, order, rowno, fitter);
    1779   setSpectrum(fitter.getResidual(), rowno);
    1780   return fitter.getFitEntry();
    1781 }
    1782 
    17831711}
    17841712//namespace asap
  • trunk/src/Scantable.h

    r1949 r1849  
    1818// AIPS++
    1919#include <casa/aips.h>
    20 #include <casa/Containers/Record.h>
    2120#include <casa/Arrays/MaskedArray.h>
    2221#include <casa/BasicSL/String.h>
     
    4847#include "STFit.h"
    4948#include "STFitEntry.h"
    50 #include "STFitter.h"
    5149
    5250namespace asap {
     
    368366
    369367  std::string summary(bool verbose=false);
    370   //std::string getTime(int whichrow=-1, bool showdate=true) const;
    371   std::string getTime(int whichrow=-1, bool showdate=true, casa::uInt prec=0) const;
     368  std::string getTime(int whichrow=-1, bool showdate=true) const;
    372369  double getIntTime(int whichrow) const { return integrCol_(whichrow); }
    373370
     
    489486  void regridChannel( int nchan, double dnu, int irow ) ;
    490487
    491   bool getFlagtraFast(int whichrow);
    492 
    493   void polyBaselineBatch(const std::vector<bool>& mask, int order);
    494   STFitEntry polyBaseline(const std::vector<bool>& mask, int order, int rowno);
    495488
    496489private:
     
    506499
    507500  std::string formatTime(const casa::MEpoch& me, bool showdate)const;
    508   std::string formatTime(const casa::MEpoch& me, bool showdate, casa::uInt prec)const;
    509501
    510502  /**
     
    514506   */
    515507  std::string formatDirection(const casa::MDirection& md) const;
     508
    516509
    517510  /**
     
    605598                                                      const casa::String&,
    606599                                                      const casa::Array<T2>&);
    607 
    608   void doPolyBaseline(const std::vector<bool>& mask, int order, int rowno, Fitter& fitter);
    609600};
    610601
  • trunk/src/ScantableWrapper.h

    r1949 r1849  
    1919#include "MathUtils.h"
    2020#include "STFit.h"
    21 #include "STFitEntry.h"
    2221#include "Scantable.h"
    2322#include "STCoordinate.h"
     
    8483    { return table_->getTsys(whichrow); }
    8584
    86   //std::string getTime(int whichrow=0) const
    87   //  { return table_->getTime(whichrow); }
    88   std::string getTime(int whichrow=0, int prec = 0) const
    89     { return table_->getTime(whichrow, true, casa::uInt(prec)); }
     85  std::string getTime(int whichrow=0) const
     86    { return table_->getTime(whichrow); }
    9087
    9188  double getIntTime(int whichrow=0) const
     
    253250  { table_->reshapeSpectrum( nmin, nmax ); }
    254251
    255   STFitEntry polyBaseline(const std::vector<bool>& mask, int order, int rowno)
    256   { return table_->polyBaseline(mask, order, rowno); }
    257 
    258   void polyBaselineBatch(const std::vector<bool>& mask, int order)
    259   { table_->polyBaselineBatch(mask, order); }
    260 
    261   bool getFlagtraFast(int whichrow=0) const
    262     { return table_->getFlagtraFast(whichrow); }
    263 
    264 
    265252private:
    266253  casa::CountedPtr<Scantable> table_;
  • trunk/src/python_LogSink.cpp

    r1949 r1849  
    4141        .def( init <> () )
    4242        .def("post", &AsapLogSink::postMessage,
    43          (boost::python::arg("priority")="INFO",
    44          boost::python::arg("origin")=""))
     43         (boost::python::arg("location")="",
     44         boost::python::arg("priority")="INFO"))
    4545        .def("pop", &AsapLogSink::popMessages)
    4646      ;
  • trunk/src/python_STFitEntry.cpp

    r1949 r1849  
    4444        .def("getfixedparameters", &STFitEntry::getParmasks)
    4545        .def("getparameters", &STFitEntry::getParameters)
    46         .def("geterrors", &STFitEntry::getErrors)
    4746        .def("getfunctions", &STFitEntry::getFunctions)
    4847        .def("getcomponents", &STFitEntry::getComponents)
     
    5049        .def("setfixedparameters", &STFitEntry::setParmasks)
    5150        .def("setparameters", &STFitEntry::setParameters)
    52         .def("seterrors", &STFitEntry::setErrors)
    5351        .def("setfunctions", &STFitEntry::setFunctions)
    5452        .def("setcomponents", &STFitEntry::setComponents)
  • trunk/src/python_STMath.cpp

    r1949 r1849  
    5959        .def("_dofs", &STMathWrapper::dofs)
    6060        .def("_stats", &STMathWrapper::statistic)
    61         .def("_statsrow", &STMathWrapper::statisticRow)
    6261        .def("_minmaxchan", &STMathWrapper::minMaxChan)
    6362        .def("_freqswitch", &STMathWrapper::freqSwitch)
  • trunk/src/python_STSelector.cpp

    r1949 r1849  
    3030        .def("_getcycles", &STSelector::getCycles)
    3131        .def("_gettypes", &STSelector::getTypes)
    32         .def("_getrows", &STSelector::getRows)
    3332        .def("_gettaql", &STSelector::getTaQL)
    3433        .def("_getorder", &STSelector::getSortOrder)
  • trunk/src/python_Scantable.cpp

    r1949 r1849  
    9999    .def("_getparangle", &ScantableWrapper::getParAngle,
    100100         (boost::python::arg("whichrow")=0) )
    101     //.def("_gettime", &ScantableWrapper::getTime,
    102     //     (boost::python::arg("whichrow")=0) )
    103101    .def("_gettime", &ScantableWrapper::getTime,
    104          (boost::python::arg("whichrow")=0,
    105           boost::python::arg("prec")=0) )
     102         (boost::python::arg("whichrow")=0) )
    106103    .def("_getinttime", &ScantableWrapper::getIntTime,
    107104         (boost::python::arg("whichrow")=0) )
     
    142139         (boost::python::arg("nmin")=-1,
    143140          boost::python::arg("nmax")=-1) )
    144     .def("_poly_baseline", &ScantableWrapper::polyBaseline)
    145     .def("_poly_baseline_batch", &ScantableWrapper::polyBaselineBatch)
    146     .def("_getflagtrafast", &ScantableWrapper::getFlagtraFast,
    147          (boost::python::arg("whichrow")=0) )
    148141  ;
    149142};
  • trunk/src/python_asap.cpp

    r1949 r1849  
    4444  #include <pyrap/Converters/PycExcp.h>
    4545  #include <pyrap/Converters/PycBasicData.h>
    46   #include <pyrap/Converters/PycValueHolder.h>
    47   #include <pyrap/Converters/PycRecord.h>
    4846#endif
    4947
     
    110108  casa::pyrap::register_convert_basicdata();
    111109  casa::pyrap::register_convert_std_vector<asap::ScantableWrapper>();
    112   casa::pyrap::register_convert_std_vector<int>();
    113   casa::pyrap::register_convert_std_vector<uint>();
    114   casa::pyrap::register_convert_std_vector<float>();
    115   casa::pyrap::register_convert_std_vector<double>();
    116   casa::pyrap::register_convert_std_vector<std::string>();
    117   casa::pyrap::register_convert_std_vector<bool>();
    118   casa::pyrap::register_convert_casa_valueholder();
    119   casa::pyrap::register_convert_casa_record();
    120110#endif
    121111}
  • trunk/test/test_scantable.py

    r1949 r1849  
    33import shutil
    44import datetime
    5 from nose.tools import *
    65from asap import scantable, selector, mask_not
    76from asap.logging import asaplog
    8 # no need for log messages
    97asaplog.disable()
     8
     9from nose.tools import *
    1010
    1111def tempdir_setup():
     
    7272        sel.set_polarisations("YY")
    7373        self.st.set_selection(sel)
    74         assert_equal(self.st.getpolnos(), [1])
     74        assert_equal(self.st.getpolnos(), (1,))
    7575        sel1 = self.st.get_selection()
    7676        assert_equal(sel1.get_pols(), [1])
    7777        self.st.set_selection(pols="XX")
    78         assert_equal(self.st.getpolnos(), [0])
     78        assert_equal(self.st.getpolnos(), (0,))
    7979
    8080
     
    165165    def test_drop_scan(self):
    166166        s0 = self.st.drop_scan(1)
    167         assert_equal(s0.getscannos(), [0])
     167        assert_equal(s0.getscannos(), (0,))
    168168        s1 = self.st.drop_scan([0])
    169         assert_equal(s1.getscannos(), [1])
     169        assert_equal(s1.getscannos(), (1,))
    170170
    171171    def test_flag(self):
     
    206206            for spec in ds:
    207207                assert_almost_equals(sum(spec)/len(spec), 0.0, 5)
    208 
    209     def test_auto_poly_baseline(self):
    210         q = self.st.auto_quotient()
    211         b = q.auto_poly_baseline(insitu=False)
    212         res_rms = (q-b).stats('rms')
    213         assert_almost_equals(res_rms[0], 0.38370, 5)
    214         assert_almost_equals(res_rms[1], 0.38780, 5)       
    215        
    216 
    217     def test_poly_baseline(self):
    218         q = self.st.auto_quotient()
    219         msk = q.create_mask([0.0, 1471.0], [1745.0, 4095.0])
    220         b = q.poly_baseline(order=0, mask=msk,insitu=False)
    221         res_rms = (q-b).stats('rms')
    222         assert_almost_equals(res_rms[0], 0.38346, 5)
    223         assert_almost_equals(res_rms[1], 0.38780, 5)       
Note: See TracChangeset for help on using the changeset viewer.