Changes in / [2373:2473]


Ignore:
Files:
9 added
59 edited

Legend:

Unmodified
Added
Removed
  • /branches/hpc33/CMakeLists.txt

    r2373 r2473  
    8686if( APPLE )
    8787   set( SO dylib )
    88    if( CMAKE_SYSTEM MATCHES ^Darwin-10 )
     88   if( CMAKE_SYSTEM MATCHES ^Darwin-10 OR
     89                CMAKE_SYSTEM MATCHES ^Darwin-11 )
    8990      if( NOT archflag )
    90          if( EXISTS /opt/casa/darwin10-64b )
     91         if( EXISTS /opt/casa/darwin11 )
     92            set( archflag x86_64 )
     93         elseif( EXISTS /opt/casa/darwin10-64b )
    9194            set( archflag x86_64 )
    9295         elseif( EXISTS /opt/casa/core2-apple-darwin10 )
     
    264267      -DPYVERSION=${PV} )
    265268else()
     269   # with CASA
    266270   if( NOT PYTHON_FOUND )
    267271      if ( NOT PYTHON_LIBNAME )
    268          set( _names 2.9 2.8 2.7 2.6 2.5.2 2.5 )
     272         #set( _names 2.9 2.8 2.7 2.6 2.5.2 2.5 )
     273         set( _names 2.6 2.5.2 2.5 )
     274         # OSX 10.7 has Python2.7 by default. CASA has't yet supported python > 2.6 anyway.
    269275         # (The library named libpython.2.5.2.dylib seems to exist only in the CASA world.)
    270276      else()
     
    276282
    277283         casa_find(
    278             PYTHON${_v}
     284            PYTHON${_v}
     285            #PREFIX_HINTS ${PYTHON_ROOT_DIR}
    279286            LIBS python${_v}
    280287            NO_REQUIRE
     
    312319      # Python library was not in a lib(64) directory!
    313320      message( WARNING "Python library path \"${PYTHON${PYTHON_LIBNAME}_LIBRARIES}\" does not contain \"/lib(64)/lib${python_library}\"" )
     321      set( python_prefix ${casa_packages} )
     322   endif()
     323
     324   #
     325   # For some unknown reason cmake sets the /usr for Lion
     326   #
     327   if( APPLE )
    314328      set( python_prefix ${casa_packages} )
    315329   endif()
  • /branches/hpc33/cmake/withcasa.cmake

    r2373 r2473  
    66# environment dependent settings
    77if( APPLE )
    8    if( NOT arch )
    9       set( arch darwin )
    10    endif()
    11    if( CMAKE_SYSTEM MATCHES ^Darwin-10 )
     8   if( CMAKE_SYSTEM MATCHES ^Darwin-10 OR
     9                CMAKE_SYSTEM MATCHES ^Darwin-11 )
     10      if ( NOT arch )
     11         set( arch darwin64 )
     12      endif()
    1213      if( NOT archflag )
    13          if( EXISTS /opt/casa/darwin10-64b )
     14         if( EXISTS /opt/casa/darwin11 )
     15            set( archflag x86_64 )
     16         elseif( EXISTS /opt/casa/darwin10-64b )
    1417            set( archflag x86_64 )
    1518         elseif( EXISTS /opt/casa/core2-apple-darwin10 )
     
    2023      endif()
    2124      if( archflag STREQUAL x86_64 )
    22          set( casa_packages /opt/casa/darwin10-64b )
     25         if( CMAKE_SYSTEM MATCHES ^Darwin-11 )
     26             set( casa_packages /opt/casa/darwin11 )
     27         else()
     28             set( casa_packages /opt/casa/darwin10-64b )
     29         endif()
    2330      else()
    2431         set( casa_packages /opt/casa/core2-apple-darwin10 )
    2532      endif()
    2633   elseif( CMAKE_SYSTEM MATCHES ^Darwin-9 )
     34      if ( NOT arch )
     35         set( arch darwin )
     36      endif()
    2737      set( casa_packages /opt/casa/core2-apple-darwin8/3rd-party )
    2838   endif()         
  • /branches/hpc33/external-alma/asdm2ASAP/ASDMFiller.cc

    r2373 r2473  
    134134        //unsigned int scanno = reader_->getScanNo() ;
    135135        unsigned int scanno = reader_->getScanNoOfCurrentRow() ;
     136        //logsink_->postLocally( LogMessage("scanno = "+String::toString(scanno),LogOrigin(className_,funcName,WHERE)) ) ;
    136137        //uInt subscanno = reader_->getSubscanNo() ;
    137138        citer = cycleno.find( scanno ) ;
     
    152153        string freqref = "" ;
    153154
     155        //logsink_->postLocally( LogMessage("numData = "+String::toString(numData),LogOrigin(className_,funcName,WHERE)) ) ;
    154156        for ( unsigned int idata = 0 ; idata < numData ; idata++ ) {
    155157          // prepare to extract binary data
     158          //logsink_->postLocally( LogMessage("prepare data...",LogOrigin(className_,funcName,WHERE)) ) ;
    156159          reader_->prepareData( idata ) ;
    157160
     
    159162          //unsigned int subscanno = reader_->getSubscanNo( idata ) ;
    160163          unsigned int subscanno = reader_->getSubscanNo() ;
     164          //logsink_->postLocally( LogMessage("subscanno = "+String::toString(subscanno),LogOrigin(className_,funcName,WHERE)) ) ;
    161165
    162166          // IFNO
    163167          //uInt ifno = reader_->getIFNo( idata ) ;
    164168          uInt ifno = reader_->getIFNo() ;
    165 
     169          //logsink_->postLocally( LogMessage("ifno = "+String::toString(ifno),LogOrigin(className_,funcName,WHERE)) ) ;
    166170          // source spec
    167171          int srctype = reader_->getSrcType( scanno, subscanno ) ;
     172          //logsink_->postLocally( LogMessage("srctype = "+String::toString(srctype),LogOrigin(className_,funcName,WHERE)) ) ;
    168173          string srcname ;
    169174          string fieldname ;
     
    185190                                      sysVel,
    186191                                      rf ) ;
    187          
     192          //logsink_->postLocally( LogMessage("srcname = "+String::toString(srcname),LogOrigin(className_,funcName,WHERE)) ) ;         
     193
    188194          // fill MOLECULE_ID and add MOLECULES row if necessary
    189195          Vector<casa::Double> restFreqs( rf.size() ) ;
     
    197203          casa::Double mjd = (casa::Double)(reader_->getTime()) ;
    198204          casa::Double interval = (casa::Double)(reader_->getInterval()) ;
     205          //logsink_->postLocally( LogMessage("mjd = "+String::toString(mjd),LogOrigin(className_,funcName,WHERE)) ) ;
    199206
    200207          // fill TIME and INTERVAL
     
    214221          unsigned int flagrow = reader_->getFlagRow() ;
    215222          setFlagrow( (uInt)flagrow ) ;
    216 
     223          //logsink_->postLocally( LogMessage("flagrow = "+String::toString(flagrow),LogOrigin(className_,funcName,WHERE)) ) ;
    217224          // fill WEATHER_ID and add WEATHER row if necessary
    218225          float temperature ;
     
    237244                       (casa::Float)windspeed,
    238245                       (casa::Float)windaz ) ;
    239 
     246          //logsink_->postLocally( LogMessage("temperature = "+String::toString(temperature),LogOrigin(className_,funcName,WHERE)) ) ;
    240247          // fill AZIMUTH, ELEVATION, DIRECTION and SCANRATE
    241248          vector<double> dir ;
     
    302309//               oss << dataShape[i] << ", " ;
    303310//           }
    304           //logsink_->postLocally( LogMessage(oss.str(),LogOrigin(className_,funcName,WHERE)) ) ;
     311//           logsink_->postLocally( LogMessage(oss.str(),LogOrigin(className_,funcName,WHERE)) ) ;
    305312                                     
    306313          //int numPol = reader_->getNumPol( idata ) ;
     
    317324          // SPECTRA, FLAGTRA, TSYS, TCAL
    318325          //float *sp = reader_->getSpectrum( idata ) ;
     326          //logsink_->postLocally( LogMessage("getting spectra...",LogOrigin(className_,funcName,WHERE)) ) ;
    319327          float *sp = reader_->getSpectrum() ;
     328          //logsink_->postLocally( LogMessage("sp[0] = "+String::toString(sp[0]),LogOrigin(className_,funcName,WHERE)) ) ;
    320329          vector< vector<float> > ts ;
    321330          vector< vector<float> > tc ;
     
    323332          reader_->getTcalAndTsys( tc, ts ) ;
    324333          Matrix<casa::Float> spectra = toMatrix( sp, numPol, numChan ) ;
     334          //logsink_->postLocally( LogMessage("spectra(0,0) = "+String::toString(spectra(0,0)),LogOrigin(className_,funcName,WHERE)) ) ;
    325335          Vector<uChar> flagtra( numChan, 0 ) ;
    326336          Matrix<casa::Float> tsys = toMatrix( ts, numPol, numChan ) ;
    327337          Matrix<casa::Float> tcal = toMatrix( tc, numPol, numChan ) ;
     338          //logsink_->postLocally( LogMessage("tsys(0,0) = "+String::toString(tsys(0,0)),LogOrigin(className_,funcName,WHERE)) ) ;
    328339//           String caltime = "" ;
    329340//           if ( anyNE( tcal, (casa::Float)1.0 ) )
  • /branches/hpc33/external-alma/asdm2ASAP/ASDMReader.cc

    r2373 r2473  
    850850                                    vector<double> &restfreq )
    851851{
     852  String funcName = "getSourceProperty" ;
    852853  ostringstream oss ;
    853854  oss << fieldRow_p->getFieldName() << "__" << vmsData_->v_fieldId[dataIndex_] ;
    854855  fieldname = oss.str() ;
     856  SourceRow *srow = 0 ;
    855857  if ( fieldRow_p->isSourceIdExists() ) {
    856858    int sourceId = fieldRow_p->getSourceId() ;
    857     SourceRow *srow = asdm_->getSource().getRowByKey( sourceId, timeInterval_, specWinTag_ ) ;
     859    srow = asdm_->getSource().getRowByKey( sourceId, timeInterval_, specWinTag_ ) ;
     860  }
     861  if ( srow != 0 ) {
     862    //logsink_->postLocally( LogMessage("timeInterval_="+String::toString(timeInterval_.getStart().getMJD()),LogOrigin(className_,funcName,WHERE)) ) ;
     863    //logsink_->postLocally( LogMessage("specWinTag_="+String::toString(specWinTag_.toString()),LogOrigin(className_,funcName,WHERE)) ) ;
     864    //SourceRow *srow = asdm_->getSource().getRowByKey( sourceId, timeInterval_, specWinTag_ ) ;
     865    //logsink_->postLocally( LogMessage("sourceId="+String::toString(sourceId),LogOrigin(className_,funcName,WHERE)) ) ;
     866    //if ( srow == 0 )
     867    //logsink_->postLocally( LogMessage("nullpo",LogOrigin(className_,funcName,WHERE)) ) ;
    858868
    859869    // source name
    860870    srcname = srow->getSourceName() ;
     871    //logsink_->postLocally( LogMessage("srcname="+String::toString(srcname),LogOrigin(className_,funcName,WHERE)) ) ;
    861872
    862873    // source direction
     
    865876    srcdir[0] = limitedAngle( srcdirA[0].get() ) ;
    866877    srcdir[1] = limitedAngle( srcdirA[1].get() ) ;
     878    //logsink_->postLocally( LogMessage("srcdir=["+String::toString(srcdir[0])+","+String::toString(srcdir[1])+"]",LogOrigin(className_,funcName,WHERE)) ) ;
    867879    if ( srow->isDirectionCodeExists() ) {
    868880      DirectionReferenceCodeMod::DirectionReferenceCode dircode = srow->getDirectionCode() ;
     
    881893    srcpm[0] = srcpmA[0].get() ;
    882894    srcpm[1] = srcpmA[1].get() ;
    883 
     895    //logsink_->postLocally( LogMessage("srcpm=["+String::toString(srcpm[0])+","+String::toString(srcpm[1])+"]",LogOrigin(className_,funcName,WHERE)) ) ;
    884896    // systemic velocity
    885897    if ( srow->isSysVelExists() ) {
     
    891903      sysvel = 0.0 ;
    892904    }
    893 
     905    //logsink_->postLocally( LogMessage("sysvel="+String::toString(sysvel),LogOrigin(className_,funcName,WHERE)) ) ;
    894906    // rest frequency
    895907    if ( srow->isRestFrequencyExists() ) {
     
    903915      restfreq.resize( 0 ) ;
    904916    }
     917    //logsink_->postLocally( LogMessage("restfreq.size()="+String::toString(restfreq.size()),LogOrigin(className_,funcName,WHERE)) ) ;
    905918  }
    906919  else {
     
    11751188  vector< vector<float> > defaultT( 1, vector<float>( 1, 1.0 ) ) ;
    11761189  SysCalRow *scrow = getSysCalRow() ;
     1190  //logsink_->postLocally( LogMessage("scrow = "+String::toString((long)scrow),LogOrigin(className_,funcName,WHERE)) ) ;
    11771191  if ( scrow == 0 ) {
    11781192    tcal = defaultT ;
     
    11841198      unsigned int numReceptor = tsysSpec.size() ;
    11851199      unsigned int numChan = tsysSpec[0].size() ;
     1200      //logsink_->postLocally( LogMessage("TSYS: numReceptor = "+String::toString(numReceptor),LogOrigin(className_,funcName,WHERE)) ) ;
     1201      //logsink_->postLocally( LogMessage("TSYS:numChan = "+String::toString(numChan),LogOrigin(className_,funcName,WHERE)) ) ;
    11861202      tsys.resize( numReceptor ) ;
    11871203      for ( unsigned int ir = 0 ; ir < numReceptor ; ir++ ) {
     
    11991215      unsigned int numReceptor = tcalSpec.size() ;
    12001216      unsigned int numChan = tcalSpec[0].size() ;
     1217      //logsink_->postLocally( LogMessage("TCAL: numReceptor = "+String::toString(numReceptor),LogOrigin(className_,funcName,WHERE)) ) ;
     1218      //logsink_->postLocally( LogMessage("TCAL: numChan = "+String::toString(numChan),LogOrigin(className_,funcName,WHERE)) ) ;
    12011219      tcal.resize( numReceptor ) ;
    12021220      for ( unsigned int ir = 0 ; ir < numReceptor ; ir++ ) {
    1203         tcal[ir].resize( numReceptor ) ;
     1221        tcal[ir].resize( numChan ) ;
    12041222        for ( unsigned int ic = 0 ; ic < numChan ; ic++ ) {
    12051223          tcal[ir][ic] = tcalSpec[ir][ic].get() ;
  • /branches/hpc33/external-alma/oldasdm2ASAP/OldASDMReader.cc

    r2373 r2473  
    12011201      tcal.resize( numReceptor ) ;
    12021202      for ( unsigned int ir = 0 ; ir < numReceptor ; ir++ ) {
    1203         tcal[ir].resize( numReceptor ) ;
     1203        tcal[ir].resize( numChan ) ;
    12041204        for ( unsigned int ic = 0 ; ic < numChan ; ic++ ) {
    12051205          tcal[ir][ic] = tcalSpec[ir][ic].get() ;
  • /branches/hpc33/python/CMakeLists.txt

    r2373 r2473  
    3838     ${PYTHONDIR}/simplelinefinder.py
    3939     ${PYTHONDIR}/utils.py
     40     ${PYTHONDIR}/asapgrid.py
    4041     ${PYTHONDIR}/svninfo.txt )
    4142
  • /branches/hpc33/python/__init__.py

    r2373 r2473  
    5252from opacity import skydip
    5353from opacity import model as opacity_model
     54from asapgrid import asapgrid
    5455from _asap import srctype
    5556
  • /branches/hpc33/python/asapmath.py

    r2373 r2473  
    988988    tb.open(tablename=filename,nomodify=True)
    989989    ant1=tb.getcol('ANTENNA1',0,-1,1)
    990     anttab=tb.getkeyword('ANTENNA').split()[-1]
     990    #anttab=tb.getkeyword('ANTENNA').split()[-1]
     991    anttab=tb.getkeyword('ANTENNA').lstrip('Table: ')
    991992    tb.close()
    992993    #tb.open(tablename=filename+'/ANTENNA',nomodify=True)
  • /branches/hpc33/src/CMakeLists.txt

    r2373 r2473  
    2121# source files for libpyrap
    2222set( ASAP_SRCS
     23     ${SRCDIR}/concurrent.cpp
    2324     ${SRCDIR}/MathUtils.cpp
    2425     ${SRCDIR}/TableTraverse.cpp
     
    5859     ${SRCDIR}/AsapLogSink.cpp
    5960     ${SRCDIR}/STUpgrade.cpp
     61     ${SRCDIR}/STGrid.cpp
    6062     ${SRCDIR}/Templates.cpp )
    6163
     
    7880     ${SRCDIR}/python_MSWriter.cpp
    7981     ${SRCDIR}/python_LogSink.cpp
     82     ${SRCDIR}/python_STGrid.cpp
    8083     ${SRCDIR}/python_asap.cpp )
    8184
     
    100103install( TARGETS ${ASAPLIB}
    101104         LIBRARY DESTINATION ${PYTHON_INSTALL_DIR} )
     105if( NOT STANDALONE )
     106  execute_process(
     107    COMMAND ln -Fs ../${PYTHON_INSTALL_DIR}/_${ASAPLIB}.so ${CMAKE_INSTALL_PREFIX}/lib/_${ASAPLIB}.so
     108    OUTPUT_VARIABLE stuff)
     109endif()
  • /branches/hpc33/src/STFitter.cpp

    r2373 r2473  
    118118    g = dynamic_cast<Gaussian1D<Float>* >(funcs_[i]);
    119119    if (g) {
    120       (*g)[0] = listGauss[i].getAmpl();
    121       (*g)[1] = listGauss[i].getCenter();
    122       (*g)[2] = listGauss[i].getFWHM();
     120      const GaussianSpectralElement *gauss = dynamic_cast<const GaussianSpectralElement *>(listGauss[i]) ;
     121      (*g)[0] = gauss->getAmpl();
     122      (*g)[1] = gauss->getCenter();
     123      (*g)[2] = gauss->getFWHM();
     124//       (*g)[0] = listGauss[i].getAmpl();
     125//       (*g)[1] = listGauss[i].getCenter();
     126//       (*g)[2] = listGauss[i].getFWHM();
    123127    }
    124128  }
  • /branches/hpc33/src/STMath.cpp

    r2373 r2473  
    5353#include "STMath.h"
    5454#include "STSelector.h"
     55#include "Accelerator.h"
    5556
    5657using namespace casa;
    5758using namespace asap;
    5859
     60
     61// 2012/02/17 TN
     62// Since STGrid is implemented, average doesn't consider direction
     63// when accumulating
    5964// tolerance for direction comparison (rad)
    60 #define TOL_OTF    1.0e-15
    61 #define TOL_POINT  2.9088821e-4  // 1 arcmin
     65// #define TOL_OTF    1.0e-15
     66// #define TOL_POINT  2.9088821e-4  // 1 arcmin
    6267
    6368STMath::STMath(bool insitu) :
     
    8388  WeightType wtype = stringToWeight(weight);
    8489
     90  // 2012/02/17 TN
     91  // Since STGrid is implemented, average doesn't consider direction
     92  // when accumulating
    8593  // check if OTF observation
    86   String obstype = in[0]->getHeader().obstype ;
    87   Double tol = 0.0 ;
    88   if ( (obstype.find( "OTF" ) != String::npos) || (obstype.find( "OBSERVE_TARGET" ) != String::npos) ) {
    89     tol = TOL_OTF ;
    90   }
    91   else {
    92     tol = TOL_POINT ;
    93   }
     94//   String obstype = in[0]->getHeader().obstype ;
     95//   Double tol = 0.0 ;
     96//   if ( (obstype.find( "OTF" ) != String::npos) || (obstype.find( "OBSERVE_TARGET" ) != String::npos) ) {
     97//     tol = TOL_OTF ;
     98//   }
     99//   else {
     100//     tol = TOL_POINT ;
     101//   }
    94102
    95103  // output
     
    142150  while (!iter.pastEnd()) {
    143151    Table subt = iter.table();
    144 //     // copy the first row of this selection into the new table
    145 //     tout.addRow();
    146 //     TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
    147 //     // re-index to 0
    148 //     if ( avmode != "SCAN" && avmode != "SOURCE" ) {
    149 //       scanColOut.put(outrowCount, uInt(0));
     152    // copy the first row of this selection into the new table
     153    tout.addRow();
     154    TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
     155    // re-index to 0
     156    if ( avmode != "SCAN" && avmode != "SOURCE" ) {
     157      scanColOut.put(outrowCount, uInt(0));
     158    }
     159    ++outrowCount;
     160    // 2012/02/17 TN
     161    // Since STGrid is implemented, average doesn't consider direction
     162    // when accumulating
     163//     MDirection::ScalarColumn dircol ;
     164//     dircol.attach( subt, "DIRECTION" ) ;
     165//     Int length = subt.nrow() ;
     166//     vector< Vector<Double> > dirs ;
     167//     vector<int> indexes ;
     168//     for ( Int i = 0 ; i < length ; i++ ) {
     169//       Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ;
     170//       //os << << count++ << ": " ;
     171//       //os << "[" << t[0] << "," << t[1] << "]" << LogIO::POST ;
     172//       bool adddir = true ;
     173//       for ( uInt j = 0 ; j < dirs.size() ; j++ ) {
     174//         //if ( allTrue( t == dirs[j] ) ) {
     175//         Double dx = t[0] - dirs[j][0] ;
     176//         Double dy = t[1] - dirs[j][1] ;
     177//         Double dd = sqrt( dx * dx + dy * dy ) ;
     178//         //if ( allNearAbs( t, dirs[j], tol ) ) {
     179//         if ( dd <= tol ) {
     180//           adddir = false ;
     181//           break ;
     182//         }
     183//       }
     184//       if ( adddir ) {
     185//         dirs.push_back( t ) ;
     186//         indexes.push_back( i ) ;
     187//       }
    150188//     }
    151 //     ++outrowCount;
    152     MDirection::ScalarColumn dircol ;
    153     dircol.attach( subt, "DIRECTION" ) ;
    154     Int length = subt.nrow() ;
    155     vector< Vector<Double> > dirs ;
    156     vector<int> indexes ;
    157     for ( Int i = 0 ; i < length ; i++ ) {
    158       Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ;
    159       //os << << count++ << ": " ;
    160       //os << "[" << t[0] << "," << t[1] << "]" << LogIO::POST ;
    161       bool adddir = true ;
    162       for ( uInt j = 0 ; j < dirs.size() ; j++ ) {
    163         //if ( allTrue( t == dirs[j] ) ) {
    164         Double dx = t[0] - dirs[j][0] ;
    165         Double dy = t[1] - dirs[j][1] ;
    166         Double dd = sqrt( dx * dx + dy * dy ) ;
    167         //if ( allNearAbs( t, dirs[j], tol ) ) {
    168         if ( dd <= tol ) {
    169           adddir = false ;
    170           break ;
    171         }
    172       }
    173       if ( adddir ) {
    174         dirs.push_back( t ) ;
    175         indexes.push_back( i ) ;
    176       }
    177     }
    178     uInt rowNum = dirs.size() ;
    179     tout.addRow( rowNum ) ;
    180     for ( uInt i = 0 ; i < rowNum ; i++ ) {
    181       TableCopy::copyRows( tout, subt, outrowCount+i, indexes[i], 1 ) ;
    182       // re-index to 0
    183       if ( avmode != "SCAN" && avmode != "SOURCE" ) {
    184         scanColOut.put(outrowCount+i, uInt(0));
    185       }       
    186     }
    187     outrowCount += rowNum ;
     189//     uInt rowNum = dirs.size() ;
     190//     tout.addRow( rowNum ) ;
     191//     for ( uInt i = 0 ; i < rowNum ; i++ ) {
     192//       TableCopy::copyRows( tout, subt, outrowCount+i, indexes[i], 1 ) ;
     193//       // re-index to 0
     194//       if ( avmode != "SCAN" && avmode != "SOURCE" ) {
     195//         scanColOut.put(outrowCount+i, uInt(0));
     196//       }       
     197//     }
     198//     outrowCount += rowNum ;
    188199    ++iter;
    189200  }
     
    205216      ROScalarColumn<Double> tmp(tin, "TIME");
    206217      Double td;tmp.get(0,td);
     218
     219#if 1
     220      static char const*const colNames1[] = { "IFNO", "BEAMNO", "POLNO" };
     221      uInt const values1[] = { rec.asuInt("IFNO"), rec.asuInt("BEAMNO"), rec.asuInt("POLNO") };
     222      SingleTypeEqPredicate<uInt, 3> myPred(tin, colNames1, values1);
     223      CustomTableExprNodeRep myNodeRep(tin, myPred);
     224      myNodeRep.link(); // to avoid automatic delete when myExpr is destructed.
     225      CustomTableExprNode myExpr(myNodeRep);
     226      Table basesubt = tin(myExpr);
     227#else
    207228      Table basesubt = tin( tin.col("BEAMNO") == Int(rec.asuInt("BEAMNO"))
    208229                         && tin.col("IFNO") == Int(rec.asuInt("IFNO"))
    209230                         && tin.col("POLNO") == Int(rec.asuInt("POLNO")) );
     231#endif
    210232      Table subt;
    211233      if ( avmode == "SOURCE") {
     
    218240      }
    219241
    220       vector<uInt> removeRows ;
    221       uInt nrsubt = subt.nrow() ;
    222       for ( uInt irow = 0 ; irow < nrsubt ; irow++ ) {
    223         //if ( !allTrue((subt.col("DIRECTION").getArrayDouble(TableExprId(irow)))==rec.asArrayDouble("DIRECTION")) ) {
    224         Vector<Double> x0 = (subt.col("DIRECTION").getArrayDouble(TableExprId(irow))) ;
    225         Vector<Double> x1 = rec.asArrayDouble("DIRECTION") ;
    226         double dx = x0[0] - x1[0];
    227         double dy = x0[1] - x1[1];
    228         Double dd = sqrt( dx * dx + dy * dy ) ;
    229         //if ( !allNearAbs((subt.col("DIRECTION").getArrayDouble(TableExprId(irow))), rec.asArrayDouble("DIRECTION"), tol ) ) {
    230         if ( dd > tol ) {
    231           removeRows.push_back( irow ) ;
    232         }
    233       }
    234       if ( removeRows.size() != 0 ) {
    235         subt.removeRow( removeRows ) ;
    236       }
     242      // 2012/02/17 TN
     243      // Since STGrid is implemented, average doesn't consider direction
     244      // when accumulating
     245//       vector<uInt> removeRows ;
     246//       uInt nrsubt = subt.nrow() ;
     247//       for ( uInt irow = 0 ; irow < nrsubt ; irow++ ) {
     248//         //if ( !allTrue((subt.col("DIRECTION").getArrayDouble(TableExprId(irow)))==rec.asArrayDouble("DIRECTION")) ) {
     249//         Vector<Double> x0 = (subt.col("DIRECTION").getArrayDouble(TableExprId(irow))) ;
     250//         Vector<Double> x1 = rec.asArrayDouble("DIRECTION") ;
     251//         double dx = x0[0] - x1[0];
     252//         double dy = x0[1] - x1[1];
     253//         Double dd = sqrt( dx * dx + dy * dy ) ;
     254//         //if ( !allNearAbs((subt.col("DIRECTION").getArrayDouble(TableExprId(irow))), rec.asArrayDouble("DIRECTION"), tol ) ) {
     255//         if ( dd > tol ) {
     256//           removeRows.push_back( irow ) ;
     257//         }
     258//       }
     259//       if ( removeRows.size() != 0 ) {
     260//         subt.removeRow( removeRows ) ;
     261//       }
    237262     
    238       if ( nrsubt == removeRows.size() )
    239         throw(AipsError("Averaging data is empty.")) ;
     263//       if ( nrsubt == removeRows.size() )
     264//         throw(AipsError("Averaging data is empty.")) ;
    240265
    241266      specCol.attach(subt,"SPECTRA");
     
    321346{
    322347  (void) mode; // currently unused
     348  // 2012/02/17 TN
     349  // Since STGrid is implemented, average doesn't consider direction
     350  // when accumulating
    323351  // check if OTF observation
    324   String obstype = in->getHeader().obstype ;
    325   Double tol = 0.0 ;
    326   if ( obstype.find( "OTF" ) != String::npos ) {
    327     tol = TOL_OTF ;
    328   }
    329   else {
    330     tol = TOL_POINT ;
    331   }
     352//   String obstype = in->getHeader().obstype ;
     353//   Double tol = 0.0 ;
     354//   if ( obstype.find( "OTF" ) != String::npos ) {
     355//     tol = TOL_OTF ;
     356//   }
     357//   else {
     358//     tol = TOL_POINT ;
     359//   }
    332360
    333361  // clone as this is non insitu
     
    362390    flagCol.attach(subt,"FLAGTRA");
    363391    tsysCol.attach(subt,"TSYS");
    364 //     tout.addRow();
    365 //     TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
    366 //     if ( avmode != "SCAN") {
    367 //       scanColOut.put(outrowCount, uInt(0));
     392
     393    tout.addRow();
     394    TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
     395    if ( avmode != "SCAN") {
     396      scanColOut.put(outrowCount, uInt(0));
     397    }
     398    Vector<Float> tmp;
     399    specCol.get(0, tmp);
     400    uInt nchan = tmp.nelements();
     401    // have to do channel by channel here as MaskedArrMath
     402    // doesn't have partialMedians
     403    Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
     404    Vector<Float> outspec(nchan);
     405    Vector<uChar> outflag(nchan,0);
     406    Vector<Float> outtsys(1);/// @fixme when tsys is channel based
     407    for (uInt i=0; i<nchan; ++i) {
     408      Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
     409      MaskedArray<Float> ma = maskedArray(specs,flags);
     410      outspec[i] = median(ma);
     411      if ( allEQ(ma.getMask(), False) )
     412        outflag[i] = userflag;// flag data
     413    }
     414    outtsys[0] = median(tsysCol.getColumn());
     415    specColOut.put(outrowCount, outspec);
     416    flagColOut.put(outrowCount, outflag);
     417    tsysColOut.put(outrowCount, outtsys);
     418    Double intsum = sum(intCol.getColumn());
     419    intColOut.put(outrowCount, intsum);
     420    ++outrowCount;
     421    ++iter;
     422
     423    // 2012/02/17 TN
     424    // Since STGrid is implemented, average doesn't consider direction
     425    // when accumulating
     426//     MDirection::ScalarColumn dircol ;
     427//     dircol.attach( subt, "DIRECTION" ) ;
     428//     Int length = subt.nrow() ;
     429//     vector< Vector<Double> > dirs ;
     430//     vector<int> indexes ;
     431//     // Handle MX mode averaging
     432//     if (in->nbeam() > 1 ) {     
     433//       length = 1;
    368434//     }
    369 //     Vector<Float> tmp;
    370 //     specCol.get(0, tmp);
    371 //     uInt nchan = tmp.nelements();
    372 //     // have to do channel by channel here as MaskedArrMath
    373 //     // doesn't have partialMedians
    374 //     Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
    375 //     Vector<Float> outspec(nchan);
    376 //     Vector<uChar> outflag(nchan,0);
    377 //     Vector<Float> outtsys(1);/// @fixme when tsys is channel based
    378 //     for (uInt i=0; i<nchan; ++i) {
    379 //       Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
    380 //       MaskedArray<Float> ma = maskedArray(specs,flags);
    381 //       outspec[i] = median(ma);
    382 //       if ( allEQ(ma.getMask(), False) )
    383 //         outflag[i] = userflag;// flag data
     435//     for ( Int i = 0 ; i < length ; i++ ) {
     436//       Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ;
     437//       bool adddir = true ;
     438//       for ( uInt j = 0 ; j < dirs.size() ; j++ ) {
     439//         //if ( allTrue( t == dirs[j] ) ) {
     440//         Double dx = t[0] - dirs[j][0] ;
     441//         Double dy = t[1] - dirs[j][1] ;
     442//         Double dd = sqrt( dx * dx + dy * dy ) ;
     443//         //if ( allNearAbs( t, dirs[j], tol ) ) {
     444//         if ( dd <= tol ) {
     445//           adddir = false ;
     446//           break ;
     447//         }
     448//       }
     449//       if ( adddir ) {
     450//         dirs.push_back( t ) ;
     451//         indexes.push_back( i ) ;
     452//       }
    384453//     }
    385 //     outtsys[0] = median(tsysCol.getColumn());
    386 //     specColOut.put(outrowCount, outspec);
    387 //     flagColOut.put(outrowCount, outflag);
    388 //     tsysColOut.put(outrowCount, outtsys);
    389 //     Double intsum = sum(intCol.getColumn());
    390 //     intColOut.put(outrowCount, intsum);
    391 //     ++outrowCount;
     454//     uInt rowNum = dirs.size() ;
     455//     tout.addRow( rowNum );
     456//     for ( uInt i = 0 ; i < rowNum ; i++ ) {
     457//       TableCopy::copyRows(tout, subt, outrowCount+i, indexes[i], 1) ;
     458//       // Handle MX mode averaging
     459//       if ( avmode != "SCAN") {
     460//         scanColOut.put(outrowCount+i, uInt(0));
     461//       }
     462//     }
     463//     MDirection::ScalarColumn dircolOut ;
     464//     dircolOut.attach( tout, "DIRECTION" ) ;
     465//     for ( uInt irow = 0 ; irow < rowNum ; irow++ ) {
     466//       Vector<Double> t = \
     467//      dircolOut(outrowCount+irow).getAngle(Unit(String("rad"))).getValue() ;
     468//       Vector<Float> tmp;
     469//       specCol.get(0, tmp);
     470//       uInt nchan = tmp.nelements();
     471//       // have to do channel by channel here as MaskedArrMath
     472//       // doesn't have partialMedians
     473//       Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
     474//       // mask spectra for different DIRECTION
     475//       for ( uInt jrow = 0 ; jrow < subt.nrow() ; jrow++ ) {
     476//         Vector<Double> direction = \
     477//        dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
     478//         //if ( t[0] != direction[0] || t[1] != direction[1] ) {
     479//         Double dx = t[0] - direction[0];
     480//         Double dy = t[1] - direction[1];
     481//         Double dd = sqrt(dx*dx + dy*dy);
     482//         //if ( !allNearAbs( t, direction, tol ) ) {
     483//         if ( dd > tol &&  in->nbeam() < 2 ) {
     484//           flags[jrow] = userflag ;
     485//         }
     486//       }
     487//       Vector<Float> outspec(nchan);
     488//       Vector<uChar> outflag(nchan,0);
     489//       Vector<Float> outtsys(1);/// @fixme when tsys is channel based
     490//       for (uInt i=0; i<nchan; ++i) {
     491//         Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
     492//         MaskedArray<Float> ma = maskedArray(specs,flags);
     493//         outspec[i] = median(ma);
     494//         if ( allEQ(ma.getMask(), False) )
     495//           outflag[i] = userflag;// flag data
     496//       }
     497//       outtsys[0] = median(tsysCol.getColumn());
     498//       specColOut.put(outrowCount+irow, outspec);
     499//       flagColOut.put(outrowCount+irow, outflag);
     500//       tsysColOut.put(outrowCount+irow, outtsys);
     501//       Vector<Double> integ = intCol.getColumn() ;
     502//       MaskedArray<Double> mi = maskedArray( integ, flags ) ;
     503//       Double intsum = sum(mi);
     504//       intColOut.put(outrowCount+irow, intsum);
     505//     }
     506//     outrowCount += rowNum ;
    392507//     ++iter;
    393     MDirection::ScalarColumn dircol ;
    394     dircol.attach( subt, "DIRECTION" ) ;
    395     Int length = subt.nrow() ;
    396     vector< Vector<Double> > dirs ;
    397     vector<int> indexes ;
    398     // Handle MX mode averaging
    399     if (in->nbeam() > 1 ) {     
    400       length = 1;
    401     }
    402     for ( Int i = 0 ; i < length ; i++ ) {
    403       Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ;
    404       bool adddir = true ;
    405       for ( uInt j = 0 ; j < dirs.size() ; j++ ) {
    406         //if ( allTrue( t == dirs[j] ) ) {
    407         Double dx = t[0] - dirs[j][0] ;
    408         Double dy = t[1] - dirs[j][1] ;
    409         Double dd = sqrt( dx * dx + dy * dy ) ;
    410         //if ( allNearAbs( t, dirs[j], tol ) ) {
    411         if ( dd <= tol ) {
    412           adddir = false ;
    413           break ;
    414         }
    415       }
    416       if ( adddir ) {
    417         dirs.push_back( t ) ;
    418         indexes.push_back( i ) ;
    419       }
    420     }
    421     uInt rowNum = dirs.size() ;
    422     tout.addRow( rowNum );
    423     for ( uInt i = 0 ; i < rowNum ; i++ ) {
    424       TableCopy::copyRows(tout, subt, outrowCount+i, indexes[i], 1) ;
    425       // Handle MX mode averaging
    426       if ( avmode != "SCAN") {
    427         scanColOut.put(outrowCount+i, uInt(0));
    428       }
    429     }
    430     MDirection::ScalarColumn dircolOut ;
    431     dircolOut.attach( tout, "DIRECTION" ) ;
    432     for ( uInt irow = 0 ; irow < rowNum ; irow++ ) {
    433       Vector<Double> t = \
    434         dircolOut(outrowCount+irow).getAngle(Unit(String("rad"))).getValue() ;
    435       Vector<Float> tmp;
    436       specCol.get(0, tmp);
    437       uInt nchan = tmp.nelements();
    438       // have to do channel by channel here as MaskedArrMath
    439       // doesn't have partialMedians
    440       Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
    441       // mask spectra for different DIRECTION
    442       for ( uInt jrow = 0 ; jrow < subt.nrow() ; jrow++ ) {
    443         Vector<Double> direction = \
    444           dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
    445         //if ( t[0] != direction[0] || t[1] != direction[1] ) {
    446         Double dx = t[0] - direction[0];
    447         Double dy = t[1] - direction[1];
    448         Double dd = sqrt(dx*dx + dy*dy);
    449         //if ( !allNearAbs( t, direction, tol ) ) {
    450         if ( dd > tol &&  in->nbeam() < 2 ) {
    451           flags[jrow] = userflag ;
    452         }
    453       }
    454       Vector<Float> outspec(nchan);
    455       Vector<uChar> outflag(nchan,0);
    456       Vector<Float> outtsys(1);/// @fixme when tsys is channel based
    457       for (uInt i=0; i<nchan; ++i) {
    458         Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
    459         MaskedArray<Float> ma = maskedArray(specs,flags);
    460         outspec[i] = median(ma);
    461         if ( allEQ(ma.getMask(), False) )
    462           outflag[i] = userflag;// flag data
    463       }
    464       outtsys[0] = median(tsysCol.getColumn());
    465       specColOut.put(outrowCount+irow, outspec);
    466       flagColOut.put(outrowCount+irow, outflag);
    467       tsysColOut.put(outrowCount+irow, outtsys);
    468       Vector<Double> integ = intCol.getColumn() ;
    469       MaskedArray<Double> mi = maskedArray( integ, flags ) ;
    470       Double intsum = sum(mi);
    471       intColOut.put(outrowCount+irow, intsum);
    472     }
    473     outrowCount += rowNum ;
    474     ++iter;
    475508  }
    476509  return out;
     
    29542987                    "Use merge first."));
    29552988 
     2989  // 2012/02/17 TN
     2990  // Since STGrid is implemented, average doesn't consider direction
     2991  // when accumulating
    29562992  // check if OTF observation
    2957   String obstype = in[0]->getHeader().obstype ;
    2958   Double tol = 0.0 ;
    2959   if ( obstype.find( "OTF" ) != String::npos ) {
    2960     tol = TOL_OTF ;
    2961   }
    2962   else {
    2963     tol = TOL_POINT ;
    2964   }
     2993//   String obstype = in[0]->getHeader().obstype ;
     2994//   Double tol = 0.0 ;
     2995//   if ( obstype.find( "OTF" ) != String::npos ) {
     2996//     tol = TOL_OTF ;
     2997//   }
     2998//   else {
     2999//     tol = TOL_POINT ;
     3000//   }
    29653001
    29663002  CountedPtr<Scantable> out ;     // processed result
     
    35573593    ScalarColumn<uInt> freqidColOut ;
    35583594    freqidColOut.attach( out->table(), "FREQ_ID" ) ;
    3559     MDirection::ScalarColumn dirColOut ;
    3560     dirColOut.attach( out->table(), "DIRECTION" ) ;
     3595//     MDirection::ScalarColumn dirColOut ;
     3596//     dirColOut.attach( out->table(), "DIRECTION" ) ;
    35613597    Table &tab = tmpout->table() ;
    35623598    Block<String> cols(1);
     
    35753611      ScalarColumn<uInt> polnos ;
    35763612      polnos.attach( iter.table(), "POLNO" ) ;
    3577       MDirection::ScalarColumn dircol ;
    3578       dircol.attach( iter.table(), "DIRECTION" ) ;
     3613//       MDirection::ScalarColumn dircol ;
     3614//       dircol.attach( iter.table(), "DIRECTION" ) ;
    35793615      uInt polno = polnos( 0 ) ;
    35803616      //os << "POLNO iteration: " << polno << LogIO::POST ;
     
    36353671        if ( polout == polno ) {
    36363672          uInt ifout = ifnoColOut( irow ) ;
    3637           Vector<Double> direction = dirColOut(irow).getAngle(Unit(String("rad"))).getValue() ;
     3673//           Vector<Double> direction = dirColOut(irow).getAngle(Unit(String("rad"))).getValue() ;
    36383674          uInt igrp ;
    36393675          for ( uInt jgrp = 0 ; jgrp < freqgrp.size() ; jgrp++ ) {
     
    36463682            for ( uInt jrow = 0 ; jrow < iter.table().nrow() ; jrow++ ) {
    36473683              uInt ifno = ifnoCol( jrow ) ;
    3648               Vector<Double> tdir = dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
    3649               //if ( ifno == freqgrp[igrp][imem] && allTrue( tdir == direction  ) ) {
    3650               Double dx = tdir[0] - direction[0] ;
    3651               Double dy = tdir[1] - direction[1] ;
    3652               Double dd = sqrt( dx * dx + dy * dy ) ;
     3684              // 2012/02/17 TN
     3685              // Since STGrid is implemented, average doesn't consider direction
     3686              // when accumulating
     3687//               Vector<Double> tdir = dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
     3688//               //if ( ifno == freqgrp[igrp][imem] && allTrue( tdir == direction  ) ) {
     3689//               Double dx = tdir[0] - direction[0] ;
     3690//               Double dy = tdir[1] - direction[1] ;
     3691//               Double dd = sqrt( dx * dx + dy * dy ) ;
    36533692              //if ( ifno == freqgrp[igrp][imem] && allNearAbs( tdir, direction, tol ) ) {
    3654               if ( ifno == freqgrp[igrp][imem] && dd <= tol ) {
     3693//               if ( ifno == freqgrp[igrp][imem] && dd <= tol ) {
     3694              if ( ifno == freqgrp[igrp][imem] ) {
    36553695                Vector<Float> spec = specCols( jrow ) ;
    36563696                Vector<uChar> flag = flagCols( jrow ) ;
     
    44234463}
    44244464
     4465vector<float> STMath::getSpectrumFromTime( double reftime,
     4466                                           CountedPtr<Scantable>& s,
     4467                                           string mode )
     4468{
     4469  LogIO os( LogOrigin( "STMath", "getSpectrumFromTime", WHERE ) ) ;
     4470  vector<float> sp ;
     4471
     4472  if ( s->nrow() == 0 ) {
     4473    os << LogIO::SEVERE << "No spectra in the input scantable. Return empty spectrum." << LogIO::POST ;
     4474    return sp ;
     4475  }
     4476  else if ( s->nrow() == 1 ) {
     4477    //os << "use row " << 0 << " (scanno = " << s->getScan( 0 ) << ")" << LogIO::POST ;
     4478    return s->getSpectrum( 0 ) ;
     4479  }
     4480  else {
     4481    ROScalarColumn<Double> timeCol( s->table(), "TIME" ) ;
     4482    Vector<Double> timeVec = timeCol.getColumn() ;
     4483    vector<int> idx = getRowIdFromTime( reftime, timeVec ) ;
     4484    if ( mode == "before" ) {
     4485      int id = -1 ;
     4486      if ( idx[0] != -1 ) {
     4487        id = idx[0] ;
     4488      }
     4489      else if ( idx[1] != -1 ) {
     4490        os << LogIO::WARN << "Failed to find a scan before reftime. return a spectrum just after the reftime." << LogIO::POST ;
     4491        id = idx[1] ;
     4492      }
     4493      //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
     4494      sp = s->getSpectrum( id ) ;
     4495    }
     4496    else if ( mode == "after" ) {
     4497      int id = -1 ;
     4498      if ( idx[1] != -1 ) {
     4499        id = idx[1] ;
     4500      }
     4501      else if ( idx[0] != -1 ) {
     4502        os << LogIO::WARN << "Failed to find a scan after reftime. return a spectrum just before the reftime." << LogIO::POST ;
     4503        id = idx[1] ;
     4504      }
     4505      //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
     4506      sp = s->getSpectrum( id ) ;
     4507    }
     4508    else if ( mode == "nearest" ) {
     4509      int id = -1 ;
     4510      if ( idx[0] == -1 ) {
     4511        id = idx[1] ;
     4512      }
     4513      else if ( idx[1] == -1 ) {
     4514        id = idx[0] ;
     4515      }
     4516      else if ( idx[0] == idx[1] ) {
     4517        id = idx[0] ;
     4518      }
     4519      else {
     4520        //double t0 = getMJD( s->getTime( idx[0] ) ) ;
     4521        //double t1 = getMJD( s->getTime( idx[1] ) ) ;
     4522//         double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
     4523//         double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
     4524        double t0 = timeVec[idx[0]] ;
     4525        double t1 = timeVec[idx[1]] ;
     4526//         cout << "t0-t0c=" << t0-t0c << endl ;
     4527//         cout << "t1-t1c=" << t1-t1c << endl ;
     4528//         double tref = getMJD( reftime ) ;
     4529        double tref = reftime ;
     4530        if ( abs( t0 - tref ) > abs( t1 - tref ) ) {
     4531          id = idx[1] ;
     4532        }
     4533        else {
     4534          id = idx[0] ;
     4535        }
     4536      }
     4537      //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
     4538      sp = s->getSpectrum( id ) ;     
     4539    }
     4540    else if ( mode == "linear" ) {
     4541      if ( idx[0] == -1 ) {
     4542        // use after
     4543        os << LogIO::WARN << "Failed to interpolate. return a spectrum just after the reftime." << LogIO::POST ;
     4544        int id = idx[1] ;
     4545        //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
     4546        sp = s->getSpectrum( id ) ;
     4547      }
     4548      else if ( idx[1] == -1 ) {
     4549        // use before
     4550        os << LogIO::WARN << "Failed to interpolate. return a spectrum just before the reftime." << LogIO::POST ;
     4551        int id = idx[0] ;
     4552        //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
     4553        sp = s->getSpectrum( id ) ;
     4554      }
     4555      else if ( idx[0] == idx[1] ) {
     4556        // use before
     4557        //os << "No need to interporate." << LogIO::POST ;
     4558        int id = idx[0] ;
     4559        //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ;
     4560        sp = s->getSpectrum( id ) ;
     4561      }
     4562      else {
     4563        // do interpolation
     4564        //os << "interpolate between " << idx[0] << " and " << idx[1] << " (scanno: " << s->getScan( idx[0] ) << ", " << s->getScan( idx[1] ) << ")" << LogIO::POST ;
     4565        //double t0 = getMJD( s->getTime( idx[0] ) ) ;
     4566        //double t1 = getMJD( s->getTime( idx[1] ) ) ;
     4567//         double t0 = s->getEpoch( idx[0] ).get( Unit( "d" ) ).getValue() ;
     4568//         double t1 = s->getEpoch( idx[1] ).get( Unit( "d" ) ).getValue() ;
     4569        double t0 = timeVec[idx[0]] ;
     4570        double t1 = timeVec[idx[1]] ;
     4571//         cout << "t0-t0c=" << t0-t0c << endl ;
     4572//         cout << "t1-t1c=" << t1-t1c << endl ;
     4573//         double tref = getMJD( reftime ) ;
     4574        double tref = reftime ;
     4575        vector<float> sp0 = s->getSpectrum( idx[0] ) ;
     4576        vector<float> sp1 = s->getSpectrum( idx[1] ) ;
     4577        for ( unsigned int i = 0 ; i < sp0.size() ; i++ ) {
     4578          float v = ( sp1[i] - sp0[i] ) / ( t1 - t0 ) * ( tref - t0 ) + sp0[i] ;
     4579          sp.push_back( v ) ;
     4580        }
     4581      }
     4582    }
     4583    else {
     4584      os << LogIO::SEVERE << "Unknown mode" << LogIO::POST ;
     4585    }
     4586    return sp ;
     4587  }
     4588}
     4589
    44254590double STMath::getMJD( string strtime )
    44264591{
     
    44814646  v.push_back( just_before ) ;
    44824647  v.push_back( just_after ) ;
     4648
     4649  return v ;
     4650}
     4651
     4652vector<int> STMath::getRowIdFromTime( double reftime, Vector<Double> &t )
     4653{
     4654//   double reft = reftime ;
     4655  double dtmin = 1.0e100 ;
     4656  double dtmax = -1.0e100 ;
     4657//   vector<double> dt ;
     4658  int just_before = -1 ;
     4659  int just_after = -1 ;
     4660  //cout << setprecision(24) << reft << endl ;
     4661//   ROScalarColumn<Double> timeCol( s->table(), "TIME" ) ;
     4662//   for ( int i = 0 ; i < s->nrow() ; i++ ) {
     4663//     cout << setprecision(24) << timeCol(i) << endl ;
     4664//     //dt.push_back( getMJD( s->getTime( i ) ) - reft ) ;
     4665//     dt.push_back( timeCol(i) - reft ) ;
     4666//   }
     4667  Vector<Double> dt = t - reftime ;
     4668  for ( unsigned int i = 0 ; i < dt.size() ; i++ ) {
     4669    if ( dt[i] > 0.0 ) {
     4670      // after reftime
     4671      if ( dt[i] < dtmin ) {
     4672        just_after = i ;
     4673        dtmin = dt[i] ;
     4674      }
     4675    }
     4676    else if ( dt[i] < 0.0 ) {
     4677      // before reftime
     4678      if ( dt[i] > dtmax ) {
     4679        just_before = i ;
     4680        dtmax = dt[i] ;
     4681      }
     4682    }
     4683    else {
     4684      // just a reftime
     4685      just_before = i ;
     4686      just_after = i ;
     4687      dtmax = 0 ;
     4688      dtmin = 0 ;
     4689      break ;
     4690    }
     4691  }
     4692
     4693  vector<int> v(2) ;
     4694  v[0] = just_before ;
     4695  v[1] = just_after ;
    44834696
    44844697  return v ;
     
    48065019                                            int index )
    48075020{
    4808   string reftime = on->getTime( index ) ;
     5021//   string reftime = on->getTime( index ) ;
     5022  ROTableColumn timeCol( on->table(), "TIME" ) ;
     5023  double reftime = timeCol.asdouble(index) ;
    48095024  vector<int> ii( 1, on->getIF( index ) ) ;
    48105025  vector<int> ib( 1, on->getBeam( index ) ) ;
  • /branches/hpc33/src/STMath.h

    r2373 r2473  
    403403
    404404  vector<float> getSpectrumFromTime( string reftime, casa::CountedPtr<Scantable>& s, string mode = "before" ) ;
     405  vector<float> getSpectrumFromTime( double reftime, casa::CountedPtr<Scantable>& s, string mode = "before" ) ;
    405406  vector<float> getTcalFromTime( string reftime, casa::CountedPtr<Scantable>& s, string mode="before" ) ;
    406407  vector<float> getTsysFromTime( string reftime, casa::CountedPtr<Scantable>& s, string mode="before" ) ;
    407408  vector<int> getRowIdFromTime( string reftime, casa::CountedPtr<Scantable>& s ) ;
     409  vector<int> getRowIdFromTime( double reftime, casa::Vector<casa::Double>& t ) ;
    408410
    409411  // Chopper-Wheel type calibration
  • /branches/hpc33/src/Scantable.h

    r2373 r2473  
    480480   */
    481481  void parallactify(bool flag)
    482     { focus().setParallactify(flag); }
     482    { focusTable_.setParallactify(flag); }
    483483
    484484  /**
  • /branches/hpc33/src/python_asap.cpp

    r2373 r2473  
    8484  asap::python::python_STAtmosphere();
    8585  asap::python::python_SrcType();
     86  asap::python::python_STGrid();
    8687
    8788#ifndef HAVE_LIBPYRAP
  • /branches/hpc33/src/python_asap.h

    r2373 r2473  
    5252    void python_STAtmosphere();
    5353    void python_SrcType();
     54    void python_STGrid();
    5455
    5556  } // python
  • /trunk/CMakeLists.txt

    r2373 r2473  
    1515message( STATUS "USE_LIBCASACORE = " ${USE_LIBCASACORE} )
    1616message( STATUS "STANDALONE = " ${STANDALONE} )
     17
     18# Use casapy's fork of casacore 
     19if ( NOT STANDALONE )
     20  add_definitions( -DUSE_CASAPY )
     21endif ()
    1722
    1823# Define compiler paths on OSX 10.5. This must be done before invoking project()
     
    4247# default is RelWithDebInfo
    4348#
     49
     50
    4451if ( NOT CMAKE_BUILD_TYPE )
    4552   set( CMAKE_BUILD_TYPE RelWithDebInfo )
     
    8693if( APPLE )
    8794   set( SO dylib )
    88    if( CMAKE_SYSTEM MATCHES ^Darwin-10 )
     95   if( CMAKE_SYSTEM MATCHES ^Darwin-10 OR
     96                CMAKE_SYSTEM MATCHES ^Darwin-11 )
    8997      if( NOT archflag )
    90          if( EXISTS /opt/casa/darwin10-64b )
     98         if( EXISTS /opt/casa/darwin11 )
     99            set( archflag x86_64 )
     100         elseif( EXISTS /opt/casa/darwin10-64b )
    91101            set( archflag x86_64 )
    92102         elseif( EXISTS /opt/casa/core2-apple-darwin10 )
     
    264274      -DPYVERSION=${PV} )
    265275else()
     276   # with CASA
    266277   if( NOT PYTHON_FOUND )
    267278      if ( NOT PYTHON_LIBNAME )
    268          set( _names 2.9 2.8 2.7 2.6 2.5.2 2.5 )
     279         #set( _names 2.9 2.8 2.7 2.6 2.5.2 2.5 )
     280         set( _names 2.6 2.5.2 2.5 )
     281         # OSX 10.7 has Python2.7 by default. CASA has't yet supported python > 2.6 anyway.
    269282         # (The library named libpython.2.5.2.dylib seems to exist only in the CASA world.)
    270283      else()
     
    276289
    277290         casa_find(
    278             PYTHON${_v}
     291            PYTHON${_v}
     292            #PREFIX_HINTS ${PYTHON_ROOT_DIR}
    279293            LIBS python${_v}
    280294            NO_REQUIRE
     
    312326      # Python library was not in a lib(64) directory!
    313327      message( WARNING "Python library path \"${PYTHON${PYTHON_LIBNAME}_LIBRARIES}\" does not contain \"/lib(64)/lib${python_library}\"" )
     328      set( python_prefix ${casa_packages} )
     329   endif()
     330
     331   #
     332   # For some unknown reason cmake sets the /usr for Lion
     333   #
     334   if( APPLE )
    314335      set( python_prefix ${casa_packages} )
    315336   endif()
     
    585606# libraries and executables
    586607#
     608set( ASAPPYLIB _asap )
    587609set( ASAPLIB asap )
    588610set( PYRAPLIB pyrap )
     
    590612set( ASAP2TO3 asap2to3 )
    591613if ( NOT STANDALONE )
    592    set( ASDM2ASAP_OLD oldasdm2ASAP )
     614#   set( ASDM2ASAP_OLD oldasdm2ASAP )
    593615   set( ASDM2ASAP asdm2ASAP )
    594616endif()
  • /trunk/cmake/withcasa.cmake

    r2373 r2473  
    66# environment dependent settings
    77if( APPLE )
    8    if( NOT arch )
    9       set( arch darwin )
    10    endif()
    11    if( CMAKE_SYSTEM MATCHES ^Darwin-10 )
     8   if( CMAKE_SYSTEM MATCHES ^Darwin-10 OR
     9                CMAKE_SYSTEM MATCHES ^Darwin-11 )
     10      if ( NOT arch )
     11         set( arch darwin64 )
     12      endif()
    1213      if( NOT archflag )
    13          if( EXISTS /opt/casa/darwin10-64b )
     14         if( EXISTS /opt/casa/darwin11 )
     15            set( archflag x86_64 )
     16         elseif( EXISTS /opt/casa/darwin10-64b )
    1417            set( archflag x86_64 )
    1518         elseif( EXISTS /opt/casa/core2-apple-darwin10 )
     
    2023      endif()
    2124      if( archflag STREQUAL x86_64 )
    22          set( casa_packages /opt/casa/darwin10-64b )
     25         if( CMAKE_SYSTEM MATCHES ^Darwin-11 )
     26             set( casa_packages /opt/casa/darwin11 )
     27         else()
     28             set( casa_packages /opt/casa/darwin10-64b )
     29         endif()
    2330      else()
    2431         set( casa_packages /opt/casa/core2-apple-darwin10 )
    2532      endif()
    2633   elseif( CMAKE_SYSTEM MATCHES ^Darwin-9 )
     34      if ( NOT arch )
     35         set( arch darwin )
     36      endif()
    2737      set( casa_packages /opt/casa/core2-apple-darwin8/3rd-party )
    2838   endif()         
     
    114124endif()
    115125message( STATUS "LIBXML2_LIBRARY = " ${LIBXML2_LIBRARY} )
    116 set( ASDM_INCLUDE_DIR_OLD ${CASA_CODE_PATH}/alma/implement/ASDM
    117                           ${CASA_CODE_PATH}/alma/implement/Enumerations
    118                           ${CASA_CODE_PATH}/alma/implement/ASDMBinaries
    119                           ${CASA_CODE_PATH}/alma/implement/Enumtcl
    120                           ${LIBXML2_INCLUDE_DIR} )
    121 set( ASDM_LIBRARY_OLD ${casaroot}/${arch}/lib/libalma${CMAKE_SHARED_LIBRARY_SUFFIX}
    122                       ${LIBXML2_LIBRARY}/libxml2${CMAKE_SHARED_LIBRARY_SUFFIX} )
    123 set( ASDM_INCLUDE_DIR ${CASA_CODE_PATH}/alma_v3/implement/ASDM
    124                       ${CASA_CODE_PATH}/alma_v3/implement/Enumerations
    125                       ${CASA_CODE_PATH}/alma_v3/implement/ASDMBinaries
    126                       ${CASA_CODE_PATH}/alma_v3/implement/Enumtcl
     126#set( ASDM_INCLUDE_DIR_OLD ${CASA_CODE_PATH}/alma/implement/ASDM
     127#                          ${CASA_CODE_PATH}/alma/implement/Enumerations
     128#                          ${CASA_CODE_PATH}/alma/implement/ASDMBinaries
     129#                          ${CASA_CODE_PATH}/alma/implement/Enumtcl
     130#                          ${LIBXML2_INCLUDE_DIR} )
     131#set( ASDM_LIBRARY_OLD ${casaroot}/${arch}/lib/libalma${CMAKE_SHARED_LIBRARY_SUFFIX}
     132#                      ${LIBXML2_LIBRARY}/libxml2${CMAKE_SHARED_LIBRARY_SUFFIX} )
     133#set( ASDM_INCLUDE_DIR ${CASA_CODE_PATH}/alma_v3/implement/ASDM
     134#                      ${CASA_CODE_PATH}/alma_v3/implement/Enumerations
     135#                      ${CASA_CODE_PATH}/alma_v3/implement/ASDMBinaries
     136#                      ${CASA_CODE_PATH}/alma_v3/implement/Enumtcl
     137#                      ${LIBXML2_INCLUDE_DIR} )
     138#set( ASDM_LIBRARY ${casaroot}/${arch}/lib/libalma_v3${CMAKE_SHARED_LIBRARY_SUFFIX}
     139#                  ${LIBXML2_LIBRARY}/libxml2${CMAKE_SHARED_LIBRARY_SUFFIX} )
     140set( ASDM_INCLUDE_DIR ${CASA_CODE_PATH}/alma/implement/ASDM
     141                      ${CASA_CODE_PATH}/alma/implement/Enumerations
     142                      ${CASA_CODE_PATH}/alma/implement/ASDMBinaries
     143                      ${CASA_CODE_PATH}/alma/implement/Enumtcl
    127144                      ${LIBXML2_INCLUDE_DIR} )
    128 set( ASDM_LIBRARY ${casaroot}/${arch}/lib/libalma_v3${CMAKE_SHARED_LIBRARY_SUFFIX}
     145set( ASDM_LIBRARY ${casaroot}/${arch}/lib/libalma${CMAKE_SHARED_LIBRARY_SUFFIX}
    129146                  ${LIBXML2_LIBRARY}/libxml2${CMAKE_SHARED_LIBRARY_SUFFIX} )
    130147add_definitions( -DWITHOUT_ACS )
     
    147164   add_subdirectory( share )
    148165   add_subdirectory( external-alma/asdm2ASAP )
    149    add_subdirectory( external-alma/oldasdm2ASAP )
     166#   add_subdirectory( external-alma/oldasdm2ASAP )
    150167endmacro( asap_add_subdirectory )
    151168
  • /trunk/external-alma/asdm2ASAP/ASDMFiller.cc

    r2373 r2473  
    7676  Vector<casa::Double> antpos = table_->getHeader().antennaposition ;
    7777
    78   //STHeader hdr = table_->getHeader() ;
    79  
    8078  // data selection
    8179  reader_->select() ;
     
    103101
    104102  // CYCLENO
    105   //unsigned int cycleno = 0 ;
    106103  map< unsigned int, unsigned int > cycleno ;
    107104  map< unsigned int, unsigned int >::iterator citer ;
     
    111108      //logsink_->postLocally( LogMessage("start configDescId "+String::toString(configDescIdList[icon])+" fieldId "+String::toString(fieldIdList[ifield]),LogOrigin(className_,funcName,WHERE)) ) ;
    112109
    113       //Bool status = reader_->setMainRow( configDescIdList[icon], fieldIdList[ifield] ) ;
    114110      if ( !(reader_->setMainRow( configDescIdList[icon], fieldIdList[ifield] )) ) {
    115111        //logsink_->postLocally( LogMessage("skip configDescId "+String::toString(configDescIdList[icon])+" fieldId "+String::toString(fieldIdList[ifield]),LogOrigin(className_,funcName,WHERE)) ) ;
     
    132128
    133129        // scan and subscan
    134         //unsigned int scanno = reader_->getScanNo() ;
    135130        unsigned int scanno = reader_->getScanNoOfCurrentRow() ;
    136131        //logsink_->postLocally( LogMessage("scanno = "+String::toString(scanno),LogOrigin(className_,funcName,WHERE)) ) ;
    137         //uInt subscanno = reader_->getSubscanNo() ;
    138132        citer = cycleno.find( scanno ) ;
    139133        if ( citer == cycleno.end() )
     
    160154
    161155          // subscan number
    162           //unsigned int subscanno = reader_->getSubscanNo( idata ) ;
    163156          unsigned int subscanno = reader_->getSubscanNo() ;
    164157          //logsink_->postLocally( LogMessage("subscanno = "+String::toString(subscanno),LogOrigin(className_,funcName,WHERE)) ) ;
    165158
    166159          // IFNO
    167           //uInt ifno = reader_->getIFNo( idata ) ;
    168160          uInt ifno = reader_->getIFNo() ;
    169161          //logsink_->postLocally( LogMessage("ifno = "+String::toString(ifno),LogOrigin(className_,funcName,WHERE)) ) ;
     
    177169          double sysVel ;
    178170          vector<double> rf ;
    179           //reader_->getSourceProperty( idata,
    180           //                            srcname,
    181           //                            fieldname,
    182           //                            srcDirection,
    183           //                            srcProperMotion,
    184           //                            sysVel,
    185           //                            rf ) ;
    186171          reader_->getSourceProperty( srcname,
    187172                                      fieldname,
     
    199184         
    200185          // time and interval
    201           //casa::Double mjd = (casa::Double)(reader_->getTime( idata )) ;
    202           //casa::Double interval = (casa::Double)(reader_->getInterval( idata )) ;
    203186          casa::Double mjd = (casa::Double)(reader_->getTime()) ;
    204187          casa::Double interval = (casa::Double)(reader_->getInterval()) ;
     
    218201
    219202          // fill FLAGROW
    220           //unsigned int flagrow = reader_->getFlagRow( idata ) ;
    221203          unsigned int flagrow = reader_->getFlagRow() ;
    222204          setFlagrow( (uInt)flagrow ) ;
     
    228210          float windspeed ;
    229211          float windaz ;
    230           //reader_->getWeatherInfo( idata,
    231           //                         temperature,
    232           //                         pressure,
    233           //                         humidity,
    234           //                         windspeed,
    235           //                         windaz ) ;
    236212          reader_->getWeatherInfo( temperature,
    237213                                   pressure,
     
    250226          double el ;
    251227          vector<double> srate ;
    252           //reader_->getPointingInfo( idata,
    253           //                          dir,
    254           //                          az,
    255           //                          el,
    256           //                          srate ) ;
    257228          reader_->getPointingInfo( dir,
    258229                                    az,
     
    282253          }
    283254          else {
    284             //reader_->getFrequency( idata, refpix, refval, incr, freqref ) ;
    285255            reader_->getFrequency( refpix, refval, incr, freqref ) ;
    286256            refval = (double)toLSRK( casa::Double(refval),
     
    298268
    299269          // loop on polarization
    300           //vector<unsigned int> dataShape = reader_->getDataShape( idata ) ;
    301270          vector<unsigned int> dataShape = reader_->getDataShape() ;
    302271//           ostringstream oss ;
     
    311280//           logsink_->postLocally( LogMessage(oss.str(),LogOrigin(className_,funcName,WHERE)) ) ;
    312281                                     
    313           //int numPol = reader_->getNumPol( idata ) ;
    314282          unsigned int numPol = dataShape[0] ;
    315283          unsigned int numChan = dataShape[1] ;
     
    318286
    319287          // OPACITY
    320           //vector<float> tau = reader_->getOpacity( idata ) ;
    321288          vector<float> tau = reader_->getOpacity() ;
    322289          Vector<casa::Float> opacity = toVector( tau, numPol ) ;
    323290
    324291          // SPECTRA, FLAGTRA, TSYS, TCAL
    325           //float *sp = reader_->getSpectrum( idata ) ;
    326           //logsink_->postLocally( LogMessage("getting spectra...",LogOrigin(className_,funcName,WHERE)) ) ;
    327292          float *sp = reader_->getSpectrum() ;
    328293          //logsink_->postLocally( LogMessage("sp[0] = "+String::toString(sp[0]),LogOrigin(className_,funcName,WHERE)) ) ;
    329294          vector< vector<float> > ts ;
    330295          vector< vector<float> > tc ;
    331           //reader_->getTcalAndTsys( idata, tc, ts ) ;
    332296          reader_->getTcalAndTsys( tc, ts ) ;
    333297          Matrix<casa::Float> spectra = toMatrix( sp, numPol, numChan ) ;
  • /trunk/external-alma/asdm2ASAP/ASDMReader.cc

    r2373 r2473  
    12711271      CalAtmosphereRow *atmrow = atmrows[row0] ;
    12721272      tau = atmrow->getTau() ;
     1273    }
     1274    else {
     1275      tau.resize( 1 ) ;
     1276      tau[0] = 0.0 ;
    12731277    }
    12741278  }
  • /trunk/external-alma/atnf/PKSIO/ASTEDataset.cc

    r2373 r2473  
    529529    c18[16] = '\0' ;
    530530    RX[i] = string( c18 ) ;
    531     // DEBUG
    532 //     if ( i == 0 ) {
    533 //       cout << "RX      " ;
    534 //     }
    535 //     else if ( ( i % 5 ) == 0 ) {
    536 //       cout << endl << "        " ;
    537 //     }
    538 //     cout << RX[i] << " " ;
    539     //
    540   }
    541   //cout << endl ;
     531  }
     532  // DEBUG
     533//   nro_debug_output( "RX", ASTE_ARYMAX, RX ) ;
     534  //
    542535  for ( int i = 0 ; i < ASTE_ARYMAX ; i++ ) {
    543536    if ( readHeader( HPBW[i], sameEndian ) == -1 ) {
     
    545538      return -1 ;
    546539    }
    547     // DEBUG
    548 //     if ( i == 0 ) {
    549 //       cout << "HPBW    " ;
    550 //     }
    551 //     else if ( ( i % 5 ) == 0 ) {
    552 //       cout << endl << "        " ;
    553 //     }
    554 //     cout << HPBW[i] << " " ;
    555     //
    556   }
    557   //cout << endl ;
     540  }
     541  // DEBUG
     542//   nro_debug_output( "HPBW", ASTE_ARYMAX, HPBW ) ;
     543  //
    558544  for ( int i = 0 ; i < ASTE_ARYMAX ; i++ ) {
    559545    if ( readHeader( EFFA[i], sameEndian ) == -1 ) {
     
    561547      return -1 ;
    562548    }
    563     // DEBUG
    564 //     if ( i == 0 ) {
    565 //       cout << "EFFA    " ;
    566 //     }
    567 //     else if ( ( i % 5 ) == 0 ) {
    568 //       cout << endl << "        " ;
    569 //     }
    570 //     cout << EFFA[i] << " " ;
    571     //
    572   }
    573   //cout << endl ;
     549  }
     550  // DEBUG
     551//   nro_debug_output( "EFFA", ASTE_ARYMAX, EFFA ) ;
     552  //
    574553  for ( int i = 0 ; i < ASTE_ARYMAX ; i++ ) {
    575554    if ( readHeader( EFFB[i], sameEndian ) == -1 ) {
     
    577556      return -1 ;
    578557    }
    579     // DEBUG
    580 //     if ( i == 0 ) {
    581 //       cout << "EFFB    " ;
    582 //     }
    583 //     else if ( ( i % 5 ) == 0 ) {
    584 //       cout << endl << "        " ;
    585 //     }
    586 //     cout << EFFB[i] << " " ;
    587     //
    588   }
    589   //cout << endl ;
     558  }
     559  // DEBUG
     560//   nro_debug_output( "EFFB", ASTE_ARYMAX, EFFB ) ;
     561  //
    590562  for ( int i = 0 ; i < ASTE_ARYMAX ; i++ ) {
    591563    if ( readHeader( EFFL[i], sameEndian ) == -1 ) {
     
    593565      return -1 ;
    594566    }
    595     // DEBUG
    596 //     if ( i == 0 ) {
    597 //       cout << "EFFL    " ;
    598 //     }
    599 //     else if ( ( i % 5 ) == 0 ) {
    600 //       cout << endl << "        " ;
    601 //     }
    602 //     cout << EFFL[i] << " " ;
    603     //
    604   }
    605   //cout << endl ;
     567  }
     568  // DEBUG
     569//   nro_debug_output( "EFFL", ASTE_ARYMAX, EFFL ) ;
     570  //
    606571  for ( int i = 0 ; i < ASTE_ARYMAX ; i++ ) {
    607572    if ( readHeader( EFSS[i], sameEndian ) == -1 ) {
     
    609574      return -1 ;
    610575    }
    611     // DEBUG
    612 //     if ( i == 0 ) {
    613 //       cout << "EFSS    " ;
    614 //     }
    615 //     else if ( ( i % 5 ) == 0 ) {
    616 //       cout << endl << "        " ;
    617 //     }
    618 //     cout << EFSS[i] << " " ;
    619     //
    620   }
    621   //cout << endl ;
     576  }
     577  // DEBUG
     578//   nro_debug_output( "EFSS", ASTE_ARYMAX, EFSS ) ;
     579  //
    622580  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    623581    if ( readHeader( GAIN[i], sameEndian ) == -1 ) {
     
    625583      return -1 ;
    626584    }
    627     // DEBUG
    628 //     if ( i == 0 ) {
    629 //       cout << "GAIN    " ;
    630 //     }
    631 //     else if ( ( i % 5 ) == 0 ) {
    632 //       cout << endl << "        " ;
    633 //     }
    634 //     cout << GAIN[i] << " " ;
    635     //
    636   }
    637   //cout << endl ;
     585  }
     586  // DEBUG
     587//   nro_debug_output( "GAIN", ASTE_ARYMAX, GAIN ) ;
     588  //
    638589  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    639590    strcpy( c4, str4.c_str() ) ;
     
    643594    }
    644595    HORN[i] = string( c4 ) ;
    645     // DEBUG
    646 //     if ( i == 0 ) {
    647 //       cout << "HORN    " ;
    648 //     }
    649 //     else if ( ( i % 5 ) == 0 ) {
    650 //       cout << endl << "        " ;
    651 //     }
    652 //     cout << HORN[i] << " " ;
    653     //
    654   }
    655   //cout << endl ;
     596  }
     597  // DEBUG
     598//   nro_debug_output( "HORN", ASTE_ARYMAX, HORN ) ;
     599  //
    656600  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    657601    strcpy( c4, str4.c_str() ) ;
     
    661605    }
    662606    POLTP[i] = string( c4 ) ;
    663     // DEBUG
    664 //     if ( i == 0 ) {
    665 //       cout << "POLTP   " ;
    666 //     }
    667 //     else if ( ( i % 5 ) == 0 ) {
    668 //       cout << endl << "        " ;
    669 //     }
    670 //     cout << POLTP[i] << " " ;
    671     //
    672   }
    673   //cout << endl ;
     607  }
     608  // DEBUG
     609//   nro_debug_output( "POLTP", ASTE_ARYMAX, POLTP ) ;
     610  //
    674611  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    675612    if ( readHeader( POLDR[i], sameEndian ) == -1 ) {
     
    677614      return -1 ;
    678615    }
    679      // DEBUG
    680 //     if ( i == 0 ) {
    681 //       cout << "POLDR   " ;
    682 //     }
    683 //     else if ( ( i % 5 ) == 0 ) {
    684 //       cout << endl << "        " ;
    685 //     }
    686 //     cout << POLDR[i] << " " ;
    687     //
    688   }
    689   //cout << endl ;
     616  }
     617  // DEBUG
     618//   nro_debug_output( "POLDR", ASTE_ARYMAX, POLDR ) ;
     619  //
    690620  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    691621    if ( readHeader( POLAN[i], sameEndian ) == -1 ) {
     
    693623      return -1 ;
    694624    }
    695     // DEBUG
    696 //     if ( i == 0 ) {
    697 //       cout << "POLAN   " ;
    698 //     }
    699 //     else if ( ( i % 5 ) == 0 ) {
    700 //       cout << endl << "        " ;
    701 //     }
    702 //     cout << POLAN[i] << " " ;
    703     //
    704   }
    705   //cout << endl ;
     625  }
     626  // DEBUG
     627//   nro_debug_output( "POLAN", ASTE_ARYMAX, POLAN ) ;
     628  //
    706629  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    707630    if ( readHeader( DFRQ[i], sameEndian ) == -1 ) {
     
    709632      return -1 ;
    710633    }
    711     // DEBUG
    712 //     if ( i == 0 ) {
    713 //       cout << "DFRQ    " ;
    714 //     }
    715 //     else if ( ( i % 5 ) == 0 ) {
    716 //       cout << endl << "        " ;
    717 //     }
    718 //     cout << DFRQ[i] << " " ;
    719     //
    720   }
    721   //cout << endl ;
     634  }
     635  // DEBUG
     636//   nro_debug_output( "DFRQ", ASTE_ARYMAX, DFRQ ) ;
     637  //
    722638  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    723639    strcpy( c4, str4.c_str() ) ;
     
    727643    }
    728644    SIDBD[i] = string( c4 ) ;
    729     // DEBUG
    730 //     if ( i == 0 ) {
    731 //       cout << "SIDBD   " ;
    732 //     }
    733 //     else if ( ( i % 5 ) == 0 ) {
    734 //       cout << endl << "        " ;
    735 //     }
    736 //     cout << SIDBD[i] << " " ;
    737     //
    738   }
    739   //cout << endl ;
     645  }
     646  // DEBUG
     647//   nro_debug_output( "SIDBD", ASTE_ARYMAX, SIDBD ) ;
     648  //
    740649  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    741650    if ( readHeader( REFN[i], sameEndian ) == -1 ) {
     
    743652      return -1 ;
    744653    }
    745     // DEBUG
    746 //     if ( i == 0 ) {
    747 //       cout << "REFN    " ;
    748 //     }
    749 //     else if ( ( i % 5 ) == 0 ) {
    750 //       cout << endl << "        " ;
    751 //     }
    752 //     cout << REFN[i] << " " ;
    753     //
    754   }
    755   //cout << endl ;
     654  }
     655  // DEBUG
     656//   nro_debug_output( "REFN", ASTE_ARYMAX, REFN ) ;
     657  //
    756658  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    757659    if ( readHeader( IPINT[i], sameEndian ) == -1 ) {
     
    759661      return -1 ;
    760662    }
    761     // DEBUG
    762 //     if ( i == 0 ) {
    763 //       cout << "IPINT   " ;
    764 //     }
    765 //     else if ( ( i % 5 ) == 0 ) {
    766 //       cout << endl << "        " ;
    767 //     }
    768 //     cout << IPINT[i] << " " ;
    769     //
    770   }
    771   //cout << endl ;
     663  }
     664  // DEBUG
     665//   nro_debug_output( "IPINT", ASTE_ARYMAX, IPINT ) ;
     666  //
    772667  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    773668    if ( readHeader( MULTN[i], sameEndian ) == -1 ) {
     
    775670      return -1 ;
    776671    }
    777     // DEBUG
    778 //     if ( i == 0 ) {
    779 //       cout << "MULTN   " ;
    780 //     }
    781 //     else if ( ( i % 5 ) == 0 ) {
    782 //       cout << endl << "        " ;
    783 //     }
    784 //     cout << MULTN[i] << " " ;
    785     //
    786   }
    787   //cout << endl ;
     672  }
     673  // DEBUG
     674//   nro_debug_output( "MULTN", ASTE_ARYMAX, MULTN ) ;
     675  //
    788676  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    789677    if ( readHeader( MLTSCF[i], sameEndian ) == -1 ) {
     
    791679      return -1 ;
    792680    }
    793     // DEBUG
    794 //     if ( i == 0 ) {
    795 //       cout << "MLTSCF  " ;
    796 //     }
    797 //     else if ( ( i % 5 ) == 0 ) {
    798 //       cout << endl << "        " ;
    799 //     }
    800 //     cout << MLTSCF[i] << " " ;
    801     //
    802   }
    803   //cout << endl ;
     681  }
     682  // DEBUG
     683//   nro_debug_output( "MLTSCF", ASTE_ARYMAX, MLTSCF ) ;
     684  //
    804685  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    805686    strcpy( c8, str8.c_str() ) ;
     
    809690    }
    810691    LAGWIND[i] = string( c8 ) ;
    811     // DEBUG
    812 //     if ( i == 0 ) {
    813 //       cout << "LAGWIND " ;
    814 //     }
    815 //     else if ( ( i % 5 ) == 0 ) {
    816 //       cout << endl << "        " ;
    817 //     }
    818 //     cout << LAGWIND[i] << " " ;
    819     //
    820   }
    821   //cout << endl ;
     692  }
     693  // DEBUG
     694//   nro_debug_output( "LAGWIND", ASTE_ARYMAX, LAGWIND ) ;
     695  //
    822696  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    823697    if ( readHeader( BEBW[i], sameEndian ) == -1 ) {
     
    825699      return -1 ;
    826700    }
    827     // DEBUG
    828 //     if ( i == 0 ) {
    829 //       cout << "BEBW    " ;
    830 //     }
    831 //     else if ( ( i % 5 ) == 0 ) {
    832 //       cout << endl << "        " ;
    833 //     }
    834 //     cout << BEBW[i] << " " ;
    835     //
    836   }
    837   //cout << endl ;
     701  }
     702  // DEBUG
     703//   nro_debug_output( "BEBW", ASTE_ARYMAX, BEBW ) ;
     704  //
    838705  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    839706    if ( readHeader( BERES[i], sameEndian ) == -1 ) {
     
    841708      return -1 ;
    842709    }
    843     // DEBUG
    844 //     if ( i == 0 ) {
    845 //       cout << "BERES   " ;
    846 //     }
    847 //     else if ( ( i % 5 ) == 0 ) {
    848 //       cout << endl << "        " ;
    849 //     }
    850 //     cout << BERES[i] << " " ;
    851     //
    852   }
    853   //cout << endl ;
     710  }
     711  // DEBUG
     712//   nro_debug_output( "BERES", ASTE_ARYMAX, BERES ) ;
     713  //
    854714  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    855715    if ( readHeader( CHWID[i], sameEndian ) == -1 ) {
     
    857717      return -1 ;
    858718    }
    859     // DEBUG
    860 //     if ( i == 0 ) {
    861 //       cout << "CHWID   " ;
    862 //     }
    863 //     else if ( ( i % 5 ) == 0 ) {
    864 //       cout << endl << "        " ;
    865 //     }
    866 //     cout << CHWID[i] << " " ;
    867     //
    868   }
    869   //cout << endl ;
     719  }
     720  // DEBUG
     721//   nro_debug_output( "CHWID", ASTE_ARYMAX, CHWID ) ;
     722  //
    870723  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    871724    if ( readHeader( ARRY[i], sameEndian ) == -1 ) {
     
    873726      return -1 ;
    874727    }
    875     // DEBUG
    876 //     if ( i == 0 ) {
    877 //       cout << "ARRY    " ;
    878 //     }
    879 //     else if ( ( i % 5 ) == 0 ) {
    880 //       cout << endl << "        " ;
    881 //     }
    882 //     cout << ARRY[i] << " " ;
    883     //
    884   }
    885   //cout << endl ;
     728  }
     729  // DEBUG
     730//   nro_debug_output( "ARRY", ASTE_ARYMAX, ARRY ) ;
     731  //
    886732  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    887733    if ( readHeader( NFCAL[i], sameEndian ) == -1 ) {
     
    889735      return -1 ;
    890736    }
    891     // DEBUG
    892 //     if ( i == 0 ) {
    893 //       cout << "NFCAL   " ;
    894 //     }
    895 //     else if ( ( i % 5 ) == 0 ) {
    896 //       cout << endl << "        " ;
    897 //     }
    898 //     cout << NFCAL[i] << " " ;
    899     //
    900   }
    901   //cout << endl ;
     737  }
     738  // DEBUG
     739//   nro_debug_output( "NFCAL", ASTE_ARYMAX, NFCAL ) ;
     740  //
    902741  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    903742    if ( readHeader( F0CAL[i], sameEndian ) == -1 ) {
     
    905744      return -1 ;
    906745    }
    907     // DEBUG
    908 //     if ( i == 0 ) {
    909 //       cout << "F0CAL   " ;
    910 //     }
    911 //     else if ( ( i % 5 ) == 0 ) {
    912 //       cout << endl << "        " ;
    913 //     }
    914 //     cout << F0CAL[i] << " " ;
    915     //
    916   }
    917   //cout << endl ;
     746  }
     747  // DEBUG
     748//   nro_debug_output( "F0CAL", ASTE_ARYMAX, F0CAL ) ;
     749  //
    918750  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    919751    for ( int j = 0 ; j < 10 ; j++ ) {
     
    922754        return -1 ;
    923755      }
    924       // DEBUG
    925 //       if ( j == 0 ) {
    926 //         if ( i < 10 )
    927 //           cout << "FQCAL0" << i << " " ;
    928 //         else
    929 //           cout << "FQCAL" << i << " " ;
    930 //       }
    931 //       else if ( ( j % 5 ) == 0 ) {
    932 //         cout << endl << "        " ;
    933 //       }
    934 //       cout << FQCAL[i][j] << " " ;
    935       //
    936     }
    937     //cout << endl ;
    938   }
     756    }
     757  }
     758  // DEBUG
     759//   nro_debug_output( "FQCAL", ASTE_ARYMAX, 10,  FQCAL ) ;
     760  //
    939761  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    940762    for ( int j = 0 ; j < 10 ; j++ ) {
     
    943765        return -1 ;
    944766      }
    945      // DEBUG
    946 //       if ( j == 0 ) {
    947 //         if ( i < 10 )
    948 //           cout << "CHCAL0" << i << " " ;
    949 //         else
    950 //           cout << "CHCAL" << i << " " ;
    951 //       }
    952 //       else if ( ( j % 5 ) == 0 ) {
    953 //         cout << endl << "        " ;
    954 //       }
    955 //       cout << CHCAL[i][j] << " " ;
    956      //
    957     }
    958     //cout << endl ;
    959   }
     767    }
     768  }
     769  // DEBUG
     770//   nro_debug_output( "CHCAL", ASTE_ARYMAX, 10, CHCAL ) ;
     771  //
    960772  for ( int i= 0 ; i < ASTE_ARYMAX ; i++) {
    961773    for ( int j = 0 ; j < 10 ; j++ ) {
     
    964776        return -1 ;
    965777      }
    966       // DEBUG
    967 //       if ( j == 0 ) {
    968 //         if ( i < 10 )
    969 //           cout << "CWCAL0" << i << " " ;
    970 //         else
    971 //           cout << "CWCAL" << i << " " ;
    972 //       }
    973 //       else if ( ( j % 5 ) == 0 ) {
    974 //         cout << endl << "        " ;
    975 //       }
    976 //       cout << CWCAL[i][j] << " " ;
    977       //
    978     }
    979     //cout << endl ;
    980   }
     778    }
     779  }
     780  // DEBUG
     781//   nro_debug_output( "CWCAL", ASTE_ARYMAX, 10, CWCAL ) ;
     782  //
    981783  if ( readHeader( SCNLEN, sameEndian ) == -1 ) {
    982784    os << LogIO::WARN << "Error while reading data SCNLEN." << LogIO::POST ;
     
    1024826      return -1 ;
    1025827    }
    1026     // DEBUG
    1027 //     if ( i == 0 ) {
    1028 //       cout << "DSBFC   " ;
    1029 //     }
    1030 //     else if ( ( i % 5 ) == 0 ) {
    1031 //       cout << endl << "        " ;
    1032 //     }
    1033 //     cout << DSBFC[i] << " " ;
    1034     //
    1035   }
    1036   //cout << endl ;
     828  }
     829  // DEBUG
     830//   nro_debug_output( "DSBFC", ASTE_ARYMAX, DSBFC ) ;
     831  //
     832
    1037833
    1038834  scanNum_ = NSCAN + 1 ; // includes ZERO scan
  • /trunk/external-alma/atnf/PKSIO/ASTEFXDataset.cc

    r2373 r2473  
    529529    c18[16] = '\0' ;
    530530    RX[i] = string( c18 ) ;
    531     // DEBUG
    532 //     if ( i == 0 ) {
    533 //       cout << "RX      " ;
    534 //     }
    535 //     else if ( ( i % 5 ) == 0 ) {
    536 //       cout << endl << "        " ;
    537 //     }
    538 //     cout << RX[i] << " " ;
    539     //
    540   }
    541   //cout << endl ;
     531  }
     532  // DEBUG
     533//   nro_debug_output( "RX", ASTE_ARYMAX_FX, RX ) ;
     534  //
    542535  for ( int i = 0 ; i < ASTE_ARYMAX_FX ; i++ ) {
    543536    if ( readHeader( HPBW[i], sameEndian ) == -1 ) {
     
    545538      return -1 ;
    546539    }
    547 //     // DEBUG
    548 //     if ( i == 0 ) {
    549 //       cout << "HPBW    " ;
    550 //     }
    551 //     else if ( ( i % 5 ) == 0 ) {
    552 //       cout << endl <    //cerr << "Error opening file " << filename_ << "." << endl ;< "        " ;
    553 //     }
    554 //     cout << HPBW[i] << " " ;
    555     //
    556   }
    557   //cout << endl ;
     540  }
     541  // DEBUG
     542//   nro_debug_output( "HPBW", ASTE_ARYMAX_FX, HPBW ) ;
     543  //
    558544  for ( int i = 0 ; i < ASTE_ARYMAX_FX ; i++ ) {
    559545    if ( readHeader( EFFA[i], sameEndian ) == -1 ) {
     
    561547      return -1 ;
    562548    }
    563     // DEBUG
    564 //     if ( i == 0 ) {
    565 //       cout << "EFFA    " ;
    566 //     }
    567 //     else if ( ( i % 5 ) == 0 ) {
    568 //       cout << endl << "        " ;
    569 //     }
    570 //     cout << EFFA[i] << " " ;
    571     //
    572   }
    573   //cout << endl ;
     549  }
     550  // DEBUG
     551//   nro_debug_output( "EFFA", ASTE_ARYMAX_FX, EFFA ) ;
     552  //
    574553  for ( int i = 0 ; i < ASTE_ARYMAX_FX ; i++ ) {
    575554    if ( readHeader( EFFB[i], sameEndian ) == -1 ) {
     
    577556      return -1 ;
    578557    }
    579     // DEBUG
    580 //     if ( i == 0 ) {
    581 //       cout << "EFFB    " ;
    582 //     }
    583 //     else if ( ( i % 5 ) == 0 ) {
    584 //       cout << endl << "        " ;
    585 //     }
    586 //     cout << EFFB[i] << " " ;
    587     //
    588   }
    589   //cout << endl ;
     558  }
     559  // DEBUG
     560//   nro_debug_output( "EFFB", ASTE_ARYMAX_FX, EFFB ) ;
     561  //
    590562  for ( int i = 0 ; i < ASTE_ARYMAX_FX ; i++ ) {
    591563    if ( readHeader( EFFL[i], sameEndian ) == -1 ) {
     
    593565      return -1 ;
    594566    }
    595     // DEBUG
    596 //     if ( i == 0 ) {
    597 //       cout << "EFFL    " ;
    598 //     }
    599 //     else if ( ( i % 5 ) == 0 ) {
    600 //       cout << endl << "        " ;
    601 //     }
    602 //     cout << EFFL[i] << " " ;
    603     //
    604   }
    605   //cout << endl ;
     567  }
     568  // DEBUG
     569//   nro_debug_output( "EFFL", ASTE_ARYMAX_FX, EFFL ) ;
     570  //
    606571  for ( int i = 0 ; i < ASTE_ARYMAX_FX ; i++ ) {
    607572    if ( readHeader( EFSS[i], sameEndian ) == -1 ) {
     
    609574      return -1 ;
    610575    }
    611     // DEBUG
    612 //     if ( i == 0 ) {
    613 //       cout << "EFSS    " ;
    614 //     }
    615 //     else if ( ( i % 5 ) == 0 ) {
    616 //       cout << endl << "        " ;
    617 //     }
    618 //     cout << EFSS[i] << " " ;
    619     //
    620   }
    621   //cout << endl ;
     576  }
     577  // DEBUG
     578//   nro_debug_output( "EFSS", ASTE_ARYMAX_FX, EFSS ) ;
     579  //
    622580  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    623581    if ( readHeader( GAIN[i], sameEndian ) == -1 ) {
     
    625583      return -1 ;
    626584    }
    627     // DEBUG
    628 //     if ( i == 0 ) {
    629 //       cout << "GAIN    " ;
    630 //     }
    631 //     else if ( ( i % 5 ) == 0 ) {
    632 //       cout << endl << "        " ;
    633 //     }
    634 //     cout << GAIN[i] << " " ;
    635     //
    636   }
    637   //cout << endl ;
     585  }
     586  // DEBUG
     587//   nro_debug_output( "GAIN", ASTE_ARYMAX_FX, GAIN ) ;
     588  //
    638589  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    639590    strcpy( c4, str4.c_str() ) ;
     
    643594    }
    644595    HORN[i] = string( c4 ) ;
    645     // DEBUG
    646 //     if ( i == 0 ) {
    647 //       cout << "HORN    " ;
    648 //     }
    649 //     else if ( ( i % 5 ) == 0 ) {
    650 //       cout << endl << "        " ;
    651 //     }
    652 //     cout << HORN[i] << " " ;
    653     //
    654   }
    655   //cout << endl ;
     596  }
     597  // DEBUG
     598//   nro_debug_output( "HORN", ASTE_ARYMAX_FX, HORN ) ;
     599  //
    656600  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    657601    strcpy( c4, str4.c_str() ) ;
     
    661605    }
    662606    POLTP[i] = string( c4 ) ;
    663     // DEBUG
    664 //     if ( i == 0 ) {
    665 //       cout << "POLTP   " ;
    666 //     }
    667 //     else if ( ( i % 5 ) == 0 ) {
    668 //       cout << endl << "        " ;
    669 //     }
    670 //     cout << POLTP[i] << " " ;
    671     //
    672   }
    673   //cout << endl ;
     607  }
     608  // DEBUG
     609//   nro_debug_output( "POLTP", ASTE_ARYMAX_FX, POLTP ) ;
     610  //
    674611  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    675612    if ( readHeader( POLDR[i], sameEndian ) == -1 ) {
     
    677614      return -1 ;
    678615    }
    679      // DEBUG
    680 //     if ( i == 0 ) {
    681 //       cout << "POLDR   " ;
    682 //     }
    683 //     else if ( ( i % 5 ) == 0 ) {
    684 //       cout << endl << "        " ;
    685 //     }
    686 //     cout << POLDR[i] << " " ;
    687     //
    688   }
    689   //cout << endl ;
     616  }
     617  // DEBUG
     618//   nro_debug_output( "POLDR", ASTE_ARYMAX_FX, POLDR ) ;
     619  //
    690620  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    691621    if ( readHeader( POLAN[i], sameEndian ) == -1 ) {
     
    693623      return -1 ;
    694624    }
    695     // DEBUG
    696 //     if ( i == 0 ) {
    697 //       cout << "POLAN   " ;
    698 //     }
    699 //     else if ( ( i % 5 ) == 0 ) {
    700 //       cout << endl << "        " ;
    701 //     }
    702 //     cout << POLAN[i] << " " ;
    703     //
    704   }
    705   //cout << endl ;
     625  }
     626  // DEBUG
     627//   nro_debug_output( "POLAN", ASTE_ARYMAX_FX, POLAN ) ;
     628  //
    706629  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    707630    if ( readHeader( DFRQ[i], sameEndian ) == -1 ) {
     
    709632      return -1 ;
    710633    }
    711     // DEBUG
    712 //     if ( i == 0 ) {
    713 //       cout << "DFRQ    " ;
    714 //     }
    715 //     else if ( ( i % 5 ) == 0 ) {
    716 //       cout << endl << "        " ;
    717 //     }
    718 //     cout << DFRQ[i] << " " ;
    719     //
    720   }
    721   //cout << endl ;
     634  }
     635  // DEBUG
     636//   nro_debug_output( "DFRQ", ASTE_ARYMAX_FX, DFRQ ) ;
     637  //
    722638  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    723639    strcpy( c4, str4.c_str() ) ;
     
    727643    }
    728644    SIDBD[i] = string( c4 ) ;
    729     // DEBUG
    730 //     if ( i == 0 ) {
    731 //       cout << "SIDBD   " ;
    732 //     }
    733 //     else if ( ( i % 5 ) == 0 ) {
    734 //       cout << endl << "        " ;
    735 //     }
    736 //     cout << SIDBD[i] << " " ;
    737     //
    738   }
    739   //cout << endl ;
     645  }
     646  // DEBUG
     647//   nro_debug_output( "SIDBD", ASTE_ARYMAX_FX, SIDBD ) ;
     648  //
    740649  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    741650    if ( readHeader( REFN[i], sameEndian ) == -1 ) {
     
    743652      return -1 ;
    744653    }
    745     // DEBUG
    746 //     if ( i == 0 ) {
    747 //       cout << "REFN    " ;
    748 //     }
    749 //     else if ( ( i % 5 ) == 0 ) {
    750 //       cout << endl << "        " ;
    751 //     }
    752 //     cout << REFN[i] << " " ;
    753     //
    754   }
    755   //cout << endl ;
     654  }
     655  // DEBUG
     656//   nro_debug_output( "REFN", ASTE_ARYMAX_FX, REFN ) ;
     657  //
    756658  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    757659    if ( readHeader( IPINT[i], sameEndian ) == -1 ) {
     
    759661      return -1 ;
    760662    }
    761     // DEBUG
    762 //     if ( i == 0 ) {
    763 //       cout << "IPINT   " ;
    764 //     }
    765 //     else if ( ( i % 5 ) == 0 ) {
    766 //       cout << endl << "        " ;
    767 //     }
    768 //     cout << IPINT[i] << " " ;
    769     //
    770   }
    771   //cout << endl ;
     663  }
     664  // DEBUG
     665//   nro_debug_output( "IPINT", ASTE_ARYMAX_FX, IPINT ) ;
     666  //
    772667  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    773668    if ( readHeader( MULTN[i], sameEndian ) == -1 ) {
     
    775670      return -1 ;
    776671    }
    777     // DEBUG
    778 //     if ( i == 0 ) {
    779 //       cout << "MULTN   " ;
    780 //     }
    781 //     else if ( ( i % 5 ) == 0 ) {
    782 //       cout << endl << "        " ;
    783 //     }
    784 //     cout << MULTN[i] << " " ;
    785     //
    786   }
    787   //cout << endl ;
     672  }
     673  // DEBUG
     674//   nro_debug_output( "MULTN", ASTE_ARYMAX_FX, MULTN ) ;
     675  //
    788676  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    789677    if ( readHeader( MLTSCF[i], sameEndian ) == -1 ) {
     
    791679      return -1 ;
    792680    }
    793     // DEBUG
    794 //     if ( i == 0 ) {
    795 //       cout << "MLTSCF  " ;
    796 //     }
    797 //     else if ( ( i % 5 ) == 0 ) {
    798 //       cout << endl << "        " ;
    799 //     }
    800 //     cout << MLTSCF[i] << " " ;
    801     //
    802   }
    803   //cout << endl ;
     681  }
     682  // DEBUG
     683//   nro_debug_output( "MLTSCF", ASTE_ARYMAX_FX, MLTSCF ) ;
     684  //
    804685  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    805686    strcpy( c8, str8.c_str() ) ;
     
    809690    }
    810691    LAGWIND[i] = string( c8 ) ;
    811     // DEBUG
    812 //     if ( i == 0 ) {
    813 //       cout << "LAGWIND " ;
    814 //     }
    815 //     else if ( ( i % 5 ) == 0 ) {
    816 //       cout << endl << "        " ;
    817 //     }
    818 //     cout << LAGWIND[i] << " " ;
    819     //
    820   }
    821   //cout << endl ;
     692  }
     693  // DEBUG
     694//   nro_debug_output( "LAGWIND", ASTE_ARYMAX_FX, LAGWIND ) ;
     695  //
    822696  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    823697    if ( readHeader( BEBW[i], sameEndian ) == -1 ) {
     
    825699      return -1 ;
    826700    }
    827     // DEBUG
    828 //     if ( i == 0 ) {
    829 //       cout << "BEBW    " ;
    830 //     }
    831 //     else if ( ( i % 5 ) == 0 ) {
    832 //       cout << endl << "        " ;
    833 //     }
    834 //     cout << BEBW[i] << " " ;
    835     //
    836   }
    837   //cout << endl ;
     701  }
     702  // DEBUG
     703//   nro_debug_output( "BEBW", ASTE_ARYMAX_FX, BEBW ) ;
     704  //
    838705  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    839706    if ( readHeader( BERES[i], sameEndian ) == -1 ) {
     
    841708      return -1 ;
    842709    }
    843     // DEBUG
    844 //     if ( i == 0 ) {
    845 //       cout << "BERES   " ;
    846 //     }
    847 //     else if ( ( i % 5 ) == 0 ) {
    848 //       cout << endl << "        " ;
    849 //     }
    850 //     cout << BERES[i] << " " ;
    851     //
    852   }
    853   //cout << endl ;
     710  }
     711  // DEBUG
     712//   nro_debug_output( "BERES", ASTE_ARYMAX_FX, BERES ) ;
     713  //
    854714  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    855715    if ( readHeader( CHWID[i], sameEndian ) == -1 ) {
     
    857717      return -1 ;
    858718    }
    859     // DEBUG
    860 //     if ( i == 0 ) {
    861 //       cout << "CHWID   " ;
    862 //     }
    863 //     else if ( ( i % 5 ) == 0 ) {
    864 //       cout << endl << "        " ;
    865 //     }
    866 //     cout << CHWID[i] << " " ;
    867     //
    868   }
    869   //cout << endl ;
     719  }
     720  // DEBUG
     721//   nro_debug_output( "CHWID", ASTE_ARYMAX_FX, CHWID ) ;
     722  //
    870723  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    871724    if ( readHeader( ARRY[i], sameEndian ) == -1 ) {
     
    873726      return -1 ;
    874727    }
    875     // DEBUG
    876 //     if ( i == 0 ) {
    877 //       cout << "ARRY    " ;
    878 //     }
    879 //     else if ( ( i % 5 ) == 0 ) {
    880 //       cout << endl << "        " ;
    881 //     }
    882 //     cout << ARRY[i] << " " ;
    883     //
    884   }
    885   //cout << endl ;
     728  }
     729  // DEBUG
     730//   nro_debug_output( "ARRY", ASTE_ARYMAX_FX, ARRY ) ;
     731  //
    886732  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    887733    if ( readHeader( NFCAL[i], sameEndian ) == -1 ) {
     
    889735      return -1 ;
    890736    }
    891     // DEBUG
    892 //     if ( i == 0 ) {
    893 //       cout << "NFCAL   " ;
    894 //     }
    895 //     else if ( ( i % 5 ) == 0 ) {
    896 //       cout << endl << "        " ;
    897 //     }
    898 //     cout << NFCAL[i] << " " ;
    899     //
    900   }
    901   //cout << endl ;
     737  }
     738  // DEBUG
     739//   nro_debug_output( "NFCAL", ASTE_ARYMAX_FX, NFCAL ) ;
     740  //
    902741  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    903742    if ( readHeader( F0CAL[i], sameEndian ) == -1 ) {
     
    905744      return -1 ;
    906745    }
    907     // DEBUG
    908 //     if ( i == 0 ) {
    909 //       cout << "F0CAL   " ;
    910 //     }
    911 //     else if ( ( i % 5 ) == 0 ) {
    912 //       cout << endl << "        " ;
    913 //     }
    914 //     cout << F0CAL[i] << " " ;
    915     //
    916   }
    917   //cout << endl ;
     746  }
     747  // DEBUG
     748//   nro_debug_output( "F0CAL", ASTE_ARYMAX_FX, F0CAL ) ;
     749  //
    918750  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    919751    for ( int j = 0 ; j < 10 ; j++ ) {
     
    922754        return -1 ;
    923755      }
    924       // DEBUG
    925 //       if ( j == 0 ) {
    926 //         if ( i < 10 )
    927 //           cout << "FQCAL0" << i << " " ;
    928 //         else
    929 //           cout << "FQCAL" << i << " " ;
    930 //       }
    931 //       else if ( ( j % 5 ) == 0 ) {
    932 //         cout << endl << "        " ;
    933 //       }
    934 //       cout << FQCAL[i][j] << " " ;
    935       //
    936     }
    937     //cout << endl ;
    938   }
     756    }
     757  }
     758  // DEBUG
     759//   nro_debug_output( "FQCAL", ASTE_ARYMAX_FX, 10, FQCAL ) ;
     760  //
    939761  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    940762    for ( int j = 0 ; j < 10 ; j++ ) {
     
    943765        return -1 ;
    944766      }
    945      // DEBUG
    946 //       if ( j == 0 ) {
    947 //         if ( i < 10 )
    948 //           cout << "CHCAL0" << i << " " ;
    949 //         else
    950 //           cout << "CHCAL" << i << " " ;
    951 //       }
    952 //       else if ( ( j % 5 ) == 0 ) {
    953 //         cout << endl << "        " ;
    954 //       }
    955 //      cout << CHCAL[i][j] << " " ;
    956      //
    957     }
    958     //cout << endl ;
    959   }
     767    }
     768  }
     769  // DEBUG
     770//   nro_debug_output( "CHCAL", ASTE_ARYMAX_FX, 10, CHCAL ) ;
     771  //
    960772  for ( int i= 0 ; i < ASTE_ARYMAX_FX ; i++) {
    961773    for ( int j = 0 ; j < 10 ; j++ ) {
     
    964776        return -1 ;
    965777      }
    966       // DEBUG
    967 //       if ( j == 0 ) {
    968 //         if ( i < 10 )
    969 //           cout << "CWCAL0" << i << " " ;
    970 //         else
    971 //           cout << "CWCAL" << i << " " ;
    972 //       }
    973 //       else if ( ( j % 5 ) == 0 ) {
    974 //         cout << endl << "        " ;
    975 //       }
    976 //       cout << CWCAL[i][j] << " " ;
    977       //
    978     }
    979     //cout << endl ;
    980   }
     778    }
     779  }
     780  // DEBUG
     781//   nro_debug_output( "CWCAL", ASTE_ARYMAX_FX, 10, CWCAL ) ;
     782  //
    981783  if ( readHeader( SCNLEN, sameEndian ) == -1 ) {
    982784    os << LogIO::WARN << "Error while reading data SCNLEN." << endl ;
     
    1024826      return -1 ;
    1025827    }
    1026      // DEBUG
    1027 //     if ( i == 0 ) {
    1028 //       cout << "DSBFC   " ;
    1029 //     }
    1030 //     else if ( ( i % 5 ) == 0 ) {
    1031 //       cout << endl << "        " ;
    1032 //     }
    1033 //     cout << DSBFC[i] << " " ;
    1034     //
    1035   }
    1036   //cout << endl ;
     828  }
     829  // DEBUG
     830//   nro_debug_output( "DSBFC", ASTE_ARYMAX_FX, DSBFC ) ;
     831  //
    1037832
    1038833  scanNum_ = NSCAN + 1 ; // includes ZERO scan
  • /trunk/external-alma/atnf/PKSIO/NRODataset.cc

    r2373 r2473  
    827827  return vlsr ;
    828828}
     829
     830uInt NRODataset::getPolNo( int i )
     831{
     832  int idx = getIndex( i ) ;
     833//   cout << "HORN[" << idx << "]=" << HORN[idx]
     834//        << ", RX[" << idx << "]=" << RX[idx] << endl ;
     835  return polNoFromRX( RX[idx].c_str() ) ;
     836}
     837
     838uInt NRODataset::polNoFromRX( const char *rx )
     839{
     840  uInt polno = 0 ;
     841  // 2012/03/15 TN
     842  // T100H/V is multi-polarization receiver which is installed
     843  // on NRO 45m telescope. Here, POLNO is assigned as follows:
     844  //
     845  //    POLNO=0: T100H
     846  //          1: T100V
     847  //
     848  // For other receivers, POLNO is always 0.
     849  if ( strncmp( rx, "T100V", 5 ) == 0 )
     850    polno = 1 ;
     851  return polno ;
     852}
  • /trunk/external-alma/atnf/PKSIO/NRODataset.h

    r2373 r2473  
    4444#include <atnf/PKSIO/NRODataRecord.h>
    4545#include <casa/namespace.h>
     46#include <casa/iomanip.h>
    4647
    4748#define SCAN_HEADER_SIZE 424
     
    200201  virtual vector<double> getFrequencies( int i ) ;
    201202  virtual uInt getArrayId( string type ) ;
     203  virtual uInt getPolNo( int irow ) ;
    202204
    203205 protected:
     
    238240  virtual double toLSR( double v, double t, double x, double y ) ;
    239241
     242  // POLNO from RX
     243  uInt polNoFromRX( const char *rx ) ;
     244
    240245  // Type of file record
    241246  string LOFIL ;
     
    518523} ;
    519524
     525// debug message output
     526template<class T> inline void nro_debug_output( char *name, int len, vector<T> &val )
     527{
     528  for ( int i = 0 ; i < len ; i++ ) {
     529    if ( i == 0 ) {
     530      cout << setw(8) << left << name ;
     531    }
     532    else if ( ( i % 5 ) == 0 ) {
     533      cout << endl << "        " ;
     534    }
     535    cout << "\'" << val[i] << "\' " ;
     536  }
     537  cout << endl ;
     538}
     539
     540template<class T> inline void nro_debug_output( char *name, int len1, int len2, vector< vector<T> > &val )
     541{
     542  for ( int i = 0 ; i < len1 ; i++ ) {
     543    for ( int j = 0 ; j < len2 ; j++ ) {
     544      if ( j == 0 ) {
     545        if ( i < 10 )
     546          cout << name << "0" << i << " " ;
     547        else
     548          cout << name << i << " " ;
     549      }
     550      else if ( ( j % 5 ) == 0 ) {
     551        cout << endl << "        " ;
     552      }
     553      cout << "\'" << val[i][j] << "\' " ;
     554    }
     555    cout << endl ;
     556  }
     557}
     558
    520559
    521560#endif /* NRO_HEADER_H */
  • /trunk/external-alma/atnf/PKSIO/NROFITSDataset.cc

    r2373 r2473  
    620620  }
    621621  // DEBUG
    622 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    623 //     if ( i == 0 ) {
    624 //       cout << "RX      " ;
    625 //     }
    626 //     else if ( ( i % 5 ) == 0 ) {
    627 //       cout << endl << "        " ;
    628 //     }
    629 //     cout << "\'" << RX[i] << "\' " ;
    630 //   }
    631 //   cout << endl ;
     622//   nro_debug_output( "RX", ARYNM, RX ) ;
    632623  //
    633624  if ( readColumn( HPBW, "HPBW", sameEndian ) != 0 ) {
     
    636627  }
    637628  // DEBUG
    638 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    639 //     if ( i == 0 ) {
    640 //       //cout << "HPBW    " ;
    641 //     }
    642 //     else if ( ( i % 5 ) == 0 ) {
    643 //       //cout << endl << "        " ;
    644 //     }
    645 //     //cout << HPBW[i] << " " ;
    646 //   }
    647 //   //cout << endl ;
     629//   nro_debug_output( "HPBW", ARYNM, HPBW ) ;
    648630  //
    649631  if ( readColumn( EFFA, "EFFA", sameEndian ) != 0 ) {
     
    652634  }
    653635  // DEBUG
    654 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    655 //     if ( i == 0 ) {
    656 //       //cout << "EFFA    " ;
    657 //     }
    658 //     else if ( ( i % 5 ) == 0 ) {
    659 //       //cout << endl << "        " ;
    660 //     }
    661 //     //cout << EFFA[i] << " " ;
    662 //   }
    663 //   //cout << endl ;
     636//   nro_debug_output( "EFFA", ARYNM, EFFA ) ;
    664637  //
    665638  if ( readColumn( EFFB, "EFFB", sameEndian ) != 0 ) {
     
    668641  }
    669642  // DEBUG
    670 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    671 //     if ( i == 0 ) {
    672 //       //cout << "EFFB    " ;
    673 //     }
    674 //     else if ( ( i % 5 ) == 0 ) {
    675 //       //cout << endl << "        " ;
    676 //     }
    677 //     //cout << EFFB[i] << " " ;
    678 //   }
    679 //   //cout << endl ;
     643//   nro_debug_output( "EFFB", ARYNM, EFFB ) ;
    680644  //
    681645  if ( readColumn( EFFL, "EFFL", sameEndian ) != 0 ) {
     
    684648  }
    685649  // DEBUG
    686 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    687 //     if ( i == 0 ) {
    688 //       //cout << "EFFL    " ;
    689 //     }
    690 //     else if ( ( i % 5 ) == 0 ) {
    691 //       //cout << endl << "        " ;
    692 //     }
    693 //     //cout << EFFL[i] << " " ;
    694 //   }
    695 //   //cout << endl ;
     650//   nro_debug_output( "EFFL", ARYNM, EFFL ) ;
    696651  //
    697652  if ( readColumn( EFSS, "EFSS", sameEndian ) != 0 ) {
     
    700655  }
    701656  // DEBUG
    702 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    703 //     if ( i == 0 ) {
    704 //       //cout << "EFSS    " ;
    705 //     }
    706 //     else if ( ( i % 5 ) == 0 ) {
    707 //       //cout << endl << "        " ;
    708 //     }
    709 //     //cout << EFSS[i] << " " ;
    710 //   }
    711 //   //cout << endl ;
     657//   nro_debug_output( "EFSS", ARYNM, EFSS ) ;
    712658  //
    713659  if ( readColumn( GAIN, "GAIN", sameEndian ) != 0 ) {
     
    716662  }
    717663  // DEBUG
    718 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    719 //     if ( i == 0 ) {
    720 //       //cout << "GAIN    " ;
    721 //     }
    722 //     else if ( ( i % 5 ) == 0 ) {
    723 //       //cout << endl << "        " ;
    724 //     }
    725 //     //cout << GAIN[i] << " " ;
    726 //   }
    727 //   //cout << endl ;
     664//   nro_debug_output( "GAIN", ARYNM, GAIN ) ;
    728665  //
    729666  if ( readColumn( HORN, "HORN" ) != 0 ) {
     
    732669  }
    733670  // DEBUG
    734 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    735 //     if ( i == 0 ) {
    736 //       //cout << "HORN    " ;
    737 //     }
    738 //     else if ( ( i % 5 ) == 0 ) {
    739 //       //cout << endl << "        " ;
    740 //     }
    741 //     //cout << "\'" << HORN[i] << "\' " ;
    742 //   }
    743 //   //cout << endl ;
     671//   nro_debug_output( "HORN", ARYNM, HORN ) ;
    744672  //
    745673  if ( readColumn( POLTP, "POLTP" ) != 0 ) {
     
    748676  }
    749677  // DEBUG
    750 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    751 //     if ( i == 0 ) {
    752 //       //cout << "POLTP   " ;
    753 //     }
    754 //     else if ( ( i % 5 ) == 0 ) {
    755 //       //cout << endl << "        " ;
    756 //     }
    757 //     //cout << "\'" << POLTP[i] << "\' " ;
    758 //   }
    759 //   //cout << endl ;
     678//   nro_debug_output( "POLTP", ARYNM, POLTP ) ;
    760679  //
    761680  vector<int> ipoldr( ARYNM, 0 ) ;
     
    767686    POLDR[i] = (double)ipoldr[i] ;
    768687  // DEBUG
    769 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    770 //     if ( i == 0 ) {
    771 //       //cout << "POLDR   " ;
    772 //     }
    773 //     else if ( ( i % 5 ) == 0 ) {
    774 //       //cout << endl << "        " ;
    775 //     }
    776 //     //cout << POLDR[i] << " " ;
    777 //   }
    778 //   //cout << endl ;
     688//   nro_debug_output( "POLDR", ARYNM, POLDR ) ;
    779689  //
    780690  if ( readColumn( POLAN, "POLAN", sameEndian ) != 0 ) {
     
    783693  }
    784694  // DEBUG
    785 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    786 //     if ( i == 0 ) {
    787 //       //cout << "POLAN   " ;
    788 //     }
    789 //     else if ( ( i % 5 ) == 0 ) {
    790 //       //cout << endl << "        " ;
    791 //     }
    792 //     //cout << POLAN[i] << " " ;
    793 //   }
    794 //   //cout << endl ;
     695//   nro_debug_output( "POLAN", ARYNM, POLAN ) ;
    795696  //
    796697  if ( readColumn( DFRQ, "DFRQ", sameEndian ) != 0 ) {
     
    799700  }
    800701  // DEBUG
    801 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    802 //     if ( i == 0 ) {
    803 //       //cout << "DFRQ    " ;
    804 //     }
    805 //     else if ( ( i % 5 ) == 0 ) {
    806 //       //cout << endl << "        " ;
    807 //     }
    808 //     //cout << DFRQ[i] << " " ;
    809 //   }
    810 //   //cout << endl ;
     702//   nro_debug_output( "DFRQ", ARYNM, DFRQ ) ;
    811703  //
    812704  if ( readColumn( SIDBD, "SIDBD" ) != 0 ) {
     
    815707  }
    816708  // DEBUG
    817 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    818 //     if ( i == 0 ) {
    819 //       //cout << "SIDBD   " ;
    820 //     }
    821 //     else if ( ( i % 5 ) == 0 ) {
    822 //       //cout << endl << "        " ;
    823 //     }
    824 //     //cout << "\'" << SIDBD[i] << "\' " ;
    825 //   }
    826 //   //cout << endl ;
     709//   nro_debug_output( "SIDBD", ARYNM, SIDBD ) ;
    827710  //
    828711  if ( readColumn( REFN, "REFN", sameEndian ) != 0 ) {
     
    831714  }
    832715  // DEBUG
    833 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    834 //     if ( i == 0 ) {
    835 //       //cout << "REFN    " ;
    836 //     }
    837 //     else if ( ( i % 5 ) == 0 ) {
    838 //       //cout << endl << "        " ;
    839 //     }
    840 //     //cout << REFN[i] << " " ;
    841 //   }
    842 //   //cout << endl ;
     716//   nro_debug_output( "REFN", ARYNM, REFN ) ;
    843717  //
    844718  if ( readColumn( IPINT, "IPINT", sameEndian ) != 0 ) {
     
    847721  }
    848722  // DEBUG
    849 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    850 //     if ( i == 0 ) {
    851 //       //cout << "IPINT   " ;
    852 //     }
    853 //     else if ( ( i % 5 ) == 0 ) {
    854 //       //cout << endl << "        " ;
    855 //     }
    856 //     //cout << IPINT[i] << " " ;
    857 //   }
    858 //   //cout << endl ;
     723//   nro_debug_output( "IPINT", ARYNM, IPINT ) ;
    859724  //
    860725  if ( readColumn( MULTN, "MULTN", sameEndian ) != 0 ) {
     
    863728  }
    864729  // DEBUG
    865 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    866 //     if ( i == 0 ) {
    867 //       //cout << "MULTN   " ;
    868 //     }
    869 //     else if ( ( i % 5 ) == 0 ) {
    870 //       //cout << endl << "        " ;
    871 //     }
    872 //     //cout << MULTN[i] << " " ;
    873 //   }
    874 //   //cout << endl ;
     730//   nro_debug_output( "MULTN", ARYNM, MULTN ) ;
    875731  //
    876732  if ( readColumn( MLTSCF, "MLTSCF", sameEndian ) != 0 ) {
     
    879735  }
    880736  // DEBUG
    881 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    882 //     if ( i == 0 ) {
    883 //       //cout << "MLTSCF  " ;
    884 //     }
    885 //     else if ( ( i % 5 ) == 0 ) {
    886 //       //cout << endl << "        " ;
    887 //     }
    888 //     //cout << MLTSCF[i] << " " ;
    889 //   }
    890 //   //cout << endl ;
     737//   nro_debug_output( "MLTSCF", ARYNM, MLTSCF ) ;
    891738  //
    892739  if ( readColumn( LAGWIND, "LAGWIN" ) != 0 ) {
     
    895742  }
    896743  // DEBUG
    897 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    898 //     if ( i == 0 ) {
    899 //       //cout << "LAGWIND " ;
    900 //     }
    901 //     else if ( ( i % 5 ) == 0 ) {
    902 //       //cout << endl << "        " ;
    903 //     }
    904 //     //cout << "\'" << LAGWIND[i] << "\' " ;
    905 //   }
    906 //   //cout << endl ;
     744//   nro_debug_output( "LAGWIND", ARYNM, LAGWIND ) ;
    907745  //
    908746  if ( readColumn( BEBW, "BEBW", sameEndian ) != 0 ) {
     
    911749  }
    912750  // DEBUG
    913 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    914 //     if ( i == 0 ) {
    915 //       //cout << "BEBW    " ;
    916 //     }
    917 //     else if ( ( i % 5 ) == 0 ) {
    918 //       //cout << endl << "        " ;
    919 //     }
    920 //     //cout << BEBW[i] << " " ;
    921 //   } 
    922 //   //cout << endl ;
     751//   nro_debug_output( "BEBW", ARYNM, BEBW ) ;
    923752  //
    924753  if ( readColumn( BERES, "BERES", sameEndian ) != 0 ) {
     
    927756  }
    928757  // DEBUG
    929 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    930 //     if ( i == 0 ) {
    931 //       //cout << "BERES   " ;
    932 //     }
    933 //     else if ( ( i % 5 ) == 0 ) {
    934 //       //cout << endl << "        " ;
    935 //     }
    936 //     //cout << BERES[i] << " " ;
    937 //   }
    938 //   //cout << endl ;
     758//   nro_debug_output( "BERES", ARYNM, BERES ) ;
    939759  //
    940760  if ( readColumn( CHWID, "CHWID", sameEndian ) != 0 ) {
     
    942762    return -1 ;
    943763  }
    944     // DEBUG
    945 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    946 //     if ( i == 0 ) {
    947 //       //cout << "CHWID   " ;
    948 //     }
    949 //     else if ( ( i % 5 ) == 0 ) {
    950 //       //cout << endl << "        " ;
    951 //     }
    952 //     //cout << CHWID[i] << " " ;
    953 //   }
    954 //   //cout << endl ;
     764  // DEBUG
     765//   nro_debug_output( "CHWID", ARYNM, CHWID ) ;
    955766  //
    956767  if ( readARRY() != 0 ) {
     
    959770  }
    960771  // DEBUG
    961 //   for ( int i = 0 ; i < NRO_FITS_ARYMAX ; i++ ) {
    962 //     if ( i == 0 ) {
    963 //       //cout << "ARRY    " ;
    964 //     }
    965 //     else if ( ( i % 20 ) == 0 ) {
    966 //       //cout << endl << "        " ;
    967 //     }
    968 //     //cout << ARRY[i] << " " ;
    969 //   }
    970 //   //cout << endl ;
     772//   nro_debug_output( "ARRY", NRO_FITS_ARYMAX, ARRY ) ;
    971773  //
    972774  if ( readColumn( NFCAL, "NFCAL", sameEndian ) != 0 ) {
     
    974776    return -1 ;
    975777  }
    976     // DEBUG
    977 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    978 //     if ( i == 0 ) {
    979 //       //cout << "NFCAL   " ;
    980 //     }
    981 //     else if ( ( i % 5 ) == 0 ) {
    982 //       //cout << endl << "        " ;
    983 //     }
    984 //     //cout << NFCAL[i] << " " ;
    985 //   }
    986 //   //cout << endl ;
     778  // DEBUG
     779//   nro_debug_output( "NFCAL", ARYNM, NFCAL ) ;
    987780  //
    988781  if ( readColumn( F0CAL, "F0CAL", sameEndian ) != 0 ) {
     
    990783    return -1 ;
    991784  }
    992     // DEBUG
    993 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    994 //     if ( i == 0 ) {
    995 //       //cout << "F0CAL   " ;
    996 //     }
    997 //     else if ( ( i % 5 ) == 0 ) {
    998 //       //cout << endl << "        " ;
    999 //     }
    1000 //     //cout << F0CAL[i] << " " ;
    1001 //   }
    1002 //   //cout << endl ;
     785  // DEBUG
     786//   nro_debug_output( "F0CAL", ARYNM, F0CAL ) ;
    1003787  //
    1004788  for ( int i= 0 ; i < 10 ; i++) {
     
    1013797  }
    1014798  // DEBUG
    1015 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    1016 //     for ( int j = 0 ; j < 10 ; j++ ) {
    1017 //       if ( j == 0 ) {
    1018 //         if ( i < 10 )
    1019 //           //cout << "FQCAL0" << i << " " ;
    1020 //         else
    1021 //           //cout << "FQCAL" << i << " " ;
    1022 //       }
    1023 //       else if ( ( j % 5 ) == 0 ) {
    1024 //         //cout << endl << "        " ;
    1025 //       }
    1026 //       //cout << FQCAL[i][j] << " " ;
    1027 //     }
    1028 //     //cout << endl ;
    1029 //   }
     799//   nro_debug_output( "FQCAL", ARYNM, 10, FQCAL ) ;
    1030800  //
    1031801  for ( int i= 0 ; i < 10 ; i++) {
     
    1040810  }
    1041811  // DEBUG
    1042 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    1043 //     for ( int j = 0 ; j < 10 ; j++ ) {
    1044 //       if ( j == 0 ) {
    1045 //         if ( i < 10 )
    1046 //           //cout << "CHCAL0" << i << " " ;
    1047 //         else
    1048 //           //cout << "CHCAL" << i << " " ;
    1049 //       }
    1050 //       else if ( ( j % 5 ) == 0 ) {
    1051 //         //cout << endl << "        " ;
    1052 //       }
    1053 //      //cout << CHCAL[i][j] << " " ;
    1054 //    }
    1055 //    //cout << endl ;
    1056 //   }
     812//   nro_debug_output( "CHCAL", ARYNM, 10, CHCAL ) ;
    1057813  //
    1058814  for ( int i= 0 ; i < 10 ; i++) {
     
    1067823  }
    1068824  // DEBUG
    1069 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    1070 //     for ( int j = 0 ; j < 10 ; j++ ) {
    1071 //       if ( j == 0 ) {
    1072 //         if ( i < 10 )
    1073 //           //cout << "CWCAL0" << i << " " ;
    1074 //         else
    1075 //           //cout << "CWCAL" << i << " " ;
    1076 //       }
    1077 //       else if ( ( j % 5 ) == 0 ) {
    1078 //         //cout << endl << "        " ;
    1079 //       }
    1080 //       //cout << CWCAL[i][j] << " " ;
    1081 //     }
    1082 //     //cout << endl ;
    1083 //   }
     825//   nro_debug_output( "CWCAL", ARYNM, 10, CWCAL ) ;
    1084826  //
    1085827  if ( readHeader( SCNLEN, "NAXIS1", sameEndian ) != 0 ) {
     
    1117859  }
    1118860  // DEBUG
    1119 //   for ( int i = 0 ; i < ARYNM ; i++ ) {
    1120 //     if ( i == 0 ) {
    1121 //       //cout << "DSBFC   " ;
    1122 //     }
    1123 //     else if ( ( i % 5 ) == 0 ) {
    1124 //       //cout << endl << "        " ;
    1125 //     }
    1126 //     //cout << DSBFC[i] << " " ;
    1127 //   }
    1128 //   //cout << endl ;
     861//   nro_debug_output( "DSBFC", ARYNM, DSBFC ) ;
    1129862  //
    1130863
     
    21971930}
    21981931
    2199 int NROFITSDataset::readTable( char *v, char *name )
    2200 {
    2201   //
    2202   // Read 'name' attribute defined as char from the 0-th row
    2203   // of the FITS Scan Record
    2204   //
    2205   int status = readTable( v, name, (int)strlen( v ), 0 ) ;
    2206 
    2207   return status ;
    2208 }
    2209 
    22101932int NROFITSDataset::readTable( char *v, char *name, int clen, int idx )
    22111933{
     
    22141936  // of the FITS Scan Record
    22151937  //
    2216   int status = 0 ;
    2217 
    2218   // skip header
    2219   fseek( fp_, FITS_HEADER_SIZE, SEEK_SET ) ;
    2220 
    2221   // find offset
    2222   int offset = getOffset( name ) ;
    2223   if ( offset == -1 ) {
    2224     //cerr << "Error, " << name << " is not found in the name list." << endl ;
    2225     return -1 ;
    2226   }
    2227   offset += idx * scanLen_ ;
    2228   //cout << "offset for " << name << " is " << offset << " bytes." << endl ;
    2229   fseek( fp_, offset, SEEK_CUR ) ;
     1938  int status = movePointer( name, idx ) ;
     1939  if ( status < 0 )
     1940    return status ;
    22301941
    22311942  // get length of char
     
    22541965}
    22551966
    2256 int NROFITSDataset::readTable( int &v, char *name, int b )
    2257 {
    2258   //
    2259   // Read 'name' attribute defined as int from the 0-th row
    2260   // of the FITS Scan Record
    2261   //
    2262   int status = readTable( v, name, b, 0 ) ;
    2263 
    2264   return status ;
    2265 }
    2266 
    22671967int NROFITSDataset::readTable( int &v, char *name, int b, int idx )
    22681968{
     
    22711971  // of the FITS Scan Record
    22721972  //
    2273   int status = 0 ;
    2274   // skip header
    2275   fseek( fp_, FITS_HEADER_SIZE, SEEK_SET ) ;
    2276 
    2277   // find offset
    2278   int offset = getOffset( name ) ;
    2279   if ( offset == -1 ) {
    2280     //cerr << "Error, " << name << " is not found in the name list." << endl ;
    2281     return -1 ;
    2282   }
    2283   offset += idx * scanLen_ ;
    2284   //cout << "offset for " << name << " is " << offset << " bytes." << endl ;
    2285   fseek( fp_, offset, SEEK_CUR ) ;
     1973  int status = movePointer( name, idx ) ;
     1974  if ( status < 0 )
     1975    return status ;
    22861976
    22871977  // read data
     
    22931983}
    22941984
    2295 int NROFITSDataset::readTable( float &v, char *name, int b )
    2296 {
    2297   //
    2298   // Read 'name' attribute defined as float from the 0-th row
    2299   // of the FITS Scan Record
    2300   //
    2301   int status = readTable( v, name, b, 0 ) ;
    2302 
    2303   return status ;
    2304 }
    2305 
    23061985int NROFITSDataset::readTable( float &v, char *name, int b, int idx )
    23071986{
     
    23101989  // of the FITS Scan Record
    23111990  //
    2312   int status = 0 ;
    2313 
    2314   // skip header
    2315   fseek( fp_, FITS_HEADER_SIZE, SEEK_SET ) ;
    2316 
    2317   // find offset
    2318   int offset = getOffset( name ) ;
    2319   if ( offset == -1 ) {
    2320     //cerr << "Error, " << name << " is not found in the name list." << endl ;
    2321     return -1 ;
    2322   }
    2323   offset += idx * scanLen_ ;
    2324   //cout << "offset for " << name << " is " << offset << " bytes." << endl ;
    2325   fseek( fp_, offset, SEEK_CUR ) ;
     1991  int status = movePointer( name, idx ) ;
     1992  if ( status < 0 )
     1993    return status ;
    23261994
    23271995  // read data
     
    23332001}
    23342002
    2335 int NROFITSDataset::readTable( double &v, char *name, int b )
    2336 {
    2337   //
    2338   // Read 'name' attribute defined as double from the 0-th row
    2339   // of the FITS Scan Record
    2340   //
    2341   int status = readTable( v, name, b, 0 ) ;
    2342 
    2343   return status ;
    2344 }
    2345 
    23462003int NROFITSDataset::readTable( double &v, char *name, int b, int idx )
    23472004{
     
    23502007  // of the FITS Scan Record
    23512008  //
    2352   int status = 0 ;
    2353 
    2354   // skip header
    2355   fseek( fp_, FITS_HEADER_SIZE, SEEK_SET ) ;
    2356 
    2357   // find offset
    2358   int offset = getOffset( name ) ;
    2359   if ( offset == -1 ) {
    2360     //cerr << "Error, " << name << " is not found in the name list." << endl ;
    2361     return -1 ;
    2362   }
    2363   offset += idx * scanLen_ ;
    2364   //cout << "offset for " << name << " is " << offset << " bytes." << endl ;
    2365   fseek( fp_, offset, SEEK_CUR ) ;
     2009  int status = movePointer( name, idx ) ;
     2010  if ( status < 0 )
     2011    return status ;
    23662012
    23672013  // read data
     
    23782024  // Read 'name' attribute defined as char array from the FITS Scan Record
    23792025  //
    2380   int status = 0 ;
    2381  
    2382   // skip header
    2383   fseek( fp_, FITS_HEADER_SIZE, SEEK_SET ) ;
    2384 
    2385   // find offset
    2386   int offset = getOffset( name ) ;
    2387   if ( offset == -1 ) {
    2388     //cerr << "Error, " << name << " is not found in the name list." << endl ;
    2389     return -1 ;
    2390   }
    2391   offset += idx * scanLen_ ;
    2392   //cout << "offset for " << name << " is " << offset << " bytes." << endl ;
    2393   fseek( fp_, offset, SEEK_CUR ) ;
     2026  int status = movePointer( name, idx ) ;
     2027  if ( status < 0 )
     2028    return status ;
    23942029
    23952030  // get length of char
     
    24262061  // Read 'name' attribute defined as int array from the FITS Scan Record
    24272062  //
    2428   int status = 0 ;
    2429  
    2430   // skip header
    2431   fseek( fp_, FITS_HEADER_SIZE, SEEK_SET ) ;
    2432 
    2433   // find offset
    2434   int offset = getOffset( name ) ;
    2435   if ( offset == -1 ) {
    2436     //cerr << "Error, " << name << " is not found in the name list." << endl ;
    2437     return -1 ;
    2438   }
    2439   offset += idx * scanLen_ ;
    2440   //cout << "offset for " << name << " is " << offset << " bytes." << endl ;
    2441   fseek( fp_, offset, SEEK_CUR ) ;
     2063  int status = movePointer( name, idx ) ;
     2064  if ( status < 0 )
     2065    return status ;
    24422066
    24432067  for ( unsigned int i = 0 ; i < v.size() ; i++ ) {
     
    24562080  // Read 'name' attribute defined as float array from the FITS Scan Record
    24572081  //
    2458   int status = 0 ;
    2459  
    2460   // skip header
    2461   fseek( fp_, FITS_HEADER_SIZE, SEEK_SET ) ;
    2462 
    2463   // find offset
    2464   int offset = getOffset( name ) ;
    2465   if ( offset == -1 ) {
    2466     //cerr << "Error, " << name << " is not found in the name list." << endl ;
    2467     return -1 ;
    2468   }
    2469   offset += idx * scanLen_ ;
    2470   //cout << "offset for " << name << " is " << offset << " bytes." << endl ;
    2471   fseek( fp_, offset, SEEK_CUR ) ;
     2082  int status = movePointer( name, idx ) ;
     2083  if ( status < 0 )
     2084    return status ;
    24722085
    24732086  for ( unsigned int i = 0 ; i < v.size() ; i++ ) {
     
    24862099  // Read 'name' attribute defined as double array from the FITS Scan Record
    24872100  //
    2488   int status = 0 ;
    2489  
    2490   // skip header
    2491   fseek( fp_, FITS_HEADER_SIZE, SEEK_SET ) ;
    2492 
    2493   // find offset
    2494   int offset = getOffset( name ) ;
    2495   if ( offset == -1 ) {
    2496     //cerr << "Error, " << name << " is not found in the name list." << endl ;
    2497     return -1 ;
    2498   }
    2499   offset += idx * scanLen_ ;
    2500   //cout << "offset for " << name << " is " << offset << " bytes." << endl ;
    2501   fseek( fp_, offset, SEEK_CUR ) ;
     2101  int status = movePointer( name, idx ) ;
     2102  if ( status < 0 )
     2103    return status ;
    25022104
    25032105  for ( unsigned int i = 0 ; i < v.size() ; i++ ) {
     
    25112113}
    25122114
    2513 int NROFITSDataset::readColumn( vector<string> &v, char *name )
    2514 {
    2515   //
    2516   // Read 0-th column of ARRYTP-dependent 'name' attributes
    2517   // defined as char array from the FITS Scan Record
    2518   //
    2519   int status = readColumn( v, name, 0 ) ;
    2520 
    2521   return status ;
    2522 }
    2523 
    25242115int NROFITSDataset::readColumn( vector<string> &v, char *name, int idx )
    25252116{
     
    25282119  // defined as char array from the FITS Scan Record
    25292120  //
    2530   int status = 0 ;
    2531 
    2532   // skip header
    2533   fseek( fp_, FITS_HEADER_SIZE, SEEK_SET ) ;
    2534 
    2535   // find offset
    2536   int offset = getOffset( name ) ;
    2537   if ( offset == -1 ) {
    2538     //cerr << "Error, " << name << " is not found in the name list." << endl ;
    2539     return -1 ;
    2540   }
    2541   //cout << "offset for " << name << " is " << offset << " bytes." << endl ;
    2542   fseek( fp_, offset, SEEK_CUR ) ;
     2121  int status = movePointer( name ) ;
     2122  if ( status < 0 )
     2123    return status ;
    25432124
    25442125  // get length of char
     
    25552136
    25562137  for ( unsigned int i = 0 ; i < v.size() ; i++ ) {
    2557     offset = scanLen_ * arrayid_[i] + xsize * idx ;
     2138    int offset = scanLen_ * arrayid_[i] + xsize * idx ;
    25582139    fseek( fp_, offset, SEEK_CUR ) ;
    25592140//     int clen = (int)strlen( v[i] ) ;
     
    25772158}
    25782159
    2579 int NROFITSDataset::readColumn( vector<int> &v, char *name, int b )
    2580 {
    2581   //
    2582   // Read 0-th column of ARRYTP-dependent 'name' attributes
    2583   // defined as int array from the FITS Scan Record
    2584   //
    2585   int status = readColumn( v, name, b, 0 ) ;
    2586 
    2587   return status ;
    2588 }
    2589 
    25902160int NROFITSDataset::readColumn( vector<int> &v, char *name, int b, int idx )
    25912161{
     
    25942164  // defined as int array from the FITS Scan Record
    25952165  //
    2596   int status = 0 ;
    2597 
    2598   // skip header
    2599   fseek( fp_, FITS_HEADER_SIZE, SEEK_SET ) ;
    2600 
    2601   // find offset
    2602   int offset = getOffset( name ) ;
    2603   if ( offset == -1 ) {
    2604     //cerr << "Error, " << name << " is not found in the name list." << endl ;
    2605     return -1 ;
    2606   }
    2607   //cout << "offset for " << name << " is " << offset << " bytes." << endl ;
    2608   fseek( fp_, offset, SEEK_CUR ) ;
     2166  int status = movePointer( name ) ;
     2167  if ( status < 0 )
     2168    return status ;
    26092169
    26102170  for ( unsigned int i = 0 ; i < v.size() ; i++ ) {
    2611     offset = scanLen_ * arrayid_[i] + sizeof(int) * idx ;
     2171    int offset = scanLen_ * arrayid_[i] + sizeof(int) * idx ;
    26122172    fseek( fp_, offset, SEEK_CUR ) ;
    26132173    fread( &v[i], 1, sizeof(int), fp_ ) ;
     
    26212181}
    26222182
    2623 int NROFITSDataset::readColumn( vector<float> &v, char *name, int b )
    2624 {
    2625   //
    2626   // Read 0-th column of ARRYTP-dependent 'name' attributes
    2627   // defined as float array from the FITS Scan Record
    2628   //
    2629   int status = readColumn( v, name, b, 0 ) ;
    2630 
    2631   return status ;
    2632 }
    2633 
    26342183int NROFITSDataset::readColumn( vector<float> &v, char *name, int b, int idx )
    26352184{
     
    26382187  // defined as float array from the FITS Scan Record
    26392188  //
    2640   int status = 0 ;
    2641 
    2642   // skip header
    2643   fseek( fp_, FITS_HEADER_SIZE, SEEK_SET ) ;
    2644 
    2645   // find offset
    2646   int offset = getOffset( name ) ;
    2647   if ( offset == -1 ) {
    2648     //cerr << "Error, " << name << " is not found in the name list." << endl ;
    2649     return -1 ;
    2650   }
    2651   //cout << "offset for " << name << " is " << offset << " bytes." << endl ;
    2652   fseek( fp_, offset, SEEK_CUR ) ;
     2189  int status = movePointer( name ) ;
     2190  if ( status < 0 )
     2191    return status ;
    26532192
    26542193  for ( unsigned int i = 0 ; i < v.size() ; i++ ) {
    2655     offset = scanLen_ * arrayid_[i] + sizeof(float) * idx ;
     2194    int offset = scanLen_ * arrayid_[i] + sizeof(float) * idx ;
    26562195    fseek( fp_, offset, SEEK_CUR ) ;
    26572196    fread( &v[i], 1, sizeof(float), fp_ ) ;
     
    26652204}
    26662205
    2667 int NROFITSDataset::readColumn( vector<double> &v, char *name, int b )
    2668 {
    2669   //
    2670   // Read 0-th column of ARRYTP-dependent 'name' attributes
    2671   // defined as double array from the FITS Scan Record
    2672   //
    2673   int status = readColumn( v, name, b, 0 ) ;
    2674 
    2675   return status ;
    2676 }
    2677 
    26782206int NROFITSDataset::readColumn( vector<double> &v, char *name, int b, int idx )
    26792207{
     
    26822210  // defined as double array from the FITS Scan Record
    26832211  //
    2684   int status = 0 ;
    2685 
    2686   // skip header
    2687   fseek( fp_, FITS_HEADER_SIZE, SEEK_SET ) ;
    2688 
    2689   // find offset
    2690   int offset = getOffset( name ) ;
    2691   if ( offset == -1 ) {
    2692     //cerr << "Error, " << name << " is not found in the name list." << endl ;
    2693     return -1 ;
    2694   }
    2695   //cout << "offset for " << name << " is " << offset << " bytes." << endl ;
    2696   fseek( fp_, offset, SEEK_CUR ) ;
     2212  int status = movePointer( name ) ;
     2213  if ( status < 0 )
     2214    return status ;
    26972215
    26982216  for ( unsigned int i = 0 ; i < v.size() ; i++ ) {
    2699     offset = scanLen_ * arrayid_[i] + sizeof(double) * idx ;
     2217    int offset = scanLen_ * arrayid_[i] + sizeof(double) * idx ;
    27002218    fseek( fp_, offset, SEEK_CUR ) ;
    27012219    fread( &v[i], 1, sizeof(double), fp_ ) ;
     
    27422260}
    27432261
     2262uInt NROFITSDataset::getPolNo( int irow )
     2263{
     2264  char rx[9] ;
     2265  readTable( rx, "RX", 8, irow ) ;
     2266  rx[8] = '\0' ;
     2267  //cout << rx << endl ;
     2268  return polNoFromRX( rx ) ;
     2269}
     2270
     2271int NROFITSDataset::movePointer( char *name, int idx )
     2272{
     2273  // find offset
     2274  int offset = getOffset( name ) ;
     2275  if ( offset == -1 ) {
     2276    //cerr << "Error, " << name << " is not found in the name list." << endl ;
     2277    return -1 ;
     2278  }
     2279
     2280  offset += idx * scanLen_ ;
     2281
     2282  //cout << "offset for " << name << " is " << offset << " bytes." << endl ;
     2283  fseek( fp_, FITS_HEADER_SIZE+offset, SEEK_SET ) ;
     2284
     2285  return 0 ;
     2286}
     2287
    27442288// double NROFITSDataset::toLSR( double v, double t, double x, double y )
    27452289// {
  • /trunk/external-alma/atnf/PKSIO/NROFITSDataset.h

    r2373 r2473  
    9797  virtual double getStartIntTime( int i ) ;
    9898  virtual double getScanTime( int i ) ;
     99  virtual uInt getPolNo( int irow ) ;
    99100
    100101 protected:
     
    104105  // Read char data
    105106  int readHeader( string &v, char *name ) ;
    106   int readTable( char *v, char *name ) ;
    107   int readTable( char *v, char *name, int clen, int idx ) ;
    108   int readTable( vector<char *> &v, char *name, int idx ) ;
    109   int readColumn( vector<string> &v, char *name ) ;
    110   int readColumn( vector<string> &v, char *name, int idx ) ;
     107  int readTable( char *v, char *name, int clen, int idx=0 ) ;
     108  int readTable( vector<char *> &v, char *name, int idx=0 ) ;
     109  int readColumn( vector<string> &v, char *name, int idx=0 ) ;
    111110
    112111  // Read int data
    113112  int readHeader( int &v, char *name, int b ) ;
    114   int readTable( int &v, char *name, int b ) ;
    115   int readTable( int &v, char *name, int b, int idx ) ;
    116   int readTable( vector<int> &v, char *name, int b, int idx ) ;
    117   int readColumn( vector<int> &v, char *name, int b ) ;
    118   int readColumn( vector<int> &v, char *name, int b, int idx ) ;
     113  int readTable( int &v, char *name, int b, int idx=0 ) ;
     114  int readTable( vector<int> &v, char *name, int b, int idx=0 ) ;
     115  int readColumn( vector<int> &v, char *name, int b, int idx=0 ) ;
    119116
    120117  // Read float data
    121118  int readHeader( float &v, char *name, int b ) ;
    122   int readTable( float &v, char *name, int b ) ;
    123   int readTable( float &v, char *name, int b, int idx ) ;
    124   int readTable( vector<float> &v, char *name, int b, int idx ) ;
    125   int readColumn( vector<float> &v, char *name, int b ) ;
    126   int readColumn( vector<float> &v, char *name, int b, int idx ) ;
     119  int readTable( float &v, char *name, int b, int idx=0 ) ;
     120  int readTable( vector<float> &v, char *name, int b, int idx=0 ) ;
     121  int readColumn( vector<float> &v, char *name, int b, int idx=0 ) ;
    127122
    128123  // Read double data
    129124  int readHeader( double &v, char *name, int b ) ;
    130   int readTable( double &v, char *name, int b ) ;
    131   int readTable( double &v, char *name, int b, int idx ) ;
    132   int readTable( vector<double> &v, char *name, int b, int idx ) ;
    133   int readColumn( vector<double> &v, char *name, int b ) ;
    134   int readColumn( vector<double> &v, char *name, int b, int idx ) ;
     125  int readTable( double &v, char *name, int b, int idx=0 ) ;
     126  int readTable( vector<double> &v, char *name, int b, int idx=0 ) ;
     127  int readColumn( vector<double> &v, char *name, int b, int idx=0 ) ;
    135128
    136129  // read ARRY
     
    154147  // get offset bytes for attributes
    155148  int getOffset( char *name ) ;
     149
     150  // move pointer to target position
     151  int movePointer( char *name, int idx=0 ) ;
    156152
    157153  // convert frequency frame
  • /trunk/external-alma/atnf/PKSIO/NROOTFDataset.cc

    r2373 r2473  
    535535    c18[16] = '\0' ;
    536536    RX[i] = string( c18 ) ;
    537     // DEBUG
    538 //     if ( i == 0 ) {
    539 //       cout << "RX      " ;
    540 //     }
    541 //     else if ( ( i % 5 ) == 0 ) {
    542 //       cout << endl << "        " ;
    543 //     }
    544 //     cout << RX[i] << " " ;
    545     //
    546   }
    547   //cout << endl ;
     537  }
     538  // DEBUG
     539//   nro_debug_output( "RX", NRO_ARYMAX, RX ) ;
     540  //
    548541  for ( int i = 0 ; i < NRO_ARYMAX ; i++ ) {
    549542    if ( readHeader( HPBW[i], sameEndian ) == -1 ) {
     
    551544      return -1 ;
    552545    }
    553     // DEBUG
    554 //     if ( i == 0 ) {
    555 //       cout << "HPBW    " ;
    556 //     }
    557 //     else if ( ( i % 5 ) == 0 ) {
    558 //       cout << endl << "        " ;
    559 //     }
    560 //     cout << HPBW[i] << " " ;
    561     //
    562   }
    563   //cout << endl ;
     546  }
     547  // DEBUG
     548//   nro_debug_output( "HPBW", NRO_ARYMAX, HPBW ) ;
     549  //
    564550  for ( int i = 0 ; i < NRO_ARYMAX ; i++ ) {
    565551    if ( readHeader( EFFA[i], sameEndian ) == -1 ) {
     
    567553      return -1 ;
    568554    }
    569     // DEBUG
    570 //     if ( i == 0 ) {
    571 //       cout << "EFFA    " ;
    572 //     }
    573 //     else if ( ( i % 5 ) == 0 ) {
    574 //       cout << endl << "        " ;
    575 //     }
    576 //     cout << EFFA[i] << " " ;
    577     //
    578   }
    579   //cout << endl ;
     555  }
     556  // DEBUG
     557//   nro_debug_output( "EFFA", NRO_ARYMAX, EFFA ) ;
     558  //
    580559  for ( int i = 0 ; i < NRO_ARYMAX ; i++ ) {
    581560    if ( readHeader( EFFB[i], sameEndian ) == -1 ) {
     
    583562      return -1 ;
    584563    }
    585     // DEBUG
    586 //     if ( i == 0 ) {
    587 //       cout << "EFFB    " ;
    588 //     }
    589 //     else if ( ( i % 5 ) == 0 ) {
    590 //       cout << endl << "        " ;
    591 //     }
    592 //     cout << EFFB[i] << " " ;
    593     //
    594   }
    595   //cout << endl ;
     564  }
     565  // DEBUG
     566//   nro_debug_output( "EFFB", NRO_ARYMAX, EFFB ) ;
     567  //
    596568  for ( int i = 0 ; i < NRO_ARYMAX ; i++ ) {
    597569    if ( readHeader( EFFL[i], sameEndian ) == -1 ) {
     
    599571      return -1 ;
    600572    }
    601     // DEBUG
    602 //     if ( i == 0 ) {
    603 //       cout << "EFFL    " ;
    604 //     }
    605 //     else if ( ( i % 5 ) == 0 ) {
    606 //       cout << endl << "        " ;
    607 //     }
    608 //     cout << EFFL[i] << " " ;
    609     //
    610   }
    611   //cout << endl ;
     573  }
     574  // DEBUG
     575//   nro_debug_output( "EFFL", NRO_ARYMAX, EFFL ) ;
     576  //
    612577  for ( int i = 0 ; i < NRO_ARYMAX ; i++ ) {
    613578    if ( readHeader( EFSS[i], sameEndian ) == -1 ) {
     
    615580      return -1 ;
    616581    }
    617     // DEBUG
    618 //     if ( i == 0 ) {
    619 //       cout << "EFSS    " ;
    620 //     }
    621 //     else if ( ( i % 5 ) == 0 ) {
    622 //       cout << endl << "        " ;
    623 //     }
    624 //     cout << EFSS[i] << " " ;
    625     //
    626   }
    627   //cout << endl ;
     582  }
     583  // DEBUG
     584//   nro_debug_output( "EFSS", NRO_ARYMAX, EFSS ) ;
     585  //
    628586  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    629587    if ( readHeader( GAIN[i], sameEndian ) == -1 ) {
     
    631589      return -1 ;
    632590    }
    633     // DEBUG
    634 //     if ( i == 0 ) {
    635 //       cout << "GAIN    " ;
    636 //     }
    637 //     else if ( ( i % 5 ) == 0 ) {
    638 //       cout << endl << "        " ;
    639 //     }
    640 //     cout << GAIN[i] << " " ;
    641     //
    642   }
    643   //cout << endl ;
     591  }
     592  // DEBUG
     593//   nro_debug_output( "GAIN", NRO_ARYMAX, GAIN ) ;
     594  //
    644595  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    645596    strcpy( c4, str4.c_str() ) ;
     
    649600    }
    650601    HORN[i] = string( c4 ) ;
    651     // DEBUG
    652 //     if ( i == 0 ) {
    653 //       cout << "HORN    " ;
    654 //     }
    655 //     else if ( ( i % 5 ) == 0 ) {
    656 //       cout << endl << "        " ;
    657 //     }
    658 //     cout << HORN[i] << " " ;
    659     //
    660   }
    661   //cout << endl ;
     602  }
     603  // DEBUG
     604//   nro_debug_output( "HORN", NRO_ARYMAX, HORN ) ;
     605  //
    662606  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    663607    strcpy( c4, str4.c_str() ) ;
     
    667611    }
    668612    POLTP[i] = string( c4 ) ;
    669     // DEBUG
    670 //     if ( i == 0 ) {
    671 //       cout << "POLTP   " ;
    672 //     }
    673 //     else if ( ( i % 5 ) == 0 ) {
    674 //       cout << endl << "        " ;
    675 //     }
    676 //     cout << POLTP[i] << " " ;
    677     //
    678   }
    679   //cout << endl ;
     613  }
     614  // DEBUG
     615//   nro_debug_output( "POLTP", NRO_ARYMAX, POLTP ) ;
     616  //
    680617  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    681618    if ( readHeader( POLDR[i], sameEndian ) == -1 ) {
     
    683620      return -1 ;
    684621    }
    685     // DEBUG
    686 //     if ( i == 0 ) {
    687 //       cout << "POLDR   " ;
    688 //     }
    689 //     else if ( ( i % 5 ) == 0 ) {
    690 //       cout << endl << "        " ;
    691 //     }
    692 //     cout << POLDR[i] << " " ;
    693     //
    694   }
    695   //cout << endl ;
     622  }
     623  // DEBUG
     624//   nro_debug_output( "POLDR", NRO_ARYMAX, POLDR ) ;
     625  //
    696626  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    697627    if ( readHeader( POLAN[i], sameEndian ) == -1 ) {
     
    699629      return -1 ;
    700630    }
    701     // DEBUG
    702 //     if ( i == 0 ) {
    703 //       cout << "POLAN   " ;
    704 //     }
    705 //     else if ( ( i % 5 ) == 0 ) {
    706 //       cout << endl << "        " ;
    707 //     }
    708 //     cout << POLAN[i] << " " ;
    709     //
    710   }
    711   //cout << endl ;
     631  }
     632  // DEBUG
     633//   nro_debug_output( "POLAN", NRO_ARYMAX, POLAN ) ;
     634  //
    712635  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    713636    if ( readHeader( DFRQ[i], sameEndian ) == -1 ) {
     
    715638      return -1 ;
    716639    }
    717     // DEBUG
    718 //     if ( i == 0 ) {
    719 //       cout << "DFRQ    " ;
    720 //     }
    721 //     else if ( ( i % 5 ) == 0 ) {
    722 //       cout << endl << "        " ;
    723 //     }
    724 //     cout << DFRQ[i] << " " ;
    725     //
    726   }
    727   //cout << endl ;
     640  }
     641  // DEBUG
     642//   nro_debug_output( "DFRQ", NRO_ARYMAX, DFRQ ) ;
     643  //
    728644  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    729645    strcpy( c4, str4.c_str() ) ;
     
    733649    }
    734650    SIDBD[i] = string( c4 ) ;
    735     // DEBUG
    736 //     if ( i == 0 ) {
    737 //       cout << "SIDBD   " ;
    738 //     }
    739 //     else if ( ( i % 5 ) == 0 ) {
    740 //       cout << endl << "        " ;
    741 //     }
    742 //     cout << SIDBD[i] << " " ;
    743     //
    744   }
    745   //cout << endl ;
     651  }
     652  // DEBUG
     653//   nro_debug_output( "SIDBD", NRO_ARYMAX, SIDBD ) ;
     654  //
    746655  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    747656    if ( readHeader( REFN[i], sameEndian ) == -1 ) {
     
    749658      return -1 ;
    750659    }
    751     // DEBUG
    752 //     if ( i == 0 ) {
    753 //       cout << "REFN    " ;
    754 //     }
    755 //     else if ( ( i % 5 ) == 0 ) {
    756 //       cout << endl << "        " ;
    757 //     }
    758 //     cout << REFN[i] << " " ;
    759     //
    760   }
    761   //cout << endl ;
     660  }
     661  // DEBUG
     662//   nro_debug_output( "REFN", NRO_ARYMAX, REFN ) ;
     663  //
    762664  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    763665    if ( readHeader( IPINT[i], sameEndian ) == -1 ) {
     
    765667      return -1 ;
    766668    }
    767     // DEBUG
    768 //     if ( i == 0 ) {
    769 //       cout << "IPINT   " ;
    770 //     }
    771 //     else if ( ( i % 5 ) == 0 ) {
    772 //       cout << endl << "        " ;
    773 //     }
    774 //     cout << IPINT[i] << " " ;
    775     //
    776   }
    777   //cout << endl ;
     669  }
     670  // DEBUG
     671//   nro_debug_output( "IPINT", NRO_ARYMAX, IPINT ) ;
     672  //
    778673  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    779674    if ( readHeader( MULTN[i], sameEndian ) == -1 ) {
     
    781676      return -1 ;
    782677    }
    783     // DEBUG
    784 //     if ( i == 0 ) {
    785 //       cout << "MULTN   " ;
    786 //     }
    787 //     else if ( ( i % 5 ) == 0 ) {
    788 //       cout << endl << "        " ;
    789 //     }
    790 //     cout << MULTN[i] << " " ;
    791     //
    792   }
    793   //cout << endl ;
     678  }
     679  // DEBUG
     680//   nro_debug_output( "MULTN", NRO_ARYMAX, MULTN ) ;
     681  //
    794682  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    795683    if ( readHeader( MLTSCF[i], sameEndian ) == -1 ) {
     
    797685      return -1 ;
    798686    }
    799     // DEBUG
    800 //     if ( i == 0 ) {
    801 //       cout << "MLTSCF  " ;
    802 //     }
    803 //     else if ( ( i % 5 ) == 0 ) {
    804 //       cout << endl << "        " ;
    805 //     }
    806 //     cout << MLTSCF[i] << " " ;
    807     //
    808   }
    809   //cout << endl ;
     687  }
     688  // DEBUG
     689//   nro_debug_output( "MLTSCF", NRO_ARYMAX, MLTSCF ) ;
     690  //
    810691  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    811692    strcpy( c8, str8.c_str() ) ;
     
    815696    }
    816697    LAGWIND[i] = string( c8 ) ;
    817     // DEBUG
    818 //     if ( i == 0 ) {
    819 //       cout << "LAGWIND " ;
    820 //     }
    821 //     else if ( ( i % 5 ) == 0 ) {
    822 //       cout << endl << "        " ;
    823 //     }
    824 //     cout << LAGWIND[i] << " " ;
    825     //
    826   }
    827   //cout << endl ;
     698  }
     699  // DEBUG
     700//   nro_debug_output( "LAGWIND", NRO_ARYMAX, LAGWIND ) ;
     701  //
    828702  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    829703    if ( readHeader( BEBW[i], sameEndian ) == -1 ) {
     
    831705      return -1 ;
    832706    }
    833     // DEBUG
    834 //     if ( i == 0 ) {
    835 //       cout << "BEBW    " ;
    836 //     }
    837 //     else if ( ( i % 5 ) == 0 ) {
    838 //       cout << endl << "        " ;
    839 //     }
    840 //     cout << BEBW[i] << " " ;
    841     //
    842   }
    843   //cout << endl ;
     707  }
     708  // DEBUG
     709//   nro_debug_output( "BEBW", NRO_ARYMAX, BEBW ) ;
     710  //
    844711  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    845712    if ( readHeader( BERES[i], sameEndian ) == -1 ) {
     
    847714      return -1 ;
    848715    }
    849     // DEBUG
    850 //     if ( i == 0 ) {
    851 //       cout << "BERES   " ;
    852 //     }
    853 //     else if ( ( i % 5 ) == 0 ) {
    854 //       cout << endl << "        " ;
    855 //     }
    856 //     cout << BERES[i] << " " ;
    857     //
    858   }
    859   //cout << endl ;
     716  }
     717  // DEBUG
     718//   nro_debug_output( "BERES", NRO_ARYMAX, BERES ) ;
     719  //
    860720  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    861721    if ( readHeader( CHWID[i], sameEndian ) == -1 ) {
     
    863723      return -1 ;
    864724    }
    865     // DEBUG
    866 //     if ( i == 0 ) {
    867 //       cout << "CHWID   " ;
    868 //     }
    869 //     else if ( ( i % 5 ) == 0 ) {
    870 //       cout << endl << "        " ;
    871 //     }
    872 //     cout << CHWID[i] << " " ;
    873     //
    874   }
    875   //cout << endl ;
     725  }
     726  // DEBUG
     727//   nro_debug_output( "CHWID", NRO_ARYMAX, CHWID ) ;
     728  //
    876729  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    877730    if ( readHeader( ARRY[i], sameEndian ) == -1 ) {
     
    879732      return -1 ;
    880733    }
    881     // DEBUG
    882 //     if ( i == 0 ) {
    883 //       cout << "ARRY    " ;
    884 //     }
    885 //     else if ( ( i % 5 ) == 0 ) {
    886 //       cout << endl << "        " ;
    887 //     }
    888 //     cout << ARRY[i] << " " ;
    889     //
    890   }
    891   //cout << endl ;
     734  }
     735  // DEBUG
     736//   nro_debug_output( "ARRY", NRO_ARYMAX, ARRY ) ;
     737  //
    892738  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    893739    if ( readHeader( NFCAL[i], sameEndian ) == -1 ) {
     
    895741      return -1 ;
    896742    }
    897     // DEBUG
    898 //     if ( i == 0 ) {
    899 //       cout << "NFCAL   " ;
    900 //     }
    901 //     else if ( ( i % 5 ) == 0 ) {
    902 //       cout << endl << "        " ;
    903 //     }
    904 //     cout << NFCAL[i] << " " ;
    905     //
    906   }
    907   //cout << endl ;
     743  }
     744  // DEBUG
     745//   nro_debug_output( "NFCAL", NRO_ARYMAX, NFCAL ) ;
     746  //
    908747  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    909748    if ( readHeader( F0CAL[i], sameEndian ) == -1 ) {
     
    911750      return -1 ;
    912751    }
    913     // DEBUG
    914 //     if ( i == 0 ) {
    915 //       cout << "F0CAL   " ;
    916 //     }
    917 //     else if ( ( i % 5 ) == 0 ) {
    918 //       cout << endl << "        " ;
    919 //     }
    920 //     cout << F0CAL[i] << " " ;
    921     //
    922   }
    923   //cout << endl ;
     752  }
     753  // DEBUG
     754//   nro_debug_output( "F0CAL", NRO_ARYMAX, F0CAL ) ;
     755  //
    924756  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    925757    for ( int j = 0 ; j < 10 ; j++ ) {
     
    928760        return -1 ;
    929761      }
    930       // DEBUG
    931 //       if ( j == 0 ) {
    932 //         if ( i < 10 )
    933 //           cout << "FQCAL0" << i << " " ;
    934 //         else
    935 //           cout << "FQCAL" << i << " " ;
    936 //       }
    937 //       else if ( ( j % 5 ) == 0 ) {
    938 //         cout << endl << "        " ;
    939 //       }
    940 //       cout << FQCAL[i][j] << " " ;
    941       //
    942     }
    943     //cout << endl ;
    944   }
     762    }
     763  }
     764  // DEBUG
     765//   nro_debug_output( "FQCAL", NRO_ARYMAX, 10, FQCAL ) ;
     766  // 
    945767  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    946768    for ( int j = 0 ; j < 10 ; j++ ) {
     
    949771        return -1 ;
    950772      }
    951      // DEBUG
    952 //       if ( j == 0 ) {
    953 //         if ( i < 10 )
    954 //           cout << "CHCAL0" << i << " " ;
    955 //         else
    956 //           cout << "CHCAL" << i << " " ;
    957 //       }
    958 //       else if ( ( j % 5 ) == 0 ) {
    959 //         cout << endl << "        " ;
    960 //       }
    961 //       cout << CHCAL[i][j] << " " ;
    962      //
    963     }
    964     //cout << endl ;
    965   }
     773    }
     774  }
     775  // DEBUG
     776//   nro_debug_output( "CHCAL", NRO_ARYMAX, 10, CHCAL ) ;
     777  // 
    966778  for ( int i = 0 ; i < NRO_ARYMAX ; i++) {
    967779    for ( int j = 0 ; j < 10 ; j++ ) {
     
    970782        return -1 ;
    971783      }
    972       // DEBUG
    973 //       if ( j == 0 ) {
    974 //         if ( i < 10 )
    975 //           cout << "CWCAL0" << i << " " ;
    976 //         else
    977 //           cout << "CWCAL" << i << " " ;
    978 //       }
    979 //       else if ( ( j % 5 ) == 0 ) {
    980 //         cout << endl << "        " ;
    981 //       }
    982 //       cout << CWCAL[i][j] << " " ;
    983       //
    984     }
    985     //cout << endl ;
    986   }
     784    }
     785  }
     786  // DEBUG
     787//   nro_debug_output( "CWCAL", NRO_ARYMAX, 10, CWCAL ) ;
     788  // 
    987789  if ( readHeader( SCNLEN, sameEndian ) == -1 ) {
    988790    os << LogIO::WARN << "Error while reading data SCNLEN." << LogIO::POST ;
  • /trunk/external-alma/atnf/PKSIO/NROReader.cc

    r2373 r2473  
    582582
    583583  // polno
    584   polno = 0 ;
     584  polno = dataset_->getPolNo( irow ) ;
    585585  //cout << "polno = " << polno << endl ;
    586586
  • /trunk/external-alma/oldasdm2ASAP/OldASDMFiller.cc

    r2373 r2473  
    7676  Vector<casa::Double> antpos = table_->getHeader().antennaposition ;
    7777
    78   //STHeader hdr = table_->getHeader() ;
    79  
    8078  // data selection
    8179  reader_->select() ;
     
    103101
    104102  // CYCLENO
    105   //unsigned int cycleno = 0 ;
    106103  map< unsigned int, unsigned int > cycleno ;
    107104  map< unsigned int, unsigned int >::iterator citer ;
     
    111108      //logsink_->postLocally( LogMessage("start configDescId "+String::toString(configDescIdList[icon])+" fieldId "+String::toString(fieldIdList[ifield]),LogOrigin(className_,funcName,WHERE)) ) ;
    112109
    113       //Bool status = reader_->setMainRow( configDescIdList[icon], fieldIdList[ifield] ) ;
    114110      if ( !(reader_->setMainRow( configDescIdList[icon], fieldIdList[ifield] )) ) {
    115111        //logsink_->postLocally( LogMessage("skip configDescId "+String::toString(configDescIdList[icon])+" fieldId "+String::toString(fieldIdList[ifield]),LogOrigin(className_,funcName,WHERE)) ) ;
     
    132128
    133129        // scan and subscan
    134         //unsigned int scanno = reader_->getScanNo() ;
    135130        unsigned int scanno = reader_->getScanNoOfCurrentRow() ;
    136         //uInt subscanno = reader_->getSubscanNo() ;
    137131        citer = cycleno.find( scanno ) ;
    138132        if ( citer == cycleno.end() )
     
    157151
    158152          // subscan number
    159           //unsigned int subscanno = reader_->getSubscanNo( idata ) ;
    160153          unsigned int subscanno = reader_->getSubscanNo() ;
    161154
    162155          // IFNO
    163           //uInt ifno = reader_->getIFNo( idata ) ;
    164156          uInt ifno = reader_->getIFNo() ;
    165157
     
    172164          double sysVel ;
    173165          vector<double> rf ;
    174           //reader_->getSourceProperty( idata,
    175           //                            srcname,
    176           //                            fieldname,
    177           //                            srcDirection,
    178           //                            srcProperMotion,
    179           //                            sysVel,
    180           //                            rf ) ;
    181166          reader_->getSourceProperty( srcname,
    182167                                      fieldname,
     
    193178         
    194179          // time and interval
    195           //casa::Double mjd = (casa::Double)(reader_->getTime( idata )) ;
    196           //casa::Double interval = (casa::Double)(reader_->getInterval( idata )) ;
    197180          casa::Double mjd = (casa::Double)(reader_->getTime()) ;
    198181          casa::Double interval = (casa::Double)(reader_->getInterval()) ;
     
    211194
    212195          // fill FLAGROW
    213           //unsigned int flagrow = reader_->getFlagRow( idata ) ;
    214196          unsigned int flagrow = reader_->getFlagRow() ;
    215197          setFlagrow( (uInt)flagrow ) ;
     
    221203          float windspeed ;
    222204          float windaz ;
    223           //reader_->getWeatherInfo( idata,
    224           //                         temperature,
    225           //                         pressure,
    226           //                         humidity,
    227           //                         windspeed,
    228           //                         windaz ) ;
    229205          reader_->getWeatherInfo( temperature,
    230206                                   pressure,
     
    243219          double el ;
    244220          vector<double> srate ;
    245           //reader_->getPointingInfo( idata,
    246           //                          dir,
    247           //                          az,
    248           //                          el,
    249           //                          srate ) ;
    250221          reader_->getPointingInfo( dir,
    251222                                    az,
     
    275246          }
    276247          else {
    277             //reader_->getFrequency( idata, refpix, refval, incr, freqref ) ;
    278248            reader_->getFrequency( refpix, refval, incr, freqref ) ;
    279249            refval = (double)toLSRK( casa::Double(refval),
     
    291261
    292262          // loop on polarization
    293           //vector<unsigned int> dataShape = reader_->getDataShape( idata ) ;
    294263          vector<unsigned int> dataShape = reader_->getDataShape() ;
    295264//           ostringstream oss ;
     
    304273          //logsink_->postLocally( LogMessage(oss.str(),LogOrigin(className_,funcName,WHERE)) ) ;
    305274                                     
    306           //int numPol = reader_->getNumPol( idata ) ;
    307275          unsigned int numPol = dataShape[0] ;
    308276          unsigned int numChan = dataShape[1] ;
     
    311279
    312280          // OPACITY
    313           //vector<float> tau = reader_->getOpacity( idata ) ;
    314281          vector<float> tau = reader_->getOpacity() ;
    315282          Vector<casa::Float> opacity = toVector( tau, numPol ) ;
    316283
    317284          // SPECTRA, FLAGTRA, TSYS, TCAL
    318           //float *sp = reader_->getSpectrum( idata ) ;
    319285          float *sp = reader_->getSpectrum() ;
    320286          vector< vector<float> > ts ;
    321287          vector< vector<float> > tc ;
    322           //reader_->getTcalAndTsys( idata, tc, ts ) ;
    323288          reader_->getTcalAndTsys( tc, ts ) ;
    324289          Matrix<casa::Float> spectra = toMatrix( sp, numPol, numChan ) ;
  • /trunk/python/asapfitter.py

    r2373 r2473  
    151151                self.x = self.data._getabcissa(row)
    152152                self.y = self.data._getspectrum(row)
    153                 self.mask = mask_and(self.mask, self.data._getmask(row))
     153                #self.mask = mask_and(self.mask, self.data._getmask(row))
     154                if len(self.x) == len(self.mask):
     155                    self.mask = mask_and(self.mask, self.data._getmask(row))
     156                else:
     157                    asaplog.push('lengths of data and mask are not the same. preset mask will be ignored')
     158                    asaplog.post('WARN','asapfit.fit')
     159                    self.mask=self.data._getmask(row)
    154160                asaplog.push("Fitting:")
    155161                i = row
     
    538544            return
    539545        if not self._p or self._p.is_dead:
    540             #if rcParams['plotter.gui']:
    541             #    from asap.asaplotgui import asaplotgui as asaplot
    542             #else:
    543             #    from asap.asaplot import asaplot
    544             #self._p = asaplot()
    545546            from asap.asapplotter import new_asaplot
     547            del self._p
    546548            self._p = new_asaplot(rcParams['plotter.gui'])
    547549        self._p.hold()
     
    659661            self.x = scan._getabcissa(r)
    660662            self.y = scan._getspectrum(r)
    661             self.mask = mask_and(self.mask, scan._getmask(r))
     663            #self.mask = mask_and(self.mask, scan._getmask(r))
     664            if len(self.x) == len(self.mask):
     665                self.mask = mask_and(self.mask, self.data._getmask(row))
     666            else:
     667                asaplog.push('lengths of data and mask are not the same. preset mask will be ignored')
     668                asaplog.post('WARN','asapfit.fit')
     669                self.mask=self.data._getmask(row)
    662670            self.data = None
    663671            self.fit()
  • /trunk/python/asapgrid.py

    r2373 r2473  
    88
    99class asapgrid:
     10    """
     11    The asapgrid class is defined to convolve data onto regular
     12    spatial grid. Typical usage is as follows:
     13
     14       # create asapgrid instance with two input data
     15       g = asapgrid( ['testimage1.asap','testimage2.asap'] )
     16       # set IFNO if necessary
     17       g.setIF( 0 )
     18       # set POLNOs if necessary
     19       g.setPolList( [0,1] )
     20       # set SCANNOs if necessary
     21       g.setScanList( [22,23,24] )
     22       # define image with full specification
     23       # you can skip some parameters (see help for defineImage)
     24       g.defineImage( nx=12, ny=12, cellx='10arcsec', celly='10arcsec',
     25                      center='J2000 10h10m10s -5d05m05s' )
     26       # set convolution function
     27       g.setFunc( func='sf', width=3 )
     28       # enable min/max clipping
     29       g.enableClip()
     30       # or, disable min/max clipping
     31       #g.disableClip()
     32       # actual gridding
     33       g.grid()
     34       # save result
     35       g.save( outfile='grid.asap' )
     36       # plot result
     37       g.plot( plotchan=1246, plotpol=-1, plotgrid=True, plotobs=True )
     38    """
    1039    def __init__( self, infile ):
    11         self.infile = infile
     40        """
     41        Create asapgrid instance.
     42
     43        infile -- input data as a string or string list if you want
     44                  to grid more than one data at once. 
     45        """
    1246        self.outfile = None
    13         self.gridder = stgrid( self.infile )
    1447        self.ifno = None
     48        self.gridder = stgrid()
     49        self.setData( infile )
    1550
    1651    def setData( self, infile ):
    17         self.gridder._setin( infile )
     52        """
     53        Set data to be processed.
     54
     55        infile -- input data as a string or string list if you want
     56                  to grid more than one data at once. 
     57        """
     58        if isinstance( infile, str ):
     59            self.gridder._setin( infile )
     60        else:
     61            self.gridder._setfiles( infile )
     62        self.infile = infile
    1863
    1964    def setIF( self, ifno ):
     65        """
     66        Set IFNO to be processed. Currently, asapgrid allows to process
     67        only one IFNO for one gridding run even if the data contains
     68        multiple IFs. If you didn't specify IFNO, default value, which
     69        is IFNO in the first spectrum, will be processed.
     70
     71        ifno -- IFNO to be processed.
     72        """
    2073        self.ifno = ifno
    2174        self.gridder._setif( self.ifno )
    2275
    2376    def setPolList( self, pollist ):
     77        """
     78        Set list of polarization components you want to process.
     79        If not specified, all POLNOs will be processed.
     80
     81        pollist -- list of POLNOs.
     82        """
    2483        self.gridder._setpollist( pollist )
    2584
    2685    def setScanList( self, scanlist ):
     86        """
     87        Set list of scans you want to process. If not specified, all
     88        scans will be processed.
     89
     90        scanlist -- list of SCANNOs.
     91        """
    2792        self.gridder._setscanlist( scanlist )
    2893
    2994    def defineImage( self, nx=-1, ny=-1, cellx='', celly='', center='' ):
     95        """
     96        Define spatial grid.
     97
     98        First two parameters, nx and ny, define number of pixels of
     99        the grid. If which of those is not specified, it will be set
     100        to the same value as the other. If none of them are specified,
     101        it will be determined from map extent and cell size.
     102
     103        Next two parameters, cellx and celly, define size of pixel.
     104        You should set those parameters as string, which is constructed
     105        numerical value and unit, e.g. '0.5arcmin', or numerical value.
     106        If those values are specified as numerical value, their units
     107        will be assumed to 'arcsec'. If which of those is not specified,
     108        it will be set to the same value as the other. If none of them
     109        are specified, it will be determined from map extent and number
     110        of pixels, or set to '1arcmin' if neither nx nor ny is set.
     111
     112        The last parameter, center, define the central coordinate of
     113        the grid. You should specify its value as a string, like,
     114
     115           'J2000 05h08m50s -16d23m30s'
     116
     117        or
     118
     119           'J2000 05:08:50 -16.23.30'
     120
     121        You can omit equinox when you specify center coordinate. In that
     122        case, J2000 is assumed. If center is not specified, it will be
     123        determined from the observed positions of input data.
     124
     125        nx -- number of pixels along x (R.A.) direction.
     126        ny -- number of pixels along y (Dec.) direction.
     127        cellx -- size of pixel in x (R.A.) direction.
     128        celly -- size of pixel in y (Dec.) direction.
     129        center -- central position of the grid.
     130        """
     131        if not isinstance( cellx, str ):
     132            cellx = '%sarcsec'%(cellx)
     133        if not isinstance( celly, str ):
     134            celly = '%sarcsec'%(celly)
    30135        self.gridder._defineimage( nx, ny, cellx, celly, center )
    31136
    32137    def setFunc( self, func='box', width=-1 ):
     138        """
     139        Set convolution function. Possible options are 'box' (Box-car,
     140        default), 'sf' (prolate spheroidal), and 'gauss' (Gaussian).
     141        Width of convolution function can be set using width parameter.
     142        By default (-1), width is automatically set depending on each
     143        convolution function. Default values for width are:
     144
     145           'box': 1 pixel
     146           'sf': 3 pixels
     147           'gauss': 1 pixel (width is used as HWHM)
     148
     149        func -- Function type ('box', 'sf', 'gauss').
     150        width -- Width of convolution function. Default (-1) is to
     151                 choose pre-defined value for each convolution function.
     152        """
    33153        self.gridder._setfunc( func, width )
    34154
    35155    def setWeight( self, weightType='uniform' ):
    36         self.gridder._setweight( weightType )
     156        """
     157        Set weight type. Possible options are 'uniform' (default),
     158        'tint' (weight by integration time), 'tsys' (weight by
     159        Tsys: 1/Tsys**2), and 'tintsys' (weight by integration time
     160        as well as Tsys: tint/Tsys**2).
     161
     162        weightType -- weight type ('uniform', 'tint', 'tsys', 'tintsys')
     163        """
     164        self.gridder._setweight( weightType )
     165
     166    def enableClip( self ):
     167        """
     168        Enable min/max clipping.
     169
     170        By default, min/max clipping is disabled so that you should
     171        call this method before actual gridding if you want to do
     172        clipping.
     173        """
     174        self.gridder._enableclip()
     175
     176    def disableClip( self ):
     177        """
     178        Disable min/max clipping.
     179        """
     180        self.gridder._disableclip()
    37181
    38182    def grid( self ):
     183        """
     184        Actual gridding which will be done based on several user inputs.
     185        """
    39186        self.gridder._grid()
    40187
    41188    def save( self, outfile='' ):
     189        """
     190        Save result. By default, output data name will be constructed
     191        from first element of input data name list (e.g. 'input.asap.grid').
     192
     193        outfile -- output data name.
     194        """
    42195        self.outfile = self.gridder._save( outfile )
    43196
    44     def plot( self, plotchan=-1, plotpol=-1 ):
     197    def plot( self, plotchan=-1, plotpol=-1, plotobs=False, plotgrid=False ):
     198        """
     199        Plot gridded data.
     200
     201        plotchan -- Which channel you want to plot. Default (-1) is
     202                    to average all the channels.
     203        plotpol -- Which polarization component you want to plot.
     204                   Default (-1) is to average all the polarization
     205                   components.
     206        plotobs -- Also plot observed position if True. Default
     207                   is False. Setting True for large amount of spectra
     208                   might be time consuming.
     209        plotgrid -- Also plot grid center if True. Default is False.
     210                    Setting True for large number of grids might be
     211                    time consuming.
     212        """
    45213        import time
    46214        t0=time.time()
     
    49217        rcParams['scantable.storage'] = 'disk'
    50218        plotter = _SDGridPlotter( self.infile, self.outfile, self.ifno )
    51         plotter.plot( chan=plotchan, pol=plotpol )
     219        plotter.plot( chan=plotchan, pol=plotpol, plotobs=plotobs, plotgrid=plotgrid )
    52220        # back to original setup
    53221        rcParams['scantable.storage'] = storg
     
    58226class _SDGridPlotter:
    59227    def __init__( self, infile, outfile=None, ifno=-1 ):
    60         self.infile = infile
     228        if isinstance( infile, str ):
     229            self.infile = [infile]
     230        else:
     231            self.infile = infile
    61232        self.outfile = outfile
    62233        if self.outfile is None:
    63             self.outfile = self.infile.rstrip('/')+'.grid'
     234            self.outfile = self.infile[0].rstrip('/')+'.grid'
    64235        self.nx = -1
    65236        self.ny = -1
     
    79250
    80251    def get( self ):
    81         self.tablein = scantable( self.infile, average=False )
    82         if self.ifno < 0:
    83             ifno = self.tablein.getif(0)
    84             print 'ifno=',ifno
    85         else:
    86             ifno = self.ifno
    87         sel = selector()
    88         sel.set_ifs( ifno )
    89         self.tablein.set_selection( sel )
    90         self.nchan = len(self.tablein._getspectrum(0))
    91         self.nrow = self.tablein.nrow()
    92         del sel
    93 
    94252        s = scantable( self.outfile, average=False )
     253        self.nchan = len(s._getspectrum(0))
    95254        nrow = s.nrow()
    96255        pols = numpy.ones( nrow, dtype=int )
     
    106265        idx = 0
    107266        d0 = s.get_direction( 0 ).split()[-1]
    108         while ( s.get_direction(self.npol*idx).split()[-1] == d0 ): 
     267        while ( s.get_direction(self.npol*idx) is not None \
     268                and s.get_direction(self.npol*idx).split()[-1] == d0 ):
    109269            idx += 1
    110270       
     
    117277        #print self.blc
    118278        #print self.trc
    119         incrx = s.get_directionval( self.npol )
    120         incry = s.get_directionval( self.nx*self.npol )
     279        if nrow > 1:
     280            incrx = s.get_directionval( self.npol )
     281            incry = s.get_directionval( self.nx*self.npol )
     282        else:
     283            incrx = [0.0,0.0]
     284            incry = [0.0,0.0]
    121285        self.cellx = abs( self.blc[0] - incrx[0] )
    122286        self.celly = abs( self.blc[1] - incry[1] )
    123287        #print 'cellx,celly=',self.cellx,self.celly
    124288
    125     def plot( self, chan=-1, pol=-1 ):
     289    def plot( self, chan=-1, pol=-1, plotobs=False, plotgrid=False ):
    126290        if pol < 0:
    127291            opt = 'averaged over pol'
    128292        else:
    129293            opt = 'pol %s'%(pol)
    130         if chan < 0:
     294        if type(chan) is list:
     295            opt += ', averaged over channel %s-%s'%(chan[0],chan[1])
     296        elif chan < 0:
    131297            opt += ', averaged over channel'
    132298        else:
    133299            opt += ', channel %s'%(chan)
    134         data = self.getData( chan, pol )
     300        data = self.getData( chan, pol )
     301        data = numpy.fliplr( data )
    135302        title = 'Gridded Image (%s)'%(opt)
    136303        pl.figure(10)
    137304        pl.clf()
    138305        # plot grid position
    139         x = numpy.arange(self.blc[0],self.trc[0]+0.5*self.cellx,self.cellx,dtype=float)
    140         #print 'len(x)=',len(x)
    141         #print 'x=',x
    142         ybase = numpy.ones(self.nx,dtype=float)*self.blc[1]
    143         #print 'len(ybase)=',len(ybase)
    144         incr = self.celly
    145         for iy in xrange(self.ny):
    146             y = ybase + iy * incr
    147             #print y
    148             pl.plot(x,y,',',color='blue')
     306        if plotgrid:
     307            x = numpy.arange(self.blc[0],self.trc[0]+0.5*self.cellx,self.cellx,dtype=float)
     308            #print 'len(x)=',len(x)
     309            #print 'x=',x
     310            ybase = numpy.ones(self.nx,dtype=float)*self.blc[1]
     311            #print 'len(ybase)=',len(ybase)
     312            incr = self.celly
     313            for iy in xrange(self.ny):
     314                y = ybase + iy * incr
     315                #print y
     316                pl.plot(x,y,',',color='blue')
    149317        # plot observed position
    150         irow = 0
    151         while ( irow < self.nrow ):
    152             chunk = self.getPointingChunk( irow )
    153             #print chunk
    154             pl.plot(chunk[0],chunk[1],',',color='green')
    155             irow += chunk.shape[1]
    156             #print irow
     318        if plotobs:
     319            for i in xrange(len(self.infile)):
     320                self.createTableIn( self.infile[i] )
     321                irow = 0
     322                while ( irow < self.nrow ):
     323                    chunk = self.getPointingChunk( irow )
     324                    #print chunk
     325                    pl.plot(chunk[0],chunk[1],',',color='green')
     326                    irow += chunk.shape[1]
     327                    #print irow
    157328        # show image
    158         extent=[self.blc[0]-0.5*self.cellx,
    159                 self.trc[0]+0.5*self.cellx,
     329        extent=[self.trc[0]+0.5*self.cellx,
     330                self.blc[0]-0.5*self.cellx,
    160331                self.blc[1]-0.5*self.celly,
    161332                self.trc[1]+0.5*self.celly]
     333        deccorr = 1.0/numpy.cos(0.5*(self.blc[1]+self.trc[1]))
    162334        pl.imshow(data,extent=extent,origin='lower',interpolation='nearest')
    163335        pl.colorbar()
    164336        pl.xlabel('R.A. [rad]')
    165337        pl.ylabel('Dec. [rad]')
     338        ax = pl.axes()
     339        ax.set_aspect(deccorr)
    166340        pl.title( title )
     341
     342    def createTableIn( self, tab ):
     343        del self.tablein
     344        self.tablein = scantable( tab, average=False )
     345        if self.ifno < 0:
     346            ifno = self.tablein.getif(0)
     347            print 'ifno=',ifno
     348        else:
     349            ifno = self.ifno
     350        sel = selector()
     351        sel.set_ifs( ifno )
     352        self.tablein.set_selection( sel )
     353        self.nchan = len(self.tablein._getspectrum(0))
     354        self.nrow = self.tablein.nrow()
     355        del sel
     356       
    167357
    168358    def getPointingChunk( self, irow ):
     
    180370
    181371    def getData( self, chan=-1, pol=-1 ):
    182         if chan == -1:
     372        if type(chan) == list:
     373            spectra = self.__chanAverage(start=chan[0],end=chan[1])
     374        elif chan == -1:
    183375            spectra = self.__chanAverage()
    184376        else:
     
    189381        else:
    190382            retval = data[pol]
    191         #retval[0][self.nx-1] = -1.0
    192383        return retval
    193384
    194     def __chanAverage( self ):
     385    def __chanAverage( self, start=-1, end=-1 ):
    195386        s = scantable( self.outfile, average=False )
    196387        nrow = s.nrow()
     
    198389        irow = 0
    199390        sp = [0 for i in xrange(self.nchan)]
     391        if start < 0:
     392            start = 0
     393        if end < 0:
     394            end = self.nchan
    200395        for i in xrange(nrow/self.npol):
    201396            for ip in xrange(self.npol):
    202                 sp = s._getspectrum( irow )
     397                sp = s._getspectrum( irow )[start:end]
    203398                spectra[ip,i] = numpy.mean( sp )
    204399                irow += 1
     400           
    205401        return spectra
    206402
  • /trunk/python/asaplot.py

    r2373 r2473  
    77from matplotlib.backends.backend_agg import FigureCanvasAgg
    88from matplotlib.backend_bases import FigureManagerBase
     9from matplotlib import _pylab_helpers
    910
    1011class asaplot(asaplotbase):
     
    2223        del v['self']
    2324        asaplotbase.__init__(self,**v)
     25        _pylab_helpers.Gcf.destroy(0)
     26        self.window = None
    2427        self.canvas = FigureCanvasAgg(self.figure)
    2528        self.figmgr = FigureManagerBase(self.canvas,1)
     29        _pylab_helpers.Gcf.figs[self.figmgr.num] = self.figmgr
    2630
    2731    def map(self):
  • /trunk/python/asaplotbase.py

    r2373 r2473  
    8282
    8383        self.buffering = buffering
     84
     85        self.events = {'button_press':None,
     86                       'button_release':None,
     87                       'motion_notify':None}
    8488
    8589    def clear(self):
     
    554558
    555559        The set_* methods of class Line2D define the attribute names and
    556         values.  For non-US usage, "colour" is recognized as synonymous with
    557         "color".
     560        values.  For non-US usage, 'colour' is recognized as synonymous with
     561        'color'.
    558562
    559563        Set the value to None to delete an attribute.
  • /trunk/python/asaplotgui.py

    r2373 r2473  
    1010# Force use of the newfangled toolbar.
    1111matplotlib.rcParams['toolbar'] = 'toolbar2'
     12from matplotlib import _pylab_helpers
     13from asap.logging import asaplog, asaplog_post_dec
    1214
    1315class asaplotgui(asaplotbase):
     
    2729
    2830        asaplotbase.__init__(self, **v)
     31        #matplotlib.rcParams["interactive"] = True
     32
     33        _pylab_helpers.Gcf.destroy(0)
    2934        self.window = Tk.Tk()
    30         def dest_callback():
    31             self.is_dead = True
    32             self.window.destroy()
    33 
    34         self.window.protocol("WM_DELETE_WINDOW", dest_callback)
     35        self.window.protocol("WM_DELETE_WINDOW", self.quit)
    3536        self.canvas = FigureCanvasTkAgg(self.figure, master=self.window)
    3637        self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
    3738        # Simply instantiating this is enough to get a working toolbar.
    38         self.figmgr = FigureManagerTkAgg(self.canvas, 1, self.window)
     39        self.figmgr = FigureManagerTkAgg(self.canvas, 0, self.window)
     40        # Register this plot to matplotlib without activating it
     41        #_pylab_helpers.Gcf.set_active(self.figmgr)
     42        _pylab_helpers.Gcf.figs[self.figmgr.num] = self.figmgr
    3943        self._set_window_title('ASAP Plotter - Tk')
     44        self.canvas.show()
    4045
    41         self.events = {'button_press':None,
    42                        'button_release':None,
    43                        'motion_notify':None}
    44 
    45         matplotlib.rcParams["interactive"] = True
    46         #self.buffering = buffering
    47 
    48         self.canvas.show()
    4946
    5047    def map(self):
     
    5350        window stack.
    5451        """
     52        if self.is_dead:
     53            raise RuntimeError( "No plotter to show. Not yet plotted or plotter is closed." )
    5554        self.window.wm_deiconify()
    5655        self.window.lift()
     
    6160        """
    6261        self.is_dead = True
    63         self.window.destroy()
     62        if not self.figmgr:
     63            return
     64        #self.window.destroy()
     65        _pylab_helpers.Gcf.destroy(self.figmgr.num)
     66        del self.window, self.canvas, self.figmgr
     67        self.window = None
     68        self.canvas = None
     69        self.figmgr = None
    6470
    6571    def show(self, hardrefresh=True):
     
    6773        Show graphics dependent on the current buffering state.
    6874        """
     75        if self.is_dead:
     76            raise RuntimeError( "No plotter to show (not yet plotted or closed)." )
    6977        if not self.buffering:
    7078            if hardrefresh:
     
    7785        Clear the figure.
    7886        """
     87        if not self.window:
     88            asaplog.push( "No plotter window to terminate." )
     89            asaplog.post( "WARN" )
     90            return
    7991        self.window.destroy()
    8092
     
    8395        Hide the ASAPlot graphics window.
    8496        """
     97        if not self.window:
     98            asaplog.push( "No plotter window to unmap." )
     99            asaplog.post( "WARN" )
     100            return
    85101        self.window.wm_withdraw()
    86102
  • /trunk/python/asaplotgui_gtk.py

    r2373 r2473  
    1212matplotlib.rcParams['toolbar'] = 'toolbar2'
    1313from matplotlib.backends.backend_gtk import NavigationToolbar2GTK as NavigationToolbar
     14from matplotlib import _pylab_helpers
    1415
    1516class asaplotgui(asaplotbase):
     
    2930
    3031        asaplotbase.__init__(self, **v)
     32        matplotlib.rcParams['interactive'] = True
    3133        matplotlib.interactive = True
     34
     35        _pylab_helpers.Gcf.destroy(0)
    3236        self.canvas = FigureCanvas(self.figure)
    3337        # Simply instantiating this is enough to get a working toolbar.
     
    3943        self.window.connect("destroy", dest_callback )
    4044        self.window.set_title('ASAP Plotter - GTK')
    41         self.events = {'button_press':None,
    42                        'button_release':None,
    43                        'motion_notify':None}
    44 
    45         self.buffering = buffering
    46         matplotlib.rcParams['interactive'] = True
    4745        #self.canvas.set_size_request(800,600)
     46        _pylab_helpers.Gcf.figs[self.figmgr.num] = self.figmgr
    4847
    4948        #self.canvas.show()
     
    5453        window stack.
    5554        """
     55        if self.is_dead:
     56            raise RuntimeError( "No plotter to show. Not yet plotted or plotter is closed." )
    5657        self.window.deiconify()
    5758        #self.window.lift()
    58 
    59 #     def position(self):
    60 #         """
    61 #         Use the mouse to get a position from a graph.
    62 #         """
    63 
    64 #         def position_disable(event):
    65 #             self.register('button_press', None)
    66 #             print '%.4f, %.4f' % (event.xdata, event.ydata)
    67 
    68 #         print 'Press any mouse button...'
    69 #         self.register('button_press', position_disable)
    70 
    7159
    7260    def quit(self):
     
    7462        Destroy the ASAPlot graphics window.
    7563        """
    76         self.window.destroy()
    77 
    78 
    79 #     def region(self):
    80 #         """
    81 #         Use the mouse to get a rectangular region from a plot.
    82 
    83 #         The return value is [x0, y0, x1, y1] in world coordinates.
    84 #         """
    85 
    86 #         def region_start(event):
    87 #             height = self.canvas.figure.bbox.height()
    88 #             self.rect = {'fig': None, 'height': height,
    89 #                          'x': event.x, 'y': height - event.y,
    90 #                          'world': [event.xdata, event.ydata,
    91 #                                    event.xdata, event.ydata]}
    92 #             self.register('button_press', None)
    93 #             self.register('motion_notify', region_draw)
    94 #             self.register('button_release', region_disable)
    95 
    96 #         def region_draw(event):
    97 #             self.canvas._tkcanvas.delete(self.rect['fig'])
    98 #             self.rect['fig'] = self.canvas._tkcanvas.create_rectangle(
    99 #                                 self.rect['x'], self.rect['y'],
    100 #                                 event.x, self.rect['height'] - event.y)
    101 
    102 #         def region_disable(event):
    103 #             self.register('motion_notify', None)
    104 #             self.register('button_release', None)
    105 
    106 #             self.canvas._tkcanvas.delete(self.rect['fig'])
    107 
    108 #             self.rect['world'][2:4] = [event.xdata, event.ydata]
    109 #             print '(%.2f, %.2f)  (%.2f, %.2f)' % (self.rect['world'][0],
    110 #                 self.rect['world'][1], self.rect['world'][2],
    111 #                 self.rect['world'][3])
    112 
    113 #         self.register('button_press', region_start)
    114 
    115 #         # This has to be modified to block and return the result (currently
    116 #         # printed by region_disable) when that becomes possible in matplotlib.
    117 
    118 #         return [0.0, 0.0, 0.0, 0.0]
    119 
    120 
    121 #     def register(self, type=None, func=None):
    122 #         """
    123 #         Register, reregister, or deregister events of type 'button_press',
    124 #         'button_release', or 'motion_notify'.
    125 
    126 #         The specified callback function should have the following signature:
    127 
    128 #             def func(event)
    129 
    130 #         where event is an MplEvent instance containing the following data:
    131 
    132 #             name                # Event name.
    133 #             canvas              # FigureCanvas instance generating the event.
    134 #             x      = None       # x position - pixels from left of canvas.
    135 #             y      = None       # y position - pixels from bottom of canvas.
    136 #             button = None       # Button pressed: None, 1, 2, 3.
    137 #             key    = None       # Key pressed: None, chr(range(255)), shift,
    138 #                                   win, or control
    139 #             inaxes = None       # Axes instance if cursor within axes.
    140 #             xdata  = None       # x world coordinate.
    141 #             ydata  = None       # y world coordinate.
    142 
    143 #         For example:
    144 
    145 #             def mouse_move(event):
    146 #                 print event.xdata, event.ydata
    147 
    148 #             a = asaplot()
    149 #             a.register('motion_notify', mouse_move)
    150 
    151 #         If func is None, the event is deregistered.
    152 
    153 #         Note that in TkAgg keyboard button presses don't generate an event.
    154 #         """
    155 
    156 #         if not self.events.has_key(type): return
    157 
    158 #         if func is None:
    159 #             if self.events[type] is not None:
    160 #                 # It's not clear that this does anything.
    161 #                 self.canvas.mpl_disconnect(self.events[type])
    162 #                 self.events[type] = None
    163 
    164 #                 # It seems to be necessary to return events to the toolbar.
    165 #                 if type == 'motion_notify':
    166 #                     self.canvas.mpl_connect(type + '_event',
    167 #                         self.figmgr.toolbar.mouse_move)
    168 #                 elif type == 'button_press':
    169 #                     self.canvas.mpl_connect(type + '_event',
    170 #                         self.figmgr.toolbar.press)
    171 #                 elif type == 'button_release':
    172 #                     self.canvas.mpl_connect(type + '_event',
    173 #                         self.figmgr.toolbar.release)
    174 
    175 #         else:
    176 #             self.events[type] = self.canvas.mpl_connect(type + '_event', func)
    177 
     64        self.is_dead = True
     65        if not self.figmgr:
     66            return
     67        #self.window.destroy()
     68        _pylab_helpers.Gcf.destroy(self.figmgr.num)
     69        del self.window, self.canvas, self.figmgr
     70        self.window = None
     71        self.canvas = None
     72        self.figmgr = None
    17873
    17974    def show(self, hardrefresh=True):
     
    18176        Show graphics dependent on the current buffering state.
    18277        """
     78        if self.is_dead:
     79            raise RuntimeError( "No plotter to show (not yet plotted or closed)." )
    18380        if not self.buffering:
    18481            if hardrefresh:
     
    19289        Clear the figure.
    19390        """
     91        if not self.window:
     92            asaplog.push( "No plotter window to terminate." )
     93            asaplog.post( "WARN" )
     94            return
    19495        self.window.destroy()
    19596
     
    19899        Hide the ASAPlot graphics window.
    199100        """
     101        if not self.window:
     102            asaplog.push( "No plotter window to unmap." )
     103            asaplog.post( "WARN" )
     104            return
    200105        self.window.wm_withdraw()
  • /trunk/python/asaplotgui_qt4.py

    r2373 r2473  
    2929
    3030        asaplotbase.__init__(self, **v)
     31        matplotlib.rcParams["interactive"] = True
    3132
     33        _pylab_helpers.Gcf.destroy(0)
    3234        self.canvas = FigureCanvasQTAgg(self.figure)
    3335        # Simply instantiating this is enough to get a working toolbar.
    34         self.figmgr = FigureManagerQTAgg(self.canvas, 1)
     36        self.figmgr = FigureManagerQTAgg(self.canvas, 0)
    3537        self.window = self.figmgr.window
    3638        self._set_window_title('ASAP Plotter - Qt4')
    37         # register this plot to matplotlib
    38         _pylab_helpers.Gcf.set_active(self.figmgr)
     39        # Register this plot to matplotlib without activating it
     40        #_pylab_helpers.Gcf.set_active(self.figmgr)
     41        _pylab_helpers.Gcf.figs[self.figmgr.num] = self.figmgr
    3942
    4043        #############
     
    4952        qt.QtCore.QObject.connect(self.window, qt.QtCore.SIGNAL('destroyed()'),dest_callback)
    5053
    51         self.events = {'button_press':None,
    52                        'button_release':None,
    53                        'motion_notify':None}
    54 
    55         matplotlib.rcParams["interactive"] = True
    56         self.buffering = buffering
    57 
    5854        self.unmap()
    5955        #self.canvas.show()
     
    6460        window stack.
    6561        """
     62        if self.is_dead:
     63            raise RuntimeError( "No plotter to show. Not yet plotted or plotter is closed." )
    6664        self.window.activateWindow()
    6765        #To raise this window to the top of the stacking order
     
    7472        """
    7573        self.is_dead = True
    76         try: self.window.close()
     74        if not self.figmgr:
     75            return
     76        try:
     77            #self.window.close()
     78            # TODO destroy casabar
     79            _pylab_helpers.Gcf.destroy(self.figmgr.num)
     80            del self.window, self.canvas, self.figmgr
     81            self.window = None
     82            self.canvas = None
     83            self.figmgr = None
    7784        except RuntimeError: pass # the window may already be closed by user
    7885
     
    8188        Show graphics dependent on the current buffering state.
    8289        """
     90        if self.is_dead:
     91            raise RuntimeError( "No plotter to show (not yet plotted or closed)." )
    8392        if not self.buffering:
    8493            if hardrefresh:
     
    93102        Clear the figure.
    94103        """
     104        if not self.window:
     105            asaplog.push( "No plotter window to terminate." )
     106            asaplog.post( "WARN" )
     107            return
    95108        self.window.close()
    96109
     
    99112        Hide the ASAPlot graphics window.
    100113        """
     114        if not self.window:
     115            asaplog.push( "No plotter window to unmap." )
     116            asaplog.post( "WARN" )
     117            return
    101118        self.window.hide()
    102119
  • /trunk/python/asapmath.py

    r2373 r2473  
    2626                  the time of the first spectrum in the first scantable
    2727                  as reference time.
     28        compel:   True forces to average overwrapped IFs.
    2829    Example:
    2930        # return a time averaged scan from scana and scanb
     
    163164    type enum is pson or psoff. The data must contains 'CAL' signal
    164165    on/off in each integration. To identify 'CAL' on state, the source type
    165     enum of poncal and poffcal need to be present in the source name field.
    166     (GBT MS data reading process to scantable automatically append these
    167     id names to the source names)
     166    enum of poncal and poffcal need to be present.
    168167
    169168    Parameters:
     
    312311        asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.')
    313312        asaplog.post('WARN')
    314         #p=asaplotgui.asaplotgui()
    315313        p=new_asaplot()
    316314        #nr=min(6,len(ifnos)*len(polnos))
     
    532530        asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.')
    533531        asaplog.post('WARN')
    534         #p=asaplotgui.asaplotgui()
    535532        p=new_asaplot()
    536533        #nr=min(6,len(ifnos)*len(polnos))
     
    627624    type enum is fson and fsoff. The data must contains 'CAL' signal
    628625    on/off in each integration. To identify 'CAL' on state, the source type
    629     enum of foncal and foffcal need to be present in the source name field.
    630     (GBT MS data reading via scantable automatically append these
    631     id names to the source names)
     626    enum of foncal and foffcal need to be present.
    632627
    633628    Parameters:
     
    745740        asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.')
    746741        asaplog.post('WARN')
    747         #p=asaplotgui.asaplotgui()
    748742        p=new_asaplot()
    749743        #nr=min(6,len(ifnos)*len(polnos))
  • /trunk/python/asapplotter.py

    r2373 r2473  
    4545        if visible is not None:
    4646            self._visible = visible
    47         self._plotter = self._newplotter(**kwargs)
    48         # additional tool bar
    49         self._plotter.figmgr.casabar=self._new_custombar()
     47        self._plotter = None
     48        self._inikwg = kwargs
    5049
    5150        self._panelling = None
     
    5554        self._rows = None
    5655        self._cols = None
    57         self._autoplot = False
    5856        self._minmaxx = None
    5957        self._minmaxy = None
     
    7674        self._panelrows = []
    7775        self._headtext={'string': None, 'textobj': None}
     76        self._colormap = None
     77        self._linestyles = None
     78        self._legendloc = None
    7879
    7980    def _translate(self, instr):
     
    8586        return None
    8687
    87     def _newplotter(self, **kwargs):
    88         return new_asaplot(self._visible,**kwargs)
     88    def _reload_plotter(self):
     89        if self._plotter is not None:
     90            if  not self._plotter.is_dead:
     91                # clear lines and axes
     92                self._plotter.clear()
     93            if self.casabar_exists():
     94                del self._plotter.figmgr.casabar
     95            self._plotter.quit()
     96            del self._plotter
     97        self._plotter = new_asaplot(self._visible,**self._inikwg)
     98        self._plotter.figmgr.casabar=self._new_custombar()
     99        # just to make sure they're set
     100        self._plotter.palette(color=0,colormap=self._colormap,
     101                              linestyle=0,linestyles=self._linestyles)
     102        self._plotter.legend(self._legendloc)
    89103
    90104    def _new_custombar(self):
     
    107121        return False
    108122
     123    def _assert_plotter(self,action="status",errmsg=None):
     124        """
     125        Check plot window status. Returns True if plot window is alive.
     126        Parameters
     127            action:    An action to take if the plotter window is not alive.
     128                       ['status'|'reload'|'halt']
     129                       The action 'status' simply returns False if asaplot
     130                       is not alive. When action='reload', plot window is
     131                       reloaded and the method returns True. Finally, an
     132                       error is raised when action='halt'.
     133            errmsg:    An error (warning) message to send to the logger,
     134                       when plot window is not alive.
     135        """
     136        if self._plotter and not self._plotter.is_dead:
     137            return True
     138        # Plotter is not alive.
     139        haltmsg = "Plotter window has not yet been loaded or is closed."
     140        if type(errmsg)==str and len(errmsg) > 0:
     141            haltmsg = errmsg
     142       
     143        if action.upper().startswith("R"):
     144            # reload plotter
     145            self._reload_plotter()
     146            return True
     147        elif action.upper().startswith("H"):
     148            # halt
     149            asaplog.push(haltmsg)
     150            asaplog.post("ERROR")
     151            raise RuntimeError(haltmsg)
     152        else:
     153            if errmsg:
     154                asaplog.push(errmsg)
     155                asaplog.post("WARN")
     156            return False
     157
     158
    109159    @asaplog_post_dec
    110160    def plot(self, scan=None):
     
    119169            are consistent e.g. all 'channel' or all 'velocity' etc.
    120170        """
     171        if not self._data and not scan:
     172            msg = "Input is not a scantable"
     173            raise TypeError(msg)
    121174        self._startrow = 0
    122175        self._ipanel = -1
    123176        self._reset_header()
    124         if self._plotter.is_dead:
    125             if self.casabar_exists():
    126                 del self._plotter.figmgr.casabar
    127             self._plotter = self._newplotter()
    128             self._plotter.figmgr.casabar=self._new_custombar()
     177        self._panelrows = []
     178
     179        self._assert_plotter(action="reload")
    129180        if self.casabar_exists():
    130181            self._plotter.figmgr.casabar.set_pagecounter(1)
    131         self._panelrows = []
     182
    132183        self._plotter.hold()
    133184        #self._plotter.clear()
    134         if not self._data and not scan:
    135             msg = "Input is not a scantable"
    136             raise TypeError(msg)
    137185        if scan:
    138186            self.set_data(scan, refresh=False)
     187        self._plotter.palette(color=0,colormap=self._colormap,
     188                              linestyle=0,linestyles=self._linestyles)
     189        self._plotter.legend(self._legendloc)
     190
    139191        self._plot(self._data)
    140192        if self._minmaxy is not None:
     
    147199
    148200    def gca(self):
     201        errmsg = "No axis to retun. Need to plot first."
     202        if not self._assert_plotter(action="status",errmsg=errmsg):
     203            return None
    149204        return self._plotter.figure.gca()
    150205
    151206    def refresh(self):
    152207        """Do a soft refresh"""
     208        errmsg = "No figure to re-plot. Need to plot first."
     209        self._assert_plotter(action="halt",errmsg=errmsg)
     210
    153211        self._plotter.figure.show()
    154212
     
    163221                        if different IFs are spread over panels (default 0)
    164222        """
    165         if self._data is None:
     223        ## this method relies on already plotted figure
     224        if not self._assert_plotter(action="status") or (self._data is None):
     225            msg = "Cannot create mask interactively on plot. Can only create mask after plotting."
     226            asaplog.push( msg )
     227            asaplog.post( "ERROR" )
    166228            return []
    167229        outmask = []
     
    210272    # forwards to matplotlib axes
    211273    def text(self, *args, **kwargs):
     274        self._assert_plotter(action="reload")
    212275        if kwargs.has_key("interactive"):
    213276            if kwargs.pop("interactive"):
     
    219282
    220283    def arrow(self, *args, **kwargs):
     284        self._assert_plotter(action="reload")
    221285        if kwargs.has_key("interactive"):
    222286            if kwargs.pop("interactive"):
     
    231295
    232296    def annotate(self, text, xy=None, xytext=None, **kwargs):
     297        self._assert_plotter(action="reload")
    233298        if kwargs.has_key("interactive"):
    234299            if kwargs.pop("interactive"):
     
    242307
    243308    def axvline(self, *args, **kwargs):
     309        self._assert_plotter(action="reload")
    244310        if kwargs.has_key("interactive"):
    245311            if kwargs.pop("interactive"):
     
    251317
    252318    def axhline(self, *args, **kwargs):
     319        self._assert_plotter(action="reload")
    253320        if kwargs.has_key("interactive"):
    254321            if kwargs.pop("interactive"):
     
    260327
    261328    def axvspan(self, *args, **kwargs):
     329        self._assert_plotter(action="reload")
    262330        if kwargs.has_key("interactive"):
    263331            if kwargs.pop("interactive"):
     
    274342
    275343    def axhspan(self, *args, **kwargs):
     344        self._assert_plotter(action="reload")
    276345        if kwargs.has_key("interactive"):
    277346            if kwargs.pop("interactive"):
     
    288357
    289358    def _axes_callback(self, axesfunc, *args, **kwargs):
     359        self._assert_plotter(action="reload")
    290360        panel = 0
    291361        if kwargs.has_key("panel"):
     
    504574        """
    505575        self._lmap = mp
    506         self._plotter.legend(mode)
     576        #self._plotter.legend(mode)
     577        self._legendloc = mode
    507578        if isinstance(fontsize, int):
    508579            from matplotlib import rc as rcp
     
    513584    def set_title(self, title=None, fontsize=None, refresh=True):
    514585        """
    515         Set the title of the plot. If multiple panels are plotted,
     586        Set the title of sub-plots. If multiple sub-plots are plotted,
    516587        multiple titles have to be specified.
    517588        Parameters:
     589            title:      a list of titles of sub-plots.
     590            fontsize:   a font size of titles (integer)
    518591            refresh:    True (default) or False. If True, the plot is
    519592                        replotted based on the new parameter setting(s).
     
    521594        Example:
    522595             # two panels are visible on the plotter
    523              plotter.set_title(["First Panel","Second Panel"])
     596             plotter.set_title(['First Panel','Second Panel'])
    524597        """
    525598        self._title = title
     
    537610            ordinate:    a list of ordinate labels. None (default) let
    538611                         data determine the labels
     612            fontsize:    a font size of vertical axis labels (integer)
    539613            refresh:     True (default) or False. If True, the plot is
    540614                         replotted based on the new parameter setting(s).
     
    542616        Example:
    543617             # two panels are visible on the plotter
    544              plotter.set_ordinate(["First Y-Axis","Second Y-Axis"])
     618             plotter.set_ordinate(['First Y-Axis','Second Y-Axis'])
    545619        """
    546620        self._ordinate = ordinate
     
    559633            abcissa:     a list of abcissa labels. None (default) let
    560634                         data determine the labels
     635            fontsize:    a font size of horizontal axis labels (integer)
    561636            refresh:     True (default) or False. If True, the plot is
    562637                         replotted based on the new parameter setting(s).
     
    564639        Example:
    565640             # two panels are visible on the plotter
    566              plotter.set_ordinate(["First X-Axis","Second X-Axis"])
     641             plotter.set_ordinate(['First X-Axis','Second X-Axis'])
    567642        """
    568643        self._abcissa = abcissa
     
    584659                        Otherwise,the parameter(s) are set without replotting.
    585660        Example:
    586              plotter.set_colors("red green blue")
     661             plotter.set_colors('red green blue')
    587662             # If for example four lines are overlaid e.g I Q U V
    588663             # 'I' will be 'red', 'Q' will be 'green', U will be 'blue'
    589664             # and 'V' will be 'red' again.
    590665        """
    591         if isinstance(colmap,str):
    592             colmap = colmap.split()
    593         self._plotter.palette(0, colormap=colmap)
     666        #if isinstance(colmap,str):
     667        #    colmap = colmap.split()
     668        #self._plotter.palette(0, colormap=colmap)
     669        self._colormap = colmap
    594670        if refresh and self._data: self.plot(self._data)
    595671
     
    604680                         is taken from the .asaprc setting
    605681                         plotter.histogram
     682            linewidth:   a line width
    606683            refresh:     True (default) or False. If True, the plot is
    607684                         replotted based on the new parameter setting(s).
     
    620697        only one color has been set.
    621698        Parameters:
    622              linestyles:     a list of linestyles to use.
     699            linestyles:      a list of linestyles to use.
    623700                             'line', 'dashed', 'dotted', 'dashdot',
    624701                             'dashdotdot' and 'dashdashdot' are
    625702                             possible
     703            linewidth:       a line width
    626704            refresh:         True (default) or False. If True, the plot is
    627705                             replotted based on the new parameter setting(s).
    628706                             Otherwise,the parameter(s) are set without replotting.
    629707        Example:
    630              plotter.set_colors("black")
    631              plotter.set_linestyles("line dashed dotted dashdot")
     708             plotter.set_colors('black')
     709             plotter.set_linestyles('line dashed dotted dashdot')
    632710             # If for example four lines are overlaid e.g I Q U V
    633711             # 'I' will be 'solid', 'Q' will be 'dashed',
    634712             # U will be 'dotted' and 'V' will be 'dashdot'.
    635713        """
    636         if isinstance(linestyles,str):
    637             linestyles = linestyles.split()
    638         self._plotter.palette(color=0,linestyle=0,linestyles=linestyles)
     714        #if isinstance(linestyles,str):
     715        #    linestyles = linestyles.split()
     716        #self._plotter.palette(color=0,linestyle=0,linestyles=linestyles)
     717        self._linestyles = linestyles
    639718        if isinstance(linewidth, float) or isinstance(linewidth, int):
    640719            from matplotlib import rc as rcp
     
    707786        If the spectrum is flagged no line will be drawn in that location.
    708787        """
     788        errmsg = "Cannot plot spectral lines. Need to plot scantable first."
     789        self._assert_plotter(action="halt",errmsg=errmsg)
    709790        if not self._data:
    710791            raise RuntimeError("No scantable has been plotted yet.")
     
    784865             dpi:         The dpi of the output non-ps plot
    785866        """
     867        errmsg = "Cannot save figure. Need to plot first."
     868        self._assert_plotter(action="halt",errmsg=errmsg)
     869       
    786870        self._plotter.save(filename,orientation,dpi)
    787871        return
     
    791875        """
    792876        Set a plotting mask for a specific polarization.
    793         This is useful for masking out "noise" Pangle outside a source.
     877        This is useful for masking out 'noise' Pangle outside a source.
    794878        Parameters:
    795879             mask:           a mask from scantable.create_mask
     
    800884        Example:
    801885             select = selector()
    802              select.setpolstrings("Pangle")
     886             select.setpolstrings('Pangle')
    803887             plotter.set_mask(mymask, select)
    804888        """
     
    12561340        PL.ion()
    12571341        PL.draw()
    1258         PL.gcf().show()
     1342        if matplotlib.get_backend() == 'Qt4Agg': PL.gcf().show()
    12591343        if (self._outfile is not None):
    12601344           PL.savefig(self._outfile)
     
    12951379        [xmin,xmax,ymin,ymax] = PL.axis()
    12961380        PL.axis([xmax,xmin,ymin,ymax])
    1297         #PL.ion()
     1381        PL.ion()
    12981382        PL.draw()
    1299         PL.gcf().show()
     1383        if matplotlib.get_backend() == 'Qt4Agg': PL.gcf().show()
    13001384        if (self._outfile is not None):
    13011385           PL.savefig(self._outfile)
     
    13051389    @asaplog_post_dec
    13061390    def plottp(self, scan=None, outfile=None):
    1307         if self._plotter.is_dead:
    1308             if self.casabar_exists():
    1309                 del self._plotter.figmgr.casabar
    1310             self._plotter = self._newplotter()
    1311             self._plotter.figmgr.casabar=self._new_custombar()
     1391        self._assert_plotter(action="reload")
    13121392        self._plotter.hold()
    13131393        self._plotter.clear()
     
    13991479        See the method help for detailed information.
    14001480        """
     1481        self._assert_plotter(action="reload")
    14011482        self._plotter.text(*args, **kwargs)
    14021483    # end matplotlib.Figure.text forwarding function
     
    14371518
    14381519        if plot:
     1520            errmsg = "Can plot header only after the first call to plot()."
     1521            self._assert_plotter(action="halt",errmsg=errmsg)
    14391522            self._plotter.hold()
    14401523            self._header_plot(headstr,fontsize=fontsize)
     
    14691552            asaplog.push("No header has been plotted. Exit without any operation")
    14701553            asaplog.post("WARN")
    1471         else:
     1554        elif self._assert_plotter(action="status"):
    14721555            self._plotter.hold()
    14731556            for textobj in self._headtext['textobj']:
  • /trunk/python/customgui_tkagg.py

    r2373 r2473  
    135135        self.disable_button()
    136136        self.figmgr.window.wm_withdraw()
     137        self._p.quit()
    137138
    138139    def enable_button(self):
     
    147148        #self.bSpec.config(relief='raised', state=Tk.DISABLED)
    148149        self.bStat.config(relief='raised', state=Tk.DISABLED)
    149         #self.bNext.config(state=Tk.DISABLED)
    150         #self.bPrev.config(state=Tk.DISABLED)
     150        self.bNext.config(state=Tk.DISABLED)
     151        self.bPrev.config(state=Tk.DISABLED)
    151152        self.button = False
    152153        self.mode = ''
     
    647648        self.disable_button()
    648649        self.figmgr.window.wm_withdraw()
     650        self._p.quit()
    649651
    650652    def enable_button(self):
  • /trunk/python/flagplotter.py

    r2373 r2473  
    2727        self._scan = None
    2828        asapplotter.__init__(self,visible=visible, **kwargs)
     29        self._assert_plotter(action='reload')
    2930        self._plotter._set_window_title('Flag Plotter')
    3031        self._panelling = 'r'
     
    100101                         without writing the output. USE WITH CARE.
    101102        """
     103        if not self._data:
     104            raise RuntimeError("No scantable has been set yet.")
    102105        # simply calls scantable.save
    103106        self._data.save(name,format,overwrite)
  • /trunk/python/interactivemask.py

    r2373 r2473  
    5555            raise TypeError(msg)
    5656
    57         self.mask = _n_bools(self.scan.nchan(),True)
     57        self.mask = _n_bools(self.scan.nchan(self.scan.getif(0)),True)
    5858        self.callback = None
    5959        self.event = None
     
    9292            self.mask = self.scan.create_mask(masklist,invert=invert)
    9393        elif invert == True:
    94             self.mask = _n_bools(self.scan.nchan(),False)
    95         else:
    96             self.mask = _n_bools(self.scan.nchan(),True)
     94            self.mask = _n_bools(self.scan.nchan(self.scan.getif(0)),False)
     95        else:
     96            self.mask = _n_bools(self.scan.nchan(self.scan.getif(0)),True)
    9797
    9898
     
    157157
    158158        #if not self.p._plotter or self.p._plotter.is_dead:
    159         if not self.p or self.p._plotter.is_dead:
     159        if not self.p:
    160160            asaplog.push('A new ASAP plotter will be loaded')
    161161            asaplog.post()
     
    163163            self.p = asapplotter()
    164164            self.newplot = True
    165 
     165        self.p._assert_plotter(action='reload')
     166       
    166167        # Plot selected spectra if needed
    167168        if self.scan != self.p._data:
     
    171172                asaplog.post("WARN")
    172173            # Need replot
    173             self.p._plotter.legend(1)
     174            self.p._legendloc = 1
    174175            self.p.plot(self.scan)
    175176            # disable casa toolbar
  • /trunk/python/logging.py

    r2373 r2473  
    5656            logs = self.logger.pop().strip()
    5757            if len(logs) > 0:
    58                 print >>sys.stdout, logs
    59                 sys.stdout.flush()
     58                if rcParams['verbose']:
     59                    print >>sys.stdout, logs
     60                    if hasattr(sys.stdout, "flush"):
     61                        sys.stdout.flush()
    6062        self._log = ""
    6163
     
    110112        level = "INFO"
    111113        try:
    112             val = f(*args, **kw)
    113             return val
    114         except Exception, ex:
    115             level = "ERROR"
    116             asaplog.push(str(ex))
    117             if rcParams['verbose']:
    118                 pass
    119             else:
    120                 raise
     114            try:
     115                val = f(*args, **kw)
     116                return val
     117            except Exception, ex:
     118                level = "ERROR"
     119                asaplog.push(str(ex))
     120                if rcParams['verbose']:
     121                    pass
     122                else:
     123                    raise
    121124        finally:
    122125            asaplog.post(level, f.func_name)
    123             #asaplog.post(level, ".".join([f.__module__,f.func_name]))
    124126    return wrap_it
    125127
  • /trunk/python/opacity.py

    r2373 r2473  
    77from asap.selector import selector
    88from asap._asap import atmosphere
    9 
     9from asap import rcParams
    1010
    1111class model(object):
     
    151151        plot:       Plot each fit (airmass vs. Tsys). Default is 'False'
    152152    """
    153     if plot:
    154         from matplotlib import pylab
    155     scan = _import_data(data)
    156     f = fitter()
    157     f.set_function(poly=1)
    158     sel = selector()
    159     basesel = scan.get_selection()
    160     inos = scan.getifnos()
    161     pnos = scan.getpolnos()
    162     opacities = []
    163     om = model(temperature, pressure, humidity)
    164     for ino in inos:
    165         sel.set_ifs(ino)
    166         opacity = []
    167         fits = []
    168         airms = []
    169         tsyss = []
     153    # quiten output
     154    verbose = rcParams["verbose"]
     155    rcParams["verbose"] = False
     156    try:
    170157        if plot:
    171             pylab.cla()
    172             pylab.ioff()
    173             pylab.clf()
    174             pylab.xlabel("Airmass")
    175             pylab.ylabel(r"$T_{sys}$")
    176         for pno in pnos:
    177             sel.set_polarisations(pno)
    178             scan.set_selection(basesel+sel)
    179             freq = scan.get_coordinate(0).get_reference_value()/1e9
    180             freqstr = "%0.4f GHz" % freq
    181             tsys = scan.get_tsys()
    182             elev = scan.get_elevation()
    183             airmass = [ 1./math.sin(i) for i in elev ]
    184             airms.append(airmass)
    185             tsyss.append(tsys)
    186             f.set_data(airmass, tsys)
    187             f.fit()
    188             fits.append(f.get_fit())
    189             params = f.get_parameters()["params"]
    190             opacity.append(params[1]/tsky)
    191         if averagepol:
    192             opacities.append(sum(opacity)/len(opacity))
    193         else:
    194             opacities += opacity
     158            from matplotlib import pylab
     159        scan = _import_data(data)
     160        f = fitter()
     161        f.set_function(poly=1)
     162        sel = selector()
     163        basesel = scan.get_selection()
     164        inos = scan.getifnos()
     165        pnos = scan.getpolnos()
     166        opacities = []
     167        om = model(temperature, pressure, humidity)
     168        for ino in inos:
     169            sel.set_ifs(ino)
     170            opacity = []
     171            fits = []
     172            airms = []
     173            tsyss = []
     174            if plot:
     175                pylab.cla()
     176                pylab.ioff()
     177                pylab.clf()
     178                pylab.xlabel("Airmass")
     179                pylab.ylabel(r"$T_{sys}$")
     180            for pno in pnos:
     181                sel.set_polarisations(pno)
     182                scan.set_selection(basesel+sel)
     183                freq = scan.get_coordinate(0).get_reference_value()/1e9
     184                freqstr = "%0.4f GHz" % freq
     185                tsys = scan.get_tsys()
     186                elev = scan.get_elevation()
     187                airmass = [ 1./math.sin(i) for i in elev ]
     188                airms.append(airmass)
     189                tsyss.append(tsys)
     190                f.set_data(airmass, tsys)
     191                f.fit()
     192                fits.append(f.get_fit())
     193                params = f.get_parameters()["params"]
     194                opacity.append(params[1]/tsky)
     195            if averagepol:
     196                opacities.append(sum(opacity)/len(opacity))
     197            else:
     198                opacities += opacity
     199            if plot:
     200                colors = ['b','g','k']
     201                n = len(airms)
     202                for i in range(n):
     203                    pylab.plot(airms[i], tsyss[i], 'o', color=colors[i])
     204                    pylab.plot(airms[i], fits[i], '-', color=colors[i])
     205                    pylab.figtext(0.7,0.3-(i/30.0),
     206                                      r"$\tau_{fit}=%0.2f$" % opacity[i],
     207                                      color=colors[i])
     208                if averagepol:
     209                    pylab.figtext(0.7,0.3-(n/30.0),
     210                                      r"$\tau_{avg}=%0.2f$" % opacities[-1],
     211                                      color='r')
     212                    n +=1
     213                pylab.figtext(0.7,0.3-(n/30.0),
     214                              r"$\tau_{model}=%0.2f$" % om.get_opacities(freq*1e9),
     215                              color='grey')
     216
     217                pylab.title("IF%d : %s" % (ino, freqstr))
     218
     219                pylab.ion()
     220                pylab.draw()
     221                raw_input("Hit <return> for next fit...")
     222            sel.reset()
     223
     224        scan.set_selection(basesel)
    195225        if plot:
    196             colors = ['b','g','k']
    197             n = len(airms)
    198             for i in range(n):
    199                 pylab.plot(airms[i], tsyss[i], 'o', color=colors[i])
    200                 pylab.plot(airms[i], fits[i], '-', color=colors[i])
    201                 pylab.figtext(0.7,0.3-(i/30.0),
    202                                   r"$\tau_{fit}=%0.2f$" % opacity[i],
    203                                   color=colors[i])
    204             if averagepol:
    205                 pylab.figtext(0.7,0.3-(n/30.0),
    206                                   r"$\tau_{avg}=%0.2f$" % opacities[-1],
    207                                   color='r')
    208                 n +=1
    209             pylab.figtext(0.7,0.3-(n/30.0),
    210                           r"$\tau_{model}=%0.2f$" % om.get_opacities(freq*1e9),
    211                           color='grey')
    212 
    213             pylab.title("IF%d : %s" % (ino, freqstr))
    214 
    215             pylab.ion()
    216             pylab.draw()
    217             raw_input("Hit <return> for next fit...")
    218         sel.reset()
    219 
    220     scan.set_selection(basesel)
    221     if plot:
    222         pylab.close()
    223     return opacities
     226            pylab.close()
     227        return opacities
     228    finally:
     229        rcParams["verbose"] = verbose
  • /trunk/python/scantable.py

    r2373 r2473  
    1919from asap.utils import _n_bools, mask_not, mask_and, mask_or, page
    2020from asap.asapfitter import fitter
     21
     22###############################################################
     23### WK temporarily added these lines for testing 2011/11/28 ###
     24###############################################################
     25#from asap._asap import TestClass
     26
     27#class testclass(TestClass):
     28#    def __init__(self, nelem):
     29#        TestClass.__init__(self, nelem)
     30
     31###############################################################
    2132
    2233
     
    264275        Parameters:
    265276
    266             name:        the name of the outputfile. For format "ASCII"
     277            name:        the name of the outputfile. For format 'ASCII'
    267278                         this is the root file name (data in 'name'.txt
    268279                         and header in 'name'_header.txt)
     
    522533
    523534            selection:    a selector object (default unset the selection), or
    524                           any combination of "pols", "ifs", "beams", "scans",
    525                           "cycles", "name", "query"
     535                          any combination of 'pols', 'ifs', 'beams', 'scans',
     536                          'cycles', 'name', 'query'
    526537
    527538        Examples::
     
    757768        return self._row_callback(self._gettsys, "Tsys")
    758769
     770    def get_tsysspectrum(self, row=-1):
     771        """\
     772        Return the channel dependent system temperatures.
     773
     774        Parameters:
     775
     776            row:    the rowno to get the information for. (default all rows)
     777
     778        Returns:
     779
     780            a list of Tsys values for the current selection
     781
     782        """
     783        return self._get_column( self._gettsysspectrum, row )
    759784
    760785    def get_weather(self, row=-1):
     
    11771202            end:      the end frequency or period to remove
    11781203
    1179             unit:     the frequency unit (default "MHz") or "" for
     1204            unit:     the frequency unit (default 'MHz') or '' for
    11801205                      explicit lag channels
    11811206
     
    12391264        if rowno is None:
    12401265            rowno = []
    1241         if mask is None:
    1242             mask = []
    12431266        if isinstance(rowno, int):
    12441267            rowno = [rowno]
    12451268        elif not (isinstance(rowno, list) or isinstance(rowno, tuple)):
    12461269            raise TypeError("The row number(s) must be int, list or tuple.")
    1247 
    12481270        if len(rowno) == 0: rowno = [i for i in xrange(self.nrow())]
    12491271
    1250         if not (isinstance(mask, list) or isinstance(mask, tuple)):
     1272        usecommonmask = True
     1273       
     1274        if mask is None:
     1275            mask = []
     1276        if isinstance(mask, list) or isinstance(mask, tuple):
     1277            if len(mask) == 0:
     1278                mask = [[]]
     1279            else:
     1280                if isinstance(mask[0], bool):
     1281                    if len(mask) != self.nchan(self.getif(rowno[0])):
     1282                        raise ValueError("The spectra and the mask have "
     1283                                         "different length.")
     1284                    mask = [mask]
     1285                elif isinstance(mask[0], list) or isinstance(mask[0], tuple):
     1286                    usecommonmask = False
     1287                    if len(mask) != len(rowno):
     1288                        raise ValueError("When specifying masks for each "
     1289                                         "spectrum, the numbers of them "
     1290                                         "must be identical.")
     1291                    for i in xrange(mask):
     1292                        if len(mask[i]) != self.nchan(self.getif(rowno[i])):
     1293                            raise ValueError("The spectra and the mask have "
     1294                                             "different length.")
     1295                else:
     1296                    raise TypeError("The mask must be a boolean list or "
     1297                                    "a list of boolean list.")
     1298        else:
    12511299            raise TypeError("The mask must be a boolean list or a list of "
    12521300                            "boolean list.")
    1253         if len(mask) == 0: mask = [True for i in xrange(self.nchan())]
    1254         if isinstance(mask[0], bool): mask = [mask]
    1255         elif not (isinstance(mask[0], list) or isinstance(mask[0], tuple)):
    1256             raise TypeError("The mask must be a boolean list or a list of "
    1257                             "boolean list.")
    1258 
    1259         usecommonmask = (len(mask) == 1)
    1260         if not usecommonmask:
    1261             if len(mask) != len(rowno):
    1262                 raise ValueError("When specifying masks for each spectrum, "
    1263                                  "the numbers of them must be identical.")
    1264         for amask in mask:
    1265             if len(amask) != self.nchan():
    1266                 raise ValueError("The spectra and the mask have different "
    1267                                  "length.")
    1268        
     1301
    12691302        res = []
    12701303
     
    13931426        if not (isinstance(mask,list) or isinstance(mask, tuple)):
    13941427            raise TypeError("The mask should be list or tuple.")
    1395         if len(mask) < 2:
    1396             raise TypeError("The mask elements should be > 1")
     1428        if len(mask) <= 0:
     1429            raise TypeError("The mask elements should be > 0")
    13971430        data = self._getabcissa(row)
    13981431        if len(data) != len(mask):
     
    14341467        if not (isinstance(mask,list) or isinstance(mask, tuple)):
    14351468            raise TypeError("The mask should be list or tuple.")
    1436         if len(mask) < 2:
    1437             raise TypeError("The mask elements should be > 1")
     1469        if len(mask) <= 0:
     1470            raise TypeError("The mask elements should be > 0")
    14381471        istart = []
    14391472        iend = []
     
    17211754                # provided your scantable is called scan
    17221755                selection = selector()
    1723                 selection.set_name("ORION*")
     1756                selection.set_name('ORION*')
    17241757                selection.set_ifs([1])
    17251758                scan.set_selection(selection)
     
    19621995                         The first row of the ascii file must give the column
    19631996                         names and these MUST include columns
    1964                          "ELEVATION" (degrees) and "FACTOR" (multiply data
     1997                         'ELEVATION' (degrees) and 'FACTOR' (multiply data
    19651998                         by this) somewhere.
    19661999                         The second row must give the data type of the
     
    19792012
    19802013            method:      Interpolation method when correcting from a table.
    1981                          Values are  "nearest", "linear" (default), "cubic"
    1982                          and "spline"
     2014                         Values are  'nearest', 'linear' (default), 'cubic'
     2015                         and 'spline'
    19832016
    19842017            insitu:      if False a new scantable is returned.
     
    20142047
    20152048            method:      Interpolation method for regridding the spectra.
    2016                          Choose from "nearest", "linear", "cubic" (default)
    2017                          and "spline"
     2049                         Choose from 'nearest', 'linear', 'cubic' (default)
     2050                         and 'spline'
    20182051
    20192052            insitu:      if False a new scantable is returned.
     
    20232056        """
    20242057        if insitu is None: insitu = rcParams["insitu"]
     2058        oldInsitu = self._math._insitu()
    20252059        self._math._setinsitu(insitu)
    20262060        varlist = vars()
     
    20282062        s = scantable(self._math._freq_align(self, reftime, method))
    20292063        s._add_history("freq_align", varlist)
     2064        self._math._setinsitu(oldInsitu)
    20302065        if insitu:
    20312066            self._assign(s)
     
    21032138
    21042139            method:      Interpolation method when correcting from a table.
    2105                          Values are  "nearest", "linear", "cubic" (default)
    2106                          and "spline"
     2140                         Values are  'nearest', 'linear', 'cubic' (default)
     2141                         and 'spline'
    21072142
    21082143            insitu:      if False a new scantable is returned.
     
    21872222
    21882223            poltype:    The new polarisation type. Valid types are:
    2189                         "linear", "circular", "stokes" and "linpol"
     2224                        'linear', 'circular', 'stokes' and 'linpol'
    21902225
    21912226        """
     
    22742309
    22752310    @asaplog_post_dec
     2311    def regrid_channel(self, width=5, plot=False, insitu=None):
     2312        """\
     2313        Regrid the spectra by the specified channel width
     2314
     2315        Parameters:
     2316
     2317            width:      The channel width (float) of regridded spectra
     2318                        in the current spectral unit.
     2319
     2320            plot:       [NOT IMPLEMENTED YET]
     2321                        plot the original and the regridded spectra.
     2322                        In this each indivual fit has to be approved, by
     2323                        typing 'y' or 'n'
     2324
     2325            insitu:     if False a new scantable is returned.
     2326                        Otherwise, the scaling is done in-situ
     2327                        The default is taken from .asaprc (False)
     2328
     2329        """
     2330        if insitu is None: insitu = rcParams['insitu']
     2331        varlist = vars()
     2332
     2333        if plot:
     2334           asaplog.post()
     2335           asaplog.push("Verification plot is not implemtnetd yet.")
     2336           asaplog.post("WARN")
     2337
     2338        s = self.copy()
     2339        s._regrid_specchan(width)
     2340
     2341        s._add_history("regrid_channel", varlist)
     2342
     2343#         if plot:
     2344#             from asap.asapplotter import new_asaplot
     2345#             theplot = new_asaplot(rcParams['plotter.gui'])
     2346#             theplot.set_panels()
     2347#             ylab=s._get_ordinate_label()
     2348#             #theplot.palette(0,["#777777","red"])
     2349#             for r in xrange(s.nrow()):
     2350#                 xsm=s._getabcissa(r)
     2351#                 ysm=s._getspectrum(r)
     2352#                 xorg=orgscan._getabcissa(r)
     2353#                 yorg=orgscan._getspectrum(r)
     2354#                 theplot.clear()
     2355#                 theplot.hold()
     2356#                 theplot.set_axes('ylabel',ylab)
     2357#                 theplot.set_axes('xlabel',s._getabcissalabel(r))
     2358#                 theplot.set_axes('title',s._getsourcename(r))
     2359#                 theplot.set_line(label='Original',color="#777777")
     2360#                 theplot.plot(xorg,yorg)
     2361#                 theplot.set_line(label='Smoothed',color="red")
     2362#                 theplot.plot(xsm,ysm)
     2363#                 ### Ugly part for legend
     2364#                 for i in [0,1]:
     2365#                     theplot.subplots[0]['lines'].append(
     2366#                         [theplot.subplots[0]['axes'].lines[i]]
     2367#                         )
     2368#                 theplot.release()
     2369#                 ### Ugly part for legend
     2370#                 theplot.subplots[0]['lines']=[]
     2371#                 res = raw_input("Accept smoothing ([y]/n): ")
     2372#                 if res.upper() == 'N':
     2373#                     s._setspectrum(yorg, r)
     2374#             theplot.quit()
     2375#             del theplot
     2376#             del orgscan
     2377
     2378        if insitu: self._assign(s)
     2379        else: return s
     2380
     2381    @asaplog_post_dec
    22762382    def _parse_wn(self, wn):
    22772383        if isinstance(wn, list) or isinstance(wn, tuple):
     
    22972403                val = int(wn[:-1])
    22982404                res = [i for i in xrange(val)]
    2299             elif wn[:2] == '>=' or wn[:2] == '=>':   # cases '>=a','=>a' : return [a,a+1,...,a_nyq]
     2405            elif wn[:2] == '>=' or wn[:2] == '=>':   # cases '>=a','=>a' : return [a,-999], which is
     2406                                                     #                     then interpreted in C++
     2407                                                     #                     side as [a,a+1,...,a_nyq]
     2408                                                     #                     (CAS-3759)
    23002409                val = int(wn[2:])
    2301                 res = [i for i in xrange(val, self.nchan()/2+1)]
    2302             elif wn[-2:] == '<=' or wn[-2:] == '=<': # cases 'a<=','a=<' : return [a,a+1,...,a_nyq]
     2410                res = [val, -999]
     2411                #res = [i for i in xrange(val, self.nchan()/2+1)]
     2412            elif wn[-2:] == '<=' or wn[-2:] == '=<': # cases 'a<=','a=<' : return [a,-999], which is
     2413                                                     #                     then interpreted in C++
     2414                                                     #                     side as [a,a+1,...,a_nyq]
     2415                                                     #                     (CAS-3759)
    23032416                val = int(wn[:-2])
    2304                 res = [i for i in xrange(val, self.nchan()/2+1)]
    2305             elif wn[0] == '>':                       # case '>a' :         return [a+1,a+2,...,a_nyq]
     2417                res = [val, -999]
     2418                #res = [i for i in xrange(val, self.nchan()/2+1)]
     2419            elif wn[0] == '>':                       # case '>a' :         return [a+1,-999], which is
     2420                                                     #                     then interpreted in C++
     2421                                                     #                     side as [a+1,a+2,...,a_nyq]
     2422                                                     #                     (CAS-3759)
    23062423                val = int(wn[1:])+1
    2307                 res = [i for i in xrange(val, self.nchan()/2+1)]
    2308             elif wn[-1] == '<':                      # case 'a<' :         return [a+1,a+2,...,a_nyq]
     2424                res = [val, -999]
     2425                #res = [i for i in xrange(val, self.nchan()/2+1)]
     2426            elif wn[-1] == '<':                      # case 'a<' :         return [a+1,-999], which is
     2427                                                     #                     then interpreted in C++
     2428                                                     #                     side as [a+1,a+2,...,a_nyq]
     2429                                                     #                     (CAS-3759)
    23092430                val = int(wn[:-1])+1
    2310                 res = [i for i in xrange(val, self.nchan()/2+1)]
     2431                res = [val, -999]
     2432                #res = [i for i in xrange(val, self.nchan()/2+1)]
    23112433
    23122434            return res
     
    23572479                                        number corresponding to the Nyquist
    23582480                                        frequency for the case of FFT).
    2359                            default is [].
     2481                           default is [0].
    23602482            rejwn:         the wave numbers NOT to be used for fitting.
    23612483                           can be set just as addwn but has higher priority:
     
    24012523                workscan = self.copy()
    24022524           
    2403             if mask          is None: mask          = [True for i in xrange(workscan.nchan())]
     2525            #if mask          is None: mask          = [True for i in xrange(workscan.nchan())]
     2526            if mask          is None: mask          = []
    24042527            if applyfft      is None: applyfft      = True
    24052528            if fftmethod     is None: fftmethod     = 'fft'
    24062529            if fftthresh     is None: fftthresh     = 3.0
    2407             if addwn         is None: addwn         = []
     2530            if addwn         is None: addwn         = [0]
    24082531            if rejwn         is None: rejwn         = []
    24092532            if clipthresh    is None: clipthresh    = 3.0
     
    24802603                                         number corresponding to the Nyquist
    24812604                                         frequency for the case of FFT).
    2482                             default is [].
     2605                            default is [0].
    24832606            rejwn:          the wave numbers NOT to be used for fitting.
    24842607                            can be set just as addwn but has higher priority:
     
    25412664                workscan = self.copy()
    25422665           
    2543             if mask           is None: mask           = [True for i in xrange(workscan.nchan())]
     2666            #if mask           is None: mask           = [True for i in xrange(workscan.nchan())]
     2667            if mask           is None: mask           = []
    25442668            if applyfft       is None: applyfft       = True
    25452669            if fftmethod      is None: fftmethod      = 'fft'
    25462670            if fftthresh      is None: fftthresh      = 3.0
    2547             if addwn          is None: addwn          = []
     2671            if addwn          is None: addwn          = [0]
    25482672            if rejwn          is None: rejwn          = []
    25492673            if clipthresh     is None: clipthresh     = 3.0
     
    26362760                workscan = self.copy()
    26372761
    2638             if mask         is None: mask         = [True for i in xrange(workscan.nchan())]
     2762            #if mask         is None: mask         = [True for i in xrange(workscan.nchan())]
     2763            if mask         is None: mask         = []
    26392764            if npiece       is None: npiece       = 2
    26402765            if clipthresh   is None: clipthresh   = 3.0
     
    27382863                workscan = self.copy()
    27392864           
    2740             if mask           is None: mask           = [True for i in xrange(workscan.nchan())]
     2865            #if mask           is None: mask           = [True for i in xrange(workscan.nchan())]
     2866            if mask           is None: mask           = []
    27412867            if npiece         is None: npiece         = 2
    27422868            if clipthresh     is None: clipthresh     = 3.0
     
    28142940                workscan = self.copy()
    28152941
    2816             if mask         is None: mask         = [True for i in \
    2817                                                        xrange(workscan.nchan())]
     2942            #if mask         is None: mask         = [True for i in \
     2943            #                                           xrange(workscan.nchan())]
     2944            if mask         is None: mask         = []
    28182945            if order        is None: order        = 0
    28192946            if plot         is None: plot         = False
     
    29533080                workscan = self.copy()
    29543081
    2955             if mask           is None: mask           = [True for i in xrange(workscan.nchan())]
     3082            #if mask           is None: mask           = [True for i in xrange(workscan.nchan())]
     3083            if mask           is None: mask           = []
    29563084            if order          is None: order          = 0
    29573085            if edge           is None: edge           = (0, 0)
  • /trunk/python/utils.py

    r2373 r2473  
    8686    else:
    8787        return message
     88
     89def toggle_verbose():
     90    from asap import rcParams
     91    rcParams['verbose'] = not bool(rcParams['verbose'])
  • /trunk/src/CMakeLists.txt

    r2373 r2473  
    2121# source files for libpyrap
    2222set( ASAP_SRCS
     23     ${SRCDIR}/concurrent.cpp
    2324     ${SRCDIR}/MathUtils.cpp
    2425     ${SRCDIR}/TableTraverse.cpp
     
    8283     ${SRCDIR}/python_asap.cpp )
    8384
    84 add_library( ${ASAPLIB} SHARED ${ASAP_SRCS} ${ASAP_PYSRCS} )
     85add_library( ${ASAPLIB} SHARED ${ASAP_SRCS} )
     86add_library( ${ASAPPYLIB} SHARED ${ASAP_PYSRCS} )
    8587
    8688# library name must be _asap.so
    87 set_target_properties( ${ASAPLIB}
     89set_target_properties( ${ASAPPYLIB}
    8890                       PROPERTIES
    89                        PREFIX _
     91                       PREFIX ""
    9092                       SUFFIX .so )
    9193
     
    9698                       #${CASACORE_LIBRARIES}
    9799                       ${WCSLIB} )
     100target_link_libraries( ${ASAPPYLIB}
     101                       ${ASAPLIB} )
    98102
    99 add_dependencies( inst ${ASAPLIB} )
     103add_dependencies( inst ${ASAPLIB}
     104                       ${ASAPPYLIB} )
    100105
    101106# install directory
    102107install( TARGETS ${ASAPLIB}
     108         LIBRARY DESTINATION ${LIB_INSTALL_DIR} )
     109install( TARGETS ${ASAPPYLIB}
    103110         LIBRARY DESTINATION ${PYTHON_INSTALL_DIR} )
    104 if( NOT STANDALONE )
    105   execute_process(
    106     COMMAND ln -Fs ../${PYTHON_INSTALL_DIR}/_asap.so ${CMAKE_INSTALL_PREFIX}/lib/_asap.so
    107     OUTPUT_VARIABLE stuff)
    108 endif()
     111#if( NOT STANDALONE )
     112#  execute_process(
     113#    COMMAND ln -Fs ../${PYTHON_INSTALL_DIR}/_${ASAPLIB}.so ${CMAKE_INSTALL_PREFIX}/lib/_${ASAPLIB}.so
     114#    OUTPUT_VARIABLE stuff)
     115#endif()
  • /trunk/src/FillerBase.cpp

    r2373 r2473  
    121121  Int idx = -1 ;
    122122  for ( uInt i = 0 ; i < nEntry ; i++ ) {
    123     if ( restfreq.conform( mEntry_[i] ) ) {
    124       if ( allEQ( restfreq, mEntry_[i] ) ) {
    125         idx = i ;
    126         break ;
    127       }
     123    if ( restfreq.conform( mEntry_[i] ) &&
     124         allEQ( restfreq, mEntry_[i] ) ) {
     125      idx = i ;
     126      break ;
    128127    }
    129128  }
     
    134133    Vector<String> tmp ;
    135134    id = table_->molecules().addEntry(restfreq,tmp,tmp) ;
    136     mEntry_.push_back( restfreq ) ;
     135    mEntry_.push_back( restfreq.copy() ) ;
    137136    mIdx_.push_back( id ) ;
    138137  }
  • /trunk/src/Makefile

    r2373 r2473  
    142142HEADERS   := MathUtils.h \
    143143             LineCatalog.h \
    144              Lorentzian1D.h \
    145              Lorentzian1DParam.h \
    146144             Logger.h \
    147145             STAttr.h \
  • /trunk/src/STFitter.cpp

    r2373 r2473  
    22//# Fitter.cc: A Fitter class for spectra
    33//#--------------------------------------------------------------------------
    4 //# Copyright (C) 2004
     4//# Copyright (C) 2004-2012
    55//# ATNF
    66//#
     
    3838#include <scimath/Functionals/CompoundFunction.h>
    3939#include <scimath/Functionals/Gaussian1D.h>
    40 #include "Lorentzian1D.h"
     40#include <scimath/Functionals/Lorentzian1D.h>
    4141#include <scimath/Functionals/Sinusoid1D.h>
    4242#include <scimath/Functionals/Polynomial.h>
     
    118118    g = dynamic_cast<Gaussian1D<Float>* >(funcs_[i]);
    119119    if (g) {
     120      const GaussianSpectralElement *gauss =
     121        dynamic_cast<const GaussianSpectralElement *>(listGauss[i]) ;
     122      (*g)[0] = gauss->getAmpl();
     123      (*g)[1] = gauss->getCenter();
     124      (*g)[2] = gauss->getFWHM();     
     125      /*
    120126      (*g)[0] = listGauss[i].getAmpl();
    121127      (*g)[1] = listGauss[i].getCenter();
    122128      (*g)[2] = listGauss[i].getFWHM();
     129      */
    123130    }
    124131  }
  • /trunk/src/STGrid.cpp

    r2373 r2473  
    1 #include <iostream>
    2 #include <fstream>
    3 
     1//
     2// C++ Implementation: STGrid
     3//
     4// Description:
     5//
     6//
     7// Author: Takeshi Nakazato <takeshi.nakazato@nao.ac.jp>, (C) 2011
     8//
     9// Copyright: See COPYING file that comes with this distribution
     10//
     11//
    412#include <casa/BasicSL/String.h>
    513#include <casa/Arrays/Vector.h>
    6 #include <casa/Arrays/Matrix.h>
    7 #include <casa/Arrays/Cube.h>
    814#include <casa/Arrays/ArrayMath.h>
    9 #include <casa/Arrays/ArrayPartMath.h>
    1015#include <casa/Quanta/Quantum.h>
    1116#include <casa/Quanta/QuantumHolder.h>
     
    1520#include <tables/Tables/Table.h>
    1621#include <tables/Tables/TableRecord.h>
     22#include <tables/Tables/TableRow.h>
    1723#include <tables/Tables/ExprNode.h>
    1824#include <tables/Tables/ScalarColumn.h>
    1925#include <tables/Tables/ArrayColumn.h>
     26#include <tables/Tables/TableCopy.h>
    2027
    2128#include <measures/Measures/MDirection.h>
    2229
    23 #include <MathUtils.h>
     30#include "MathUtils.h"
     31#include <atnf/PKSIO/SrcType.h>
    2432
    2533#include "STGrid.h"
    2634
    2735using namespace std ;
     36using namespace concurrent ;
    2837using namespace casa ;
    2938using namespace asap ;
     
    3140namespace asap {
    3241
     42// for performance check
     43double eToInt = 0.0 ;
     44double eGetWeight = 0.0 ;
     45
    3346// constructor
    3447STGrid::STGrid()
     48  : vshape_( 1 ), wshape_( 2 ), dshape_( 2 )
    3549{
    3650  init() ;
     
    3852
    3953STGrid::STGrid( const string infile )
     54  : vshape_( 1 ), wshape_( 2 ), dshape_( 2 )
    4055{
    4156  init() ;
    4257
    4358  setFileIn( infile ) ;
     59}
     60
     61STGrid::STGrid( const vector<string> infile )
     62{
     63  init() ;
     64
     65  setFileList( infile ) ;
    4466}
    4567
     
    6082  userSupport_ = -1 ;
    6183  convSampling_ = 100 ;
     84  nprocessed_ = 0 ;
     85  nchunk_ = 0 ;
     86
     87  // initialize user input
     88  nxUI_ = -1 ;
     89  nyUI_ = -1 ;
     90  cellxUI_ = "" ;
     91  cellyUI_ = "" ;
     92  centerUI_ = "" ;
     93  doclip_ = False ;
    6294}
    6395
    6496void STGrid::setFileIn( const string infile )
    6597{
     98  nfile_ = 1 ;
    6699  String name( infile ) ;
    67   if ( infile_.compare( name ) != 0 ) {
    68     infile_ = String( infile ) ;
    69     tab_ = Table( infile_ ) ;
     100  infileList_.resize( nfile_ ) ;
     101  infileList_[0] = String(infile) ;
     102}
     103
     104void STGrid::setFileList( const vector<string> infile )
     105{
     106  nfile_ = infile.size() ;
     107  infileList_.resize( nfile_ ) ;
     108  for ( uInt i = 0 ; i < nfile_ ; i++ ) {
     109    infileList_[i] = infile[i] ;
    70110  }
    71111}
     
    74114{
    75115  pollist_.assign( Vector<uInt>( pols ) ) ;
    76   cout << "pollist_ = " << pollist_ << endl ;
    77116}
    78117
     
    80119{
    81120  scanlist_.assign( Vector<uInt>( scans ) ) ;
    82   cout << "scanlist_ = " << scanlist_ << endl ;
    83121}
    84122
     
    87125  wtype_ = String( wType ) ;
    88126  wtype_.upcase() ;
    89   cout << "wtype_ = " << wtype_ << endl ;
    90127}
    91128
     
    96133                          string scenter )
    97134{
    98   ROArrayColumn<Double> dirCol( tab_, "DIRECTION" ) ;
    99   Matrix<Double> direction = dirCol.getColumn() ;
    100   Double rmax, rmin, dmax, dmin ;
    101   minMax( rmin, rmax, direction.row( 0 ) ) ;
    102   minMax( dmin, dmax, direction.row( 1 ) ) ;
    103 
    104   Int npx = (Int)nx ;
    105   Int npy = (Int)ny ;
    106   String cellx( scellx ) ;
    107   String celly( scelly ) ;
    108   String center( scenter ) ;
    109   setupGrid( npx, npy,
    110              cellx, celly,
    111              rmin, rmax,
    112              dmin, dmax,
    113              center ) ;
     135  nxUI_ = (Int)nx ;
     136  nyUI_ = (Int)ny ;
     137  cellxUI_ = String( scellx ) ;
     138  cellyUI_ = String( scelly ) ;
     139  centerUI_ = String( scenter ) ;
    114140}
    115141 
     
    150176                Double*);
    151177}
    152 void STGrid::grid()
     178void STGrid::call_ggridsd( Array<Double> &xypos,
     179                           Array<Complex> &spectra,
     180                           Int &nvispol,
     181                           Int &nvischan,
     182                           Array<Int> &flagtra,
     183                           Array<Int> &flagrow,
     184                           Array<Float> &weight,
     185                           Int &nrow,
     186                           Int &irow,
     187                           Array<Complex> &gdata,
     188                           Array<Float> &gwgt,
     189                           Int &nx,
     190                           Int &ny,
     191                           Int &npol,
     192                           Int &nchan,
     193                           Int &support,
     194                           Int &sampling,
     195                           Vector<Float> &convFunc,
     196                           Int *chanMap,
     197                           Int *polMap )
     198{
     199  // parameters for gridding
     200  Int idopsf = 0 ;
     201  Int len = npol*nchan ;
     202  Double *sumw_p = new Double[len] ;
     203  {
     204    Double *work_p = sumw_p ;
     205    for ( Int i = 0 ; i < len ; i++ ) {
     206      *work_p = 0.0 ;
     207      work_p++ ;
     208    }
     209  }
     210
     211  // prepare pointer
     212  Bool deletePos, deleteData, deleteWgt, deleteFlag, deleteFlagR, deleteConv, deleteDataG, deleteWgtG ;
     213  Double *xy_p = xypos.getStorage( deletePos ) ;
     214  const Complex *values_p = spectra.getStorage( deleteData ) ;
     215  const Int *flag_p = flagtra.getStorage( deleteFlag ) ;
     216  const Int *rflag_p = flagrow.getStorage( deleteFlagR ) ;
     217  const Float *wgt_p = weight.getStorage( deleteWgt ) ;
     218  Complex *grid_p = gdata.getStorage( deleteDataG ) ;
     219  Float *wgrid_p = gwgt.getStorage( deleteWgtG ) ;
     220  Float *conv_p = convFunc.getStorage( deleteConv ) ;
     221
     222  // pass copy of irow to ggridsd since it will be modified in theroutine
     223  Int irowCopy = irow ;
     224     
     225  // call ggridsd
     226  ggridsd( xy_p,
     227           values_p,
     228           &nvispol,
     229           &nvischan,
     230           &idopsf,
     231           flag_p,
     232           rflag_p,
     233           wgt_p,
     234           &nrow,
     235           &irowCopy,
     236           grid_p,
     237           wgrid_p,
     238           &nx,
     239           &ny,
     240           &npol,
     241           &nchan,
     242           &support,
     243           &sampling,
     244           conv_p,
     245           chanMap,
     246           polMap,
     247           sumw_p ) ;
     248
     249  // finalization
     250  xypos.putStorage( xy_p, deletePos ) ;
     251  spectra.freeStorage( values_p, deleteData ) ;
     252  flagtra.freeStorage( flag_p, deleteFlag ) ;
     253  flagrow.freeStorage( rflag_p, deleteFlagR ) ;
     254  weight.freeStorage( wgt_p, deleteWgt ) ;
     255  gdata.putStorage( grid_p, deleteDataG ) ;
     256  gwgt.putStorage( wgrid_p, deleteWgtG ) ;
     257  convFunc.putStorage( conv_p, deleteConv ) ;
     258  delete sumw_p ;
     259}
     260
     261#define NEED_UNDERSCORES
     262#if defined(NEED_UNDERSCORES)
     263#define ggridsd2 ggridsd2_
     264#endif
     265extern "C" {
     266   void ggridsd2(Double*,
     267                 const Complex*,
     268                 Int*,
     269                 Int*,
     270                 Int*,
     271                 const Int*,
     272                 const Int*,
     273                 const Float*,
     274                 Int*,
     275                 Int*,
     276                 Complex*,
     277                 Float*,
     278                 Int*,
     279                 Complex*,
     280                 Float*,
     281                 Float*,
     282                 Complex*,
     283                 Float*,
     284                 Float*,
     285                 Int*,
     286                 Int*,
     287                 Int *,
     288                 Int *,
     289                 Int*,
     290                 Int*,
     291                 Float*,
     292                 Int*,
     293                 Int*,
     294                 Double*);
     295}
     296void STGrid::call_ggridsd2( Array<Double> &xypos,
     297                            Array<Complex> &spectra,
     298                            Int &nvispol,
     299                            Int &nvischan,
     300                            Array<Int> &flagtra,
     301                            Array<Int> &flagrow,
     302                            Array<Float> &weight,
     303                            Int &nrow,
     304                            Int &irow,
     305                            Array<Complex> &gdata,
     306                            Array<Float> &gwgt,
     307                            Array<Int> &npoints,
     308                            Array<Complex> &clipmin,
     309                            Array<Float> &clipwmin,
     310                            Array<Float> &clipcmin,
     311                            Array<Complex> &clipmax,
     312                            Array<Float> &clipwmax,
     313                            Array<Float> &clipcmax,
     314                            Int &nx,
     315                            Int &ny,
     316                            Int &npol,
     317                            Int &nchan,
     318                            Int &support,
     319                            Int &sampling,
     320                            Vector<Float> &convFunc,
     321                            Int *chanMap,
     322                            Int *polMap )
     323{
     324  // parameters for gridding
     325  Int idopsf = 0 ;
     326  Int len = npol*nchan ;
     327  Double *sumw_p = new Double[len] ;
     328  {
     329    Double *work_p = sumw_p ;
     330    for ( Int i = 0 ; i < len ; i++ ) {
     331      *work_p = 0.0 ;
     332      work_p++ ;
     333    }
     334  }
     335
     336  // prepare pointer
     337  Bool deletePos, deleteData, deleteWgt, deleteFlag, deleteFlagR, deleteConv, deleteDataG, deleteWgtG, deleteNpts, deleteCMin, deleteCWMin, deleteCCMin, deleteCMax, deleteCWMax, deleteCCMax ;
     338  Double *xy_p = xypos.getStorage( deletePos ) ;
     339  const Complex *values_p = spectra.getStorage( deleteData ) ;
     340  const Int *flag_p = flagtra.getStorage( deleteFlag ) ;
     341  const Int *rflag_p = flagrow.getStorage( deleteFlagR ) ;
     342  const Float *wgt_p = weight.getStorage( deleteWgt ) ;
     343  Complex *grid_p = gdata.getStorage( deleteDataG ) ;
     344  Float *wgrid_p = gwgt.getStorage( deleteWgtG ) ;
     345  Float *conv_p = convFunc.getStorage( deleteConv ) ;
     346  Int *npts_p = npoints.getStorage( deleteNpts ) ;
     347  Complex *cmin_p = clipmin.getStorage( deleteCMin ) ;
     348  Float *cwmin_p = clipwmin.getStorage( deleteCWMin ) ;
     349  Float *ccmin_p = clipcmin.getStorage( deleteCCMin ) ;
     350  Complex *cmax_p = clipmax.getStorage( deleteCMax ) ;
     351  Float *cwmax_p = clipwmax.getStorage( deleteCWMax ) ;
     352  Float *ccmax_p = clipcmax.getStorage( deleteCCMax ) ;
     353
     354  // pass copy of irow to ggridsd since it will be modified in theroutine
     355  Int irowCopy = irow ;
     356     
     357  // call ggridsd
     358  ggridsd2( xy_p,
     359            values_p,
     360            &nvispol,
     361            &nvischan,
     362            &idopsf,
     363            flag_p,
     364            rflag_p,
     365            wgt_p,
     366            &nrow,
     367            &irowCopy,
     368            grid_p,
     369            wgrid_p,
     370            npts_p,
     371            cmin_p,
     372            cwmin_p,
     373            ccmin_p,
     374            cmax_p,
     375            cwmax_p,
     376            ccmax_p,
     377            &nx,
     378            &ny,
     379            &npol,
     380            &nchan,
     381            &support,
     382            &sampling,
     383            conv_p,
     384            chanMap,
     385            polMap,
     386            sumw_p ) ;
     387
     388  // finalization
     389  xypos.putStorage( xy_p, deletePos ) ;
     390  spectra.freeStorage( values_p, deleteData ) ;
     391  flagtra.freeStorage( flag_p, deleteFlag ) ;
     392  flagrow.freeStorage( rflag_p, deleteFlagR ) ;
     393  weight.freeStorage( wgt_p, deleteWgt ) ;
     394  gdata.putStorage( grid_p, deleteDataG ) ;
     395  gwgt.putStorage( wgrid_p, deleteWgtG ) ;
     396  convFunc.putStorage( conv_p, deleteConv ) ;
     397  clipmin.putStorage( cmin_p, deleteCMin ) ;
     398  clipwmin.putStorage( cwmin_p, deleteCWMin ) ;
     399  clipcmin.putStorage( ccmin_p, deleteCCMin ) ;
     400  clipmax.putStorage( cmax_p, deleteCMax ) ;
     401  clipwmax.putStorage( cwmax_p, deleteCWMax ) ;
     402  clipcmax.putStorage( ccmax_p, deleteCCMax ) ;
     403  delete sumw_p ;
     404}
     405
     406void STGrid::grid()
    153407{
    154408  LogIO os( LogOrigin("STGrid", "grid", WHERE) ) ;
    155 
    156   // retrieve data
    157   Cube<Float> spectra ;
    158   Matrix<Double> direction ;
    159   Cube<uChar> flagtra ;
    160   Matrix<uInt> rflag ;
    161   Matrix<Float> weight ;
    162   double t0, t1 ;
     409  double t0,t1 ;
     410
     411  // data selection
    163412  t0 = mathutil::gettimeofday_sec() ;
    164   getData( spectra, direction, flagtra, rflag, weight ) ;
     413  selectData() ;
    165414  t1 = mathutil::gettimeofday_sec() ;
    166   os << "getData: elapsed time is " << t1-t0 << " sec." << LogIO::POST ;
    167   IPosition sshape = spectra.shape() ;
    168   //os << "spectra.shape()=" << spectra.shape() << LogIO::POST ;
    169   //os << "max(spectra) = " << max(spectra) << LogIO::POST ;
    170   //os << "weight = " << weight << LogIO::POST ;
    171 
    172   // flagtra: uChar -> Int
    173   // rflag: uInt -> Int
    174   Cube<Int> flagI ;
    175   Matrix<Int> rflagI ;
    176   t0 = mathutil::gettimeofday_sec() ;
    177   toInt( &flagtra, &flagI ) ;
    178   toInt( &rflag, &rflagI ) ;
    179   t1 = mathutil::gettimeofday_sec() ;
    180   os << "toInt: elapsed time is " << t1-t0 << " sec." << LogIO::POST ;
    181  
     415  os << LogIO::DEBUGGING << "selectData: elapsed time is " << t1-t0 << " sec." << LogIO::POST ;
     416
     417  setupGrid() ;
     418  setupArray() ;
     419
     420  if ( wtype_.compare("UNIFORM") != 0 &&
     421       wtype_.compare("TINT") != 0 &&
     422       wtype_.compare("TSYS") != 0 &&
     423       wtype_.compare("TINTSYS") != 0 ) {
     424    LogIO os( LogOrigin("STGrid", "grid", WHERE) ) ;
     425    os << LogIO::WARN << "Unsupported weight type '" << wtype_ << "', apply UNIFORM weight" << LogIO::POST ;
     426    wtype_ = "UNIFORM" ;
     427  }
     428
    182429  // grid parameter
    183430  os << LogIO::DEBUGGING ;
     431  os << "----------" << endl ;
     432  os << "Data selection summary" << endl ;
     433  os << "   ifno = " << ifno_ << endl ;
     434  os << "   pollist = " << pollist_ << endl ;
     435  os << "   scanlist = " << scanlist_ << endl ;
    184436  os << "----------" << endl ;
    185437  os << "Grid parameter summary" << endl ;
     
    187439  os << "   (cellx,celly) = (" << cellx_ << "," << celly_ << ")" << endl ;
    188440  os << "   center = " << center_ << endl ;
     441  os << "   weighting = " << wtype_ << endl ;
     442  os << "   convfunc = " << convType_ << " with support " << convSupport_ << endl ;
     443  os << "   doclip = " << (doclip_?"True":"False") << endl ;
    189444  os << "----------" << LogIO::POST ;
    190445  os << LogIO::NORMAL ;
    191446
     447  if ( doclip_ )
     448    gridPerRowWithClipping() ;
     449  else
     450    gridPerRow() ;
     451}
     452
     453void STGrid::updateChunkShape()
     454{
     455  // TODO: nchunk_ must be determined from nchan_, npol_, and (nx_,ny_)
     456  //       by considering data size to be allocated for ggridsd input/output
     457  nchunk_ = 400 ;
     458  nchunk_ = min( nchunk_, nrow_ ) ;
     459  vshape_ = IPosition( 1, nchunk_ ) ;
     460  wshape_ = IPosition( 2, nchan_, nchunk_ ) ;
     461  dshape_ = IPosition( 2, 2, nchunk_ ) ;
     462}
     463
     464struct STGChunk {
     465  Int nrow ;
     466  Array<Complex> spectra;
     467  Array<Int> flagtra;
     468  Array<Int> rflag;
     469  Array<Float> weight;
     470  Array<Double> direction;
     471  STGChunk(IPosition const &wshape, IPosition const &vshape,
     472           IPosition const &dshape)
     473    : spectra(wshape), flagtra(wshape), rflag(vshape), weight(wshape),
     474      direction(dshape)
     475  { }
     476};
     477
     478struct STCommonData {
     479  Int gnx;
     480  Int gny;
     481  Int *chanMap;
     482  Vector<Float> convFunc ;
     483  Array<Complex> gdataArrC;
     484  Array<Float> gwgtArr;
     485  STCommonData(IPosition const &gshape, Array<Float> const &data)
     486    : gdataArrC(gshape, 0.0), gwgtArr(data) {}
     487};
     488
     489struct STCommonDataWithClipping {
     490  Int gnx;
     491  Int gny;
     492  Int *chanMap;
     493  Vector<Float> convFunc ;
     494  Array<Complex> gdataArrC;
     495  Array<Float> gwgtArr;
     496  Array<Int> npoints ;
     497  Array<Complex> clipMin ;
     498  Array<Float> clipWMin ;
     499  Array<Float> clipCMin ;
     500  Array<Complex> clipMax ;
     501  Array<Float> clipWMax ;
     502  Array<Float> clipCMax ; 
     503  STCommonDataWithClipping(IPosition const &gshape,
     504                           IPosition const &pshape,
     505                           Array<Float> const &data)
     506    : gdataArrC(gshape, 0.0),
     507      gwgtArr(data),
     508      npoints(pshape, 0),
     509      clipMin(gshape, Complex(FLT_MAX,0.0)),
     510      clipWMin(gshape, 0.0),
     511      clipCMin(gshape, 0.0),
     512      clipMax(gshape, Complex(-FLT_MAX,0.0)),
     513      clipWMax(gshape, 0.0),
     514      clipCMax(gshape, 0.0)
     515  {}
     516};
     517
     518#define DO_AHEAD 3
     519
     520struct STContext {
     521  STCommonData &common;
     522  FIFO<STGChunk *, DO_AHEAD> queue;
     523  STGrid *const self;
     524  const Int pol;
     525  STContext(STGrid *obj, STCommonData &common, Int pol)
     526    : self(obj), common(common), pol(pol) {}
     527};
     528
     529struct STContextWithClipping {
     530  STCommonDataWithClipping &common;
     531  FIFO<STGChunk *, DO_AHEAD> queue;
     532  STGrid *const self;
     533  const Int pol;
     534  STContextWithClipping(STGrid *obj, STCommonDataWithClipping &common, Int pol)
     535    : self(obj), common(common), pol(pol) {}
     536};
     537
     538
     539bool STGrid::produceChunk(void *ctx) throw(PCException)
     540{
     541  STContext &context = *(STContext *)ctx;
     542  if ( context.self->nprocessed_ >= context.self->nrow_ ) {
     543    return false;
     544  }
     545  STGChunk *chunk = new STGChunk(context.self->wshape_,
     546                                 context.self->vshape_,
     547                                 context.self->dshape_);
     548
     549  double t0 = mathutil::gettimeofday_sec() ;
     550  chunk->nrow = context.self->getDataChunk(
     551        context.self->wshape_, context.self->vshape_, context.self->dshape_,
     552        chunk->spectra, chunk->direction,
     553        chunk->flagtra, chunk->rflag, chunk->weight);
     554  double t1 = mathutil::gettimeofday_sec() ;
     555  context.self->eGetData_ += t1-t0 ;
     556
     557  context.queue.lock();
     558  context.queue.put(chunk);
     559  context.queue.unlock();
     560  return true;
     561}
     562
     563void STGrid::consumeChunk(void *ctx) throw(PCException)
     564{
     565  STContext &context = *(STContext *)ctx;
     566  STGChunk *chunk = NULL;
     567  try {
     568    context.queue.lock();
     569    chunk = context.queue.get();
     570    context.queue.unlock();
     571  } catch (FullException &e) {
     572    context.queue.unlock();
     573    // TODO: log error
     574    throw PCException();
     575  }
     576
     577  double t0, t1 ;
     578  // world -> pixel
     579  Array<Double> xypos( context.self->dshape_ ) ;
     580  t0 = mathutil::gettimeofday_sec() ;
     581  context.self->toPixel( chunk->direction, xypos ) ;
     582  t1 = mathutil::gettimeofday_sec() ;
     583  context.self->eToPixel_ += t1-t0 ;
     584   
     585  // call ggridsd
     586  Int nvispol = 1 ;
     587  Int irow = -1 ;
     588  t0 = mathutil::gettimeofday_sec() ;
     589  context.self->call_ggridsd( xypos,
     590                chunk->spectra,
     591                nvispol,
     592                context.self->nchan_,
     593                chunk->flagtra,
     594                chunk->rflag,
     595                chunk->weight,
     596                chunk->nrow,
     597                irow,
     598                context.common.gdataArrC,
     599                context.common.gwgtArr,
     600                context.common.gnx,
     601                context.common.gny,
     602                context.self->npol_,
     603                context.self->nchan_,
     604                context.self->convSupport_,
     605                context.self->convSampling_,
     606                context.common.convFunc,
     607                context.common.chanMap,
     608                (Int*)&context.pol ) ;
     609  t1 = mathutil::gettimeofday_sec() ;
     610  context.self->eGGridSD_ += t1-t0 ;
     611 
     612  delete chunk;
     613}
     614
     615void STGrid::gridPerRow()
     616{
     617  LogIO os( LogOrigin("STGrid", "gridPerRow", WHERE) ) ;
     618  double t0, t1 ;
     619
     620
     621  // grid data
     622  // Extend grid plane with convSupport_
     623  //   Int gnx = nx_+convSupport_*2 ;
     624  //   Int gny = ny_+convSupport_*2 ;
     625  Int gnx = nx_;
     626  Int gny = ny_;
     627
     628  IPosition gshape( 4, gnx, gny, npol_, nchan_ ) ;
     629  // 2011/12/20 TN
     630  // data_ and gwgtArr share storage
     631  data_.resize( gshape ) ;
     632  data_ = 0.0 ;
     633  STCommonData common = STCommonData(gshape, data_);
     634  common.gnx = gnx ;
     635  common.gny = gny ;
     636
     637  // parameters for gridding
     638  Int *chanMap = new Int[nchan_] ;
     639  for ( Int i = 0 ; i < nchan_ ; i++ ) {
     640    chanMap[i] = i ;
     641  }
     642  common.chanMap = chanMap;
     643
    192644  // convolution kernel
    193   Vector<Float> convFunc ;
    194645  t0 = mathutil::gettimeofday_sec() ;
    195   setConvFunc( convFunc ) ;
     646  setConvFunc( common.convFunc ) ;
    196647  t1 = mathutil::gettimeofday_sec() ;
    197   os << "setConvFunc: elapsed time is " << t1-t0 << " sec." << LogIO::POST ;
    198   //cout << "convSupport=" << convSupport_ << endl ;
    199   //cout << "convFunc=" << convFunc << endl ;
    200 
     648  os << LogIO::DEBUGGING << "setConvFunc: elapsed time is " << t1-t0 << " sec." << LogIO::POST ;
     649
     650  // for performance check
     651  eGetData_ = 0.0 ;
     652  eToPixel_ = 0.0 ;
     653  eGGridSD_ = 0.0 ;
     654  double eInitPol = 0.0 ;
     655
     656  for ( uInt ifile = 0 ; ifile < nfile_ ; ifile++ ) {
     657    initTable( ifile ) ;
     658
     659    os << "start table " << ifile << ": " << infileList_[ifile] << LogIO::POST ;   
     660    Broker broker = Broker(produceChunk, consumeChunk);
     661    for ( Int ipol = 0 ; ipol < npol_ ; ipol++ ) {
     662      t0 = mathutil::gettimeofday_sec() ;
     663      initPol( ipol ) ; // set ptab_ and attach()
     664      t1 = mathutil::gettimeofday_sec() ;
     665      eInitPol += t1-t0 ;
     666     
     667      STContext context(this, common, ipol);
     668     
     669      os << "start pol " << ipol << LogIO::POST ;
     670     
     671      nprocessed_ = 0 ;
     672#if 1
     673      broker.runProducerAsMasterThread(&context, DO_AHEAD);
     674#else
     675      for (;;) {
     676        bool produced = produceChunk(&context);
     677        if (! produced) {
     678          break;
     679        }
     680        consumeChunk(&context);
     681      }
     682#endif
     683
     684      os << "end pol " << ipol << LogIO::POST ;
     685
     686    }
     687    os << "end table " << ifile << LogIO::POST ;   
     688  }
     689  os << LogIO::DEBUGGING << "initPol: elapsed time is " << eInitPol << " sec." << LogIO::POST ;
     690  os << LogIO::DEBUGGING << "getData: elapsed time is " << eGetData_-eToInt-eGetWeight << " sec." << LogIO::POST ;
     691  os << LogIO::DEBUGGING << "toPixel: elapsed time is " << eToPixel_ << " sec." << LogIO::POST ;
     692  os << LogIO::DEBUGGING << "ggridsd: elapsed time is " << eGGridSD_ << " sec." << LogIO::POST ;
     693  os << LogIO::DEBUGGING << "toInt: elapsed time is " << eToInt << " sec." << LogIO::POST ;
     694  os << LogIO::DEBUGGING << "getWeight: elapsed time is " << eGetWeight << " sec." << LogIO::POST ;
     695 
     696  delete chanMap ;
     697
     698  // set data
     699  setData( common.gdataArrC, common.gwgtArr ) ;
     700
     701}
     702
     703void STGrid::consumeChunkWithClipping(void *ctx) throw(PCException)
     704{
     705  STContextWithClipping &context = *(STContextWithClipping *)ctx;
     706  STGChunk *chunk = NULL;
     707  try {
     708    context.queue.lock();
     709    chunk = context.queue.get();
     710    context.queue.unlock();
     711  } catch (FullException &e) {
     712    context.queue.unlock();
     713    // TODO: log error
     714    throw PCException();
     715  }
     716
     717  double t0, t1 ;
    201718  // world -> pixel
    202   Matrix<Double> xypos( direction.shape(), 0.0 ) ;
     719  Array<Double> xypos( context.self->dshape_ ) ;
    203720  t0 = mathutil::gettimeofday_sec() ;
    204   toPixel( direction, xypos ) ; 
     721  context.self->toPixel( chunk->direction, xypos ) ;
    205722  t1 = mathutil::gettimeofday_sec() ;
    206   os << "toPixel: elapsed time is " << t1-t0 << " sec." << LogIO::POST ;
     723  context.self->eToPixel_ += t1-t0 ;
     724   
     725  // call ggridsd
     726  Int nvispol = 1 ;
     727  Int irow = -1 ;
     728  t0 = mathutil::gettimeofday_sec() ;
     729  context.self->call_ggridsd2( xypos,
     730                chunk->spectra,
     731                nvispol,
     732                context.self->nchan_,
     733                chunk->flagtra,
     734                chunk->rflag,
     735                chunk->weight,
     736                chunk->nrow,
     737                irow,
     738                context.common.gdataArrC,
     739                context.common.gwgtArr,
     740                context.common.npoints,
     741                context.common.clipMin,
     742                context.common.clipWMin,
     743                context.common.clipCMin,
     744                context.common.clipMax,
     745                context.common.clipWMax,
     746                context.common.clipCMax,
     747                context.common.gnx,
     748                context.common.gny,
     749                context.self->npol_,
     750                context.self->nchan_,
     751                context.self->convSupport_,
     752                context.self->convSampling_,
     753                context.common.convFunc,
     754                context.common.chanMap,
     755                (Int*)&context.pol ) ;
     756  t1 = mathutil::gettimeofday_sec() ;
     757  context.self->eGGridSD_ += t1-t0 ;
    207758 
    208   // call ggridsd
    209   Bool deletePos, deleteData, deleteWgt, deleteFlag, deleteFlagR, deleteConv, deleteDataG, deleteWgtG ;
    210   Double *xypos_p = xypos.getStorage( deletePos ) ;
    211   Cube<Complex> dataC( spectra.shape(), 0.0 ) ;
    212   setReal( dataC, spectra ) ;
    213   const Complex *data_p = dataC.getStorage( deleteData ) ;
    214   const Float *wgt_p = weight.getStorage( deleteWgt ) ;
    215   const Int *flag_p = flagI.getStorage( deleteFlag ) ;
    216   const Int *rflag_p = rflagI.getStorage( deleteFlagR ) ;
    217   Float *conv_p = convFunc.getStorage( deleteConv ) ;
     759  delete chunk;
     760}
     761
     762void STGrid::gridPerRowWithClipping()
     763{
     764  LogIO os( LogOrigin("STGrid", "gridPerRowWithClipping", WHERE) ) ;
     765  double t0, t1 ;
     766
     767
     768  // grid data
    218769  // Extend grid plane with convSupport_
    219   Int gnx = nx_ ;
    220   Int gny = ny_ ;
    221 //   Int gnx = nx_+convSupport_*2 ;
    222 //   Int gny = ny_+convSupport_*2 ;
     770  //   Int gnx = nx_+convSupport_*2 ;
     771  //   Int gny = ny_+convSupport_*2 ;
     772  Int gnx = nx_;
     773  Int gny = ny_;
     774
    223775  IPosition gshape( 4, gnx, gny, npol_, nchan_ ) ;
    224   Array<Complex> gdataArrC( gshape, 0.0 ) ;
    225   Array<Float> gwgtArr( gshape, 0.0 ) ;
    226   Complex *gdata_p = gdataArrC.getStorage( deleteDataG ) ;
    227   Float *wdata_p = gwgtArr.getStorage( deleteWgtG ) ;
    228   Int idopsf = 0 ;
     776  IPosition pshape( 3, gnx, gny, npol_ ) ;
     777  // 2011/12/20 TN
     778  // data_ and gwgtArr share storage
     779  data_.resize( gshape ) ;
     780  data_ = 0.0 ;
     781  STCommonDataWithClipping common = STCommonDataWithClipping( gshape,
     782                                                              pshape,
     783                                                              data_ ) ;
     784  common.gnx = gnx ;
     785  common.gny = gny ;
     786
     787  // parameters for gridding
    229788  Int *chanMap = new Int[nchan_] ;
    230   {
    231     Int *work_p = chanMap ;
    232     for ( Int i = 0 ; i < nchan_ ; i++ ) {
    233       *work_p = i ;
    234       work_p++ ;
    235     }
    236   }
    237   Int *polMap = new Int[npol_] ;
    238   {
    239     Int *work_p = polMap ;
    240     for ( Int i = 0 ; i < npol_ ; i++ ) {
    241       *work_p = i ;
    242       work_p++ ;
    243     }
    244   }
    245   Double *sumw_p = new Double[npol_*nchan_] ;
    246   {
    247     Double *work_p = sumw_p ;
    248     for ( Int i = 0 ; i < npol_*nchan_ ; i++ ) {
    249       *work_p = 0.0 ;
    250       work_p++ ;
    251     }
    252   }
     789  for ( Int i = 0 ; i < nchan_ ; i++ ) {
     790    chanMap[i] = i ;
     791  }
     792  common.chanMap = chanMap;
     793
     794  // convolution kernel
    253795  t0 = mathutil::gettimeofday_sec() ;
    254   Int irow = -1 ;
    255   ggridsd( xypos_p,
    256            data_p,
    257            &npol_,
    258            &nchan_,
    259            &idopsf,
    260            flag_p,
    261            rflag_p,
    262            wgt_p,
    263            &nrow_,
    264            &irow,
    265            gdata_p,
    266            wdata_p,
    267            &gnx,
    268            &gny,
    269            &npol_,
    270            &nchan_,
    271            &convSupport_,
    272            &convSampling_,
    273            conv_p,
    274            chanMap,
    275            polMap,
    276            sumw_p ) ;
     796  setConvFunc( common.convFunc ) ;
    277797  t1 = mathutil::gettimeofday_sec() ;
    278   os << "ggridsd: elapsed time is " << t1-t0 << " sec." << LogIO::POST ;
    279   xypos.putStorage( xypos_p, deletePos ) ;
    280   dataC.freeStorage( data_p, deleteData ) ;
    281   weight.freeStorage( wgt_p, deleteWgt ) ;
    282   flagI.freeStorage( flag_p, deleteFlag ) ;
    283   rflagI.freeStorage( rflag_p, deleteFlagR ) ;
    284   convFunc.putStorage( conv_p, deleteConv ) ;
    285   delete polMap ;
     798  os << LogIO::DEBUGGING << "setConvFunc: elapsed time is " << t1-t0 << " sec." << LogIO::POST ;
     799
     800  // for performance check
     801  eGetData_ = 0.0 ;
     802  eToPixel_ = 0.0 ;
     803  eGGridSD_ = 0.0 ;
     804  double eInitPol = 0.0 ;
     805
     806  for ( uInt ifile = 0 ; ifile < nfile_ ; ifile++ ) {
     807    initTable( ifile ) ;
     808
     809    os << "start table " << ifile << ": " << infileList_[ifile] << LogIO::POST ;   
     810    Broker broker = Broker(produceChunk, consumeChunkWithClipping);
     811    for ( Int ipol = 0 ; ipol < npol_ ; ipol++ ) {
     812      t0 = mathutil::gettimeofday_sec() ;
     813      initPol( ipol ) ; // set ptab_ and attach()
     814      t1 = mathutil::gettimeofday_sec() ;
     815      eInitPol += t1-t0 ;
     816     
     817      STContextWithClipping context(this, common, ipol);
     818     
     819      os << "start pol " << ipol << LogIO::POST ;
     820     
     821      nprocessed_ = 0 ;
     822#if 1
     823      broker.runProducerAsMasterThread(&context, DO_AHEAD);
     824#else
     825      for (;;) {
     826        bool produced = produceChunk(&context);
     827        if (! produced) {
     828          break;
     829        }
     830        consumeChunkWithClipping(&context);
     831      }
     832#endif
     833
     834      os << "end pol " << ipol << LogIO::POST ;
     835
     836    }
     837    os << "end table " << ifile << LogIO::POST ;   
     838  }
     839  os << LogIO::DEBUGGING << "initPol: elapsed time is " << eInitPol << " sec." << LogIO::POST ;
     840  os << LogIO::DEBUGGING << "getData: elapsed time is " << eGetData_-eToInt-eGetWeight << " sec." << LogIO::POST ;
     841  os << LogIO::DEBUGGING << "toPixel: elapsed time is " << eToPixel_ << " sec." << LogIO::POST ;
     842  os << LogIO::DEBUGGING << "ggridsd2: elapsed time is " << eGGridSD_ << " sec." << LogIO::POST ;
     843  os << LogIO::DEBUGGING << "toInt: elapsed time is " << eToInt << " sec." << LogIO::POST ;
     844  os << LogIO::DEBUGGING << "getWeight: elapsed time is " << eGetWeight << " sec." << LogIO::POST ;
     845 
    286846  delete chanMap ;
    287   gdataArrC.putStorage( gdata_p, deleteDataG ) ;
    288   gwgtArr.putStorage( wdata_p, deleteWgtG ) ;
    289   Array<Float> gdataArr = real( gdataArrC ) ;
    290   setData( data_, gdataArr, gwgtArr ) ;
    291   //Matrix<Double> sumWeight( IPosition( 2, npol_, nchan_ ), sumw_p, TAKE_OVER ) ;
    292   delete sumw_p ;
    293   //cout << "sumWeight = " << sumWeight << endl ;
    294 //   os << "gdataArr = " << gdataArr << LogIO::POST ;
    295 //   os << "gwgtArr = " << gwgtArr << LogIO::POST ;
    296 //   os << "data_ " << data_ << LogIO::POST ;
    297 }
    298 
    299 void STGrid::setData( Array<Float> &data,
    300                       Array<Float> &gdata,
     847
     848  // clip min and max in each grid
     849//   os << "BEFORE CLIPPING" << LogIO::POST ;
     850//   os << "gdataArrC=" << common.gdataArrC << LogIO::POST ;
     851//   os << "gwgtArr=" << common.gwgtArr << LogIO::POST ;
     852  t0 = mathutil::gettimeofday_sec() ;
     853  clipMinMax( common.gdataArrC,
     854              common.gwgtArr,
     855              common.npoints,
     856              common.clipMin,
     857              common.clipWMin,
     858              common.clipCMin,
     859              common.clipMax,
     860              common.clipWMax,
     861              common.clipCMax ) ;
     862  t1 = mathutil::gettimeofday_sec() ;
     863  os << LogIO::DEBUGGING << "clipMinMax: elapsed time is " << t1-t0 << " sec." << LogIO::POST ;
     864//   os << "AFTER CLIPPING" << LogIO::POST ;
     865//   os << "gdataArrC=" << common.gdataArrC << LogIO::POST ;
     866//   os << "gwgtArr=" << common.gwgtArr << LogIO::POST ;
     867
     868  // set data
     869  setData( common.gdataArrC, common.gwgtArr ) ;
     870
     871}
     872
     873void STGrid::clipMinMax( Array<Complex> &grid,
     874                         Array<Float> &weight,
     875                         Array<Int> &npoints,
     876                         Array<Complex> &clipmin,
     877                         Array<Float> &clipwmin,
     878                         Array<Float> &clipcmin,
     879                         Array<Complex> &clipmax,
     880                         Array<Float> &clipwmax,
     881                         Array<Float> &clipcmax )
     882{
     883  //LogIO os( LogOrigin("STGrid","clipMinMax",WHERE) ) ;
     884
     885  // prepare pointers
     886  Bool delG, delW, delNP, delCMin, delCWMin, delCCMin, delCMax, delCWMax, delCCMax ;
     887  Complex *grid_p = grid.getStorage( delG ) ;
     888  Float *wgt_p = weight.getStorage( delW ) ;
     889  const Int *npts_p = npoints.getStorage( delNP ) ;
     890  const Complex *cmin_p = clipmin.getStorage( delCMin ) ;
     891  const Float *cwmin_p = clipwmin.getStorage( delCWMin ) ;
     892  const Float *ccmin_p = clipcmin.getStorage( delCCMin ) ;
     893  const Complex *cmax_p = clipmax.getStorage( delCMax ) ;
     894  const Float *cwmax_p = clipwmax.getStorage( delCWMax ) ;
     895  const Float *ccmax_p = clipcmax.getStorage( delCCMax ) ;
     896
     897  const IPosition &gshape = grid.shape() ;
     898  long offset = gshape[0] * gshape[1] * gshape[2] ; // nx * ny * npol
     899  Int nchan = gshape[3] ;
     900  long origin = nchan * offset ;
     901  for ( long i = 0 ; i < offset ; i++ ) {
     902    if ( *npts_p > 2 ) {
     903      for ( Int ichan = 0 ; ichan < nchan ; ichan++ ) {
     904        // clip minimum and maximum
     905        *grid_p -= (*cmin_p)*(*cwmin_p)*(*ccmin_p)
     906          + (*cmax_p)*(*cwmax_p)*(*ccmax_p) ;
     907        *wgt_p -= (*cwmin_p)*(*ccmin_p)
     908          + (*cwmax_p)*(*ccmax_p) ;
     909       
     910        grid_p += offset ;
     911        wgt_p += offset ;
     912        cmin_p += offset ;
     913        cwmin_p += offset ;
     914        ccmin_p += offset ;
     915        cmax_p += offset ;
     916        cwmax_p += offset ;
     917        ccmax_p += offset ;
     918      }
     919      grid_p -= origin ;
     920      wgt_p -= origin ;
     921      cmin_p -= origin ;
     922      cwmin_p -= origin ;
     923      ccmin_p -= origin ;
     924      cmax_p -= origin ;
     925      cwmax_p -= origin ;
     926      ccmax_p -= origin ;
     927    }
     928    grid_p++ ;
     929    wgt_p++ ;
     930    npts_p++ ;
     931    cmin_p++ ;
     932    cwmin_p++ ;
     933    ccmin_p++ ;
     934    cmax_p++ ;
     935    cwmax_p++ ;
     936    ccmax_p++ ;
     937  }
     938  grid_p -= offset ;
     939  wgt_p -= offset ;
     940  npts_p -= offset ;
     941  cmin_p -= offset ;
     942  cwmin_p -= offset ;
     943  ccmin_p -= offset ;
     944  cmax_p -= offset ;
     945  cwmax_p -= offset ;
     946  ccmax_p -= offset ; 
     947
     948  // finalization
     949  grid.putStorage( grid_p, delG ) ;
     950  weight.putStorage( wgt_p, delW ) ;
     951  npoints.freeStorage( npts_p, delNP ) ;
     952  clipmin.freeStorage( cmin_p, delCMin ) ;
     953  clipwmin.freeStorage( cwmin_p, delCWMin ) ;
     954  clipcmin.freeStorage( ccmin_p, delCCMin ) ;
     955  clipmax.freeStorage( cmax_p, delCMax ) ;
     956  clipwmax.freeStorage( cwmax_p, delCWMax ) ;
     957  clipcmax.freeStorage( ccmax_p, delCCMax ) ;
     958}
     959
     960void STGrid::initPol( Int ipol )
     961{
     962  LogIO os( LogOrigin("STGrid","initPol",WHERE) ) ;
     963  if ( npolOrg_ == 1 ) {
     964    os << "single polarization data." << LogIO::POST ;
     965    ptab_ = tab_ ;
     966  }
     967  else
     968    ptab_ = tab_( tab_.col("POLNO") == pollist_[ipol] ) ;
     969
     970  attach( ptab_ ) ;
     971}
     972
     973void STGrid::initTable( uInt idx )
     974{
     975  tab_ = tableList_[idx] ;
     976  nrow_ = rows_[idx] ;
     977  updateChunkShape() ;
     978}
     979
     980void STGrid::setData( Array<Complex> &gdata,
    301981                      Array<Float> &gwgt )
    302982{
     983  // 2011/12/20 TN
     984  // gwgt and data_ share storage
    303985  LogIO os( LogOrigin("STGrid","setData",WHERE) ) ;
    304986  double t0, t1 ;
    305987  t0 = mathutil::gettimeofday_sec() ;
    306   data.resize( gdata.shape() ) ;
    307   uInt len = data.nelements() ;
    308   Float *w0_p ;
    309   const Float *w1_p, *w2_p ;
    310   Bool b0, b1, b2 ;
    311   Float *data_p = data.getStorage( b0 ) ;
    312   const Float *gdata_p = gdata.getStorage( b1 ) ;
    313   const Float *gwgt_p = gwgt.getStorage( b2 ) ;
    314   w0_p = data_p ;
     988  uInt len = data_.nelements() ;
     989  const Complex *w1_p ;
     990  Float *w2_p ;
     991  Bool b1, b2 ;
     992  const Complex *gdata_p = gdata.getStorage( b1 ) ;
     993  Float *gwgt_p = data_.getStorage( b2 ) ;
    315994  w1_p = gdata_p ;
    316995  w2_p = gwgt_p ;
    317996  for ( uInt i = 0 ; i < len ; i++ ) {
    318     *w0_p = (*w2_p > 0.0) ? (*w1_p / *w2_p) : 0.0 ;
    319     w0_p++ ;
     997    if ( *w2_p > 0.0 ) *w2_p = (*w1_p).real() / *w2_p ;
    320998    w1_p++ ;
    321999    w2_p++ ;
    3221000  }
    323   data.putStorage( data_p, b0 ) ;
    3241001  gdata.freeStorage( gdata_p, b1 ) ;
    325   gwgt.freeStorage( gwgt_p, b2 ) ;
     1002  data_.putStorage( gwgt_p, b2 ) ;
    3261003  t1 = mathutil::gettimeofday_sec() ;
    327   os << "setData: elapsed time is " << t1-t0 << " sec." << LogIO::POST ;
     1004  os << LogIO::DEBUGGING << "setData: elapsed time is " << t1-t0 << " sec." << LogIO::POST ;
     1005}
     1006
     1007void STGrid::setupGrid()
     1008{
     1009  Double xmin,xmax,ymin,ymax ;
     1010  mapExtent( xmin, xmax, ymin, ymax ) ;
     1011 
     1012  setupGrid( nxUI_, nyUI_, cellxUI_, cellyUI_,
     1013             xmin, xmax, ymin, ymax, centerUI_ ) ;
    3281014}
    3291015
     
    3381024                        String &center )
    3391025{
     1026  LogIO os( LogOrigin("STGrid","setupGrid",WHERE) ) ;
    3401027  //cout << "nx=" << nx << ", ny=" << ny << endl ;
    3411028
     
    3711058    center_(0) = xcen.getValue( "rad" ) ;
    3721059    center_(1) = ycen.getValue( "rad" ) ;
    373   }
    374 
     1060    double base = 0.5 * (xmin + xmax) ;
     1061    int maxrotate = 1 ;
     1062    int nelem = 2 * maxrotate + 1 ;
     1063    double *sep = new double[nelem] ;
     1064    for ( int i = 0 ; i < nelem ; i++ )
     1065      sep[i] = abs(base - center_[0] - (i-maxrotate) * C::_2pi) ;
     1066//     os << "sep[0]=" << sep[0] << endl 
     1067//        << "sep[1]=" << sep[1] << endl
     1068//        << "sep[2]=" << sep[2] << LogIO::POST ;
     1069    int idx = 0 ;
     1070    base = sep[0] ;
     1071    int nrotate = 0 ;
     1072    while ( idx < nelem ) {
     1073      if ( base > sep[idx] ) {
     1074        base = sep[idx] ;
     1075        nrotate = idx ;
     1076      }
     1077      idx++ ;
     1078    }
     1079    delete sep ;
     1080    nrotate -= maxrotate ;
     1081//     os << "nrotate = " << nrotate << LogIO::POST ;
     1082    center_[0] += nrotate * C::_2pi ;
     1083  }
     1084//   os << "xmin=" << xmin << LogIO::POST ;
     1085//   os << "center_=" << center_ << LogIO::POST ;
     1086
     1087
     1088  nx_ = nx ;
     1089  ny_ = ny ;
     1090  if ( nx < 0 && ny > 0 ) {
     1091    nx_ = ny ;
     1092    ny_ = ny ;
     1093  }
     1094  if ( ny < 0 && nx > 0 ) {
     1095    nx_ = nx ;
     1096    ny_ = nx ;
     1097  }
    3751098
    3761099  //Double wx = xmax - xmin ;
     
    3811104  wx *= 1.10 ;
    3821105  wy *= 1.10 ;
     1106
    3831107  Quantum<Double> qcellx ;
    3841108  Quantum<Double> qcelly ;
    385   nx_ = nx ;
    386   ny_ = ny ;
    387   if ( nx < 0 && ny > 0 ) {
    388     nx_ = ny ;
    389     ny_ = ny ;
    390   }
    391   if ( ny < 0 && nx > 0 ) {
    392     nx_ = nx ;
    393     ny_ = nx ;
    394   }
    3951109  //cout << "nx_ = " << nx_ << ",  ny_ = " << ny_ << endl ;
    3961110  if ( cellx.size() != 0 && celly.size() != 0 ) {
     
    3991113  }
    4001114  else if ( celly.size() != 0 ) {
    401     cout << "Using celly to x-axis..." << endl ;
     1115    os << "Using celly to x-axis..." << LogIO::POST ;
    4021116    readQuantity( qcelly, celly ) ;
    4031117    qcellx = qcelly ;
    4041118  }
    4051119  else if ( cellx.size() != 0 ) {
    406     cout << "Using cellx to y-axis..." << endl ;
     1120    os << "Using cellx to y-axis..." << LogIO::POST ;
    4071121    readQuantity( qcellx, cellx ) ;
    4081122    qcelly = qcellx ;
     
    4101124  else {
    4111125    if ( nx_ < 0 ) {
    412       cout << "No user preference in grid setting. Using default..." << endl ;
     1126      os << "No user preference in grid setting. Using default..." << LogIO::POST ;
    4131127      readQuantity( qcellx, "1.0arcmin" ) ;
    4141128      qcelly = qcellx ;
    4151129    }
    4161130    else {
     1131      if ( wx == 0.0 ) {
     1132        os << "Using default spatial extent (10arcmin) in x" << LogIO::POST ;
     1133        wx = 0.00290888 ;
     1134      }
     1135      if ( wy == 0.0 ) {
     1136        os << "Using default spatial extent (10arcmin) in y" << LogIO::POST ;
     1137        wy = 0.00290888 ;
     1138      }
    4171139      qcellx = Quantum<Double>( wx/nx_, "rad" ) ;
    4181140      qcelly = Quantum<Double>( wy/ny_, "rad" ) ;
     
    4201142  }
    4211143  cellx_ = qcellx.getValue( "rad" ) ;
     1144  // DEC correction
     1145  cellx_ /= cos( center_[1] ) ;
    4221146  celly_ = qcelly.getValue( "rad" ) ;
     1147  //os << "cellx_=" << cellx_ << ", celly_=" << celly_ << ", cos("<<center_(1)<<")=" << cos(center_(1)) << LogIO::POST ;
    4231148  if ( nx_ < 0 ) {
     1149    if ( wx == 0.0 ) {
     1150      os << "Using default spatial extent (10arcmin) in x" << LogIO::POST ;
     1151      wx = 0.00290888 ;
     1152    }
     1153    if ( wy == 0.0 ) {
     1154      os << "Using default spatial extent (10arcmin) in y" << LogIO::POST ;
     1155      wy = 0.00290888 ;
     1156    }
    4241157    nx_ = Int( ceil( wx/cellx_ ) ) ;
    4251158    ny_ = Int( ceil( wy/celly_ ) ) ;
     
    4271160}
    4281161
    429 void STGrid::selectData( Table &tab )
    430 {
     1162void STGrid::mapExtent( Double &xmin, Double &xmax,
     1163                        Double &ymin, Double &ymax )
     1164{
     1165  //LogIO os( LogOrigin("STGrid","mapExtent",WHERE) ) ;
     1166  directionCol_.attach( tableList_[0], "DIRECTION" ) ;
     1167  Matrix<Double> direction = directionCol_.getColumn() ;
     1168  //os << "dirCol.nrow() = " << dirCol.nrow() << LogIO::POST ;
     1169  minMax( xmin, xmax, direction.row( 0 ) ) ;
     1170  minMax( ymin, ymax, direction.row( 1 ) ) ;
     1171  Double amin, amax, bmin, bmax ;
     1172  for ( uInt i = 1 ; i < nfile_ ; i++ ) {
     1173    directionCol_.attach( tableList_[i], "DIRECTION" ) ;
     1174    direction.assign( directionCol_.getColumn() ) ;
     1175    //os << "dirCol.nrow() = " << dirCol.nrow() << LogIO::POST ;
     1176    minMax( amin, amax, direction.row( 0 ) ) ;
     1177    minMax( bmin, bmax, direction.row( 1 ) ) ;
     1178    xmin = min( xmin, amin ) ;
     1179    xmax = max( xmax, amax ) ;
     1180    ymin = min( ymin, bmin ) ;
     1181    ymax = max( ymax, bmax ) ;
     1182  }
     1183  //os << "(xmin,xmax)=(" << xmin << "," << xmax << ")" << LogIO::POST ;
     1184  //os << "(ymin,ymax)=(" << ymin << "," << ymax << ")" << LogIO::POST ;
     1185}
     1186
     1187void STGrid::selectData()
     1188{
     1189  LogIO os( LogOrigin("STGrid","selectData",WHERE) ) ;   
    4311190  Int ifno = ifno_ ;
    432   Table taborg( infile_ ) ;
    433   if ( ifno == -1 ) {
    434     LogIO os( LogOrigin("STGrid","selectData",WHERE) ) ;
    435 //     os << LogIO::SEVERE
    436 //        << "Please set IFNO before actual gridding"
    437 //        << LogIO::EXCEPTION ;
     1191  tableList_.resize( nfile_ ) ;
     1192  if ( ifno_ == -1 ) {
     1193    Table taborg( infileList_[0] ) ;
    4381194    ROScalarColumn<uInt> ifnoCol( taborg, "IFNO" ) ;
    439     ifno = ifnoCol( 0 ) ;
     1195    ifno_ = ifnoCol( 0 ) ;
    4401196    os << LogIO::WARN
    441        << "IFNO is not given. Using default IFNO: " << ifno << LogIO::POST ;
    442   }
    443 //   tab = taborg( taborg.col("IFNO") == ifno ) ;
    444   TableExprNode node ;
    445   node = taborg.col("IFNO") == ifno ;
    446   if ( scanlist_.size() > 0 ) {
    447     node = node && taborg.col("SCANNO").in( scanlist_ ) ;
    448   }
    449   tab = taborg( node ) ;
    450   if ( tab.nrow() == 0 ) {
    451     LogIO os( LogOrigin("STGrid","selectData",WHERE) ) ;
    452     os << LogIO::SEVERE
    453        << "No corresponding rows for given selection: IFNO " << ifno
    454        << " SCANNO " << scanlist_
    455        << LogIO::EXCEPTION ;
    456   }
    457 }
    458 
    459 void STGrid::getData( Cube<Float> &spectra,
    460                       Matrix<Double> &direction,
    461                       Cube<uChar> &flagtra,
    462                       Matrix<uInt> &rflag,
    463                       Matrix<Float> &weight )
    464 {
    465   Table tab ;
    466   selectData( tab ) ;
    467   updatePolList( tab ) ;
    468 //   cout << "npol_ = " << npol_ << endl ;
    469 //   cout << "nchan_ = " << nchan_ << endl ;
    470 //   cout << "nrow_ = " << nrow_ << endl ;
    471   spectra.resize( npol_, nchan_, nrow_ ) ;
    472   flagtra.resize( npol_, nchan_, nrow_ ) ;
    473   rflag.resize( npol_, nrow_ ) ;
    474   Cube<Float> tsys( npol_, nchan_, nrow_ ) ;
    475   Matrix<Double> tint( npol_, nrow_ ) ;
    476   // boolean for pointer access
    477   Bool bsp, bfl, bfr, bts, bti ;
    478   // pointer to the data
    479   Float *sp_p = spectra.getStorage( bsp ) ;
    480   uChar *fl_p = flagtra.getStorage( bfl ) ;
    481   uInt *fr_p = rflag.getStorage( bfr ) ;
    482   Float *ts_p = tsys.getStorage( bts ) ;
    483   Double *ti_p = tint.getStorage( bti ) ;
    484   // working pointer
    485   Float *wsp_p = sp_p ;
    486   uChar *wfl_p = fl_p ;
    487   uInt *wfr_p = fr_p ;
    488   Float *wts_p = ts_p ;
    489   Double *wti_p = ti_p ;
    490   uInt len = nchan_ * nrow_ ;
    491   IPosition mshape( 2, nchan_, nrow_ ) ;
    492   IPosition vshape( 1, nrow_ ) ;
    493   for ( Int ipol = 0 ; ipol < npol_ ; ipol++ ) {
    494     Table subt = tab( tab.col("POLNO") == pollist_[ipol] ) ;
    495     ROArrayColumn<Float> spectraCol( subt, "SPECTRA" ) ;
    496     ROArrayColumn<Double> directionCol( subt, "DIRECTION" ) ;
    497     ROArrayColumn<uChar> flagtraCol( subt, "FLAGTRA" ) ;
    498     ROScalarColumn<uInt> rflagCol( subt, "FLAGROW" ) ;
    499     ROArrayColumn<Float> tsysCol( subt, "TSYS" ) ;
    500     ROScalarColumn<Double> tintCol( subt, "INTERVAL" ) ;
    501     Matrix<Float> spSlice( mshape, wsp_p, SHARE ) ;
    502     Matrix<uChar> flSlice( mshape, wfl_p, SHARE ) ;
    503     Vector<uInt> frSlice( vshape, wfr_p, SHARE ) ;
    504     spectraCol.getColumn( spSlice ) ;
    505     flagtraCol.getColumn( flSlice ) ;
    506     rflagCol.getColumn( frSlice ) ;
    507     if ( ipol == 0 )
    508       directionCol.getColumn( direction ) ;
    509     Vector<Float> tmpF = tsysCol( 0 ) ;
    510     Vector<Double> tmpD( vshape, wti_p, SHARE ) ;
    511     Matrix<Float> tsSlice( mshape, wts_p, SHARE ) ;
    512     if ( tmpF.nelements() == (uInt)nchan_ ) {
    513       tsysCol.getColumn( tsSlice ) ;
     1197       << "IFNO is not given. Using default IFNO: " << ifno_ << LogIO::POST ;
     1198  }
     1199  for ( uInt i = 0 ; i < nfile_ ; i++ ) {
     1200    Table taborg( infileList_[i] ) ;
     1201    TableExprNode node ;
     1202    if ( ifno != -1 || isMultiIF( taborg ) ) {
     1203      os << "apply selection on IFNO" << LogIO::POST ;
     1204      node = taborg.col("IFNO") == ifno_ ;
     1205    }
     1206    if ( scanlist_.size() > 0 ) {
     1207      os << "apply selection on SCANNO" << LogIO::POST ;
     1208      node = node && taborg.col("SCANNO").in( scanlist_ ) ;
     1209    }
     1210    if ( node.isNull() ) {
     1211      tableList_[i] = taborg ;
    5141212    }
    5151213    else {
    516       tsSlice = tmpF( 0 ) ;
    517     }
    518     tintCol.getColumn( tmpD ) ;
    519 
    520     wsp_p += len ;
    521     wfl_p += len ;
    522     wfr_p += nrow_ ;
    523     wts_p += len ;
    524     wti_p += nrow_ ;
    525   }
    526   spectra.putStorage( sp_p, bsp ) ;
    527   flagtra.putStorage( fl_p, bfl ) ;
    528   rflag.putStorage( fr_p, bfr ) ;
    529   tsys.putStorage( ts_p, bts ) ;
    530   tint.putStorage( ti_p, bti ) ;
    531 
     1214      tableList_[i] = taborg( node ) ;
     1215    }
     1216    os << LogIO::DEBUGGING << "tableList_[" << i << "].nrow()=" << tableList_[i].nrow() << LogIO::POST ;
     1217    if ( tableList_[i].nrow() == 0 ) {
     1218      os << LogIO::SEVERE
     1219         << "No corresponding rows for given selection: IFNO " << ifno_ ;
     1220      if ( scanlist_.size() > 0 )
     1221        os << " SCANNO " << scanlist_ ;
     1222      os << LogIO::EXCEPTION ;
     1223    }
     1224  }
     1225}
     1226
     1227Bool STGrid::isMultiIF( Table &tab )
     1228{
     1229  ROScalarColumn<uInt> ifnoCol( tab, "IFNO" ) ;
     1230  Vector<uInt> ifnos = ifnoCol.getColumn() ;
     1231  return anyNE( ifnos, ifnos[0] ) ;
     1232}
     1233
     1234void STGrid::attach( Table &tab )
     1235{
     1236  // attach to table
     1237  spectraCol_.attach( tab, "SPECTRA" ) ;
     1238  flagtraCol_.attach( tab, "FLAGTRA" ) ;
     1239  directionCol_.attach( tab, "DIRECTION" ) ;
     1240  flagRowCol_.attach( tab, "FLAGROW" ) ;
     1241  tsysCol_.attach( tab, "TSYS" ) ;
     1242  intervalCol_.attach( tab, "INTERVAL" ) ;
     1243}
     1244
     1245Int STGrid::getDataChunk(
     1246                         IPosition const &wshape,
     1247                         IPosition const &vshape,
     1248                         IPosition const &dshape,
     1249                         Array<Complex> &spectra,
     1250                         Array<Double> &direction,
     1251                         Array<Int> &flagtra,
     1252                         Array<Int> &rflag,
     1253                         Array<Float> &weight )
     1254{
     1255  LogIO os( LogOrigin("STGrid","getDataChunk",WHERE) ) ;
     1256
     1257  Array<Float> spectraF_(wshape);
     1258  Array<uChar> flagtraUC_(wshape);
     1259  Array<uInt> rflagUI_(vshape);
     1260  Int nrow = getDataChunk( spectraF_, direction, flagtraUC_, rflagUI_, weight ) ;
     1261  if ( nrow < nchunk_ ) {
     1262    spectra.resize( spectraF_.shape() ) ;
     1263    flagtra.resize( flagtraUC_.shape() ) ;
     1264    rflag.resize( rflagUI_.shape() ) ;
     1265  }
     1266  double t0, t1 ;
     1267  t0 = mathutil::gettimeofday_sec() ;
     1268  convertArray( spectra, spectraF_ ) ;
     1269  toInt( flagtraUC_, flagtra ) ;
     1270  toInt( rflagUI_, rflag ) ;
     1271  t1 = mathutil::gettimeofday_sec() ;
     1272  eToInt = t1 - t0 ;
     1273 
     1274  return nrow ;
     1275}
     1276
     1277#if 0
     1278Int STGrid::getDataChunk( Array<Complex> &spectra,
     1279                          Array<Double> &direction,
     1280                          Array<Int> &flagtra,
     1281                          Array<Int> &rflag,
     1282                          Array<Float> &weight )
     1283{
     1284  LogIO os( LogOrigin("STGrid","getDataChunk",WHERE) ) ;
     1285  Int nrow = getDataChunk( spectraF_, direction, flagtraUC_, rflagUI_, weight ) ;
     1286  if ( nrow < nchunk_ ) {
     1287    spectra.resize( spectraF_.shape() ) ;
     1288    flagtra.resize( flagtraUC_.shape() ) ;
     1289    rflag.resize( rflagUI_.shape() ) ;
     1290  }
     1291  double t0, t1 ;
     1292  t0 = mathutil::gettimeofday_sec() ;
     1293  convertArray( spectra, spectraF_ ) ;
     1294  toInt( flagtraUC_, flagtra ) ;
     1295  toInt( rflagUI_, rflag ) ;
     1296  t1 = mathutil::gettimeofday_sec() ;
     1297  eToInt = t1 - t0 ;
     1298 
     1299  return nrow ;
     1300}
     1301#endif
     1302
     1303Int STGrid::getDataChunk( Array<Float> &spectra,
     1304                          Array<Double> &direction,
     1305                          Array<uChar> &flagtra,
     1306                          Array<uInt> &rflag,
     1307                          Array<Float> &weight )
     1308{
     1309  LogIO os( LogOrigin("STGrid","getDataChunk",WHERE) ) ;
     1310  Int nrow = spectra.shape()[1] ;
     1311  Int remainingRow = nrow_ - nprocessed_ ;
     1312  if ( remainingRow < nrow ) {
     1313    nrow = remainingRow ;
     1314    IPosition mshape( 2, nchan_, nrow ) ;
     1315    IPosition vshape( 1, nrow ) ;
     1316    spectra.resize( mshape ) ;
     1317    flagtra.resize( mshape ) ;
     1318    direction.resize( IPosition(2,2,nrow) ) ;
     1319    rflag.resize( vshape ) ;
     1320    weight.resize( mshape ) ;
     1321  }
     1322  // 2011/12/22 TN
     1323  // tsys shares its storage with weight
     1324  Array<Float> tsys( weight ) ;
     1325  Array<Double> tint( rflag.shape() ) ;
     1326
     1327  Vector<uInt> rflagVec( rflag ) ;
     1328  Vector<Double> tintVec( tint ) ;
     1329
     1330  RefRows rows( nprocessed_, nprocessed_+nrow-1, 1 ) ;
     1331  //os<<LogIO::DEBUGGING<<"nprocessed_="<<nprocessed_<<": rows.nrows()="<<rows.nrows()<<LogIO::POST ;
     1332  spectraCol_.getColumnCells( rows, spectra ) ;
     1333  flagtraCol_.getColumnCells( rows, flagtra ) ;
     1334  directionCol_.getColumnCells( rows, direction ) ;
     1335  flagRowCol_.getColumnCells( rows, rflagVec ) ;
     1336  intervalCol_.getColumnCells( rows, tintVec ) ;
     1337  Vector<Float> tsysTemp = tsysCol_( nprocessed_ ) ;
     1338  if ( tsysTemp.nelements() == (uInt)nchan_ )
     1339    tsysCol_.getColumnCells( rows, tsys ) ;
     1340  else
     1341    tsys = tsysTemp[0] ;
     1342
     1343  double t0,t1 ;
     1344  t0 = mathutil::gettimeofday_sec() ;
    5321345  getWeight( weight, tsys, tint ) ;
    533 }
    534 
    535 void STGrid::updatePolList( Table &tab )
    536 {
    537   ROScalarColumn<uInt> polnoCol( tab, "POLNO" ) ;
     1346  t1 = mathutil::gettimeofday_sec() ;
     1347  eGetWeight += t1-t0 ;
     1348
     1349  nprocessed_ += nrow ;
     1350 
     1351  return nrow ;
     1352}
     1353
     1354void STGrid::setupArray()
     1355{
     1356  LogIO os( LogOrigin("STGrid","setupArray",WHERE) ) ;
     1357  ROScalarColumn<uInt> polnoCol( tableList_[0], "POLNO" ) ;
    5381358  Vector<uInt> pols = polnoCol.getColumn() ;
     1359  //os << pols << LogIO::POST ;
    5391360  Vector<uInt> pollistOrg ;
    540   uInt npolOrg = 0 ;
     1361  npolOrg_ = 0 ;
    5411362  uInt polno ;
    5421363  for ( uInt i = 0 ; i < polnoCol.nrow() ; i++ ) {
     
    5441365    polno = pols( i ) ;
    5451366    if ( allNE( pollistOrg, polno ) ) {
    546       pollistOrg.resize( npolOrg+1, True ) ;
    547       pollistOrg[npolOrg] = polno ;
    548       npolOrg++ ;
     1367      pollistOrg.resize( npolOrg_+1, True ) ;
     1368      pollistOrg[npolOrg_] = polno ;
     1369      npolOrg_++ ;
    5491370    }
    5501371  }
     
    5651386  npol_ = pollist_.size() ;
    5661387  if ( npol_ == 0 ) {
    567     LogIO os( LogOrigin("STGrid","updatePolList",WHERE) ) ;
    5681388    os << LogIO::SEVERE << "Empty pollist" << LogIO::EXCEPTION ;
    5691389  }
    570   nrow_ = tab.nrow() / npolOrg ;
    571   ROArrayColumn<uChar> tmpCol( tab, "FLAGTRA" ) ;
    572   nchan_ = tmpCol( 0 ).nelements() ;
    573 //   LogIO os( LogOrigin("STGrid","updatePolList",WHERE) ) ;
     1390  rows_.resize( nfile_ ) ;
     1391  for ( uInt i = 0 ; i < nfile_ ; i++ ) {
     1392    rows_[i] = tableList_[i].nrow() / npolOrg_ ;
     1393    //if ( nrow_ < rows_[i] )
     1394    //  nrow_ = rows_[i] ;
     1395  }
     1396  flagtraCol_.attach( tableList_[0], "FLAGTRA" ) ;
     1397  nchan_ = flagtraCol_( 0 ).nelements() ;
    5741398//   os << "npol_ = " << npol_ << "(" << pollist_ << ")" << endl
    5751399//      << "nchan_ = " << nchan_ << endl
     
    5771401}
    5781402
    579 void STGrid::getWeight( Matrix<Float> &w,
    580                         Cube<Float> &tsys,
    581                         Matrix<Double> &tint )
     1403void STGrid::getWeight( Array<Float> &w,
     1404                              Array<Float> &tsys,
     1405                              Array<Double> &tint )
    5821406{
    5831407  LogIO os( LogOrigin("STGrid","getWeight",WHERE) ) ;
    584   double t0, t1 ;
    585   t0 = mathutil::gettimeofday_sec() ;
    586   // resize
    587   w.resize( nchan_, nrow_ ) ;
     1408
     1409  // 2011/12/22 TN
     1410  // w (weight) and tsys share storage
     1411  IPosition refShape = tsys.shape() ;
     1412  Int nchan = refShape[0] ;
     1413  Int nrow = refShape[1] ;
     1414//   os << "nchan=" << nchan << ", nrow=" << nrow << LogIO::POST ;
     1415//   os << "w.shape()=" << w.shape() << endl
     1416//      << "tsys.shape()=" << tsys.shape() << endl
     1417//      << "tint.shape()=" << tint.shape() << LogIO::POST ;
    5881418
    5891419  // set weight
    590   Bool warn = False ;
    5911420  if ( wtype_.compare( "UNIFORM" ) == 0 ) {
    5921421    w = 1.0 ;
    5931422  }
    5941423  else if ( wtype_.compare( "TINT" ) == 0 ) {
    595     if ( npol_ > 1 ) warn = True ;
    5961424    Bool b0, b1 ;
    5971425    Float *w_p = w.getStorage( b0 ) ;
     
    5991427    const Double *ti_p = tint.getStorage( b1 ) ;
    6001428    const Double *w1_p = ti_p ;
    601     for ( Int irow = 0 ; irow < nrow_ ; irow++ ) {
    602       Float val = (Float)(polMean( w1_p )) ;
    603       for ( Int ichan = 0 ; ichan < nchan_ ; ichan++ ) {
    604         *w0_p = val ;
     1429    for ( Int irow = 0 ; irow < nrow ; irow++ ) {
     1430      for ( Int ichan = 0 ; ichan < nchan ; ichan++ ) {
     1431        *w0_p = *w1_p ;
    6051432        w0_p++ ;
    6061433      }
     1434      w1_p++ ;
    6071435    }
    6081436    w.putStorage( w_p, b0 ) ;
     
    6101438  }
    6111439  else if ( wtype_.compare( "TSYS" ) == 0 ) {
    612     if ( npol_ > 1 ) warn = True ;
    613     Bool b0, b1 ;
     1440    Bool b0 ;
    6141441    Float *w_p = w.getStorage( b0 ) ;
    6151442    Float *w0_p = w_p ;
    616     const Float *ts_p = tsys.getStorage( b1 ) ;
    617     const Float *w1_p = ts_p ;
    618     for ( Int irow = 0 ; irow < nrow_ ; irow++ ) {
    619       for ( Int ichan = 0 ; ichan < nchan_ ; ichan++ ) {
    620         Float val = polMean( w1_p ) ;
    621         *w0_p = 1.0 / ( val * val ) ;
     1443    for ( Int irow = 0 ; irow < nrow ; irow++ ) {
     1444      for ( Int ichan = 0 ; ichan < nchan ; ichan++ ) {
     1445        Float temp = *w0_p ;
     1446        *w0_p = 1.0 / ( temp * temp ) ;
    6221447        w0_p++ ;
    6231448      }
    6241449    }
    6251450    w.putStorage( w_p, b0 ) ;
    626     tsys.freeStorage( ts_p, b1 ) ;
    6271451  }
    6281452  else if ( wtype_.compare( "TINTSYS" ) == 0 ) {
    629     if ( npol_ > 1 ) warn = True ;
    630     Bool b0, b1, b2 ;
     1453    Bool b0, b1 ;
    6311454    Float *w_p = w.getStorage( b0 ) ;
    6321455    Float *w0_p = w_p ;
    6331456    const Double *ti_p = tint.getStorage( b1 ) ;
    6341457    const Double *w1_p = ti_p ;
    635     const Float *ts_p = tsys.getStorage( b2 ) ;
    636     const Float *w2_p = ts_p ;
    637     for ( Int irow = 0 ; irow < nrow_ ; irow++ ) {
    638       Float interval = (Float)(polMean( w1_p )) ;
    639       for ( Int ichan = 0 ; ichan < nchan_ ; ichan++ ) {
    640         Float temp = polMean( w2_p ) ;
     1458    for ( Int irow = 0 ; irow < nrow ; irow++ ) {
     1459      Float interval = *w1_p ;
     1460      for ( Int ichan = 0 ; ichan < nchan ; ichan++ ) {
     1461        Float temp = *w0_p ;
    6411462        *w0_p = interval / ( temp * temp ) ;
    6421463        w0_p++ ;
    6431464      }
     1465      w1_p++ ;
    6441466    }
    6451467    w.putStorage( w_p, b0 ) ;
    6461468    tint.freeStorage( ti_p, b1 ) ;
    647     tsys.freeStorage( ts_p, b2 ) ;
    6481469  }
    6491470  else {
    6501471    //LogIO os( LogOrigin("STGrid", "getWeight", WHERE) ) ;
    651     os << LogIO::WARN << "Unsupported weight type '" << wtype_ << "', apply UNIFORM weight" << LogIO::POST ;
     1472    //os << LogIO::WARN << "Unsupported weight type '" << wtype_ << "', apply UNIFORM weight" << LogIO::POST ;
    6521473    w = 1.0 ;
    6531474  }
    654 
    655   if ( npol_ > 1 ) {
    656     //LogIO os( LogOrigin("STGrid", "getWeight", WHERE) ) ;
    657     os << LogIO::WARN << "STGrid doesn't support assigning polarization-dependent weight. Use averaged weight over polarization." << LogIO::POST ;
    658   }
    659   t1 = mathutil::gettimeofday_sec() ;
    660   os << "getWeight: elapsed time is " << t1-t0 << " sec" << LogIO::POST ;
    661 }
    662 
    663 Float STGrid::polMean( const Float *p )
    664 {
    665   Float v = 0.0 ;
    666   for ( Int i = 0 ; i < npol_ ; i++ ) {
    667     v += *p ;
    668     p++ ;
    669   }
    670   v /= npol_ ;
    671   return v ;
    672 }
    673 
    674 Double STGrid::polMean( const Double *p )
    675 {
    676   Double v = 0.0 ;
    677   for ( Int i = 0 ; i < npol_ ; i++ ) {
    678     v += *p ;
    679     p++ ;
    680   }
    681   v /= npol_ ;
    682   return v ;
    683 }
    684 
    685 void STGrid::toInt( Array<uChar> *u, Array<Int> *v )
    686 {
    687   uInt len = u->nelements() ;
     1475}
     1476
     1477void STGrid::toInt( Array<uChar> &u, Array<Int> &v )
     1478{
     1479  uInt len = u.nelements() ;
    6881480  Int *int_p = new Int[len] ;
    6891481  Bool deleteIt ;
    690   const uChar *data_p = u->getStorage( deleteIt ) ;
     1482  const uChar *data_p = u.getStorage( deleteIt ) ;
    6911483  Int *i_p = int_p ;
    6921484  const uChar *u_p = data_p ;
     
    6961488    u_p++ ;
    6971489  }
    698   u->freeStorage( data_p, deleteIt ) ;
    699   v->takeStorage( u->shape(), int_p, TAKE_OVER ) ;
    700 }
    701 
    702 void STGrid::toInt( Array<uInt> *u, Array<Int> *v )
    703 {
    704   uInt len = u->nelements() ;
     1490  u.freeStorage( data_p, deleteIt ) ;
     1491  v.takeStorage( u.shape(), int_p, TAKE_OVER ) ;
     1492}
     1493
     1494void STGrid::toInt( Array<uInt> &u, Array<Int> &v )
     1495{
     1496  uInt len = u.nelements() ;
    7051497  Int *int_p = new Int[len] ;
    7061498  Bool deleteIt ;
    707   const uInt *data_p = u->getStorage( deleteIt ) ;
     1499  const uInt *data_p = u.getStorage( deleteIt ) ;
    7081500  Int *i_p = int_p ;
    7091501  const uInt *u_p = data_p ;
     
    7131505    u_p++ ;
    7141506  }
    715   u->freeStorage( data_p, deleteIt ) ;
    716   v->takeStorage( u->shape(), int_p, TAKE_OVER ) ;
    717 }
    718 
    719 void STGrid::toPixel( Matrix<Double> &world, Matrix<Double> &pixel )
     1507  u.freeStorage( data_p, deleteIt ) ;
     1508  v.takeStorage( u.shape(), int_p, TAKE_OVER ) ;
     1509}
     1510
     1511void STGrid::toPixel( Array<Double> &world, Array<Double> &pixel )
    7201512{
    7211513  // gridding will be done on (nx_+2*convSupport_) x (ny_+2*convSupport_)
    7221514  // grid plane to avoid unexpected behavior on grid edge
    723   Vector<Double> pixc( 2 ) ;
    724   pixc(0) = Double( nx_-1 ) * 0.5 ;
    725   pixc(1) = Double( ny_-1 ) * 0.5 ;
    726 //   pixc(0) = Double( nx_+2*convSupport_-1 ) * 0.5 ;
    727 //   pixc(1) = Double( ny_+2*convSupport_-1 ) * 0.5 ;
     1515  Block<Double> pixc( 2 ) ;
     1516  pixc[0] = Double( nx_-1 ) * 0.5 ;
     1517  pixc[1] = Double( ny_-1 ) * 0.5 ;
     1518//   pixc[0] = Double( nx_+2*convSupport_-1 ) * 0.5 ;
     1519//   pixc[1] = Double( ny_+2*convSupport_-1 ) * 0.5 ;
    7281520  uInt nrow = world.shape()[1] ;
    729   Vector<Double> cell( 2 ) ;
    730   cell(0) = cellx_ ;
    731   cell(1) = celly_ ;
    732   for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
    733     for ( uInt i = 0 ; i < 2 ; i++ ) {
    734       pixel( i, irow ) = pixc(i) + ( world(i, irow) - center_(i) ) / cell(i) ;
    735     }
    736   }
    737 //   String gridfile = "grid."+convType_+"."+String::toString(convSupport_)+".dat" ;
    738 //   ofstream ofs( gridfile.c_str(), ios::out ) ;
    739 //   ofs << "center " << center_(0) << " " << pixc(0)
    740 //       << " " << center_(1) << " " << pixc(1) << endl ;
    741 //   for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
    742 //     ofs << irow ;
    743 //     for ( uInt i = 0 ; i < 2 ; i++ ) {
    744 //       ofs << " " << world(i, irow) << " " << pixel(i, irow) ;
    745 //     }
    746 //     ofs << endl ;
    747 //   }
    748 //   ofs.close() ;
     1521  Bool bw, bp ;
     1522  const Double *w_p = world.getStorage( bw ) ;
     1523  Double *p_p = pixel.getStorage( bp ) ;
     1524  const Double *ww_p = w_p ;
     1525  Double *wp_p = p_p ;
     1526  for ( uInt i = 0 ; i < nrow ; i++ ) {
     1527    *wp_p = pixc[0] + ( *ww_p - center_[0] ) / cellx_ ;
     1528    wp_p++ ;
     1529    ww_p++ ;
     1530    *wp_p = pixc[1] + ( *ww_p - center_[1] ) / celly_ ;
     1531    wp_p++ ;
     1532    ww_p++ ;
     1533  }
     1534  world.freeStorage( w_p, bw ) ;
     1535  pixel.putStorage( p_p, bp ) ; 
    7491536}
    7501537
     
    8121599    // to take into account Gaussian tail
    8131600    if ( convSupport_ < 0 )
    814       convSupport_ = 12 ; // 3 * 4
     1601      convSupport_ = 4 ; // 1 * 4
    8151602    else {
    8161603      convSupport_ = userSupport_ * 4 ;
     
    8391626  String outfile_ ;
    8401627  if ( outfile.size() == 0 ) {
    841     if ( infile_.lastchar() == '/' ) {
    842       outfile_ = infile_.substr( 0, infile_.size()-1 ) ;
     1628    if ( infileList_[0].lastchar() == '/' ) {
     1629      outfile_ = infileList_[0].substr( 0, infileList_[0].size()-1 ) ;
    8431630    }
    8441631    else {
    845       outfile_ = infile_ ;
     1632      outfile_ = infileList_[0] ;
    8461633    }
    8471634    outfile_ += ".grid" ;
     
    8971684
    8981685  t1 = mathutil::gettimeofday_sec() ;
    899   os << "saveData: elapsed time is " << t1-t0 << " sec." << LogIO::POST ;
    900  
     1686  os << LogIO::DEBUGGING << "saveData: elapsed time is " << t1-t0 << " sec." << LogIO::POST ;
     1687
     1688  fillMainColumns( tab ) ;
     1689
    9011690  return outfile_ ;
    9021691}
     
    9041693void STGrid::prepareTable( Table &tab, String &name )
    9051694{
    906   Table t( infile_, Table::Old ) ;
     1695  Table t( infileList_[0], Table::Old ) ;
    9071696  t.deepCopy( name, Table::New, False, t.endianFormat(), True ) ;
    9081697  tab = Table( name, Table::Update ) ;
    909 }
    910 }
     1698  // 2012/02/13 TN
     1699  // explicitly copy subtables since no rows including subtables are
     1700  // copied by Table::deepCopy with noRows=True
     1701  TableCopy::copySubTables( tab, t ) ;
     1702}
     1703
     1704void STGrid::fillMainColumns( Table &tab )
     1705{
     1706  // values for fill
     1707  Table t( infileList_[0], Table::Old ) ;
     1708  Table tsel = t( t.col( "IFNO" ) == (uInt)ifno_, 1 ) ;
     1709  ROTableRow row( tsel ) ;
     1710  row.get( 0 ) ;
     1711  const TableRecord &rec = row.record() ;
     1712  uInt freqId = rec.asuInt( "FREQ_ID" ) ;
     1713  uInt molId = rec.asuInt( "MOLECULE_ID" ) ;
     1714  uInt tcalId = rec.asuInt( "TCAL_ID" ) ;
     1715  uInt focusId = rec.asuInt( "FOCUS_ID" ) ;
     1716  uInt weatherId = rec.asuInt( "WEATHER_ID" ) ;
     1717  String srcname = rec.asString( "SRCNAME" ) ;
     1718  String fieldname = rec.asString( "FIELDNAME" ) ;
     1719  Vector<Float> defaultTsys( 1, 1.0 ) ;
     1720  // @todo how to set flagtra for gridded spectra?
     1721  Vector<uChar> flagtra = rec.asArrayuChar( "FLAGTRA" ) ;
     1722  flagtra = (uChar)0 ;
     1723  Float opacity = rec.asFloat( "OPACITY" ) ;
     1724  Double srcvel = rec.asDouble( "SRCVELOCITY" ) ;
     1725  Vector<Double> srcpm = rec.asArrayDouble( "SRCPROPERMOTION" ) ;
     1726  Vector<Double> srcdir = rec.asArrayDouble( "SRCDIRECTION" ) ;
     1727  Vector<Double> scanrate = rec.asArrayDouble( "SCANRATE" ) ;
     1728  Double time = rec.asDouble( "TIME" ) ;
     1729  Double interval = rec.asDouble( "INTERVAL" ) ;
     1730
     1731  // fill columns
     1732  Int nrow = tab.nrow() ;
     1733  ScalarColumn<uInt> scannoCol( tab, "SCANNO" ) ;
     1734  ScalarColumn<uInt> ifnoCol( tab, "IFNO" ) ;
     1735  ScalarColumn<uInt> freqIdCol( tab, "FREQ_ID" ) ;
     1736  ScalarColumn<uInt> molIdCol( tab, "MOLECULE_ID" ) ;
     1737  ScalarColumn<uInt> tcalidCol( tab, "TCAL_ID" ) ;
     1738  ScalarColumn<Int> fitidCol( tab, "FIT_ID" ) ;
     1739  ScalarColumn<uInt> focusidCol( tab, "FOCUS_ID" ) ;
     1740  ScalarColumn<uInt> weatheridCol( tab, "WEATHER_ID" ) ;
     1741  ArrayColumn<uChar> flagtraCol( tab, "FLAGTRA" ) ;
     1742  ScalarColumn<uInt> rflagCol( tab, "FLAGROW" ) ;
     1743  ArrayColumn<Float> tsysCol( tab, "TSYS" ) ;
     1744  ScalarColumn<String> srcnameCol( tab, "SRCNAME" ) ;
     1745  ScalarColumn<String> fieldnameCol( tab, "FIELDNAME" ) ;
     1746  ScalarColumn<Int> srctypeCol( tab, "SRCTYPE" ) ;
     1747  ScalarColumn<Float> opacityCol( tab, "OPACITY" ) ;
     1748  ScalarColumn<Double> srcvelCol( tab, "SRCVELOCITY" ) ;
     1749  ArrayColumn<Double> srcpmCol( tab, "SRCPROPERMOTION" ) ;
     1750  ArrayColumn<Double> srcdirCol( tab, "SRCDIRECTION" ) ;
     1751  ArrayColumn<Double> scanrateCol( tab, "SCANRATE" ) ;
     1752  ScalarColumn<Double> timeCol( tab, "TIME" ) ;
     1753  ScalarColumn<Double> intervalCol( tab, "INTERVAL" ) ;
     1754  for ( Int i = 0 ; i < nrow ; i++ ) {
     1755    scannoCol.put( i, (uInt)i ) ;
     1756    ifnoCol.put( i, (uInt)ifno_ ) ;
     1757    freqIdCol.put( i, freqId ) ;
     1758    molIdCol.put( i, molId ) ;
     1759    tcalidCol.put( i, tcalId ) ;
     1760    fitidCol.put( i, -1 ) ;
     1761    focusidCol.put( i, focusId ) ;
     1762    weatheridCol.put( i, weatherId ) ;
     1763    flagtraCol.put( i, flagtra ) ;
     1764    rflagCol.put( i, 0 ) ;
     1765    tsysCol.put( i, defaultTsys ) ;
     1766    srcnameCol.put( i, srcname ) ;
     1767    fieldnameCol.put( i, fieldname ) ;
     1768    srctypeCol.put( i, (Int)SrcType::PSON ) ;
     1769    opacityCol.put( i, opacity ) ;
     1770    srcvelCol.put( i, srcvel ) ;
     1771    srcpmCol.put( i, srcpm ) ;
     1772    srcdirCol.put( i, srcdir ) ;
     1773    scanrateCol.put( i, scanrate ) ;
     1774    timeCol.put( i, time ) ;
     1775    intervalCol.put( i, interval ) ;
     1776  }
     1777}
     1778
     1779}
  • /trunk/src/STGrid.h

    r2373 r2473  
    1919
    2020#include <casa/BasicSL/String.h>
     21#include <casa/Arrays/Array.h>
    2122#include <casa/Arrays/Vector.h>
    22 #include <casa/Arrays/Matrix.h>
    23 #include <casa/Arrays/Cube.h>
    24 // #include <casa/Arrays/ArrayMath.h>
    25 // #include <casa/Inputs/Input.h>
    26 // #include <casa/Quanta/Quantum.h>
    27 // #include <casa/Quanta/QuantumHolder.h>
    28 // #include <casa/Utilities/CountedPtr.h>
     23#include <casa/Containers/RecordField.h>
    2924
    3025#include <tables/Tables/Table.h>
    31 // #include <tables/Tables/ScalarColumn.h>
    32 // #include <tables/Tables/ArrayColumn.h>
    33 
    34 // #include <measures/Measures/MDirection.h>
    35 
    36 // #include "Scantable.h"
     26#include <tables/Tables/ScalarColumn.h>
     27#include <tables/Tables/ArrayColumn.h>
     28
     29#include "concurrent.h"
    3730
    3831using namespace std ;
     
    4538  STGrid() ;
    4639  STGrid( const string infile ) ;
     40  STGrid( const vector<string> infile ) ;
    4741  virtual ~STGrid() {} ;
    4842
    4943  void setFileIn( const string infile ) ;
     44  void setFileList( const vector<string> infile ) ;
    5045
    5146  void setIF( unsigned int ifno ) { ifno_ = ifno ; } ;
     
    6560  void setWeight( const string wType="uniform" ) ;
    6661
     62  void enableClip() { doclip_ = True ; } ;
     63  void disableClip() { doclip_ = False ; } ;
     64
    6765  void grid() ;
    6866 
     
    7270  void init() ;
    7371
     72  // actual gridding
     73  void gridPerRow() ;
     74  void gridPerRowWithClipping() ;
     75
     76  // clipping
     77  void clipMinMax( Array<Complex> &data,
     78                   Array<Float> &weight,
     79                   Array<Int> &npoints,
     80                   Array<Complex> &clipmin,
     81                   Array<Float> &clipwmin,
     82                   Array<Float> &clipcmin,
     83                   Array<Complex> &clipmax,
     84                   Array<Float> &clipwmax,
     85                   Array<Float> &clipcmax ) ;
     86                   
     87
     88  void setupGrid() ;
    7489  void setupGrid( Int &nx,
    7590                  Int &ny,
     
    8196                  Double &ymax,
    8297                  String &center ) ;
    83 
    84   void setData( Array<Float> &data,
    85                 Array<Float> &gdata,
     98  void mapExtent( Double &xmin, Double &xmax,
     99                  Double &ymin, Double &ymax ) ;
     100
     101  void setData( Array<Complex> &gdata,
    86102                Array<Float> &gwgt ) ;
    87103 
    88   void getData( Cube<Float> &spectra,
    89                 Matrix<Double> &direction,
    90                 Cube<uChar> &flagtra,
    91                 Matrix<uInt> &rflag,
    92                 Matrix<Float> &weight ) ;
    93 
    94   void getWeight( Matrix<Float> &w,
    95                   Cube<Float> &tsys,
    96                   Matrix<Double> &tint ) ;
    97 
    98   void toInt( Array<uChar> *u, Array<Int> *v ) ;
    99   void toInt( Array<uInt> *u, Array<Int> *v ) ;
    100 
    101   void toPixel( Matrix<Double> &world, Matrix<Double> &pixel ) ;
     104  Int getDataChunk( IPosition const &wshape,
     105                    IPosition const &vshape,
     106                    IPosition const &dshape,
     107                    Array<Complex> &spectra,
     108                    Array<Double> &direction,
     109                    Array<Int> &flagtra,
     110                    Array<Int> &rflag,
     111                    Array<Float> &weight ) ;
     112  Int getDataChunk( Array<Complex> &spectra,
     113                    Array<Double> &direction,
     114                    Array<Int> &flagtra,
     115                    Array<Int> &rflag,
     116                    Array<Float> &weight ) ;
     117  Int getDataChunk( Array<Float> &spectra,
     118                    Array<Double> &direction,
     119                    Array<uChar> &flagtra,
     120                    Array<uInt> &rflag,
     121                    Array<Float> &weight ) ;
     122
     123  void getWeight( Array<Float> &w,
     124                  Array<Float> &tsys,
     125                  Array<Double> &tint ) ;
     126 
     127  void toInt( Array<uChar> &u, Array<Int> &v ) ;
     128  void toInt( Array<uInt> &u, Array<Int> &v ) ;
     129
     130  void toPixel( Array<Double> &world, Array<Double> &pixel ) ;
    102131 
    103132  void boxFunc( Vector<Float> &convFunc, Int &convSize ) ;
     
    106135  void pbFunc( Vector<Float> &convFunc ) ;
    107136  void setConvFunc( Vector<Float> &convFunc ) ;
    108   void selectData( Table &tab ) ;
    109 
    110   Float polMean( const Float *p ) ;
    111   Double polMean( const Double *p ) ;
    112 
    113   void updatePolList( Table &tab ) ;
    114137
    115138  void prepareTable( Table &tab, String &name ) ;
    116139
    117   String infile_ ;
     140  void selectData() ;
     141  void setupArray() ;
     142
     143  void updateChunkShape() ;
     144  void attach( Table &tab ) ;
     145
     146  void call_ggridsd( Array<Double> &xy,
     147                     Array<Complex> &values,
     148                     Int &nvispol,
     149                     Int &nvischan,
     150                     Array<Int> &flag,
     151                     Array<Int> &rflag,
     152                     Array<Float> &weight,
     153                     Int &nrow,
     154                     Int &irow,
     155                     Array<Complex> &grid,
     156                     Array<Float> &wgrid,
     157                     Int &nx,
     158                     Int &ny,
     159                     Int &npol,
     160                     Int &nchan,
     161                     Int &support,
     162                     Int &sampling,
     163                     Vector<Float> &convFunc,
     164                     Int *chanMap,
     165                     Int *polMap ) ;
     166  void call_ggridsd2( Array<Double> &xy,
     167                      Array<Complex> &values,
     168                      Int &nvispol,
     169                      Int &nvischan,
     170                      Array<Int> &flag,
     171                      Array<Int> &rflag,
     172                      Array<Float> &weight,
     173                      Int &nrow,
     174                      Int &irow,
     175                      Array<Complex> &grid,
     176                      Array<Float> &wgrid,
     177                      Array<Int> &npoints,
     178                      Array<Complex> &clipmin,
     179                      Array<Float> &clipwmin,
     180                      Array<Float> &clipcmin,
     181                      Array<Complex> &clipmax,
     182                      Array<Float> &clipwmax,
     183                      Array<Float> &clipcmax,
     184                      Int &nx,
     185                      Int &ny,
     186                      Int &npol,
     187                      Int &nchan,
     188                      Int &support,
     189                      Int &sampling,
     190                      Vector<Float> &convFunc,
     191                      Int *chanMap,
     192                      Int *polMap ) ;
     193
     194  void initPol( Int ipol ) ;
     195  void initTable( uInt idx ) ;
     196  Bool isMultiIF( Table &tab ) ;
     197  void fillMainColumns( Table &tab ) ;
     198  static bool produceChunk(void *ctx) throw(concurrent::PCException);
     199  static void consumeChunk(void *ctx) throw(concurrent::PCException);
     200  static void consumeChunkWithClipping(void *ctx) throw(concurrent::PCException);
     201
     202
     203  // user input
     204  Int nxUI_ ;
     205  Int nyUI_ ;
     206  String cellxUI_ ;
     207  String cellyUI_ ;
     208  String centerUI_ ;
     209
     210  Block<String> infileList_ ;
     211  uInt nfile_ ;
    118212  Int ifno_ ;
     213  Bool doclip_ ;
     214
    119215  Int nx_ ;
    120216  Int ny_ ;
    121217  Int npol_ ;
     218  Int npolOrg_ ;
    122219  Int nchan_ ;
    123   Int nrow_ ;
    124220  Double cellx_ ;
    125221  Double celly_ ;
     
    129225  Int userSupport_ ;
    130226  Int convSampling_ ;
    131   Array<Float> data_ ;
    132227  Vector<uInt> pollist_ ;
    133228  Vector<uInt> scanlist_ ;
    134229  String wtype_ ;
     230  Block<Table> tableList_ ;
     231  Vector<uInt> rows_ ;
     232  Int nchunk_ ;
     233
     234  /////////////// gridPerRow variable
     235  IPosition vshape_;
     236  IPosition wshape_;
     237  IPosition dshape_;
     238  // loop variable
     239  Int nrow_ ;
     240  Array<Float> data_ ;
    135241
    136242  Table tab_ ;
     243  // per pol
     244  Table ptab_ ;
     245  ROArrayColumn<Float> spectraCol_ ;
     246  ROArrayColumn<uChar> flagtraCol_ ;
     247  ROArrayColumn<Double> directionCol_ ;
     248  ROScalarColumn<uInt> flagRowCol_ ;
     249  ROArrayColumn<Float> tsysCol_ ;
     250  ROScalarColumn<Double> intervalCol_ ;
     251
     252  Int nprocessed_ ;
     253
     254
     255  double eGetData_;
     256  double eToPixel_;
     257  double eGGridSD_;
    137258};
    138259}
  • /trunk/src/STLineFinder.cpp

    r2373 r2473  
    886886STLineFinder::STLineFinder() throw() : edge(0,0)
    887887{
     888  useScantable = true;
    888889  setOptions();
    889890}
     
    925926  itsNoiseBox = in_noise_box;
    926927  itsUseMedian = in_median;
    927 
    928   useScantable = true;
    929928}
    930929
     
    936935  scan=in_scan.getCP();
    937936  AlwaysAssert(!scan.null(),AipsError);
     937  useScantable = true;
    938938}
    939939
     
    943943void STLineFinder::setData(const std::vector<float> &in_spectrum)
    944944{
    945   spectrum = Vector<Float>(in_spectrum);
     945  //spectrum = Vector<Float>(in_spectrum);
     946  spectrum.assign( Vector<Float>(in_spectrum) );
    946947  useScantable = false;
    947948}
     
    966967  // no mask given...
    967968  if (in_mask.size() == 0) {
    968     mask = Vector<Bool>(nchan,True);
     969    //mask = Vector<Bool>(nchan,True);
     970    mask.assign( Vector<Bool>(nchan,True) );
    969971  } else {
    970972    // use provided mask
    971     mask=Vector<Bool>(in_mask);
     973    //mask=Vector<Bool>(in_mask);
     974    mask.assign( Vector<Bool>(in_mask) );
    972975  }
    973976  if (mask.nelements()!=nchan)
  • /trunk/src/STMath.cpp

    r2373 r2473  
    5757using namespace asap;
    5858
     59// 2012/02/17 TN
     60// Since STGrid is implemented, average doesn't consider direction
     61// when accumulating
    5962// tolerance for direction comparison (rad)
    60 #define TOL_OTF    1.0e-15
    61 #define TOL_POINT  2.9088821e-4  // 1 arcmin
     63// #define TOL_OTF    1.0e-15
     64// #define TOL_POINT  2.9088821e-4  // 1 arcmin
    6265
    6366STMath::STMath(bool insitu) :
     
    8386  WeightType wtype = stringToWeight(weight);
    8487
     88  // 2012/02/17 TN
     89  // Since STGrid is implemented, average doesn't consider direction
     90  // when accumulating
    8591  // check if OTF observation
    86   String obstype = in[0]->getHeader().obstype ;
    87   Double tol = 0.0 ;
    88   if ( (obstype.find( "OTF" ) != String::npos) || (obstype.find( "OBSERVE_TARGET" ) != String::npos) ) {
    89     tol = TOL_OTF ;
    90   }
    91   else {
    92     tol = TOL_POINT ;
    93   }
     92//   String obstype = in[0]->getHeader().obstype ;
     93//   Double tol = 0.0 ;
     94//   if ( (obstype.find( "OTF" ) != String::npos) || (obstype.find( "OBSERVE_TARGET" ) != String::npos) ) {
     95//     tol = TOL_OTF ;
     96//   }
     97//   else {
     98//     tol = TOL_POINT ;
     99//   }
    94100
    95101  // output
     
    142148  while (!iter.pastEnd()) {
    143149    Table subt = iter.table();
    144 //     // copy the first row of this selection into the new table
    145 //     tout.addRow();
    146 //     TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
    147 //     // re-index to 0
    148 //     if ( avmode != "SCAN" && avmode != "SOURCE" ) {
    149 //       scanColOut.put(outrowCount, uInt(0));
     150    // copy the first row of this selection into the new table
     151    tout.addRow();
     152    TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
     153    // re-index to 0
     154    if ( avmode != "SCAN" && avmode != "SOURCE" ) {
     155      scanColOut.put(outrowCount, uInt(0));
     156    }
     157    ++outrowCount;
     158    // 2012/02/17 TN
     159    // Since STGrid is implemented, average doesn't consider direction
     160    // when accumulating
     161//     MDirection::ScalarColumn dircol ;
     162//     dircol.attach( subt, "DIRECTION" ) ;
     163//     Int length = subt.nrow() ;
     164//     vector< Vector<Double> > dirs ;
     165//     vector<int> indexes ;
     166//     for ( Int i = 0 ; i < length ; i++ ) {
     167//       Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ;
     168//       //os << << count++ << ": " ;
     169//       //os << "[" << t[0] << "," << t[1] << "]" << LogIO::POST ;
     170//       bool adddir = true ;
     171//       for ( uInt j = 0 ; j < dirs.size() ; j++ ) {
     172//         //if ( allTrue( t == dirs[j] ) ) {
     173//         Double dx = t[0] - dirs[j][0] ;
     174//         Double dy = t[1] - dirs[j][1] ;
     175//         Double dd = sqrt( dx * dx + dy * dy ) ;
     176//         //if ( allNearAbs( t, dirs[j], tol ) ) {
     177//         if ( dd <= tol ) {
     178//           adddir = false ;
     179//           break ;
     180//         }
     181//       }
     182//       if ( adddir ) {
     183//         dirs.push_back( t ) ;
     184//         indexes.push_back( i ) ;
     185//       }
    150186//     }
    151 //     ++outrowCount;
    152     MDirection::ScalarColumn dircol ;
    153     dircol.attach( subt, "DIRECTION" ) ;
    154     Int length = subt.nrow() ;
    155     vector< Vector<Double> > dirs ;
    156     vector<int> indexes ;
    157     for ( Int i = 0 ; i < length ; i++ ) {
    158       Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ;
    159       //os << << count++ << ": " ;
    160       //os << "[" << t[0] << "," << t[1] << "]" << LogIO::POST ;
    161       bool adddir = true ;
    162       for ( uInt j = 0 ; j < dirs.size() ; j++ ) {
    163         //if ( allTrue( t == dirs[j] ) ) {
    164         Double dx = t[0] - dirs[j][0] ;
    165         Double dy = t[1] - dirs[j][1] ;
    166         Double dd = sqrt( dx * dx + dy * dy ) ;
    167         //if ( allNearAbs( t, dirs[j], tol ) ) {
    168         if ( dd <= tol ) {
    169           adddir = false ;
    170           break ;
    171         }
    172       }
    173       if ( adddir ) {
    174         dirs.push_back( t ) ;
    175         indexes.push_back( i ) ;
    176       }
    177     }
    178     uInt rowNum = dirs.size() ;
    179     tout.addRow( rowNum ) ;
    180     for ( uInt i = 0 ; i < rowNum ; i++ ) {
    181       TableCopy::copyRows( tout, subt, outrowCount+i, indexes[i], 1 ) ;
    182       // re-index to 0
    183       if ( avmode != "SCAN" && avmode != "SOURCE" ) {
    184         scanColOut.put(outrowCount+i, uInt(0));
    185       }       
    186     }
    187     outrowCount += rowNum ;
     187//     uInt rowNum = dirs.size() ;
     188//     tout.addRow( rowNum ) ;
     189//     for ( uInt i = 0 ; i < rowNum ; i++ ) {
     190//       TableCopy::copyRows( tout, subt, outrowCount+i, indexes[i], 1 ) ;
     191//       // re-index to 0
     192//       if ( avmode != "SCAN" && avmode != "SOURCE" ) {
     193//         scanColOut.put(outrowCount+i, uInt(0));
     194//       }       
     195//     }
     196//     outrowCount += rowNum ;
    188197    ++iter;
    189198  }
     
    218227      }
    219228
    220       vector<uInt> removeRows ;
    221       uInt nrsubt = subt.nrow() ;
    222       for ( uInt irow = 0 ; irow < nrsubt ; irow++ ) {
    223         //if ( !allTrue((subt.col("DIRECTION").getArrayDouble(TableExprId(irow)))==rec.asArrayDouble("DIRECTION")) ) {
    224         Vector<Double> x0 = (subt.col("DIRECTION").getArrayDouble(TableExprId(irow))) ;
    225         Vector<Double> x1 = rec.asArrayDouble("DIRECTION") ;
    226         double dx = x0[0] - x1[0];
    227         double dy = x0[1] - x1[1];
    228         Double dd = sqrt( dx * dx + dy * dy ) ;
    229         //if ( !allNearAbs((subt.col("DIRECTION").getArrayDouble(TableExprId(irow))), rec.asArrayDouble("DIRECTION"), tol ) ) {
    230         if ( dd > tol ) {
    231           removeRows.push_back( irow ) ;
    232         }
    233       }
    234       if ( removeRows.size() != 0 ) {
    235         subt.removeRow( removeRows ) ;
    236       }
     229      // 2012/02/17 TN
     230      // Since STGrid is implemented, average doesn't consider direction
     231      // when accumulating
     232//       vector<uInt> removeRows ;
     233//       uInt nrsubt = subt.nrow() ;
     234//       for ( uInt irow = 0 ; irow < nrsubt ; irow++ ) {
     235//         //if ( !allTrue((subt.col("DIRECTION").getArrayDouble(TableExprId(irow)))==rec.asArrayDouble("DIRECTION")) ) {
     236//         Vector<Double> x0 = (subt.col("DIRECTION").getArrayDouble(TableExprId(irow))) ;
     237//         Vector<Double> x1 = rec.asArrayDouble("DIRECTION") ;
     238//         double dx = x0[0] - x1[0];
     239//         double dy = x0[1] - x1[1];
     240//         Double dd = sqrt( dx * dx + dy * dy ) ;
     241//         //if ( !allNearAbs((subt.col("DIRECTION").getArrayDouble(TableExprId(irow))), rec.asArrayDouble("DIRECTION"), tol ) ) {
     242//         if ( dd > tol ) {
     243//           removeRows.push_back( irow ) ;
     244//         }
     245//       }
     246//       if ( removeRows.size() != 0 ) {
     247//         subt.removeRow( removeRows ) ;
     248//       }
    237249     
    238       if ( nrsubt == removeRows.size() )
    239         throw(AipsError("Averaging data is empty.")) ;
     250//       if ( nrsubt == removeRows.size() )
     251//         throw(AipsError("Averaging data is empty.")) ;
    240252
    241253      specCol.attach(subt,"SPECTRA");
     
    321333{
    322334  (void) mode; // currently unused
     335  // 2012/02/17 TN
     336  // Since STGrid is implemented, average doesn't consider direction
     337  // when accumulating
    323338  // check if OTF observation
    324   String obstype = in->getHeader().obstype ;
    325   Double tol = 0.0 ;
    326   if ( obstype.find( "OTF" ) != String::npos ) {
    327     tol = TOL_OTF ;
    328   }
    329   else {
    330     tol = TOL_POINT ;
    331   }
     339//   String obstype = in->getHeader().obstype ;
     340//   Double tol = 0.0 ;
     341//   if ( obstype.find( "OTF" ) != String::npos ) {
     342//     tol = TOL_OTF ;
     343//   }
     344//   else {
     345//     tol = TOL_POINT ;
     346//   }
    332347
    333348  // clone as this is non insitu
     
    362377    flagCol.attach(subt,"FLAGTRA");
    363378    tsysCol.attach(subt,"TSYS");
    364 //     tout.addRow();
    365 //     TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
    366 //     if ( avmode != "SCAN") {
    367 //       scanColOut.put(outrowCount, uInt(0));
     379
     380    tout.addRow();
     381    TableCopy::copyRows(tout, subt, outrowCount, 0, 1);
     382    if ( avmode != "SCAN") {
     383      scanColOut.put(outrowCount, uInt(0));
     384    }
     385    Vector<Float> tmp;
     386    specCol.get(0, tmp);
     387    uInt nchan = tmp.nelements();
     388    // have to do channel by channel here as MaskedArrMath
     389    // doesn't have partialMedians
     390    Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
     391    Vector<Float> outspec(nchan);
     392    Vector<uChar> outflag(nchan,0);
     393    Vector<Float> outtsys(1);/// @fixme when tsys is channel based
     394    for (uInt i=0; i<nchan; ++i) {
     395      Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
     396      MaskedArray<Float> ma = maskedArray(specs,flags);
     397      outspec[i] = median(ma);
     398      if ( allEQ(ma.getMask(), False) )
     399        outflag[i] = userflag;// flag data
     400    }
     401    outtsys[0] = median(tsysCol.getColumn());
     402    specColOut.put(outrowCount, outspec);
     403    flagColOut.put(outrowCount, outflag);
     404    tsysColOut.put(outrowCount, outtsys);
     405    Double intsum = sum(intCol.getColumn());
     406    intColOut.put(outrowCount, intsum);
     407    ++outrowCount;
     408    ++iter;
     409
     410    // 2012/02/17 TN
     411    // Since STGrid is implemented, average doesn't consider direction
     412    // when accumulating
     413//     MDirection::ScalarColumn dircol ;
     414//     dircol.attach( subt, "DIRECTION" ) ;
     415//     Int length = subt.nrow() ;
     416//     vector< Vector<Double> > dirs ;
     417//     vector<int> indexes ;
     418//     // Handle MX mode averaging
     419//     if (in->nbeam() > 1 ) {     
     420//       length = 1;
    368421//     }
    369 //     Vector<Float> tmp;
    370 //     specCol.get(0, tmp);
    371 //     uInt nchan = tmp.nelements();
    372 //     // have to do channel by channel here as MaskedArrMath
    373 //     // doesn't have partialMedians
    374 //     Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
    375 //     Vector<Float> outspec(nchan);
    376 //     Vector<uChar> outflag(nchan,0);
    377 //     Vector<Float> outtsys(1);/// @fixme when tsys is channel based
    378 //     for (uInt i=0; i<nchan; ++i) {
    379 //       Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
    380 //       MaskedArray<Float> ma = maskedArray(specs,flags);
    381 //       outspec[i] = median(ma);
    382 //       if ( allEQ(ma.getMask(), False) )
    383 //         outflag[i] = userflag;// flag data
     422//     for ( Int i = 0 ; i < length ; i++ ) {
     423//       Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ;
     424//       bool adddir = true ;
     425//       for ( uInt j = 0 ; j < dirs.size() ; j++ ) {
     426//         //if ( allTrue( t == dirs[j] ) ) {
     427//         Double dx = t[0] - dirs[j][0] ;
     428//         Double dy = t[1] - dirs[j][1] ;
     429//         Double dd = sqrt( dx * dx + dy * dy ) ;
     430//         //if ( allNearAbs( t, dirs[j], tol ) ) {
     431//         if ( dd <= tol ) {
     432//           adddir = false ;
     433//           break ;
     434//         }
     435//       }
     436//       if ( adddir ) {
     437//         dirs.push_back( t ) ;
     438//         indexes.push_back( i ) ;
     439//       }
    384440//     }
    385 //     outtsys[0] = median(tsysCol.getColumn());
    386 //     specColOut.put(outrowCount, outspec);
    387 //     flagColOut.put(outrowCount, outflag);
    388 //     tsysColOut.put(outrowCount, outtsys);
    389 //     Double intsum = sum(intCol.getColumn());
    390 //     intColOut.put(outrowCount, intsum);
    391 //     ++outrowCount;
     441//     uInt rowNum = dirs.size() ;
     442//     tout.addRow( rowNum );
     443//     for ( uInt i = 0 ; i < rowNum ; i++ ) {
     444//       TableCopy::copyRows(tout, subt, outrowCount+i, indexes[i], 1) ;
     445//       // Handle MX mode averaging
     446//       if ( avmode != "SCAN") {
     447//         scanColOut.put(outrowCount+i, uInt(0));
     448//       }
     449//     }
     450//     MDirection::ScalarColumn dircolOut ;
     451//     dircolOut.attach( tout, "DIRECTION" ) ;
     452//     for ( uInt irow = 0 ; irow < rowNum ; irow++ ) {
     453//       Vector<Double> t = \
     454//      dircolOut(outrowCount+irow).getAngle(Unit(String("rad"))).getValue() ;
     455//       Vector<Float> tmp;
     456//       specCol.get(0, tmp);
     457//       uInt nchan = tmp.nelements();
     458//       // have to do channel by channel here as MaskedArrMath
     459//       // doesn't have partialMedians
     460//       Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
     461//       // mask spectra for different DIRECTION
     462//       for ( uInt jrow = 0 ; jrow < subt.nrow() ; jrow++ ) {
     463//         Vector<Double> direction = \
     464//        dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
     465//         //if ( t[0] != direction[0] || t[1] != direction[1] ) {
     466//         Double dx = t[0] - direction[0];
     467//         Double dy = t[1] - direction[1];
     468//         Double dd = sqrt(dx*dx + dy*dy);
     469//         //if ( !allNearAbs( t, direction, tol ) ) {
     470//         if ( dd > tol &&  in->nbeam() < 2 ) {
     471//           flags[jrow] = userflag ;
     472//         }
     473//       }
     474//       Vector<Float> outspec(nchan);
     475//       Vector<uChar> outflag(nchan,0);
     476//       Vector<Float> outtsys(1);/// @fixme when tsys is channel based
     477//       for (uInt i=0; i<nchan; ++i) {
     478//         Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
     479//         MaskedArray<Float> ma = maskedArray(specs,flags);
     480//         outspec[i] = median(ma);
     481//         if ( allEQ(ma.getMask(), False) )
     482//           outflag[i] = userflag;// flag data
     483//       }
     484//       outtsys[0] = median(tsysCol.getColumn());
     485//       specColOut.put(outrowCount+irow, outspec);
     486//       flagColOut.put(outrowCount+irow, outflag);
     487//       tsysColOut.put(outrowCount+irow, outtsys);
     488//       Vector<Double> integ = intCol.getColumn() ;
     489//       MaskedArray<Double> mi = maskedArray( integ, flags ) ;
     490//       Double intsum = sum(mi);
     491//       intColOut.put(outrowCount+irow, intsum);
     492//     }
     493//     outrowCount += rowNum ;
    392494//     ++iter;
    393     MDirection::ScalarColumn dircol ;
    394     dircol.attach( subt, "DIRECTION" ) ;
    395     Int length = subt.nrow() ;
    396     vector< Vector<Double> > dirs ;
    397     vector<int> indexes ;
    398     // Handle MX mode averaging
    399     if (in->nbeam() > 1 ) {     
    400       length = 1;
    401     }
    402     for ( Int i = 0 ; i < length ; i++ ) {
    403       Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ;
    404       bool adddir = true ;
    405       for ( uInt j = 0 ; j < dirs.size() ; j++ ) {
    406         //if ( allTrue( t == dirs[j] ) ) {
    407         Double dx = t[0] - dirs[j][0] ;
    408         Double dy = t[1] - dirs[j][1] ;
    409         Double dd = sqrt( dx * dx + dy * dy ) ;
    410         //if ( allNearAbs( t, dirs[j], tol ) ) {
    411         if ( dd <= tol ) {
    412           adddir = false ;
    413           break ;
    414         }
    415       }
    416       if ( adddir ) {
    417         dirs.push_back( t ) ;
    418         indexes.push_back( i ) ;
    419       }
    420     }
    421     uInt rowNum = dirs.size() ;
    422     tout.addRow( rowNum );
    423     for ( uInt i = 0 ; i < rowNum ; i++ ) {
    424       TableCopy::copyRows(tout, subt, outrowCount+i, indexes[i], 1) ;
    425       // Handle MX mode averaging
    426       if ( avmode != "SCAN") {
    427         scanColOut.put(outrowCount+i, uInt(0));
    428       }
    429     }
    430     MDirection::ScalarColumn dircolOut ;
    431     dircolOut.attach( tout, "DIRECTION" ) ;
    432     for ( uInt irow = 0 ; irow < rowNum ; irow++ ) {
    433       Vector<Double> t = \
    434         dircolOut(outrowCount+irow).getAngle(Unit(String("rad"))).getValue() ;
    435       Vector<Float> tmp;
    436       specCol.get(0, tmp);
    437       uInt nchan = tmp.nelements();
    438       // have to do channel by channel here as MaskedArrMath
    439       // doesn't have partialMedians
    440       Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0)));
    441       // mask spectra for different DIRECTION
    442       for ( uInt jrow = 0 ; jrow < subt.nrow() ; jrow++ ) {
    443         Vector<Double> direction = \
    444           dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
    445         //if ( t[0] != direction[0] || t[1] != direction[1] ) {
    446         Double dx = t[0] - direction[0];
    447         Double dy = t[1] - direction[1];
    448         Double dd = sqrt(dx*dx + dy*dy);
    449         //if ( !allNearAbs( t, direction, tol ) ) {
    450         if ( dd > tol &&  in->nbeam() < 2 ) {
    451           flags[jrow] = userflag ;
    452         }
    453       }
    454       Vector<Float> outspec(nchan);
    455       Vector<uChar> outflag(nchan,0);
    456       Vector<Float> outtsys(1);/// @fixme when tsys is channel based
    457       for (uInt i=0; i<nchan; ++i) {
    458         Vector<Float> specs = specCol.getColumn(Slicer(Slice(i)));
    459         MaskedArray<Float> ma = maskedArray(specs,flags);
    460         outspec[i] = median(ma);
    461         if ( allEQ(ma.getMask(), False) )
    462           outflag[i] = userflag;// flag data
    463       }
    464       outtsys[0] = median(tsysCol.getColumn());
    465       specColOut.put(outrowCount+irow, outspec);
    466       flagColOut.put(outrowCount+irow, outflag);
    467       tsysColOut.put(outrowCount+irow, outtsys);
    468       Vector<Double> integ = intCol.getColumn() ;
    469       MaskedArray<Double> mi = maskedArray( integ, flags ) ;
    470       Double intsum = sum(mi);
    471       intColOut.put(outrowCount+irow, intsum);
    472     }
    473     outrowCount += rowNum ;
    474     ++iter;
    475495  }
    476496  return out;
     
    19101930  ArrayColumn<Float> specCol(tout, "SPECTRA");
    19111931  ArrayColumn<uChar> flagCol(tout, "FLAGTRA");
     1932  ArrayColumn<Float> tsysCol(tout, "TSYS");
     1933
    19121934  for (uInt i=0; i < tout.nrow(); ++i ) {
    19131935    MaskedArray<Float> main  = maskedArray(specCol(i), flagCol(i));
    19141936    MaskedArray<Float> maout;
    19151937    LatticeUtilities::bin(maout, main, 0, Int(width));
    1916     /// @todo implement channel based tsys binning
    19171938    specCol.put(i, maout.getArray());
    19181939    flagCol.put(i, flagsFromMA(maout));
     1940    if (tsysCol(i).nelements() == specCol(i).nelements()) {
     1941      MaskedArray<Float> matsysin = maskedArray(tsysCol(i), flagCol(i));
     1942      MaskedArray<Float> matsysout;
     1943      LatticeUtilities::bin(matsysout, matsysin, 0, Int(width));
     1944      tsysCol.put(i, matsysout.getArray());
     1945    }
    19191946    // take only the first binned spectrum's length for the deprecated
    19201947    // global header item nChan
     
    27502777                             mask, timeCol(i), !first,
    27512778                             interp, False);
    2752           (void) ok; // unused stop compiler nagging     
     2779          (void) ok; // unused stop compiler nagging
    27532780          // back into scantable
    27542781          flagOut.resize(maskOut.nelements());
     
    29542981                    "Use merge first."));
    29552982 
     2983  // 2012/02/17 TN
     2984  // Since STGrid is implemented, average doesn't consider direction
     2985  // when accumulating
    29562986  // check if OTF observation
    2957   String obstype = in[0]->getHeader().obstype ;
    2958   Double tol = 0.0 ;
    2959   if ( obstype.find( "OTF" ) != String::npos ) {
    2960     tol = TOL_OTF ;
    2961   }
    2962   else {
    2963     tol = TOL_POINT ;
    2964   }
     2987//   String obstype = in[0]->getHeader().obstype ;
     2988//   Double tol = 0.0 ;
     2989//   if ( obstype.find( "OTF" ) != String::npos ) {
     2990//     tol = TOL_OTF ;
     2991//   }
     2992//   else {
     2993//     tol = TOL_POINT ;
     2994//   }
    29652995
    29662996  CountedPtr<Scantable> out ;     // processed result
     
    30153045      uInt rows = tmpin[itable]->nrow() ;
    30163046      uInt freqnrows = tmpin[itable]->frequencies().table().nrow() ;
     3047      freqIDCol.attach( tmpin[itable]->table(), "FREQ_ID" ) ;
     3048      //ifnoCol.attach( tmpin[itable]->table(), "IFNO" ) ;
    30173049      for ( uInt irow = 0 ; irow < rows ; irow++ ) {
    30183050        if ( freqid[itable].size() == freqnrows ) {
     
    30203052        }
    30213053        else {
    3022           freqIDCol.attach( tmpin[itable]->table(), "FREQ_ID" ) ;
    3023           ifnoCol.attach( tmpin[itable]->table(), "IFNO" ) ;
    30243054          uInt id = freqIDCol( irow ) ;
    30253055          if ( freqid[itable].size() == 0 || count( freqid[itable].begin(), freqid[itable].end(), id ) == 0 ) {
    30263056            //os << "itable = " << itable << ": IF " << id << " is included in the list" << LogIO::POST ;
    30273057            vector<double> abcissa = tmpin[itable]->getAbcissa( irow ) ;
     3058            double lbedge, rbedge;
    30283059            freqid[itable].push_back( id ) ;
    3029             iffreq[itable].push_back( abcissa[0] - 0.5 * ( abcissa[1] - abcissa[0] ) ) ;
    3030             iffreq[itable].push_back( abcissa[abcissa.size()-1] + 0.5 * ( abcissa[1] - abcissa[0] ) ) ;
     3060            lbedge = abcissa[0] - 0.5 * ( abcissa[1] - abcissa[0] );
     3061            rbedge = abcissa[abcissa.size()-1] + 0.5 * ( abcissa[1] - abcissa[0] );
     3062            iffreq[itable].push_back( min(lbedge, rbedge) ) ;
     3063            iffreq[itable].push_back( max(lbedge, rbedge) ) ;
    30313064          }
    30323065        }
     
    31133146    // Grouping continuous IF groups (without frequency gap)
    31143147    // freqgrp: list of IF group indexes in each frequency group
    3115     // freqrange: list of minimum and maximum frequency in each frequency group
    31163148    // freqgrp[numgrp][nummember]
    31173149    // freqgrp: [[ifgrp00, ifgrp01, ifgrp02, ...],
     
    31193151    //           ...
    31203152    //           [ifgrpn0, ifgrpn1, ifgrpn2, ...]]
    3121     // freqrange[numgrp*2]
    3122     // freqrange: [min_grp0, max_grp0, min_grp1, max_grp1, ...]
    31233153    vector< vector<uInt> > freqgrp ;
    31243154    double freqrange = 0.0 ;
     
    31363166      freqrange = ifgfreq[2*i+1] ;
    31373167    }
    3138        
     3168
    31393169
    31403170    // print IF groups
     
    33253355
    33263356    // save column values in the vector
    3327     vector< vector<uInt> > freqTableIdVec( insize ) ;
    33283357    vector< vector<uInt> > freqIdVec( insize ) ;
    33293358    vector< vector<uInt> > ifNoVec( insize ) ;
    33303359    for ( uInt itable = 0 ; itable < insize ; itable++ ) {
    3331       ScalarColumn<uInt> freqIDs ;
    3332       freqIDs.attach( newin[itable]->frequencies().table(), "ID" ) ;
    33333360      ifnoCol.attach( newin[itable]->table(), "IFNO" ) ;
    33343361      freqIDCol.attach( newin[itable]->table(), "FREQ_ID" ) ;
    3335       for ( uInt irow = 0 ; irow < newin[itable]->frequencies().table().nrow() ; irow++ ) {
    3336         freqTableIdVec[itable].push_back( freqIDs( irow ) ) ;
    3337       }
    33383362      for ( uInt irow = 0 ; irow < newin[itable]->table().nrow() ; irow++ ) {
    33393363        freqIdVec[itable].push_back( freqIDCol( irow ) ) ;
     
    33503374      vector<uInt> freqIdUpdate ;
    33513375      for ( uInt irow = 0 ; irow < rows ; irow++ ) {
    3352         uInt ifno = ifNoVec[itable][irow] ;  // IFNO is reset by group index
     3376        uInt ifno = ifNoVec[itable][irow] ;  // IFNO is reset by group index (IF group index)
    33533377        double minfreq = ifgfreq[2*ifno] ;
    33543378        double maxfreq = ifgfreq[2*ifno+1] ;
     
    33583382        double resol = abcissa[1] - abcissa[0] ;
    33593383        //os << "abcissa range  : [" << abcissa[0] << "," << abcissa[nchan-1] << "]" << LogIO::POST ;
    3360         if ( minfreq <= abcissa[0] )
    3361           nminchan = 0 ;
     3384        uInt imin, imax;
     3385        int sigres;
     3386        if ( resol >= 0. ) {
     3387          imin = 0;
     3388          imax = nchan - 1 ;
     3389          sigres = 1 ;
     3390        } else {
     3391          imin = nchan - 1 ;
     3392          imax = 0 ;
     3393          sigres = -1 ;
     3394          resol = abs(resol) ;
     3395        }
     3396        if ( minfreq <= abcissa[imin] )
     3397          nminchan = imin ;
    33623398        else {
    33633399          //double cfreq = ( minfreq - abcissa[0] ) / resol ;
    3364           double cfreq = ( minfreq - abcissa[0] + 0.5 * resol ) / resol ;
    3365           nminchan = int(cfreq) + ( ( cfreq - int(cfreq) <= 0.5 ) ? 0 : 1 ) ;
     3400          double cfreq = ( minfreq - abcissa[imin] + 0.5 * resol ) / resol ;
     3401          nminchan = imin + sigres * (int(cfreq) + ( ( cfreq - int(cfreq) <= 0.5 ) ? 0 : 1 )) ;
    33663402        }
    3367         if ( maxfreq >= abcissa[abcissa.size()-1] )
    3368           nmaxchan = abcissa.size() - 1 ;
     3403        if ( maxfreq >= abcissa[imax] )
     3404          nmaxchan = imax;
    33693405        else {
    33703406          //double cfreq = ( abcissa[abcissa.size()-1] - maxfreq ) / resol ;
    3371           double cfreq = ( abcissa[abcissa.size()-1] - maxfreq + 0.5 * resol ) / resol ;
    3372           nmaxchan = abcissa.size() - 1 - int(cfreq) - ( ( cfreq - int(cfreq) >= 0.5 ) ? 1 : 0 ) ;
     3407          double cfreq = ( abcissa[imax] - maxfreq + 0.5 * resol ) / resol ;
     3408          nmaxchan = imax - sigres * (int(cfreq) +( ( cfreq - int(cfreq) >= 0.5 ) ? 1 : 0 )) ;
    33733409        }
    33743410        //os << "channel range (" << irow << "): [" << nminchan << "," << nmaxchan << "]" << LogIO::POST ;
     3411        if ( nmaxchan < nminchan ) {
     3412          int tmp = nmaxchan ;
     3413          nmaxchan = nminchan ;
     3414          nminchan = tmp ;
     3415        }
    33753416        if ( nmaxchan > nminchan ) {
    33763417          newin[itable]->reshapeSpectrum( nminchan, nmaxchan, irow ) ;
    33773418          int newchan = nmaxchan - nminchan + 1 ;
    3378           if ( count( freqIdUpdate.begin(), freqIdUpdate.end(), freqIdVec[itable][irow] ) == 0 && newchan < nchan )
     3419          if ( count( freqIdUpdate.begin(), freqIdUpdate.end(), freqIdVec[itable][irow] ) == 0 && newchan < nchan ) {
    33793420            freqIdUpdate.push_back( freqIdVec[itable][irow] ) ;
     3421
     3422            // Update before nminchan is lost
     3423            uInt freqId = freqIdVec[itable][irow] ;
     3424            Double refpix ;
     3425            Double refval ;
     3426            Double increment ;
     3427            newin[itable]->frequencies().getEntry( refpix, refval, increment, freqId ) ;
     3428            //refval = refval - ( refpix - nminchan ) * increment ;
     3429            refval = abcissa[nminchan] ;
     3430            refpix = 0 ;
     3431            newin[itable]->frequencies().setEntry( refpix, refval, increment, freqId ) ;
     3432          }
    33803433        }
    33813434        else {
     
    33833436        }
    33843437      }
    3385       for ( uInt i = 0 ; i < freqIdUpdate.size() ; i++ ) {
    3386         uInt freqId = freqIdUpdate[i] ;
    3387         Double refpix ;
    3388         Double refval ;
    3389         Double increment ;
     3438//       for ( uInt i = 0 ; i < freqIdUpdate.size() ; i++ ) {
     3439//      uInt freqId = freqIdUpdate[i] ;
     3440//      Double refpix ;
     3441//      Double refval ;
     3442//      Double increment ;
    33903443       
    3391         // update row
    3392         newin[itable]->frequencies().getEntry( refpix, refval, increment, freqId ) ;
    3393         refval = refval - ( refpix - nminchan ) * increment ;
    3394         refpix = 0 ;
    3395         newin[itable]->frequencies().setEntry( refpix, refval, increment, freqId ) ;
    3396       }   
     3444//      // update row
     3445//      newin[itable]->frequencies().getEntry( refpix, refval, increment, freqId ) ;
     3446//      refval = refval - ( refpix - nminchan ) * increment ;
     3447//      refpix = 0 ;
     3448//      newin[itable]->frequencies().setEntry( refpix, refval, increment, freqId ) ;
     3449//       }   
    33973450    }
    33983451
     
    34313484            if ( nchan < minchan ) {
    34323485              minchan = nchan ;
    3433               maxdnu = dnu ;
     3486              maxdnu = abs(dnu) ;
    34343487              newin[tableid]->frequencies().getEntry( refpixref, refvalref, refinc, rowid ) ;
    34353488              refreqid = rowid ;
    34363489              reftable = tableid ;
     3490              // Spectra are reversed when dnu < 0
     3491              if (dnu < 0)
     3492                refpixref = minchan - 1 -refpixref ;
    34373493            }
    34383494          }
     
    34493505          //os << "   regridChannel applied to " ;
    34503506          //if ( tableid != reftable )
    3451           refreqid = newin[tableid]->frequencies().addEntry( refpixref, refvalref, refinc ) ;
     3507          refreqid = newin[tableid]->frequencies().addEntry( refpixref, refvalref, maxdnu ) ;
    34523508          for ( uInt irow = 0 ; irow < newin[tableid]->table().nrow() ; irow++ ) {
    34533509            uInt tfreqid = freqIdVec[tableid][irow] ;
     
    34703526          vector<double> abcissa = newin[tableid]->getAbcissa( index ) ;
    34713527          minchan = abcissa.size() ;
    3472           maxdnu = abcissa[1] - abcissa[0] ;
     3528          maxdnu = abs( abcissa[1] - abcissa[0]) ;
    34733529        }
    34743530      }
     
    35403596          vector<double> abcissa = tmpout->getAbcissa( irow ) ;
    35413597          double bw = ( abcissa[1] - abcissa[0] ) * abcissa.size() ;
    3542           int nchan = (int)( bw / gmaxdnu[igrp] ) ;
     3598          int nchan = (int) abs( bw / gmaxdnu[igrp] ) ;
     3599          // All spectra will have positive frequency increments
    35433600          tmpout->regridChannel( nchan, gmaxdnu[igrp], irow ) ;
    35443601          break ;
     
    35573614    ScalarColumn<uInt> freqidColOut ;
    35583615    freqidColOut.attach( out->table(), "FREQ_ID" ) ;
    3559     MDirection::ScalarColumn dirColOut ;
    3560     dirColOut.attach( out->table(), "DIRECTION" ) ;
     3616//     MDirection::ScalarColumn dirColOut ;
     3617//     dirColOut.attach( out->table(), "DIRECTION" ) ;
    35613618    Table &tab = tmpout->table() ;
    35623619    Block<String> cols(1);
    35633620    cols[0] = String("POLNO") ;
    35643621    TableIterator iter( tab, cols ) ;
    3565     bool done = false ;
    35663622    vector< vector<uInt> > sizes( freqgrp.size() ) ;
    35673623    while( !iter.pastEnd() ) {
     
    35753631      ScalarColumn<uInt> polnos ;
    35763632      polnos.attach( iter.table(), "POLNO" ) ;
    3577       MDirection::ScalarColumn dircol ;
    3578       dircol.attach( iter.table(), "DIRECTION" ) ;
     3633//       MDirection::ScalarColumn dircol ;
     3634//       dircol.attach( iter.table(), "DIRECTION" ) ;
    35793635      uInt polno = polnos( 0 ) ;
    35803636      //os << "POLNO iteration: " << polno << LogIO::POST ;
     
    36143670//       }
    36153671      // get a list of number of channels for each frequency group member
    3616       if ( !done ) {
    3617         for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
    3618           sizes[igrp].resize( freqgrp[igrp].size() ) ;
    3619           for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) {
    3620             for ( uInt irow = 0 ; irow < iter.table().nrow() ; irow++ ) {
    3621               uInt ifno = ifnoCol( irow ) ;
    3622               if ( ifno == freqgrp[igrp][imem] ) {
    3623                 Vector<Float> spec = specCols( irow ) ;
    3624                 sizes[igrp][imem] = spec.nelements() ;
    3625                 break ;
    3626               }               
    3627             }
    3628           }
    3629         }
    3630         done = true ;
     3672      for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) {
     3673        sizes[igrp].resize( freqgrp[igrp].size() ) ;
     3674        for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) {
     3675          for ( uInt irow = 0 ; irow < iter.table().nrow() ; irow++ ) {
     3676            uInt ifno = ifnoCol( irow ) ;
     3677            if ( ifno == freqgrp[igrp][imem] ) {
     3678              Vector<Float> spec = specCols( irow ) ;
     3679              sizes[igrp][imem] = spec.nelements() ;
     3680              break ;
     3681            }
     3682          }
     3683        }
    36313684      }
    36323685      // combine spectra
     
    36353688        if ( polout == polno ) {
    36363689          uInt ifout = ifnoColOut( irow ) ;
    3637           Vector<Double> direction = dirColOut(irow).getAngle(Unit(String("rad"))).getValue() ;
     3690//           Vector<Double> direction = dirColOut(irow).getAngle(Unit(String("rad"))).getValue() ;
    36383691          uInt igrp ;
    36393692          for ( uInt jgrp = 0 ; jgrp < freqgrp.size() ; jgrp++ ) {
     
    36463699            for ( uInt jrow = 0 ; jrow < iter.table().nrow() ; jrow++ ) {
    36473700              uInt ifno = ifnoCol( jrow ) ;
    3648               Vector<Double> tdir = dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
    3649               //if ( ifno == freqgrp[igrp][imem] && allTrue( tdir == direction  ) ) {
    3650               Double dx = tdir[0] - direction[0] ;
    3651               Double dy = tdir[1] - direction[1] ;
    3652               Double dd = sqrt( dx * dx + dy * dy ) ;
     3701              // 2012/02/17 TN
     3702              // Since STGrid is implemented, average doesn't consider direction
     3703              // when accumulating
     3704//               Vector<Double> tdir = dircol(jrow).getAngle(Unit(String("rad"))).getValue() ;
     3705//               //if ( ifno == freqgrp[igrp][imem] && allTrue( tdir == direction  ) ) {
     3706//               Double dx = tdir[0] - direction[0] ;
     3707//               Double dy = tdir[1] - direction[1] ;
     3708//               Double dd = sqrt( dx * dx + dy * dy ) ;
    36533709              //if ( ifno == freqgrp[igrp][imem] && allNearAbs( tdir, direction, tol ) ) {
    3654               if ( ifno == freqgrp[igrp][imem] && dd <= tol ) {
     3710//               if ( ifno == freqgrp[igrp][imem] && dd <= tol ) {
     3711              if ( ifno == freqgrp[igrp][imem] ) {
    36553712                Vector<Float> spec = specCols( jrow ) ;
    36563713                Vector<uChar> flag = flagCols( jrow ) ;
     
    36713728          specColOut.put( irow, newspec ) ;
    36723729          flagColOut.put( irow, newflag ) ;
    3673           // IFNO renumbering
     3730          // IFNO renumbering (renumbered as frequency group ID)
    36743731          ifnoColOut.put( irow, igrp ) ;
    36753732        }
     
    36823739      uInt index = 0 ;
    36833740      uInt pixShift = 0 ;
     3741
    36843742      while ( freqgrp[igrp][index] != gmemid[igrp] ) {
    36853743        pixShift += sizes[igrp][index++] ;
    36863744      }
    36873745      for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) {
    3688         if ( ifnoColOut( irow ) == gmemid[igrp] && !updated[igrp] ) {
     3746        //if ( ifnoColOut( irow ) == gmemid[igrp] && !updated[igrp] ) {
     3747        if ( ifnoColOut( irow ) == igrp && !updated[igrp] ) {
    36893748          uInt freqidOut = freqidColOut( irow ) ;
    36903749          //os << "freqgrp " << igrp << " freqidOut = " << freqidOut << LogIO::POST ;
     
    36933752          double increm ;
    36943753          out->frequencies().getEntry( refpix, refval, increm, freqidOut ) ;
     3754          if (increm < 0)
     3755            refpix = sizes[igrp][index] - 1 - refpix ; // reversed
    36953756          refpix += pixShift ;
    3696           out->frequencies().setEntry( refpix, refval, increm, freqidOut ) ;
     3757          out->frequencies().setEntry( refpix, refval, gmaxdnu[igrp], freqidOut ) ;
    36973758          updated[igrp] = true ;
    36983759        }
  • /trunk/src/STMathWrapper.h

    r2373 r2473  
    197197                                   const std::string& refTime,
    198198                                   const std::string& method  )
    199   { return ScantableWrapper(STMath::frequencyAlign(in.getCP())); }
     199  { return ScantableWrapper(STMath::frequencyAlign(in.getCP(),
     200                                                   refTime, method)); }
    200201
    201202  ScantableWrapper convertPolarisation( const ScantableWrapper& in,
  • /trunk/src/Scantable.cpp

    r2373 r2473  
    7070#include "STUpgrade.h"
    7171#include "Scantable.h"
     72
     73#define debug 1
    7274
    7375using namespace casa;
     
    18851887}
    18861888
     1889void asap::Scantable::regridSpecChannel( double dnu, int nChan )
     1890{
     1891  LogIO os( LogOrigin( "Scantable", "regridChannel()", WHERE ) ) ;
     1892  os << "Regrid abcissa with spectral resoultion " << dnu << " " << freqTable_.getUnitString() << " with channel number " << ((nChan>0)? String(nChan) : "covering band width")<< LogIO::POST ;
     1893  int freqnrow = freqTable_.table().nrow() ;
     1894  Vector<bool> firstTime( freqnrow, true ) ;
     1895  double oldincr, factor;
     1896  uInt currId;
     1897  Double refpix ;
     1898  Double refval ;
     1899  Double increment ;
     1900  for ( int irow = 0 ; irow < nrow() ; irow++ ) {
     1901    currId = mfreqidCol_(irow);
     1902    vector<double> abcissa = getAbcissa( irow ) ;
     1903    if (nChan < 0) {
     1904      int oldsize = abcissa.size() ;
     1905      double bw = (abcissa[oldsize-1]-abcissa[0]) +                     \
     1906        0.5 * (abcissa[1]-abcissa[0] + abcissa[oldsize-1]-abcissa[oldsize-2]) ;
     1907      nChan = int( ceil( abs(bw/dnu) ) ) ;
     1908    }
     1909    // actual regridding
     1910    regridChannel( nChan, dnu, irow ) ;
     1911
     1912    // update FREQUENCIES subtable
     1913    if (firstTime[currId]) {
     1914      oldincr = abcissa[1]-abcissa[0] ;
     1915      factor = dnu/oldincr ;
     1916      firstTime[currId] = false ;
     1917      freqTable_.getEntry( refpix, refval, increment, currId ) ;
     1918
     1919      //refval = refval - ( refpix + 0.5 * (1 - factor) ) * increment ;
     1920      if (factor > 0 ) {
     1921        refpix = (refpix + 0.5)/factor - 0.5;
     1922      } else {
     1923        refpix = (abcissa.size() - 0.5 - refpix)/abs(factor) - 0.5;
     1924      }
     1925      freqTable_.setEntry( refpix, refval, increment*factor, currId ) ;
     1926      //os << "ID" << currId << ": channel width (Orig) = " << oldincr << " [" << freqTable_.getUnitString() << "], scale factor = " << factor << LogIO::POST ;
     1927      //os << "     frequency increment (Orig) = " << increment << "-> (New) " << increment*factor << LogIO::POST ;
     1928    }
     1929  }
     1930}
     1931
    18871932void asap::Scantable::regridChannel( int nChan, double dnu )
    18881933{
     
    19051950  }
    19061951
    1907   // change channel number for specCol_ and flagCol_
    1908   Vector<Float> newspec( nChan, 0 ) ;
    1909   Vector<uChar> newflag( nChan, false ) ;
     1952  // change channel number for specCol_, flagCol_, and tsysCol_ (if necessary)
    19101953  vector<string> coordinfo = getCoordInfo() ;
    19111954  string oldinfo = coordinfo[0] ;
     
    19331976  Vector<Float> oldspec = specCol_( irow ) ;
    19341977  Vector<uChar> oldflag = flagsCol_( irow ) ;
     1978  Vector<Float> oldtsys = tsysCol_( irow ) ;
    19351979  Vector<Float> newspec( nChan, 0 ) ;
    1936   Vector<uChar> newflag( nChan, false ) ;
     1980  Vector<uChar> newflag( nChan, true ) ;
     1981  Vector<Float> newtsys ;
     1982  bool regridTsys = false ;
     1983  if (oldtsys.size() == oldspec.size()) {
     1984    regridTsys = true ;
     1985    newtsys.resize(nChan,false) ;
     1986    newtsys = 0 ;
     1987  }
    19371988
    19381989  // regrid
     
    19401991  int oldsize = abcissa.size() ;
    19411992  double olddnu = abcissa[1] - abcissa[0] ;
    1942   //int refChan = 0 ;
    1943   //double frac = 0.0 ;
    1944   //double wedge = 0.0 ;
    1945   //double pile = 0.0 ;
    1946   int ichan = 0 ;
     1993  //int ichan = 0 ;
    19471994  double wsum = 0.0 ;
    1948   Vector<Float> zi( nChan+1 ) ;
    1949   Vector<Float> yi( oldsize + 1 ) ;
    1950   zi[0] = abcissa[0] - 0.5 * olddnu ;
    1951   zi[1] = zi[1] + dnu ;
    1952   for ( int ii = 2 ; ii < nChan ; ii++ )
     1995  Vector<double> zi( nChan+1 ) ;
     1996  Vector<double> yi( oldsize + 1 ) ;
     1997  yi[0] = abcissa[0] - 0.5 * olddnu ;
     1998  for ( int ii = 1 ; ii < oldsize ; ii++ )
     1999    yi[ii] = 0.5* (abcissa[ii-1] + abcissa[ii]) ;
     2000  yi[oldsize] = abcissa[oldsize-1] \
     2001    + 0.5 * (abcissa[oldsize-1] - abcissa[oldsize-2]) ;
     2002  //zi[0] = abcissa[0] - 0.5 * olddnu ;
     2003  zi[0] = ((olddnu*dnu > 0) ? yi[0] : yi[oldsize]) ;
     2004  for ( int ii = 1 ; ii < nChan ; ii++ )
    19532005    zi[ii] = zi[0] + dnu * ii ;
    19542006  zi[nChan] = zi[nChan-1] + dnu ;
    1955   yi[0] = abcissa[0] - 0.5 * olddnu ;
    1956   yi[1] = abcissa[1] + 0.5 * olddnu ;
    1957   for ( int ii = 2 ; ii < oldsize ; ii++ )
    1958     yi[ii] = abcissa[ii-1] + olddnu ;
    1959   yi[oldsize] = abcissa[oldsize-1] + 0.5 * olddnu ;
    1960   if ( dnu > 0.0 ) {
    1961     for ( int ii = 0 ; ii < nChan ; ii++ ) {
    1962       double zl = zi[ii] ;
    1963       double zr = zi[ii+1] ;
    1964       for ( int j = ichan ; j < oldsize ; j++ ) {
    1965         double yl = yi[j] ;
    1966         double yr = yi[j+1] ;
    1967         if ( yl <= zl ) {
    1968           if ( yr <= zl ) {
    1969             continue ;
    1970           }
    1971           else if ( yr <= zr ) {
    1972             newspec[ii] += oldspec[j] * ( yr - zl ) ;
    1973             newflag[ii] = newflag[ii] || oldflag[j] ;
    1974             wsum += ( yr - zl ) ;
    1975           }
    1976           else {
    1977             newspec[ii] += oldspec[j] * dnu ;
    1978             newflag[ii] = newflag[ii] || oldflag[j] ;
    1979             wsum += dnu ;
    1980             ichan = j ;
    1981             break ;
    1982           }
    1983         }
    1984         else if ( yl < zr ) {
    1985           if ( yr <= zr ) {
    1986               newspec[ii] += oldspec[j] * ( yr - yl ) ;
    1987               newflag[ii] = newflag[ii] || oldflag[j] ;
    1988               wsum += ( yr - yl ) ;
    1989           }
    1990           else {
    1991             newspec[ii] += oldspec[j] * ( zr - yl ) ;
    1992             newflag[ii] = newflag[ii] || oldflag[j] ;
    1993             wsum += ( zr - yl ) ;
    1994             ichan = j ;
    1995             break ;
    1996           }
    1997         }
    1998         else {
    1999           ichan = j - 1 ;
    2000           break ;
    2001         }
    2002       }
    2003       if ( wsum != 0.0 )
    2004         newspec[ii] /= wsum ;
    2005       wsum = 0.0 ;
    2006     }
    2007   }
    2008   else if ( dnu < 0.0 ) {
    2009     for ( int ii = 0 ; ii < nChan ; ii++ ) {
    2010       double zl = zi[ii] ;
    2011       double zr = zi[ii+1] ;
    2012       for ( int j = ichan ; j < oldsize ; j++ ) {
    2013         double yl = yi[j] ;
    2014         double yr = yi[j+1] ;
    2015         if ( yl >= zl ) {
    2016           if ( yr >= zl ) {
    2017             continue ;
    2018           }
    2019           else if ( yr >= zr ) {
    2020             newspec[ii] += oldspec[j] * abs( yr - zl ) ;
    2021             newflag[ii] = newflag[ii] || oldflag[j] ;
    2022             wsum += abs( yr - zl ) ;
    2023           }
    2024           else {
    2025             newspec[ii] += oldspec[j] * abs( dnu ) ;
    2026             newflag[ii] = newflag[ii] || oldflag[j] ;
    2027             wsum += abs( dnu ) ;
    2028             ichan = j ;
    2029             break ;
    2030           }
    2031         }
    2032         else if ( yl > zr ) {
    2033           if ( yr >= zr ) {
    2034             newspec[ii] += oldspec[j] * abs( yr - yl ) ;
    2035             newflag[ii] = newflag[ii] || oldflag[j] ;
    2036             wsum += abs( yr - yl ) ;
    2037           }
    2038           else {
    2039             newspec[ii] += oldspec[j] * abs( zr - yl ) ;
    2040             newflag[ii] = newflag[ii] || oldflag[j] ;
    2041             wsum += abs( zr - yl ) ;
    2042             ichan = j ;
    2043             break ;
    2044           }
    2045         }
    2046         else {
    2047           ichan = j - 1 ;
    2048           break ;
    2049         }
    2050       }
    2051       if ( wsum != 0.0 )
    2052         newspec[ii] /= wsum ;
    2053       wsum = 0.0 ;
    2054     }
    2055   }
    2056 //    * ichan = 0
    2057 //    ***/
    2058 //   //ofs << "olddnu = " << olddnu << ", dnu = " << dnu << endl ;
    2059 //   pile += dnu ;
    2060 //   wedge = olddnu * ( refChan + 1 ) ;
    2061 //   while ( wedge < pile ) {
    2062 //     newspec[0] += olddnu * oldspec[refChan] ;
    2063 //     newflag[0] = newflag[0] || oldflag[refChan] ;
    2064 //     //ofs << "channel " << refChan << " is included in new channel 0" << endl ;
    2065 //     refChan++ ;
    2066 //     wedge += olddnu ;
    2067 //     wsum += olddnu ;
    2068 //     //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
     2007  // Access zi and yi in ascending order
     2008  int izs = ((dnu > 0) ? 0 : nChan ) ;
     2009  int ize = ((dnu > 0) ? nChan : 0 ) ;
     2010  int izincr = ((dnu > 0) ? 1 : -1 ) ;
     2011  int ichan =  ((olddnu > 0) ? 0 : oldsize ) ;
     2012  int iye = ((olddnu > 0) ? oldsize : 0 ) ;
     2013  int iyincr = ((olddnu > 0) ? 1 : -1 ) ;
     2014  //for ( int ii = izs ; ii != ize ; ii+=izincr ){
     2015  int ii = izs ;
     2016  while (ii != ize) {
     2017    // always zl < zr
     2018    double zl = zi[ii] ;
     2019    double zr = zi[ii+izincr] ;
     2020    // Need to access smaller index for the new spec, flag, and tsys.
     2021    // Values between zi[k] and zi[k+1] should be stored in newspec[k], etc.
     2022    int i = min(ii, ii+izincr) ;
     2023    //for ( int jj = ichan ; jj != iye ; jj+=iyincr ) {
     2024    int jj = ichan ;
     2025    while (jj != iye) {
     2026      // always yl < yr
     2027      double yl = yi[jj] ;
     2028      double yr = yi[jj+iyincr] ;
     2029      // Need to access smaller index for the original spec, flag, and tsys.
     2030      // Values between yi[k] and yi[k+1] are stored in oldspec[k], etc.
     2031      int j = min(jj, jj+iyincr) ;
     2032      if ( yr <= zl ) {
     2033        jj += iyincr ;
     2034        continue ;
     2035      }
     2036      else if ( yl <= zl ) {
     2037        if ( yr < zr ) {
     2038          if (!oldflag[j]) {
     2039            newspec[i] += oldspec[j] * ( yr - zl ) ;
     2040            if (regridTsys) newtsys[i] += oldtsys[j] * ( yr - zl ) ;
     2041            wsum += ( yr - zl ) ;
     2042          }
     2043          newflag[i] = newflag[i] && oldflag[j] ;
     2044        }
     2045        else {
     2046          if (!oldflag[j]) {
     2047            newspec[i] += oldspec[j] * abs(dnu) ;
     2048            if (regridTsys) newtsys[i] += oldtsys[j] * abs(dnu) ;
     2049            wsum += abs(dnu) ;
     2050          }
     2051          newflag[i] = newflag[i] && oldflag[j] ;
     2052          ichan = jj ;
     2053          break ;
     2054        }
     2055      }
     2056      else if ( yl < zr ) {
     2057        if ( yr <= zr ) {
     2058          if (!oldflag[j]) {
     2059            newspec[i] += oldspec[j] * ( yr - yl ) ;
     2060            if (regridTsys) newtsys[i] += oldtsys[j] * ( yr - yl ) ;
     2061            wsum += ( yr - yl ) ;
     2062          }
     2063          newflag[i] = newflag[i] && oldflag[j] ;
     2064        }
     2065        else {
     2066          if (!oldflag[j]) {
     2067            newspec[i] += oldspec[j] * ( zr - yl ) ;
     2068            if (regridTsys) newtsys[i] += oldtsys[j] * ( zr - yl ) ;
     2069            wsum += ( zr - yl ) ;
     2070          }
     2071          newflag[i] = newflag[i] && oldflag[j] ;
     2072          ichan = jj ;
     2073          break ;
     2074        }
     2075      }
     2076      else {
     2077        ichan = jj - iyincr ;
     2078        break ;
     2079      }
     2080      jj += iyincr ;
     2081    }
     2082    if ( wsum != 0.0 ) {
     2083      newspec[i] /= wsum ;
     2084      if (regridTsys) newtsys[i] /= wsum ;
     2085    }
     2086    wsum = 0.0 ;
     2087    ii += izincr ;
     2088  }
     2089//   if ( dnu > 0.0 ) {
     2090//     for ( int ii = 0 ; ii < nChan ; ii++ ) {
     2091//       double zl = zi[ii] ;
     2092//       double zr = zi[ii+1] ;
     2093//       for ( int j = ichan ; j < oldsize ; j++ ) {
     2094//         double yl = yi[j] ;
     2095//         double yr = yi[j+1] ;
     2096//         if ( yl <= zl ) {
     2097//           if ( yr <= zl ) {
     2098//             continue ;
     2099//           }
     2100//           else if ( yr <= zr ) {
     2101//          if (!oldflag[j]) {
     2102//            newspec[ii] += oldspec[j] * ( yr - zl ) ;
     2103//            if (regridTsys) newtsys[ii] += oldtsys[j] * ( yr - zl ) ;
     2104//            wsum += ( yr - zl ) ;
     2105//          }
     2106//          newflag[ii] = newflag[ii] && oldflag[j] ;
     2107//           }
     2108//           else {
     2109//          if (!oldflag[j]) {
     2110//            newspec[ii] += oldspec[j] * dnu ;
     2111//            if (regridTsys) newtsys[ii] += oldtsys[j] * dnu ;
     2112//            wsum += dnu ;
     2113//          }
     2114//          newflag[ii] = newflag[ii] && oldflag[j] ;
     2115//             ichan = j ;
     2116//             break ;
     2117//           }
     2118//         }
     2119//         else if ( yl < zr ) {
     2120//           if ( yr <= zr ) {
     2121//          if (!oldflag[j]) {
     2122//            newspec[ii] += oldspec[j] * ( yr - yl ) ;
     2123//            if (regridTsys) newtsys[ii] += oldtsys[j] * ( yr - yl ) ;
     2124//               wsum += ( yr - yl ) ;
     2125//          }
     2126//          newflag[ii] = newflag[ii] && oldflag[j] ;
     2127//           }
     2128//           else {
     2129//          if (!oldflag[j]) {
     2130//            newspec[ii] += oldspec[j] * ( zr - yl ) ;
     2131//            if (regridTsys) newtsys[ii] += oldtsys[j] * ( zr - yl ) ;
     2132//            wsum += ( zr - yl ) ;
     2133//          }
     2134//          newflag[ii] = newflag[ii] && oldflag[j] ;
     2135//             ichan = j ;
     2136//             break ;
     2137//           }
     2138//         }
     2139//         else {
     2140//           ichan = j - 1 ;
     2141//           break ;
     2142//         }
     2143//       }
     2144//       if ( wsum != 0.0 ) {
     2145//         newspec[ii] /= wsum ;
     2146//      if (regridTsys) newtsys[ii] /= wsum ;
     2147//       }
     2148//       wsum = 0.0 ;
     2149//     }
    20692150//   }
    2070 //   frac = ( wedge - pile ) / olddnu ;
    2071 //   wsum += ( 1.0 - frac ) * olddnu ;
    2072 //   newspec[0] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
    2073 //   newflag[0] = newflag[0] || oldflag[refChan] ;
    2074 //   //ofs << "channel " << refChan << " is partly included in new channel 0" << " with fraction of " << ( 1.0 - frac ) << endl ;
    2075 //   //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
    2076 //   newspec[0] /= wsum ;
    2077 //   //ofs << "newspec[0] = " << newspec[0] << endl ;
    2078 //   //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
    2079 
    2080 //   /***
    2081 //    * ichan = 1 - nChan-2
    2082 //    ***/
    2083 //   for ( int ichan = 1 ; ichan < nChan - 1 ; ichan++ ) {
    2084 //     pile += dnu ;
    2085 //     newspec[ichan] += frac * olddnu * oldspec[refChan] ;
    2086 //     newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
    2087 //     //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << frac << endl ;
    2088 //     refChan++ ;
    2089 //     wedge += olddnu ;
    2090 //     wsum = frac * olddnu ;
    2091 //     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
    2092 //     while ( wedge < pile ) {
    2093 //       newspec[ichan] += olddnu * oldspec[refChan] ;
    2094 //       newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
    2095 //       //ofs << "channel " << refChan << " is included in new channel " << ichan << endl ;
    2096 //       refChan++ ;
    2097 //       wedge += olddnu ;
    2098 //       wsum += olddnu ;
    2099 //       //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
     2151//   else if ( dnu < 0.0 ) {
     2152//     for ( int ii = 0 ; ii < nChan ; ii++ ) {
     2153//       double zl = zi[ii] ;
     2154//       double zr = zi[ii+1] ;
     2155//       for ( int j = ichan ; j < oldsize ; j++ ) {
     2156//         double yl = yi[j] ;
     2157//         double yr = yi[j+1] ;
     2158//         if ( yl >= zl ) {
     2159//           if ( yr >= zl ) {
     2160//             continue ;
     2161//           }
     2162//           else if ( yr >= zr ) {
     2163//          if (!oldflag[j]) {
     2164//            newspec[ii] += oldspec[j] * abs( yr - zl ) ;
     2165//            if (regridTsys) newtsys[ii] += oldtsys[j] * abs( yr - zl ) ;
     2166//            wsum += abs( yr - zl ) ;
     2167//          }
     2168//          newflag[ii] = newflag[ii] && oldflag[j] ;
     2169//           }
     2170//           else {
     2171//          if (!oldflag[j]) {
     2172//            newspec[ii] += oldspec[j] * abs( dnu ) ;
     2173//            if (regridTsys) newtsys[ii] += oldtsys[j] * abs( dnu ) ;
     2174//            wsum += abs( dnu ) ;
     2175//          }
     2176//          newflag[ii] = newflag[ii] && oldflag[j] ;
     2177//             ichan = j ;
     2178//             break ;
     2179//           }
     2180//         }
     2181//         else if ( yl > zr ) {
     2182//           if ( yr >= zr ) {
     2183//          if (!oldflag[j]) {
     2184//            newspec[ii] += oldspec[j] * abs( yr - yl ) ;
     2185//            if (regridTsys) newtsys[ii] += oldtsys[j] * abs( yr - yl ) ;
     2186//            wsum += abs( yr - yl ) ;
     2187//          }
     2188//          newflag[ii] = newflag[ii] && oldflag[j] ;
     2189//           }
     2190//           else {
     2191//          if (!oldflag[j]) {
     2192//            newspec[ii] += oldspec[j] * abs( zr - yl ) ;
     2193//            if (regridTsys) newtsys[ii] += oldtsys[j] * abs( zr - yl ) ;
     2194//            wsum += abs( zr - yl ) ;
     2195//          }
     2196//          newflag[ii] = newflag[ii] && oldflag[j] ;
     2197//             ichan = j ;
     2198//             break ;
     2199//           }
     2200//         }
     2201//         else {
     2202//           ichan = j - 1 ;
     2203//           break ;
     2204//         }
     2205//       }
     2206//       if ( wsum != 0.0 ) {
     2207//         newspec[ii] /= wsum ;
     2208//      if (regridTsys) newtsys[ii] /= wsum ;
     2209//       }
     2210//       wsum = 0.0 ;
    21002211//     }
    2101 //     frac = ( wedge - pile ) / olddnu ;
    2102 //     wsum += ( 1.0 - frac ) * olddnu ;
    2103 //     newspec[ichan] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
    2104 //     newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
    2105 //     //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << ( 1.0 - frac ) << endl ;
    2106 //     //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
    2107 //     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
    2108 //     newspec[ichan] /= wsum ;
    2109 //     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << endl ;
    21102212//   }
    2111 
    2112 //   /***
    2113 //    * ichan = nChan-1
    2114 //    ***/
    2115 //   // NOTE: Assumed that all spectra have the same bandwidth
    2116 //   pile += dnu ;
    2117 //   newspec[nChan-1] += frac * olddnu * oldspec[refChan] ;
    2118 //   newflag[nChan-1] = newflag[nChan-1] || oldflag[refChan] ;
    2119 //   //ofs << "channel " << refChan << " is partly included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
    2120 //   refChan++ ;
    2121 //   wedge += olddnu ;
    2122 //   wsum = frac * olddnu ;
    2123 //   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
    2124 //   for ( int jchan = refChan ; jchan < oldsize ; jchan++ ) {
    2125 //     newspec[nChan-1] += olddnu * oldspec[jchan] ;
    2126 //     newflag[nChan-1] = newflag[nChan-1] || oldflag[jchan] ;
    2127 //     wsum += olddnu ;
    2128 //     //ofs << "channel " << jchan << " is included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
    2129 //     //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
    2130 //   }
    2131 //   //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
    2132 //   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
    2133 //   newspec[nChan-1] /= wsum ;
    2134 //   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << endl ;
    2135 
    2136 //   // ofs.close() ;
     2213// //   //ofs << "olddnu = " << olddnu << ", dnu = " << dnu << endl ;
     2214// //   pile += dnu ;
     2215// //   wedge = olddnu * ( refChan + 1 ) ;
     2216// //   while ( wedge < pile ) {
     2217// //     newspec[0] += olddnu * oldspec[refChan] ;
     2218// //     newflag[0] = newflag[0] || oldflag[refChan] ;
     2219// //     //ofs << "channel " << refChan << " is included in new channel 0" << endl ;
     2220// //     refChan++ ;
     2221// //     wedge += olddnu ;
     2222// //     wsum += olddnu ;
     2223// //     //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
     2224// //   }
     2225// //   frac = ( wedge - pile ) / olddnu ;
     2226// //   wsum += ( 1.0 - frac ) * olddnu ;
     2227// //   newspec[0] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
     2228// //   newflag[0] = newflag[0] || oldflag[refChan] ;
     2229// //   //ofs << "channel " << refChan << " is partly included in new channel 0" << " with fraction of " << ( 1.0 - frac ) << endl ;
     2230// //   //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ;
     2231// //   newspec[0] /= wsum ;
     2232// //   //ofs << "newspec[0] = " << newspec[0] << endl ;
     2233// //   //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
     2234
     2235// //   /***
     2236// //    * ichan = 1 - nChan-2
     2237// //    ***/
     2238// //   for ( int ichan = 1 ; ichan < nChan - 1 ; ichan++ ) {
     2239// //     pile += dnu ;
     2240// //     newspec[ichan] += frac * olddnu * oldspec[refChan] ;
     2241// //     newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
     2242// //     //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << frac << endl ;
     2243// //     refChan++ ;
     2244// //     wedge += olddnu ;
     2245// //     wsum = frac * olddnu ;
     2246// //     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
     2247// //     while ( wedge < pile ) {
     2248// //       newspec[ichan] += olddnu * oldspec[refChan] ;
     2249// //       newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
     2250// //       //ofs << "channel " << refChan << " is included in new channel " << ichan << endl ;
     2251// //       refChan++ ;
     2252// //       wedge += olddnu ;
     2253// //       wsum += olddnu ;
     2254// //       //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
     2255// //     }
     2256// //     frac = ( wedge - pile ) / olddnu ;
     2257// //     wsum += ( 1.0 - frac ) * olddnu ;
     2258// //     newspec[ichan] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ;
     2259// //     newflag[ichan] = newflag[ichan] || oldflag[refChan] ;
     2260// //     //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << ( 1.0 - frac ) << endl ;
     2261// //     //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
     2262// //     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ;
     2263// //     newspec[ichan] /= wsum ;
     2264// //     //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << endl ;
     2265// //   }
     2266
     2267// //   /***
     2268// //    * ichan = nChan-1
     2269// //    ***/
     2270// //   // NOTE: Assumed that all spectra have the same bandwidth
     2271// //   pile += dnu ;
     2272// //   newspec[nChan-1] += frac * olddnu * oldspec[refChan] ;
     2273// //   newflag[nChan-1] = newflag[nChan-1] || oldflag[refChan] ;
     2274// //   //ofs << "channel " << refChan << " is partly included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
     2275// //   refChan++ ;
     2276// //   wedge += olddnu ;
     2277// //   wsum = frac * olddnu ;
     2278// //   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
     2279// //   for ( int jchan = refChan ; jchan < oldsize ; jchan++ ) {
     2280// //     newspec[nChan-1] += olddnu * oldspec[jchan] ;
     2281// //     newflag[nChan-1] = newflag[nChan-1] || oldflag[jchan] ;
     2282// //     wsum += olddnu ;
     2283// //     //ofs << "channel " << jchan << " is included in new channel " << nChan-1 << " with fraction of " << frac << endl ;
     2284// //     //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
     2285// //   }
     2286// //   //ofs << "wedge = " << wedge << ", pile = " << pile << endl ;
     2287// //   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ;
     2288// //   newspec[nChan-1] /= wsum ;
     2289// //   //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << endl ;
     2290
     2291// //   // ofs.close() ;
    21372292
    21382293  specCol_.put( irow, newspec ) ;
    21392294  flagsCol_.put( irow, newflag ) ;
     2295  if (regridTsys) tsysCol_.put( irow, newtsys );
    21402296
    21412297  return ;
     
    26972853  }
    26982854
    2699   addAuxWaveNumbers(addNWaves, rejectNWaves, nWaves);
     2855  addAuxWaveNumbers(whichrow, addNWaves, rejectNWaves, nWaves);
    27002856}
    27012857
     
    27792935}
    27802936
    2781 void Scantable::addAuxWaveNumbers(const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, std::vector<int>& nWaves)
    2782 {
     2937void Scantable::addAuxWaveNumbers(const int whichrow, const std::vector<int>& addNWaves, const std::vector<int>& rejectNWaves, std::vector<int>& nWaves)
     2938{
     2939  std::vector<int> tempAddNWaves, tempRejectNWaves;
    27832940  for (uInt i = 0; i < addNWaves.size(); ++i) {
     2941    tempAddNWaves.push_back(addNWaves[i]);
     2942  }
     2943  if ((tempAddNWaves.size() == 2) && (tempAddNWaves[1] == -999)) {
     2944    setWaveNumberListUptoNyquistFreq(whichrow, tempAddNWaves);
     2945  }
     2946
     2947  for (uInt i = 0; i < rejectNWaves.size(); ++i) {
     2948    tempRejectNWaves.push_back(rejectNWaves[i]);
     2949  }
     2950  if ((tempRejectNWaves.size() == 2) && (tempRejectNWaves[1] == -999)) {
     2951    setWaveNumberListUptoNyquistFreq(whichrow, tempRejectNWaves);
     2952  }
     2953
     2954  for (uInt i = 0; i < tempAddNWaves.size(); ++i) {
    27842955    bool found = false;
    27852956    for (uInt j = 0; j < nWaves.size(); ++j) {
    2786       if (nWaves[j] == addNWaves[i]) {
     2957      if (nWaves[j] == tempAddNWaves[i]) {
    27872958        found = true;
    27882959        break;
    27892960      }
    27902961    }
    2791     if (!found) nWaves.push_back(addNWaves[i]);
    2792   }
    2793 
    2794   for (uInt i = 0; i < rejectNWaves.size(); ++i) {
     2962    if (!found) nWaves.push_back(tempAddNWaves[i]);
     2963  }
     2964
     2965  for (uInt i = 0; i < tempRejectNWaves.size(); ++i) {
    27952966    for (std::vector<int>::iterator j = nWaves.begin(); j != nWaves.end(); ) {
    2796       if (*j == rejectNWaves[i]) {
     2967      if (*j == tempRejectNWaves[i]) {
    27972968        j = nWaves.erase(j);
    27982969      } else {
     
    28052976    sort(nWaves.begin(), nWaves.end());
    28062977    unique(nWaves.begin(), nWaves.end());
     2978  }
     2979}
     2980
     2981void Scantable::setWaveNumberListUptoNyquistFreq(const int whichrow, std::vector<int>& nWaves)
     2982{
     2983  if ((nWaves.size() == 2)&&(nWaves[1] == -999)) {
     2984    int val = nWaves[0];
     2985    int nyquistFreq = nchan(getIF(whichrow))/2+1;
     2986    nWaves.clear();
     2987    if (val > nyquistFreq) {  // for safety, at least nWaves contains a constant; CAS-3759
     2988      nWaves.push_back(0);
     2989    }
     2990    while (val <= nyquistFreq) {
     2991      nWaves.push_back(val);
     2992      val++;
     2993    }
    28072994  }
    28082995}
     
    28443031
    28453032      //FOR DEBUGGING------------
     3033      /*
    28463034      if (whichrow < 0) {// == nRow -1) {
    28473035        cout << "+++ i=" << setw(3) << whichrow << ", IF=" << setw(2) << getIF(whichrow);
     
    28553043        cout << flush;
    28563044      }
     3045      */
    28573046      //-------------------------
    28583047
     
    31893378  std::vector<bool> mask = getMask(whichrow);
    31903379  uInt maskSize = mask.size();
    3191   if (maskSize != inMask.size()) {
    3192     throw(AipsError("mask sizes are not the same."));
    3193   }
    3194   for (uInt i = 0; i < maskSize; ++i) {
    3195     mask[i] = mask[i] && inMask[i];
     3380  if (inMask.size() != 0) {
     3381    if (maskSize != inMask.size()) {
     3382      throw(AipsError("mask sizes are not the same."));
     3383    }
     3384    for (uInt i = 0; i < maskSize; ++i) {
     3385      mask[i] = mask[i] && inMask[i];
     3386    }
    31963387  }
    31973388
     
    35153706std::string Scantable::getMaskRangeList(const std::vector<bool>& mask, int whichrow, const casa::String& coordInfo, bool hasSameNchan, bool verbose)
    35163707{
    3517   if (mask.size() < 2) {
    3518     throw(AipsError("The mask elements should be > 1"));
     3708  if (mask.size() <= 0) {
     3709    throw(AipsError("The mask elements should be > 0"));
    35193710  }
    35203711  int IF = getIF(whichrow);
     
    35493740std::vector<int> Scantable::getMaskEdgeIndices(const std::vector<bool>& mask)
    35503741{
    3551   if (mask.size() < 2) {
    3552     throw(AipsError("The mask elements should be > 1"));
     3742  if (mask.size() <= 0) {
     3743    throw(AipsError("The mask elements should be > 0"));
    35533744  }
    35543745
  • /trunk/src/Scantable.h

    r2373 r2473  
    501501  void regridChannel( int nchan, double dnu ) ;
    502502  void regridChannel( int nchan, double dnu, int irow ) ;
     503
     504  void regridSpecChannel( double dnu, int nchan=-1 ) ;
    503505
    504506  bool getFlagtraFast(casa::uInt whichrow);
     
    739741                           const std::string& fftThAttr,
    740742                           std::vector<int>& nWaves);
    741   void addAuxWaveNumbers(const std::vector<int>& addNWaves,
     743  void addAuxWaveNumbers(const int whichrow,
     744                         const std::vector<int>& addNWaves,
    742745                         const std::vector<int>& rejectNWaves,
    743746                         std::vector<int>& nWaves);
     747  void setWaveNumberListUptoNyquistFreq(const int whichrow,
     748                                        std::vector<int>& nWaves);
    744749  bool hasSameNchanOverIFs();
    745750  std::string getMaskRangeList(const std::vector<bool>& mask,
  • /trunk/src/ScantableWrapper.h

    r2373 r2473  
    268268  { table_->reshapeSpectrum( nmin, nmax ); }
    269269
     270  void regridSpecChannel( double dnu, int nchan )
     271  { table_->regridSpecChannel( dnu, nchan ); }
     272
    270273  void polyBaseline(const std::vector<bool>& mask, int order, bool getresidual=true, const std::string& showprogress="true,1000", const bool outlog=false, const std::string& blfile="")
    271274  { table_->polyBaseline(mask, order, getresidual, showprogress, outlog, blfile); }
  • /trunk/src/Templates.cpp

    r2373 r2473  
    3636#include <casa/Utilities/CountedPtr.h>
    3737
    38 template class casa::CountedConstPtr<asap::Scantable>;
     38//template class casa::CountedConstPtr<asap::Scantable>;
    3939template class casa::CountedPtr<asap::Scantable>;
    4040template class casa::CountedPtr<asap::STPol>;
    41 template class casa::PtrRep<asap::Scantable>;
    42 template class casa::SimpleCountedConstPtr<asap::Scantable>;
    43 template class casa::SimpleCountedConstPtr<asap::STPol>;
    44 template class casa::SimpleCountedPtr<asap::Scantable>;
    45 template class casa::SimpleCountedPtr<asap::STPol>;
    4641
    4742#include <casa/Arrays/ArrayLogical.h>
  • /trunk/src/python_STGrid.cpp

    r2373 r2473  
    2121    .def( init <> () )
    2222    .def( init < const std::string > () )
     23    .def( init < const std::vector<std::string> > () )
    2324    .def("_setif", &STGrid::setIF)
    2425    .def("_setpollist", &STGrid::setPolList)
     
    2829    .def("_grid", &STGrid::grid)
    2930    .def("_setin", &STGrid::setFileIn)
     31    .def("_setfiles", &STGrid::setFileList)
    3032    .def("_setweight", &STGrid::setWeight)
     33    .def("_enableclip", &STGrid::enableClip)
     34    .def("_disableclip", &STGrid::disableClip)
    3135    .def("_save", &STGrid::saveData)
    3236    ;
  • /trunk/src/python_Scantable.cpp

    r2373 r2473  
    145145         (boost::python::arg("nmin")=-1,
    146146          boost::python::arg("nmax")=-1) )
     147    .def("_regrid_specchan", &ScantableWrapper::regridSpecChannel,
     148         (boost::python::arg("nchan")=-1) )
    147149    .def("_poly_baseline", &ScantableWrapper::polyBaseline)
    148150    .def("_auto_poly_baseline", &ScantableWrapper::autoPolyBaseline)
Note: See TracChangeset for help on using the changeset viewer.