source: trunk/src/MSFiller.cpp @ 2219

Last change on this file since 2219 was 2219, checked in by Takeshi Nakazato, 13 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: Yes/No?

Module(s): Module Names change impacts.

Description: Describe your changes here...

FreqRefFrame? is retrieved from the data.

File size: 62.0 KB
RevLine 
[1974]1//
2// C++ Interface: MSFiller
3//
4// Description:
5//
6// This class is specific filler for MS format
7//
8// Takeshi Nakazato <takeshi.nakazato@nao.ac.jp>, (C) 2010
9//
10// Copyright: See COPYING file that comes with this distribution
11//
12//
13
14#include <iostream>
15#include <map>
16
17#include <tables/Tables/ExprNode.h>
18#include <tables/Tables/TableIter.h>
[1987]19#include <tables/Tables/TableColumn.h>
[1974]20#include <tables/Tables/ScalarColumn.h>
21#include <tables/Tables/ArrayColumn.h>
[1987]22#include <tables/Tables/TableParse.h>
[2002]23#include <tables/Tables/TableRow.h>
[1974]24
[2002]25#include <casa/Containers/RecordField.h>
[1974]26#include <casa/Logging/LogIO.h>
27#include <casa/Arrays/Slicer.h>
28#include <casa/Quanta/MVTime.h>
[1987]29#include <casa/OS/Path.h>
[1974]30
31#include <measures/Measures/Stokes.h>
32#include <measures/Measures/MEpoch.h>
[1987]33#include <measures/Measures/MCEpoch.h>
34#include <measures/Measures/MFrequency.h>
35#include <measures/Measures/MCFrequency.h>
36#include <measures/Measures/MPosition.h>
37#include <measures/Measures/MCPosition.h>
38#include <measures/Measures/MDirection.h>
39#include <measures/Measures/MCDirection.h>
40#include <measures/Measures/MeasConvert.h>
[1974]41#include <measures/TableMeasures/ScalarMeasColumn.h>
[1987]42#include <measures/TableMeasures/ArrayMeasColumn.h>
43#include <measures/TableMeasures/ScalarQuantColumn.h>
44#include <measures/TableMeasures/ArrayQuantColumn.h>
[1974]45
[2021]46#include <ms/MeasurementSets/MSAntennaIndex.h>
47
[1974]48#include <atnf/PKSIO/SrcType.h>
49
50#include "MSFiller.h"
51#include "STHeader.h"
52
[1988]53#include <ctime>
54#include <sys/time.h>
55
[2017]56using namespace casa ;
57using namespace std ;
58
59namespace asap {
60double MSFiller::gettimeofday_sec()
[1988]61{
62  struct timeval tv ;
63  gettimeofday( &tv, NULL ) ;
64  return tv.tv_sec + (double)tv.tv_usec*1.0e-6 ;
65}
66
[1974]67MSFiller::MSFiller( casa::CountedPtr<Scantable> stable )
68  : table_( stable ),
[1987]69    tablename_( "" ),
[1974]70    antenna_( -1 ),
[2021]71    antennaStr_(""),
[2206]72    getPt_( True ),
[1974]73    isFloatData_( False ),
74    isData_( False ),
75    isDoppler_( False ),
76    isFlagCmd_( False ),
77    isFreqOffset_( False ),
78    isHistory_( False ),
79    isProcessor_( False ),
80    isSysCal_( False ),
[1993]81    isWeather_( False ),
82    colTsys_( "TSYS_SPECTRUM" ),
83    colTcal_( "TCAL_SPECTRUM" )
[1974]84{
85  os_ = LogIO() ;
86  os_.origin( LogOrigin( "MSFiller", "MSFiller()", WHERE ) ) ;
87}
88
89MSFiller::~MSFiller()
90{
91  os_.origin( LogOrigin( "MSFiller", "~MSFiller()", WHERE ) ) ;
92}
93
94bool MSFiller::open( const std::string &filename, const casa::Record &rec )
95{
96  os_.origin( LogOrigin( "MSFiller", "open()", WHERE ) ) ;
[2004]97//   double startSec = gettimeofday_sec() ;
98//   os_ << "start MSFiller::open() startsec=" << startSec << LogIO::POST ;
[1974]99  //os_ << "   filename = " << filename << endl ;
100
101  // parsing MS options
102  if ( rec.isDefined( "ms" ) ) {
103    Record msrec = rec.asRecord( "ms" ) ;
104    if ( msrec.isDefined( "getpt" ) ) {
105      getPt_ = msrec.asBool( "getpt" ) ;
106    }
107    if ( msrec.isDefined( "antenna" ) ) {
108      if ( msrec.type( msrec.fieldNumber( "antenna" ) ) == TpInt ) {
109        antenna_ = msrec.asInt( "antenna" ) ;
110      }
111      else {
[2021]112        //antenna_ = atoi( msrec.asString( "antenna" ).c_str() ) ;
113        antennaStr_ = msrec.asString( "antenna" ) ;
[1974]114      }
115    }
116    else {
117      antenna_ = 0 ;
118    }
119  }
120
[1987]121  MeasurementSet *tmpMS = new MeasurementSet( filename, Table::Old ) ;
122  //mstable_ = (*tmpMS)( tmpMS->col("ANTENNA1") == antenna_
123  //                     && tmpMS->col("ANTENNA1") == tmpMS->col("ANTENNA2") ) ;
124  tablename_ = tmpMS->tableName() ;
[2021]125  if ( antenna_ == -1 && antennaStr_.size() > 0 ) {
126    MSAntennaIndex msAntIdx( tmpMS->antenna() ) ;
127    Vector<Int> id = msAntIdx.matchAntennaName( antennaStr_ ) ;
128    if ( id.size() > 0 )
129      antenna_ = id[0] ;
130  }
[2025]131
132  os_ << "Parsing MS options" << endl ;
133  os_ << "   getPt = " << getPt_ << endl ;
134  os_ << "   antenna = " << antenna_ << endl ;
135  os_ << "   antennaStr = " << antennaStr_ << LogIO::POST ;
136
[1987]137  mstable_ = MeasurementSet( (*tmpMS)( tmpMS->col("ANTENNA1") == antenna_
138                                       && tmpMS->col("ANTENNA1") == tmpMS->col("ANTENNA2") ) ) ;
139//   stringstream ss ;
140//   ss << "SELECT FROM $1 WHERE ANTENNA1 == ANTENNA2 && ANTENNA1 == " << antenna_ ;
141//   String taql( ss.str() ) ;
142//   mstable_ = MeasurementSet( tableCommand( taql, *tmpMS ) ) ;
143  delete tmpMS ;
[1974]144
145  // check which data column exists
[1987]146  isFloatData_ = mstable_.tableDesc().isColumn( "FLOAT_DATA" ) ;
147  isData_ = mstable_.tableDesc().isColumn( "DATA" ) ;
[1974]148
[2004]149//   double endSec = gettimeofday_sec() ;
150//   os_ << "end MSFiller::open() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
[1974]151  return true ;
152}
153
154void MSFiller::fill()
155{
156  os_.origin( LogOrigin( "MSFiller", "fill()", WHERE ) ) ;
[2004]157//   double startSec = gettimeofday_sec() ;
158//   os_ << "start MSFiller::fill() startSec=" << startSec << LogIO::POST ;
[1974]159
[2004]160//   double time0 = gettimeofday_sec() ;
161//   os_ << "start init fill: " << time0 << LogIO::POST ;
[1990]162
[1974]163  // Initialize header
164  STHeader sdh ; 
165  sdh.nchan = 0 ;
166  sdh.npol = 0 ;
167  sdh.nif = 0 ;
168  sdh.nbeam = 0 ;
169  sdh.observer = "" ;
170  sdh.project = "" ;
171  sdh.obstype = "" ;
172  sdh.antennaname = "" ;
173  sdh.antennaposition.resize( 0 ) ;
174  sdh.equinox = 0.0 ;
175  sdh.freqref = "" ;
176  sdh.reffreq = -1.0 ;
177  sdh.bandwidth = 0.0 ;
178  sdh.utc = 0.0 ;
179  sdh.fluxunit = "" ;
180  sdh.epoch = "" ;
181  sdh.poltype = "" ;
182 
183  // check if optional table exists
[1987]184  //const TableRecord msrec = tablesel_.keywordSet() ;
185  const TableRecord msrec = mstable_.keywordSet() ;
[1974]186  isDoppler_ = msrec.isDefined( "DOPPLER" ) ;
[2004]187  if ( isDoppler_ )
188    if ( mstable_.doppler().nrow() == 0 )
189      isDoppler_ = False ;
[1974]190  isFlagCmd_ = msrec.isDefined( "FLAG_CMD" ) ;
[2004]191  if ( isFlagCmd_ )
192    if ( mstable_.flagCmd().nrow() == 0 )
193      isFlagCmd_ = False ;
[1974]194  isFreqOffset_ = msrec.isDefined( "FREQ_OFFSET" ) ;
[2004]195  if ( isFreqOffset_ )
196    if ( mstable_.freqOffset().nrow() == 0 )
197      isFreqOffset_ = False ;
[1974]198  isHistory_ = msrec.isDefined( "HISTORY" ) ;
[2004]199  if ( isHistory_ )
200    if ( mstable_.history().nrow() == 0 )
201      isHistory_ = False ;
[1974]202  isProcessor_ = msrec.isDefined( "PROCESSOR" ) ;
[2004]203  if ( isProcessor_ )
204    if ( mstable_.processor().nrow() == 0 )
205      isProcessor_ = False ;
[1974]206  isSysCal_ = msrec.isDefined( "SYSCAL" ) ;
[2004]207  if ( isSysCal_ )
208    if ( mstable_.sysCal().nrow() == 0 )
209      isSysCal_ = False ;
[1974]210  isWeather_ = msrec.isDefined( "WEATHER" ) ;
[2004]211  if ( isWeather_ )
212    if ( mstable_.weather().nrow() == 0 )
213      isWeather_ = False ;
214
[1974]215  // Access to MS subtables
[1987]216  MSField fieldtab = mstable_.field() ;
217  MSPolarization poltab = mstable_.polarization() ;
218  MSDataDescription ddtab = mstable_.dataDescription() ;
219  MSObservation obstab = mstable_.observation() ;
220  MSSource srctab = mstable_.source() ;
221  MSSpectralWindow spwtab = mstable_.spectralWindow() ;
222  MSSysCal caltab = mstable_.sysCal() ;
[1974]223  if ( caltab.nrow() == 0 )
224    isSysCal_ = False ;
[1993]225  else {
[2159]226    if ( !caltab.tableDesc().isColumn( colTcal_ ) ) {
[1993]227      colTcal_ = "TCAL" ;
[2159]228      if ( !caltab.tableDesc().isColumn( colTcal_ ) )
229        colTcal_ = "NONE" ;
230    }
231    if ( !caltab.tableDesc().isColumn( colTsys_ ) ) {
[1993]232      colTsys_ = "TSYS" ;
[2159]233      if ( !caltab.tableDesc().isColumn( colTcal_ ) )
234        colTsys_ = "NONE" ;
235    }
[1993]236  }
[2004]237//   colTcal_ = "TCAL" ;
238//   colTsys_ = "TSYS" ;
[1987]239  MSPointing pointtab = mstable_.pointing() ;
240  if ( mstable_.weather().nrow() == 0 )
[1974]241    isWeather_ = False ;
[1987]242  MSState stattab = mstable_.state() ;
243  MSAntenna anttab = mstable_.antenna() ;
[1974]244
[1987]245  // TEST
246  // memory allocation by boost::object_pool
247  boost::object_pool<ROTableColumn> *tpoolr = new boost::object_pool<ROTableColumn> ;
248  //
[1974]249
[1987]250  // SUBTABLES: FREQUENCIES
[2217]251  string freqFrame = getFrame() ;
252  table_->frequencies().setFrame( freqFrame ) ;
253  table_->frequencies().setFrame( freqFrame, True ) ;
[1974]254
255  // SUBTABLES: WEATHER
[2004]256  fillWeather() ;
[1974]257
258  // SUBTABLES: FOCUS
259  fillFocus() ;
260
261  // SUBTABLES: TCAL
[2004]262  fillTcal( tpoolr ) ;
[1974]263
264  // SUBTABLES: FIT
265  //fillFit() ;
266
267  // SUBTABLES: HISTORY
268  //fillHistory() ;
269
[1987]270  // shared pointers
271  ROTableColumn *tcolr ;
272
[1974]273  // MAIN
274  // Iterate over several ids
275  map<Int, uInt> ifmap ; // (IFNO, FREQ_ID) pair
[1987]276  ROArrayQuantColumn<Double> *sharedQDArrCol = new ROArrayQuantColumn<Double>( anttab, "POSITION" ) ;
277  Vector< Quantum<Double> > antpos = (*sharedQDArrCol)( antenna_ ) ;
278  delete sharedQDArrCol ;
[1974]279  MPosition mp( MVPosition( antpos ), MPosition::ITRF ) ;
[1990]280  if ( getPt_ ) {
281    //pointtab = pointtab( pointtab.col("ANTENNA_ID")==antenna_ ).sort("TIME") ;
282    pointtab = MSPointing( pointtab( pointtab.col("ANTENNA_ID")==antenna_ ).sort("TIME") ) ;
283  }
[1987]284  tcolr = tpoolr->construct( anttab, "STATION" ) ;
285  String stationName = tcolr->asString( antenna_ ) ;
286  tpoolr->destroy( tcolr ) ;
287  tcolr = tpoolr->construct( anttab, "NAME" ) ;
288  String antennaName = tcolr->asString( antenna_ ) ;
289  tpoolr->destroy( tcolr ) ;
290  sdh.antennaposition.resize( 3 ) ;
291  for ( int i = 0 ; i < 3 ; i++ )
292    sdh.antennaposition[i] = antpos[i].getValue( "m" ) ;
293  String telescopeName = "" ;
294
[2021]295//   double time1 = gettimeofday_sec() ;
296//   os_ << "end fill init: " << time1 << " (" << time1-time0 << "sec)" << LogIO::POST ;
[1990]297
[2002]298  // row based
299  Table &stab = table_->table() ;
300  TableRow row( stab ) ;
301  TableRecord &trec = row.record() ;
302  RecordFieldPtr< Array<Float> > spRF( trec, "SPECTRA" ) ;
303  RecordFieldPtr< Array<uChar> > ucarrRF( trec, "FLAGTRA" ) ;
304  RecordFieldPtr<Double> timeRF( trec, "TIME" ) ;
305  RecordFieldPtr< Array<Float> > tsysRF( trec, "TSYS" ) ;
306  RecordFieldPtr<Double> intervalRF( trec, "INTERVAL" ) ;
307  RecordFieldPtr< Array<Double> > dirRF( trec, "DIRECTION" ) ;
308  RecordFieldPtr<Float> azRF( trec, "AZIMUTH" ) ;
309  RecordFieldPtr<Float> elRF( trec, "ELEVATION" ) ;
310  RecordFieldPtr< Array<Double> > scrRF( trec, "SCANRATE" ) ;
311  RecordFieldPtr<uInt> cycleRF( trec, "CYCLENO" ) ;
312  RecordFieldPtr<uInt> flrRF( trec, "FLAGROW" ) ;
313  RecordFieldPtr<uInt> tcalidRF( trec, "TCAL_ID" ) ;
314  RecordFieldPtr<uInt> widRF( trec, "WEATHER_ID" ) ;
315  RecordFieldPtr<uInt> polnoRF( trec, "POLNO" ) ;
316
317
318  // REFBEAMNO
319  RecordFieldPtr<Int> intRF( trec, "REFBEAMNO" ) ;
320  *intRF = 0 ;
321
322  // FIT_ID
323  intRF.attachToRecord( trec, "FIT_ID" ) ;
324  *intRF = -1 ;
325
326  // OPACITY
327  RecordFieldPtr<Float> floatRF( trec, "OPACITY" ) ;
328  *floatRF = 0.0 ;
329
[1978]330  //
331  // ITERATION: OBSERVATION_ID
332  //
[1987]333  TableIterator iter0( mstable_, "OBSERVATION_ID" ) ;
[1974]334  while( !iter0.pastEnd() ) {
[2021]335//     time0 = gettimeofday_sec() ;
336//     os_ << "start 0th iteration: " << time0 << LogIO::POST ;
[1987]337    Table t0 = iter0.table() ;
338    tcolr = tpoolr->construct( t0, "OBSERVATION_ID" ) ;
339    Int obsId = tcolr->asInt( 0 ) ;
340    tpoolr->destroy( tcolr ) ;
341    if ( sdh.observer == "" ) {
342      tcolr = tpoolr->construct( obstab, "OBSERVER" ) ;
343      sdh.observer = tcolr->asString( obsId ) ;
344      tpoolr->destroy( tcolr ) ;
345    }
346    if ( sdh.project == "" ) {
347      tcolr = tpoolr->construct( obstab, "PROJECT" ) ;
348      sdh.observer = tcolr->asString( obsId ) ;
349      tpoolr->destroy( tcolr ) ;
350    }
351    ROArrayMeasColumn<MEpoch> *tmpMeasCol = new ROArrayMeasColumn<MEpoch>( obstab, "TIME_RANGE" ) ;
352    MEpoch me = (*tmpMeasCol)( obsId )( IPosition(1,0) ) ;
353    delete tmpMeasCol ;
[1974]354    if ( sdh.utc == 0.0 ) {
[2035]355      sdh.utc = me.get( "d" ).getValue() ;
[1974]356    }
[1987]357    if ( telescopeName == "" ) {
358      tcolr = tpoolr->construct( obstab, "TELESCOPE_NAME" ) ;
[2025]359      telescopeName = tcolr->asString( obsId ) ;
[1987]360      tpoolr->destroy( tcolr ) ;
361    }
[1978]362    Int nbeam = 0 ;
[2021]363//     time1 = gettimeofday_sec() ;
364//     os_ << "end 0th iteration init: " << time1 << " (" << time1-time0 << "sec)" << LogIO::POST ;
[1974]365    //
366    // ITERATION: FEED1
367    //
368    TableIterator iter1( t0, "FEED1" ) ;
369    while( !iter1.pastEnd() ) {
[2021]370//       time0 = gettimeofday_sec() ;
371//       os_ << "start 1st iteration: " << time0 << LogIO::POST ;
[1987]372      Table t1 = iter1.table() ;
373      // assume FEED1 == FEED2
374      tcolr = tpoolr->construct( t1, "FEED1" ) ;
375      Int feedId = tcolr->asInt( 0 ) ;
376      tpoolr->destroy( tcolr ) ;
[1974]377      nbeam++ ;
[2002]378
379      // BEAMNO
380      RecordFieldPtr<uInt> uintRF( trec, "BEAMNO" ) ;
381      *uintRF = feedId ;
382
383      // FOCUS_ID
384      uintRF.attachToRecord( trec, "FOCUS_ID" ) ;
385      *uintRF = 0 ;
386
[2021]387//       time1 = gettimeofday_sec() ;
388//       os_ << "end 1st iteration init: " << time1 << " (" << time1-time0 << "sec)" << LogIO::POST ;
[1974]389      //
390      // ITERATION: FIELD_ID
391      //
392      TableIterator iter2( t1, "FIELD_ID" ) ;
393      while( !iter2.pastEnd() ) {
[2021]394//         time0 = gettimeofday_sec() ;
395//         os_ << "start 2nd iteration: " << time0 << LogIO::POST ;
[1987]396        Table t2 = iter2.table() ;
397        tcolr = tpoolr->construct( t2, "FIELD_ID" ) ;
398        Int fieldId = tcolr->asInt( 0 ) ;
399        tpoolr->destroy( tcolr ) ;
400        tcolr = tpoolr->construct( fieldtab, "SOURCE_ID" ) ;
401        Int srcId = tcolr->asInt( fieldId ) ;
402        tpoolr->destroy( tcolr ) ;
403        tcolr = tpoolr->construct( fieldtab, "NAME" ) ;
404        String fieldName = tcolr->asString( fieldId ) + "__" + String::toString(fieldId) ;
405        tpoolr->destroy( tcolr ) ;
[2004]406        ROArrayMeasColumn<MDirection> *delayDirCol = new ROArrayMeasColumn<MDirection>( fieldtab, "DELAY_DIR" ) ;
407        Vector<MDirection> delayDir = (*delayDirCol)( fieldId ) ;
408        delete delayDirCol ;
409        Vector<Double> defaultScanrate( 2, 0.0 ) ;
410        Vector<Double> defaultDir = delayDir[0].getAngle( "rad" ).getValue() ;
411        if ( delayDir.nelements() > 1 )
412          defaultScanrate = delayDir[1].getAngle( "rad" ).getValue() ;
413         
[2002]414
415        // FIELDNAME
416        RecordFieldPtr<String> strRF( trec, "FIELDNAME" ) ;
417        *strRF = fieldName ;
418
419
[2021]420//         time1 = gettimeofday_sec() ;
421//         os_ << "end 2nd iteration init: " << time1 << " (" << time1-time0 << "sec)" << LogIO::POST ;
[1974]422        //
423        // ITERATION: DATA_DESC_ID
424        //
425        TableIterator iter3( t2, "DATA_DESC_ID" ) ;
426        while( !iter3.pastEnd() ) {
[2021]427//           time0 = gettimeofday_sec() ;
428//           os_ << "start 3rd iteration: " << time0 << LogIO::POST ;
[1987]429          Table t3 = iter3.table() ;
430          tcolr = tpoolr->construct( t3, "DATA_DESC_ID" ) ;
431          Int ddId = tcolr->asInt( 0 ) ;
432          tpoolr->destroy( tcolr ) ;
433          tcolr = tpoolr->construct( ddtab, "POLARIZATION_ID" ) ;
434          Int polId = tcolr->asInt( ddId ) ;
435          tpoolr->destroy( tcolr ) ;
436          tcolr = tpoolr->construct( ddtab, "SPECTRAL_WINDOW_ID" ) ;
437          Int spwId = tcolr->asInt( ddId ) ;
438          tpoolr->destroy( tcolr ) ;
[2002]439
440          // IFNO
441          uintRF.attachToRecord( trec, "IFNO" ) ;
442          *uintRF = (uInt)spwId ;
443
[1974]444          // polarization information
[1987]445          tcolr = tpoolr->construct( poltab, "NUM_CORR" ) ;
446          Int npol = tcolr->asInt( polId ) ;
447          tpoolr->destroy( tcolr ) ;
448          ROArrayColumn<Int> *roArrICol = new ROArrayColumn<Int>( poltab, "CORR_TYPE" ) ;
449          Vector<Int> corrtype = (*roArrICol)( polId ) ;
450          delete roArrICol ;
[2021]451//           os_ << "npol = " << npol << LogIO::POST ;
452//           os_ << "corrtype = " << corrtype << LogIO::POST ;
[1974]453          // source information
[2033]454//           os_ << "srcId = " << srcId << ", spwId = " << spwId << LogIO::POST ;
[2004]455          MSSource srctabSel = srctab( srctab.col("SOURCE_ID") == srcId && srctab.col("SPECTRAL_WINDOW_ID") == spwId ) ;
456          if ( srctabSel.nrow() == 0 ) {
457            srctabSel = srctab( srctab.col("SOURCE_ID") == srcId && srctab.col("SPECTRAL_WINDOW_ID") == -1 ) ;
458          }
[2033]459          String srcName( "" ) ;
460          Vector<Double> srcPM( 2, 0.0 ) ;
461          Vector<Double> srcDir( 2, 0.0 ) ;
462          MDirection md ;
463          Int numLines = 0 ;
464          ROArrayColumn<Double> *roArrDCol = 0 ;
465          if ( srctabSel.nrow() > 0 ) {
466            // source name
467            tcolr = tpoolr->construct( srctabSel, "NAME" ) ;
468            srcName = tcolr->asString( 0 ) ;
469            tpoolr->destroy( tcolr ) ;
[2002]470
[2033]471            // source proper motion
472            roArrDCol = new ROArrayColumn<Double>( srctabSel, "PROPER_MOTION" ) ;
473            srcPM = (*roArrDCol)( 0 ) ;
474            delete roArrDCol ;
475           
476            // source direction
477            roArrDCol = new ROArrayColumn<Double>( srctabSel, "DIRECTION" ) ;
478            srcDir = (*roArrDCol)( 0 ) ;
479            delete roArrDCol ;
480
481            // source direction as MDirection object
482            ROScalarMeasColumn<MDirection> *tmpMeasCol = new ROScalarMeasColumn<MDirection>( srctabSel, "DIRECTION" ) ;
483            md = (*tmpMeasCol)( 0 ) ;
484            delete tmpMeasCol ;
485
486            // number of lines
487            tcolr = tpoolr->construct( srctabSel, "NUM_LINES" ) ;
[2059]488            numLines = tcolr->asInt( 0 ) ;
[2033]489            tpoolr->destroy( tcolr ) ;
490
491          }
492          else {
493            md = MDirection( Quantum<Double>(0.0,Unit("rad")), Quantum<Double>(0.0,Unit("rad")) ) ;
494          }
495
[2002]496          // SRCNAME
497          strRF.attachToRecord( trec, "SRCNAME" ) ;
498          *strRF = srcName ;
499
[2033]500//           os_ << "srcName = " << srcName << LogIO::POST ;
[2002]501
502          // SRCPROPERMOTION
503          RecordFieldPtr< Array<Double> > darrRF( trec, "SRCPROPERMOTION" ) ;
504          *darrRF = srcPM ;
505
[1974]506          //os_ << "srcPM = " << srcPM << LogIO::POST ;
[2002]507
508          // SRCDIRECTION
509          darrRF.attachToRecord( trec, "SRCDIRECTION" ) ;
510          *darrRF = srcDir ;
511
[1974]512          //os_ << "srcDir = " << srcDir << LogIO::POST ;
[2021]513
[1974]514          // for MOLECULES subtable
[2021]515//           os_ << "numLines = " << numLines << LogIO::POST ;
516
[1974]517          Vector<Double> restFreqs( numLines, 0.0 ) ;
518          Vector<String> transitionName( numLines, "" ) ;
[2021]519          Vector<Double> sysVels ;
520          Double sysVel = 0.0 ;
[1974]521          if ( numLines != 0 ) {
[1987]522            if ( srctabSel.tableDesc().isColumn( "REST_FREQUENCY" ) ) {
523              sharedQDArrCol = new ROArrayQuantColumn<Double>( srctabSel, "REST_FREQUENCY" ) ;
524              Array< Quantum<Double> > qRestFreqs = (*sharedQDArrCol)( 0 ) ;
525              delete sharedQDArrCol ;
526              for ( int i = 0 ; i < numLines ; i++ ) {
527                restFreqs[i] = qRestFreqs( IPosition( 1, i ) ).getValue( "Hz" ) ;
528              }
[1974]529            }
[2033]530//             os_ << "restFreqs = " << restFreqs << LogIO::POST ;
[1974]531            if ( srctabSel.tableDesc().isColumn( "TRANSITION" ) ) {
[2004]532              ROArrayColumn<String> transitionCol( srctabSel, "TRANSITION" ) ;
533              if ( transitionCol.isDefined( 0 ) )
534                transitionName = transitionCol( 0 ) ;
535              //os_ << "transitionNameCol.nrow() = " << transitionCol.nrow() << LogIO::POST ;
[1974]536            }
[2021]537            if ( srctabSel.tableDesc().isColumn( "SYSVEL" ) ) {
538              roArrDCol = new ROArrayColumn<Double>( srctabSel, "SYSVEL" ) ;
539              sysVels = (*roArrDCol)( 0 ) ;
540              delete roArrDCol ;
541            }
542            if ( !sysVels.empty() ) {
543              //os_ << "sysVels.shape() = " << sysVels.shape() << LogIO::POST ;
544              // NB: assume all SYSVEL values are the same
545              sysVel = sysVels( IPosition(1,0) ) ;
546            }
[1974]547          }
[2021]548
549          // SRCVELOCITY
550          RecordFieldPtr<Double> doubleRF( trec, "SRCVELOCITY" ) ;
551          *doubleRF = sysVel ;
552
553//           os_ << "sysVel = " << sysVel << LogIO::POST ;
554
[1974]555          uInt molId = table_->molecules().addEntry( restFreqs, transitionName, transitionName ) ;
[2002]556
557          // MOLECULE_ID
558          uintRF.attachToRecord( trec, "MOLECULE_ID" ) ;
559          *uintRF = molId ;
560
[1974]561          // spectral setup
562          MeasFrame mf( me, mp, md ) ;
[1987]563          tcolr = tpoolr->construct( spwtab, "MEAS_FREQ_REF" ) ;
564          MFrequency::Types freqRef = MFrequency::castType((uInt)(tcolr->asInt(spwId))) ;
565          tpoolr->destroy( tcolr ) ;
566          tcolr = tpoolr->construct( spwtab, "NUM_CHAN" ) ;
567          Int nchan = tcolr->asInt( spwId ) ;
[2102]568          Bool iswvr = False ;
569          if ( nchan == 4 ) iswvr = True ;
[1987]570          tpoolr->destroy( tcolr ) ;
[1974]571          Bool even = False ;
572          if ( (nchan/2)*2 == nchan ) even = True ;
[1993]573          sdh.nchan = max( sdh.nchan, nchan ) ;
[1987]574          ROScalarQuantColumn<Double> *tmpQuantCol = new ROScalarQuantColumn<Double>( spwtab, "TOTAL_BANDWIDTH" ) ;
575          Double totbw = (*tmpQuantCol)( spwId ).getValue( "Hz" ) ;
576          delete tmpQuantCol ;
[1993]577          sdh.bandwidth = max( sdh.bandwidth, totbw ) ;
[2219]578          if ( sdh.freqref == "" && nchan != 4)
579            sdh.freqref = MFrequency::showType( freqRef ) ;
580            //sdh.freqref = "LSRK" ;
[1974]581          if ( sdh.reffreq == -1.0 ) {
[1987]582            tmpQuantCol = new ROScalarQuantColumn<Double>( spwtab, "REF_FREQUENCY" ) ;
583            Quantum<Double> qreffreq = (*tmpQuantCol)( spwId ) ;
584            delete tmpQuantCol ;
[1974]585            if ( freqRef == MFrequency::LSRK ) {
586              sdh.reffreq = qreffreq.getValue("Hz") ;
587            }
588            else {
589              MFrequency::Convert tolsr( freqRef, MFrequency::Ref( MFrequency::LSRK, mf ) ) ;
590              sdh.reffreq = tolsr( qreffreq ).get("Hz").getValue() ;
591            }
592          }
593          Int refchan = nchan / 2 ;
594          IPosition refip( 1, refchan ) ;
[2083]595          Double refpix = 0.5*(nchan-1) ;
[1974]596          Double refval = 0.0 ;
[1987]597          sharedQDArrCol = new ROArrayQuantColumn<Double>( spwtab, "CHAN_WIDTH" ) ;
598          Double increment = (*sharedQDArrCol)( spwId )( refip ).getValue( "Hz" ) ;
599          delete sharedQDArrCol ;
[2033]600//           os_ << "nchan = " << nchan << " refchan = " << refchan << "(even=" << even << ") refpix = " << refpix << LogIO::POST ;
[1987]601          sharedQDArrCol = new ROArrayQuantColumn<Double>( spwtab, "CHAN_FREQ" ) ;
602          Vector< Quantum<Double> > chanFreqs = (*sharedQDArrCol)( spwId ) ;
603          delete sharedQDArrCol ;
[2187]604          if ( nchan > 1 && chanFreqs[0].getValue("Hz") > chanFreqs[1].getValue("Hz") )
605            increment *= -1.0 ;
[1974]606          if ( freqRef == MFrequency::LSRK ) {
607            if ( even ) {
608              IPosition refip0( 1, refchan-1 ) ;
609              Double refval0 = chanFreqs(refip0).getValue("Hz") ;
610              Double refval1 = chanFreqs(refip).getValue("Hz") ;
611              refval = 0.5 * ( refval0 + refval1 ) ;
612            }
613            else {
614              refval = chanFreqs(refip).getValue("Hz") ;
615            }
616          }
617          else {
618            MFrequency::Convert tolsr( freqRef, MFrequency::Ref( MFrequency::LSRK, mf ) ) ;
619            if ( even ) {
620              IPosition refip0( 1, refchan-1 ) ;
621              Double refval0 = chanFreqs(refip0).getValue("Hz") ;
622              Double refval1 = chanFreqs(refip).getValue("Hz") ;
623              refval = 0.5 * ( refval0 + refval1 ) ;
624              refval = tolsr( refval ).get("Hz").getValue() ;
625            }
626            else {
627              refval = tolsr( chanFreqs(refip) ).get("Hz").getValue() ;
628            }
629          }
630          uInt freqId = table_->frequencies().addEntry( refpix, refval, increment ) ;
631          if ( ifmap.find( spwId ) == ifmap.end() ) {
632            ifmap.insert( pair<Int, uInt>(spwId,freqId) ) ;
633            //os_ << "added to ifmap: (" << spwId << "," << freqId << ")" << LogIO::POST ;
634          }
[2002]635
636          // FREQ_ID
637          uintRF.attachToRecord( trec, "FREQ_ID" ) ;
638          *uintRF = freqId ;
639
[1974]640          // for TSYS and TCAL
[2004]641          Vector<MEpoch> scTime ;
642          Vector<Double> scInterval ;
643          ROArrayColumn<Float> scTsysCol ;
644          MSSysCal caltabsel ;
645          if ( isSysCal_ ) {
646            caltabsel = caltab( caltab.col("ANTENNA_ID") == antenna_ && caltab.col("FEED_ID") == feedId && caltab.col("SPECTRAL_WINDOW_ID") == spwId ).sort("TIME") ;
647            ROScalarMeasColumn<MEpoch> scTimeCol( caltabsel, "TIME" ) ;
648            scTime.resize( caltabsel.nrow() ) ;
649            for ( uInt irow = 0 ; irow < caltabsel.nrow() ; irow++ )
650              scTime[irow] = scTimeCol( irow ) ;
651            ROScalarColumn<Double> *scIntervalCol = new ROScalarColumn<Double>( caltabsel, "INTERVAL" ) ;
652            scInterval = scIntervalCol->getColumn() ;
653            delete scIntervalCol ;
[2159]654            if ( colTsys_ != "NONE" )
655              scTsysCol.attach( caltabsel, colTsys_ ) ;
[2004]656          }
[2102]657
658          sdh.npol = max( sdh.npol, npol ) ;
659          if ( !iswvr && sdh.poltype == "" ) sdh.poltype = getPolType( corrtype[0] ) ;
660
[2021]661//           time1 = gettimeofday_sec() ;
662//           os_ << "end 3rd iteration init: " << time1 << " (" << time1-time0 << "sec)" << LogIO::POST ;
[1974]663          //
664          // ITERATION: SCAN_NUMBER
665          //
666          TableIterator iter4( t3, "SCAN_NUMBER" ) ;
667          while( !iter4.pastEnd() ) {
[2021]668//             time0 = gettimeofday_sec() ;
669//             os_ << "start 4th iteration: " << time0 << LogIO::POST ;
[1987]670            Table t4 = iter4.table() ;
671            tcolr = tpoolr->construct( t4, "SCAN_NUMBER" ) ;
672            Int scanNum = tcolr->asInt( 0 ) ;
673            tpoolr->destroy( tcolr ) ;
[2002]674
675            // SCANNO
676            uintRF.attachToRecord( trec, "SCANNO" ) ;
677            *uintRF = scanNum - 1 ;
678
[2021]679//             time1 = gettimeofday_sec() ;
680//             os_ << "end 4th iteration init: " << time1 << " (" << time1-time0 << "sec)" << LogIO::POST ;
[1974]681            //
682            // ITERATION: STATE_ID
683            //
684            TableIterator iter5( t4, "STATE_ID" ) ;
685            while( !iter5.pastEnd() ) {
[2033]686//               time0 = gettimeofday_sec() ;
687//               os_ << "start 5th iteration: " << time0 << LogIO::POST ;
[1987]688              Table t5 = iter5.table() ;
689              tcolr = tpoolr->construct( t5, "STATE_ID" ) ;
690              Int stateId = tcolr->asInt( 0 ) ;
691              tpoolr->destroy( tcolr ) ;
692              tcolr = tpoolr->construct( stattab, "OBS_MODE" ) ;
693              String obstype = tcolr->asString( stateId ) ;
694              tpoolr->destroy( tcolr ) ;
[1974]695              if ( sdh.obstype == "" ) sdh.obstype = obstype ;
696
697              Int nrow = t5.nrow() ;
[2033]698//               time1 = gettimeofday_sec() ;
699//               os_ << "end 5th iteration init: " << time1 << " (" << time1-time0 << "sec)" << LogIO::POST ;
[2002]700
[2004]701              uInt cycle = 0 ;
702
[2002]703              Cube<Float> spArr ;
704              Cube<Bool> flArr ;
[1974]705              if ( isFloatData_ ) {
[2002]706                ROArrayColumn<Bool> mFlagCol( t5, "FLAG" ) ;
[1974]707                ROArrayColumn<Float> mFloatDataCol( t5, "FLOAT_DATA" ) ;
[2002]708                spArr = mFloatDataCol.getColumn() ;
709                flArr = mFlagCol.getColumn() ;
[1974]710                if ( sdh.fluxunit == "" ) {
[2002]711                  const TableRecord &dataColKeys = mFloatDataCol.keywordSet() ;
[1974]712                  if ( dataColKeys.isDefined( "UNIT" ) )
713                    sdh.fluxunit = dataColKeys.asString( "UNIT" ) ;
714                }
715              }
716              else if ( isData_ ) {
[2002]717                spArr.resize( npol, nchan, nrow ) ;
[2004]718                flArr.resize( npol, nchan, nrow ) ;
[2002]719                ROArrayColumn<Bool> mFlagCol( t5, "FLAG" ) ;
[1974]720                ROArrayColumn<Complex> mDataCol( t5, "DATA" ) ;
[1987]721                for ( Int irow = 0 ; irow < nrow ; irow++ ) {
722                  Bool crossOK = False ;
723                  Matrix<Complex> sp = mDataCol( irow ) ;
[2002]724                  Matrix<Bool> fl = mFlagCol( irow ) ;
[2004]725                  Matrix<Float> spxy = spArr.xyPlane( irow ) ;
726                  Matrix<Bool> flxy = flArr.xyPlane( irow ) ;
[1987]727                  for ( Int ipol = 0 ; ipol < npol ; ipol++ ) {
728                    if ( corrtype[ipol] == Stokes::XY || corrtype[ipol] == Stokes::YX
729                         || corrtype[ipol] == Stokes::RL || corrtype[ipol] == Stokes::LR ) {
730                      if ( !crossOK ) {
[2004]731                        spxy.row( ipol ) = real( sp.row( ipol ) ) ;
732                        flxy.row( ipol ) = fl.row( ipol ) ;
[2002]733                        if ( corrtype[ipol] == Stokes::XY || corrtype[ipol] == Stokes::RL ) {
[2004]734                          spxy.row( ipol+1 ) = imag( sp.row( ipol ) ) ;
735                          flxy.row( ipol+1 ) = fl.row( ipol ) ;
[2002]736                        }                       
737                        else {
[2004]738                          spxy.row( ipol+1 ) = imag( conj( sp.row( ipol ) ) ) ;
739                          flxy.row( ipol+1 ) = fl.row( ipol ) ;
[2002]740                        }
[2004]741                        crossOK = True ;
[1974]742                      }
743                    }
[1987]744                    else {
[2004]745                      spxy.row( ipol ) = real( sp.row( ipol ) ) ;
746                      flxy.row( ipol ) = fl.row( ipol ) ;
[1987]747                    }
[1974]748                  }
[1987]749                }
[1974]750                if ( sdh.fluxunit == "" ) {
[2002]751                  const TableRecord &dataColKeys = mDataCol.keywordSet() ;
[1974]752                  if ( dataColKeys.isDefined( "UNIT" ) )
[2002]753                    sdh.fluxunit = dataColKeys.asString( "UNIT" ) ;
754                }
[1974]755              }
[1987]756              ROScalarMeasColumn<MEpoch> *mTimeCol = new ROScalarMeasColumn<MEpoch>( t5, "TIME" ) ;
[2002]757              Block<MEpoch> mTimeB( nrow ) ;
758              for ( Int irow = 0 ; irow < nrow ; irow++ )
759                mTimeB[irow] = (*mTimeCol)( irow ) ;
760              ROTableColumn *mIntervalCol = tpoolr->construct( t5, "INTERVAL" ) ;
761              ROTableColumn *mFlagRowCol = tpoolr->construct( t5, "FLAG_ROW" ) ;
762              Block<Int> sysCalIdx( nrow, -1 ) ;
763              if ( isSysCal_ ) {
[2017]764                getSysCalTime( scTime, scInterval, mTimeB, sysCalIdx ) ;
[1974]765              }
[2002]766              delete mTimeCol ;
767              Matrix<Float> defaulttsys( npol, 1, 1.0 ) ;
768              Int srcType = getSrcType( stateId, tpoolr ) ;
769              uInt diridx = 0 ;
770              MDirection::Types dirType ;
771              uInt wid = 0 ;
772              Int pidx = 0 ;
773              Bool crossOK = False ;
774              Block<uInt> polnos( npol, 99 ) ;
775              for ( Int ipol = 0 ; ipol < npol ; ipol++ ) {
776                Block<uInt> p = getPolNo( corrtype[ipol] ) ;
777                if ( p.size() > 1 ) {
778                  if ( crossOK ) continue ;
779                  else {
780                    polnos[pidx] = p[0] ;
781                    pidx++ ;
782                    polnos[pidx] = p[1] ;
783                    pidx++ ;
784                    crossOK = True ;
[1974]785                  }
786                }
[2002]787                else {
788                  polnos[pidx] = p[0] ;
789                  pidx++ ;
790                }
[1974]791              }
[2002]792             
793              // SRCTYPE
794              intRF.attachToRecord( trec, "SRCTYPE" ) ;
795              *intRF = srcType ;
[1974]796
[2002]797              for ( Int irow = 0 ; irow < nrow ; irow++ ) {
798                // CYCLENO
799                *cycleRF = cycle ;
[1987]800
[2002]801                // FLAGROW
802                *flrRF = (uInt)mFlagRowCol->asBool( irow ) ;
803
804                // SPECTRA, FLAG
805                Matrix<Float> sp = spArr.xyPlane( irow ) ;
806                Matrix<Bool> flb = flArr.xyPlane( irow ) ;
807                Matrix<uChar> fl( flb.shape() ) ;
808                convertArray( fl, flb ) ;
809
810                // TIME
[2004]811                *timeRF = mTimeB[irow].get("d").getValue() ;
[2002]812
813                // INTERVAL
814                *intervalRF = (Double)(mIntervalCol->asdouble( irow )) ;
815
816                // TSYS
817                Matrix<Float> tsys ;
[2159]818                if ( sysCalIdx[irow] != -1 && colTsys_ != "NONE" )
[2204]819                  tsys = scTsysCol( sysCalIdx[irow] ) ;
[2002]820                else
821                  tsys = defaulttsys ;
822
823                // TCAL_ID
[2004]824                Block<uInt> tcalids( npol, 0 ) ;
[2159]825                if ( sysCalIdx[irow] != -1 && colTcal_ != "NONE" ) {
[2004]826                  tcalids = getTcalId( feedId, spwId, scTime[sysCalIdx[irow]] ) ;
[1987]827                }
828
[2002]829                // WEATHER_ID
830                if ( isWeather_ )
831                  wid = getWeatherId( wid, mTimeB[irow].get("s").getValue() ) ;
832                *widRF = wid ;
833                 
[1987]834
[2002]835                // DIRECTION, AZEL, SCANRATE
836                if ( getPt_ ) {
[1974]837                  Vector<Double> dir ;
838                  Vector<Double> scanrate ;
839                  String refString ;
[2002]840                  diridx = getDirection( diridx, dir, scanrate, refString, pointtab, mTimeB[irow].get("s").getValue() ) ;
[1974]841                  MDirection::getType( dirType, refString ) ;
[2002]842                  mf.resetEpoch( mTimeB[irow] ) ;
[1974]843                  mf.resetDirection( MDirection( MVDirection(dir), dirType ) ) ;
844                  if ( refString == "J2000" ) {
[2002]845                    *dirRF = dir ;
[1974]846                    MDirection::Convert toazel( dirType, MDirection::Ref( MDirection::AZEL, mf ) ) ;
847                    Vector<Double> azel = toazel( dir ).getAngle("rad").getValue() ;
[2002]848                    *azRF = (Float)azel(0) ;
849                    *elRF = (Float)azel(1) ;
[1974]850                  }
851                  else if ( refString(0,4) == "AZEL" ) {
[2002]852                    *azRF = (Float)dir(0) ;
853                    *elRF = (Float)dir(1) ;
[1974]854                    MDirection::Convert toj2000( dirType, MDirection::Ref( MDirection::J2000, mf ) ) ;
855                    Vector<Double> newdir = toj2000( dir ).getAngle("rad").getValue() ;
[2002]856                    *dirRF = newdir ;
[1974]857                  }
858                  else {
859                    MDirection::Convert toazel( dirType, MDirection::Ref( MDirection::AZEL, mf ) ) ;
860                    Vector<Double> azel = toazel( dir ).getAngle("rad").getValue() ;
861                    MDirection::Convert toj2000( dirType, MDirection::Ref( MDirection::J2000, mf ) ) ;
862                    Vector<Double> newdir = toj2000( dir ).getAngle("rad").getValue() ;
[2002]863                    *dirRF = newdir ;
864                    *azRF = (Float)azel(0) ;
865                    *elRF = (Float)azel(1) ;
[1974]866                  }
867                  if ( scanrate.size() != 0 ) {
[2002]868                    *scrRF = scanrate ;
[1974]869                  }
870                  else {
[2002]871                    *scrRF = defaultScanrate ;
[1974]872                  }
873                }
[2002]874                else {
875                  String ref = md.getRefString() ;
[2004]876                  //Vector<Double> defaultDir = srcDir ;
[2002]877                  MDirection::getType( dirType, "J2000" ) ;
878                  if ( ref != "J2000" ) {
879                    ROScalarMeasColumn<MEpoch> tmCol( pointtab, "TIME" ) ;
880                    mf.resetEpoch( tmCol( 0 ) ) ;
881                    MDirection::Convert toj2000( dirType, MDirection::Ref( MDirection::J2000, mf ) ) ;
882                    defaultDir = toj2000( defaultDir ).getAngle("rad").getValue() ;
[1974]883                  }
[2002]884                  mf.resetEpoch( mTimeB[irow] ) ;
885                  MDirection::Convert toazel( dirType, MDirection::Ref( MDirection::AZEL, mf ) ) ;
886                  Vector<Double> azel = toazel( defaultDir ).getAngle("rad").getValue() ;
887                  *azRF = (Float)azel(0) ;
888                  *elRF = (Float)azel(1) ;
889                  *dirRF = defaultDir ;
890                  *scrRF = defaultScanrate ;
[1974]891                }
892
[2002]893                // Polarization dependent things
894                for ( Int ipol = 0 ; ipol < npol ; ipol++ ) {
895                  // POLNO
896                  *polnoRF = polnos[ipol] ;
[1987]897
[2019]898                  //*spRF = sp.row( ipol ) ;
899                  //*ucarrRF = fl.row( ipol ) ;
900                  //*tsysRF = tsys.row( ipol ) ;
901                  spRF.define( sp.row( ipol ) ) ;
902                  ucarrRF.define( fl.row( ipol ) ) ;
903                  tsysRF.define( tsys.row( ipol ) ) ;
[2002]904                  *tcalidRF = tcalids[ipol] ;
[1987]905
[2002]906                  // Commit row
907                  stab.addRow() ;
908                  row.put( stab.nrow()-1 ) ;
[1987]909                }
[2004]910
911                cycle++ ;
[1987]912              }
[2002]913              tpoolr->destroy( mIntervalCol ) ;
914              tpoolr->destroy( mFlagRowCol ) ;
[1987]915
[2033]916//               time1 = gettimeofday_sec() ;
917//               os_ << "end 5th iteration: " << time1 << " (" << time1-time0 << "sec)" << LogIO::POST ;
[1974]918
919              iter5.next() ;
920            }
[1978]921
922
[1974]923            iter4.next() ;
924          }
[1978]925
926
[1974]927          iter3.next() ;
928        }
[1978]929
[1990]930             
[1974]931        iter2.next() ;
932      }
[1978]933
934
[1974]935      iter1.next() ;
936    }
937    if ( sdh.nbeam < nbeam ) sdh.nbeam = nbeam ;
[1978]938
[1974]939    iter0.next() ;
940  }
941
[1987]942
943  delete tpoolr ;
944
945
[1978]946  // Table Keywords
[2078]947  sdh.nif = ifmap.size() ;
[1987]948  if ( ( telescopeName == "" ) || ( antennaName == telescopeName ) ) {
[1974]949    sdh.antennaname = antennaName ;
950  }
951  else {
952    sdh.antennaname = telescopeName + "//" + antennaName ;
953  }
[2185]954  if ( stationName != "" && stationName != antennaName ) {
[1974]955    sdh.antennaname += "@" + stationName ;
956  }
[1987]957  ROArrayColumn<Double> pdirCol( pointtab, "DIRECTION" ) ;
958  String dirref = pdirCol.keywordSet().asRecord("MEASINFO").asString("Ref") ;
[1974]959  if ( dirref == "AZELGEO" || dirref == "AZEL" ) {
960    dirref = "J2000" ;
961  }
962  sscanf( dirref.chars()+1, "%f", &sdh.equinox ) ;
963  sdh.epoch = "UTC" ;
964  if (sdh.freqref == "TOPO") {
965    sdh.freqref = "TOPOCENT";
966  } else if (sdh.freqref == "GEO") {
967    sdh.freqref = "GEOCENTR";
968  } else if (sdh.freqref == "BARY") {
969    sdh.freqref = "BARYCENT";
970  } else if (sdh.freqref == "GALACTO") {
971    sdh.freqref = "GALACTOC";
972  } else if (sdh.freqref == "LGROUP") {
973    sdh.freqref = "LOCALGRP";
974  } else if (sdh.freqref == "CMB") {
975    sdh.freqref = "CMBDIPOL";
976  } else if (sdh.freqref == "REST") {
977    sdh.freqref = "SOURCE";
978  }
979  table_->setHeader( sdh ) ;
[1987]980
981  // save path to POINTING table
[2207]982  // 2011/07/06 TN
983  // Path to POINTING table in original MS will not be written
984  // if getPt_ is True
[1987]985  Path datapath( tablename_ ) ;
[2207]986  if ( !getPt_ ) {
987    String pTabName = datapath.absoluteName() + "/POINTING" ;
988    stab.rwKeywordSet().define( "POINTING", pTabName ) ;
989  }
[1987]990
991  // for GBT
[2024]992  if ( antennaName.contains( "GBT" ) ) {
[1987]993    String goTabName = datapath.absoluteName() + "/GBT_GO" ;
[1990]994    stab.rwKeywordSet().define( "GBT_GO", goTabName ) ;
[1987]995  }
[2022]996
997  // for MS created from ASDM
998  //mstable_.keywordSet().print(cout) ;
999  const TableRecord &msKeys = mstable_.keywordSet() ;
1000  uInt nfields = msKeys.nfields() ;
1001  for ( uInt ifield = 0 ; ifield < nfields ; ifield++ ) {
1002    String name = msKeys.name( ifield ) ;
1003    //os_ << "name = " << name << LogIO::POST ;
1004    if ( name.find( "ASDM" ) != String::npos ) {
1005      String asdmpath = msKeys.asTable( ifield ).tableName() ;
1006      os_ << "ASDM table: " << asdmpath << LogIO::POST ;
1007      stab.rwKeywordSet().define( name, asdmpath ) ;
1008    }
1009  }
1010
[2004]1011//   double endSec = gettimeofday_sec() ;
1012//   os_ << "end MSFiller::fill() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
[1974]1013}
1014
1015void MSFiller::close()
1016{
[1987]1017  //tablesel_.closeSubTables() ;
[1974]1018  mstable_.closeSubTables() ;
[1987]1019  //tablesel_.unlock() ;
[1974]1020  mstable_.unlock() ;
1021}
1022
[1987]1023Int MSFiller::getSrcType( Int stateId, boost::object_pool<ROTableColumn> *tpool )
[1974]1024{
[2004]1025//   double startSec = gettimeofday_sec() ;
1026//   os_ << "start MSFiller::getSrcType() startSec=" << startSec << LogIO::POST ;
[1974]1027
1028  MSState statetab = mstable_.state() ;
[1987]1029  ROTableColumn *sharedCol ;
1030  sharedCol = tpool->construct( statetab, "OBS_MODE" ) ;
1031  String obsMode = sharedCol->asString( stateId ) ;
1032  tpool->destroy( sharedCol ) ;
1033  sharedCol = tpool->construct( statetab, "SIG" ) ;
1034  Bool sig = sharedCol->asBool( stateId ) ;
1035  tpool->destroy( sharedCol ) ;
1036  sharedCol = tpool->construct( statetab, "REF" ) ;
1037  Bool ref = sharedCol->asBool( stateId ) ;
1038  tpool->destroy( sharedCol ) ;
1039  sharedCol = tpool->construct( statetab, "CAL" ) ;
1040  Double cal = (Double)(sharedCol->asdouble( stateId )) ;
1041  tpool->destroy( sharedCol ) ;
[1974]1042  //os_ << "OBS_MODE = " << obsMode << LogIO::POST ;
1043
1044  // determine separator
1045  String sep = "" ;
[2039]1046  String tmpStr = obsMode.substr( 0, obsMode.find_first_of( "," ) ) ;
[2049]1047  //os_ << "tmpStr = " << tmpStr << LogIO::POST ;
[2039]1048  //if ( obsMode.find( ":" ) != String::npos ) {
1049  if ( tmpStr.find( ":" ) != String::npos ) {
[1974]1050    sep = ":" ;
1051  }
[2039]1052  //else if ( obsMode.find( "." ) != String::npos ) {
1053  else if ( tmpStr.find( "." ) != String::npos ) {
[1974]1054    sep = "." ;
1055  }
[2167]1056  else if ( tmpStr.find( "#" ) != String::npos ) {
1057    sep = "#" ;
1058  }
[2039]1059  //else if ( obsMode.find( "_" ) != String::npos ) {
1060  else if ( tmpStr.find( "_" ) != String::npos ) {
1061    sep = "_" ;
1062  }
[2049]1063  //os_ << "separator = " << sep << LogIO::POST ;
[2028]1064
[1974]1065  // determine SRCTYPE
1066  Int srcType = SrcType::NOTYPE ;
1067  if ( sep == ":" ) {
1068    // sep == ":"
1069    //
1070    // GBT case
1071    //
1072    // obsMode1=Nod
1073    //    NOD
1074    // obsMode1=OffOn
1075    //    obsMode2=PSWITCHON:  PSON
1076    //    obsMode2=PSWITCHOFF: PSOFF
1077    // obsMode1=??
1078    //    obsMode2=FSWITCH:
1079    //       SIG=1: FSON
1080    //       REF=1: FSOFF
[1987]1081    // Calibration scan if CAL != 0
[1974]1082    Int epos = obsMode.find_first_of( sep ) ;
1083    Int nextpos = obsMode.find_first_of( sep, epos+1 ) ;
1084    String obsMode1 = obsMode.substr( 0, epos ) ;
1085    String obsMode2 = obsMode.substr( epos+1, nextpos-epos-1 ) ;
1086    if ( obsMode1 == "Nod" ) {
1087      srcType = SrcType::NOD ;
1088    }
1089    else if ( obsMode1 == "OffOn" ) {
1090      if ( obsMode2 == "PSWITCHON" ) srcType = SrcType::PSON ;
1091      if ( obsMode2 == "PSWITCHOFF" ) srcType = SrcType::PSOFF ;
1092    }
1093    else {
1094      if ( obsMode2 == "FSWITCH" ) {
1095        if ( sig ) srcType = SrcType::FSON ;
1096        if ( ref ) srcType = SrcType::FSOFF ;
1097      }
1098    }
[1987]1099    if ( cal > 0.0 ) {
1100      if ( srcType == SrcType::NOD )
1101        srcType = SrcType::NODCAL ;
1102      else if ( srcType == SrcType::PSON )
1103        srcType = SrcType::PONCAL ;
1104      else if ( srcType == SrcType::PSOFF )
1105        srcType = SrcType::POFFCAL ;
1106      else if ( srcType == SrcType::FSON )
1107        srcType = SrcType::FONCAL ;
1108      else if ( srcType == SrcType::FSOFF )
1109        srcType = SrcType::FOFFCAL ;
1110      else
1111        srcType = SrcType::CAL ;
1112    }
[1974]1113  }
[2167]1114  else if ( sep == "." || sep == "#" ) {
1115    // sep == "." or "#"
[1974]1116    //
[2039]1117    // ALMA & EVLA case (MS via ASDM) before3.1
[1974]1118    //
1119    // obsMode1=CALIBRATE_*
1120    //    obsMode2=ON_SOURCE: PONCAL
1121    //    obsMode2=OFF_SOURCE: POFFCAL
1122    // obsMode1=OBSERVE_TARGET
1123    //    obsMode2=ON_SOURCE: PON
1124    //    obsMode2=OFF_SOURCE: POFF
[2028]1125    string substr[2] ;
1126    int numSubstr = split( obsMode, substr, 2, "," ) ;
1127    //os_ << "numSubstr = " << numSubstr << LogIO::POST ;
1128    //for ( int i = 0 ; i < numSubstr ; i++ )
1129    //os_ << "substr[" << i << "] = " << substr[i] << LogIO::POST ;
1130    String obsType( substr[0] ) ;
1131    //os_ << "obsType = " << obsType << LogIO::POST ;
1132    Int epos = obsType.find_first_of( sep ) ;
1133    Int nextpos = obsType.find_first_of( sep, epos+1 ) ;
1134    String obsMode1 = obsType.substr( 0, epos ) ;
1135    String obsMode2 = obsType.substr( epos+1, nextpos-epos-1 ) ;
[2035]1136    //os_ << "obsMode1 = " << obsMode1 << LogIO::POST ;
1137    //os_ << "obsMode2 = " << obsMode2 << LogIO::POST ;
[1974]1138    if ( obsMode1.find( "CALIBRATE_" ) == 0 ) {
1139      if ( obsMode2 == "ON_SOURCE" ) srcType = SrcType::PONCAL ;
1140      if ( obsMode2 == "OFF_SOURCE" ) srcType = SrcType::POFFCAL ;
1141    }
1142    else if ( obsMode1 == "OBSERVE_TARGET" ) {
1143      if ( obsMode2 == "ON_SOURCE" ) srcType = SrcType::PSON ;
1144      if ( obsMode2 == "OFF_SOURCE" ) srcType = SrcType::PSOFF ;
1145    }
1146  }
[2039]1147  else if ( sep == "_" ) {
1148    // sep == "_"
1149    //
1150    // ALMA & EVLA case (MS via ASDM) after 3.2
1151    //
1152    // obsMode1=CALIBRATE_*
1153    //    obsMode2=ON_SOURCE: PONCAL
1154    //    obsMode2=OFF_SOURCE: POFFCAL
1155    // obsMode1=OBSERVE_TARGET
1156    //    obsMode2=ON_SOURCE: PON
1157    //    obsMode2=OFF_SOURCE: POFF
1158    string substr[2] ;
1159    int numSubstr = split( obsMode, substr, 2, "," ) ;
[2041]1160    //os_ << "numSubstr = " << numSubstr << LogIO::POST ;
[2039]1161    //for ( int i = 0 ; i < numSubstr ; i++ )
1162    //os_ << "substr[" << i << "] = " << substr[i] << LogIO::POST ;
1163    String obsType( substr[0] ) ;
1164    //os_ << "obsType = " << obsType << LogIO::POST ;
1165    string substr2[4] ;
1166    int numSubstr2 = split( obsType, substr2, 4, sep ) ;
1167    //Int epos = obsType.find_first_of( sep ) ;
1168    //Int nextpos = obsType.find_first_of( sep, epos+1 ) ;
1169    //String obsMode1 = obsType.substr( 0, epos ) ;
1170    //String obsMode2 = obsType.substr( epos+1, nextpos-epos-1 ) ;
1171    String obsMode1( substr2[0] ) ;
1172    String obsMode2( substr2[2] ) ;
1173    //os_ << "obsMode1 = " << obsMode1 << LogIO::POST ;
1174    //os_ << "obsMode2 = " << obsMode2 << LogIO::POST ;
1175    if ( obsMode1.find( "CALIBRATE" ) == 0 ) {
1176      if ( obsMode2 == "ON" ) srcType = SrcType::PONCAL ;
1177      if ( obsMode2 == "OFF" ) srcType = SrcType::POFFCAL ;
1178    }
1179    else if ( obsMode1 == "OBSERVE" ) {
1180      if ( obsMode2 == "ON" ) srcType = SrcType::PSON ;
1181      if ( obsMode2 == "OFF" ) srcType = SrcType::PSOFF ;
1182    }
1183  }
[1974]1184  else {
1185    if ( sig ) srcType = SrcType::SIG ;
1186    if ( ref ) srcType = SrcType::REF ;
1187  }
1188   
1189  //os_ << "srcType = " << srcType << LogIO::POST ;
[2004]1190//   double endSec = gettimeofday_sec() ;
1191//   os_ << "end MSFiller::getSrcType() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
[1974]1192  return srcType ;
1193}
1194
[2002]1195//Vector<uInt> MSFiller::getPolNo( Int corrType )
1196Block<uInt> MSFiller::getPolNo( Int corrType )
[1974]1197{
[2004]1198//   double startSec = gettimeofday_sec() ;
1199//   os_ << "start MSFiller::getPolNo() startSec=" << startSec << LogIO::POST ;
[2002]1200  Block<uInt> polno( 1 ) ;
[1974]1201
1202  if ( corrType == Stokes::I || corrType == Stokes::RR || corrType == Stokes::XX ) {
1203    polno = 0 ;
1204  }
1205  else if ( corrType == Stokes::Q || corrType == Stokes::LL || corrType == Stokes::YY ) {
1206    polno = 1 ;
1207  }
1208  else if ( corrType == Stokes::U ) {
1209    polno = 2 ;
1210  }
1211  else if ( corrType == Stokes::V ) {
1212    polno = 3 ;
1213  }
1214  else if ( corrType == Stokes::RL || corrType == Stokes::XY || corrType == Stokes::LR || corrType == Stokes::RL ) {
1215    polno.resize( 2 ) ;
1216    polno[0] = 2 ;
1217    polno[1] = 3 ;
1218  }
1219  else if ( corrType == Stokes::Plinear ) {
1220    polno[0] = 1 ;
1221  }
1222  else if ( corrType == Stokes::Pangle ) {
1223    polno[0] = 2 ;
1224  }
1225  else {
1226    polno = 99 ;
1227  }
1228  //os_ << "polno = " << polno << LogIO::POST ;
[2004]1229//   double endSec = gettimeofday_sec() ;
1230//   os_ << "end MSFiller::getPolNo() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
[1974]1231 
1232  return polno ;
1233}
1234
1235String MSFiller::getPolType( Int corrType )
1236{
[2004]1237//   double startSec = gettimeofday_sec() ;
1238//   os_ << "start MSFiller::getPolType() startSec=" << startSec << LogIO::POST ;
[1974]1239  String poltype = "" ;
1240
1241  if ( corrType == Stokes::I || corrType == Stokes::Q || corrType == Stokes::U || corrType == Stokes::V )
1242    poltype = "stokes" ;
1243  else if ( corrType == Stokes::XX || corrType == Stokes::YY || corrType == Stokes::XY || corrType == Stokes::YX )
1244    poltype = "linear" ;
1245  else if ( corrType == Stokes::RR || corrType == Stokes::LL || corrType == Stokes::RL || corrType == Stokes::LR )
1246    poltype = "circular" ;
1247  else if ( corrType == Stokes::Plinear || corrType == Stokes::Pangle )
1248    poltype = "linpol" ;
1249
[2004]1250//   double endSec = gettimeofday_sec() ;
1251//   os_ << "end MSFiller::getPolType() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
[1974]1252  return poltype ;
1253}
1254
1255void MSFiller::fillWeather()
1256{
[2004]1257//   double startSec = gettimeofday_sec() ;
1258//   os_ << "start MSFiller::fillWeather() startSec=" << startSec << LogIO::POST ;
1259
1260  if ( !isWeather_ ) {
1261    // add dummy row
1262    table_->weather().table().addRow(1,True) ;
1263    return ;
1264  }
1265
[1987]1266  Table mWeather = mstable_.weather()  ;
1267  //Table mWeatherSel = mWeather( mWeather.col("ANTENNA_ID") == antenna_ ).sort("TIME") ;
1268  Table mWeatherSel( mWeather( mWeather.col("ANTENNA_ID") == antenna_ ).sort("TIME") ) ;
[1974]1269  //os_ << "mWeatherSel.nrow() = " << mWeatherSel.nrow() << LogIO::POST ;
1270  if ( mWeatherSel.nrow() == 0 ) {
[2025]1271    os_ << "No rows with ANTENNA_ID = " << antenna_ << " in WEATHER table, Try -1..." << LogIO::POST ;
[1987]1272    mWeatherSel = Table( MSWeather( mWeather( mWeather.col("ANTENNA_ID") == -1 ) ) ) ;
[1974]1273    if ( mWeatherSel.nrow() == 0 ) {
1274      os_ << "No rows in WEATHER table" << LogIO::POST ;
1275    }
1276  }
[1987]1277  uInt wnrow = mWeatherSel.nrow() ;
[1974]1278  //os_ << "wnrow = " << wnrow << LogIO::POST ;
1279
1280  if ( wnrow == 0 )
1281    return ;
1282
1283  Table wtab = table_->weather().table() ;
1284  wtab.addRow( wnrow ) ;
1285
[1987]1286  ScalarColumn<Float> *fCol ;
1287  ROScalarColumn<Float> *sharedFloatCol ;
1288  if ( mWeatherSel.tableDesc().isColumn( "TEMPERATURE" ) ) {
1289    fCol = new ScalarColumn<Float>( wtab, "TEMPERATURE" ) ;
1290    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "TEMPERATURE" ) ;
1291    fCol->putColumn( *sharedFloatCol ) ;
1292    delete sharedFloatCol ;
1293    delete fCol ;
1294  }
1295  if ( mWeatherSel.tableDesc().isColumn( "PRESSURE" ) ) {
1296    fCol = new ScalarColumn<Float>( wtab, "PRESSURE" ) ;
1297    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "PRESSURE" ) ;
1298    fCol->putColumn( *sharedFloatCol ) ;
1299    delete sharedFloatCol ;
1300    delete fCol ;
1301  }
1302  if ( mWeatherSel.tableDesc().isColumn( "REL_HUMIDITY" ) ) {
1303    fCol = new ScalarColumn<Float>( wtab, "HUMIDITY" ) ;
1304    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "REL_HUMIDITY" ) ;
1305    fCol->putColumn( *sharedFloatCol ) ;
1306    delete sharedFloatCol ;
1307    delete fCol ;
1308  }
1309  if ( mWeatherSel.tableDesc().isColumn( "WIND_SPEED" ) ) { 
1310    fCol = new ScalarColumn<Float>( wtab, "WINDSPEED" ) ;
1311    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "WIND_SPEED" ) ;
1312    fCol->putColumn( *sharedFloatCol ) ;
1313    delete sharedFloatCol ;
1314    delete fCol ;
1315  }
1316  if ( mWeatherSel.tableDesc().isColumn( "WIND_DIRECTION" ) ) {
1317    fCol = new ScalarColumn<Float>( wtab, "WINDAZ" ) ;
1318    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "WIND_DIRECTION" ) ;
1319    fCol->putColumn( *sharedFloatCol ) ;
1320    delete sharedFloatCol ;
1321    delete fCol ;
1322  }
[1974]1323  ScalarColumn<uInt> idCol( wtab, "ID" ) ;
[1987]1324  for ( uInt irow = 0 ; irow < wnrow ; irow++ )
1325    idCol.put( irow, irow ) ;
[1974]1326
[1987]1327  ROScalarQuantColumn<Double> tqCol( mWeatherSel, "TIME" ) ;
1328  ROScalarColumn<Double> tCol( mWeatherSel, "TIME" ) ;
1329  String tUnit = tqCol.getUnits() ;
1330  mwTime_ = tCol.getColumn() ;
[1974]1331  if ( tUnit == "d" )
1332    mwTime_ *= 86400.0 ;
[1987]1333  tqCol.attach( mWeatherSel, "INTERVAL" ) ;
1334  tCol.attach( mWeatherSel, "INTERVAL" ) ;
1335  String iUnit = tqCol.getUnits() ;
1336  mwInterval_ = tCol.getColumn() ;
[1974]1337  if ( iUnit == "d" )
1338    mwInterval_ *= 86400.0 ;
1339  //os_ << "mwTime[0] = " << mwTime_[0] << " mwInterval[0] = " << mwInterval_[0] << LogIO::POST ;
[2004]1340//   double endSec = gettimeofday_sec() ;
1341//   os_ << "end MSFiller::fillWeather() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
[1974]1342}
1343
1344void MSFiller::fillFocus()
1345{
[2004]1346//   double startSec = gettimeofday_sec() ;
1347//   os_ << "start MSFiller::fillFocus() startSec=" << startSec << LogIO::POST ;
[1974]1348  // tentative
1349  Table tab = table_->focus().table() ;
1350  tab.addRow( 1 ) ;
1351  ScalarColumn<uInt> idCol( tab, "ID" ) ;
1352  idCol.put( 0, 0 ) ;
[2004]1353//   double endSec = gettimeofday_sec() ;
1354//   os_ << "end MSFiller::fillFocus() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
[1974]1355}
1356
[2002]1357void MSFiller::fillTcal( boost::object_pool<ROTableColumn> *tpoolr )
[1974]1358{
[2004]1359//   double startSec = gettimeofday_sec() ;
1360//   os_ << "start MSFiller::fillTcal() startSec=" << startSec << LogIO::POST ;
[1987]1361
[2004]1362  if ( !isSysCal_ ) {
1363    // add dummy row
[2025]1364    os_ << "No SYSCAL rows" << LogIO::POST ;
[2004]1365    table_->tcal().table().addRow(1,True) ;
[2021]1366    Vector<Float> defaultTcal( 1, 1.0 ) ;
1367    ArrayColumn<Float> tcalCol( table_->tcal().table(), "TCAL" ) ;
1368    tcalCol.put( 0, defaultTcal ) ;
[2004]1369    return ;
1370  }
1371
[2159]1372  if ( colTcal_ == "NONE" ) {
1373    // add dummy row
1374    os_ << "No TCAL column" << LogIO::POST ;
1375    table_->tcal().table().addRow(1,True) ;
1376    Vector<Float> defaultTcal( 1, 1.0 ) ;
1377    ArrayColumn<Float> tcalCol( table_->tcal().table(), "TCAL" ) ;
1378    tcalCol.put( 0, defaultTcal ) ;
1379    return ;
1380  }
1381
[1987]1382  Table sctab = mstable_.sysCal() ;
[1974]1383  if ( sctab.nrow() == 0 ) {
[2025]1384    os_ << "No SYSCAL rows" << LogIO::POST ;
[1974]1385    return ;
1386  }
[1987]1387  Table sctabsel( sctab( sctab.col("ANTENNA_ID") == antenna_ ) ) ;
[1974]1388  if ( sctabsel.nrow() == 0 ) {
[2025]1389    os_ << "No SYSCAL rows" << LogIO::POST ;
[1974]1390    return ;
1391  }
[2164]1392  ROArrayColumn<Float> *tmpTcalCol = new ROArrayColumn<Float>( sctabsel, colTcal_ ) ;
1393  // return if any rows without Tcal value exists
1394  Bool notDefined = False ;
1395  for ( uInt irow = 0 ; irow < sctabsel.nrow() ; irow++ ) {
1396    if ( !tmpTcalCol->isDefined( irow ) ) {
1397      notDefined = True ;
1398      break ;
1399    }
1400  }
1401  if ( notDefined ) {
1402    os_ << "No TCAL value" << LogIO::POST ;
1403    delete tmpTcalCol ;
1404    table_->tcal().table().addRow(1,True) ;
1405    Vector<Float> defaultTcal( 1, 1.0 ) ;
1406    ArrayColumn<Float> tcalCol( table_->tcal().table(), "TCAL" ) ;
1407    tcalCol.put( 0, defaultTcal ) ;
1408    return ;
1409  }   
[1987]1410  uInt npol = tmpTcalCol->shape( 0 )(0) ;
1411  delete tmpTcalCol ;
[1974]1412  //os_ << "fillTcal(): npol = " << npol << LogIO::POST ;
1413  Table tab = table_->tcal().table() ;
1414  ArrayColumn<Float> tcalCol( tab, "TCAL" ) ;
[1987]1415  ROTableColumn *sharedCol ;
[1974]1416  uInt oldnr = 0 ;
1417  uInt newnr = 0 ;
[2002]1418  TableRow row( tab ) ;
1419  TableRecord &trec = row.record() ;
1420  RecordFieldPtr<uInt> idRF( trec, "ID" ) ;
1421  RecordFieldPtr<String> timeRF( trec, "TIME" ) ;
1422  RecordFieldPtr< Array<Float> > tcalRF( trec, "TCAL" ) ;
[1974]1423  TableIterator iter0( sctabsel, "FEED_ID" ) ;
1424  while( !iter0.pastEnd() ) {
[1987]1425    Table t0 = iter0.table() ;
[1988]1426    sharedCol = tpoolr->construct( t0, "FEED_ID" ) ;
[1987]1427    Int feedId = sharedCol->asInt( 0 ) ;
[1988]1428    tpoolr->destroy( sharedCol ) ;
[1974]1429    TableIterator iter1( t0, "SPECTRAL_WINDOW_ID" ) ;
1430    while( !iter1.pastEnd() ) {
[1988]1431      Table t1 = iter1.table() ;
1432      sharedCol = tpoolr->construct( t1, "SPECTRAL_WINDOW_ID" ) ;
[1987]1433      Int spwId = sharedCol->asInt( 0 ) ;
[1988]1434      tpoolr->destroy( sharedCol ) ;
[2002]1435      tmpTcalCol = new ROArrayColumn<Float>( t1, colTcal_ ) ;
1436      ROScalarQuantColumn<Double> scTimeCol( t1, "TIME" ) ;
1437      Vector<uInt> idminmax( 2, oldnr ) ;
1438      for ( uInt irow = 0 ; irow < t1.nrow() ; irow++ ) {
1439        String sTime = MVTime( scTimeCol(irow) ).string( MVTime::YMD ) ;
1440        *timeRF = sTime ;
[1988]1441        uInt idx = oldnr ;
[2002]1442        Matrix<Float> subtcal = (*tmpTcalCol)( irow ) ;
[1988]1443        for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
[2002]1444          *idRF = idx++ ;
[2019]1445          //*tcalRF = subtcal.row( ipol ) ;
1446          tcalRF.define( subtcal.row( ipol ) ) ;
[2002]1447
1448          // commit row
1449          tab.addRow() ;
1450          row.put( tab.nrow()-1 ) ;
1451
1452          newnr++ ;
[1974]1453        }
[2002]1454        idminmax[0] = oldnr ;
[1988]1455        idminmax[1] = newnr - 1 ;
1456        oldnr = newnr ;
1457
[1990]1458        String key = keyTcal( feedId, spwId, sTime ) ;
[1988]1459        tcalrec_.define( key, idminmax ) ;
[1974]1460      }
[2002]1461      delete tmpTcalCol ;
[1974]1462      iter1++ ;
1463    }
1464    iter0++ ;
1465  }
1466
1467  //tcalrec_.print( std::cout ) ;
[2004]1468//   double endSec = gettimeofday_sec() ;
1469//   os_ << "end MSFiller::fillTcal() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
[1974]1470}
1471
1472uInt MSFiller::getWeatherId( uInt idx, Double wtime )
1473{
[2004]1474//   double startSec = gettimeofday_sec() ;
1475//   os_ << "start MSFiller::getWeatherId() startSec=" << startSec << LogIO::POST ;
[1974]1476  uInt nrow = mwTime_.size() ;
[2019]1477  if ( nrow < 2 )
[1974]1478    return 0 ;
1479  uInt wid = nrow ;
1480  for ( uInt i = idx ; i < nrow-1 ; i++ ) {
1481    Double tStart = mwTime_[i]-0.5*mwInterval_[i] ;
1482    // use of INTERVAL column is problematic
1483    // since there are "blank" time of weather monitoring
1484    //Double tEnd = tStart + mwInterval_[i] ;
1485    Double tEnd = mwTime_[i+1]-0.5*mwInterval_[i+1] ;
1486    //os_ << "tStart = " << tStart << " dtEnd = " << tEnd-tStart << " dwtime = " << wtime-tStart << LogIO::POST ;
1487    if ( wtime >= tStart && wtime <= tEnd ) {
1488      wid = i ;
1489      break ;
1490    }
1491  }
1492  if ( wid == nrow ) {
1493    uInt i = nrow - 1 ;
1494    Double tStart = mwTime_[i-1]+0.5*mwInterval_[i-1] ;
1495    Double tEnd = mwTime_[i]+0.5*mwInterval_[i] ;
1496    //os_ << "tStart = " << tStart << " dtEnd = " << tEnd-tStart << " dwtime = " << wtime-tStart << LogIO::POST ;
1497    if ( wtime >= tStart && wtime <= tEnd )
[2021]1498      wid = i-1 ;
1499    else
[1974]1500      wid = i ;
1501  }
1502
1503  //if ( wid == nrow )
1504  //os_ << LogIO::WARN << "Couldn't find correct WEATHER_ID for time " << wtime << LogIO::POST ;
1505
[2004]1506//   double endSec = gettimeofday_sec() ;
1507//   os_ << "end MSFiller::getWeatherId() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
[1974]1508  return wid ;
1509}
1510
[2017]1511void MSFiller::getSysCalTime( Vector<MEpoch> &scTime, Vector<Double> &scInterval, Block<MEpoch> &tcol, Block<Int> &tidx )
[1974]1512{
[2004]1513//   double startSec = gettimeofday_sec() ;
1514//   os_ << "start MSFiller::getSysCalTime() startSec=" << startSec << LogIO::POST ;
1515
1516  if ( !isSysCal_ )
1517    return ;
1518
[2017]1519  uInt nrow = tidx.nelements() ;
[2002]1520  if ( scTime.nelements() == 0 )
[1993]1521    return ;
[2019]1522  else if ( scTime.nelements() == 1 ) {
1523    tidx[0] = 0 ;
1524    return ;
1525  }
[2002]1526  uInt scnrow = scTime.nelements() ;
[1974]1527  uInt idx = 0 ;
1528  const Double half = 0.5e0 ;
[2003]1529  // execute  binary search
1530  idx = binarySearch( scTime, tcol[0].get( "s" ).getValue() ) ;
1531  if ( idx != 0 )
1532    idx -= 1 ;
[1974]1533  for ( uInt i = 0 ; i < nrow ; i++ ) {
[2002]1534    Double t = tcol[i].get( "s" ).getValue() ;
[2017]1535    Double tsc = scTime[0].get( "s" ).getValue() ;
1536    if ( t < tsc ) {
1537      tidx[i] = 0 ;
1538      continue ;
1539    }
[1974]1540    for ( uInt j = idx ; j < scnrow-1 ; j++ ) {
[2002]1541      Double tsc1 = scTime[j].get( "s" ).getValue() ;
1542      Double dt1 = scInterval[j] ;
1543      Double tsc2 = scTime[j+1].get( "s" ).getValue() ;
1544      Double dt2 = scInterval[j+1] ;
[1974]1545      if ( t > tsc1-half*dt1 && t <= tsc2-half*dt2 ) {
[2002]1546        tidx[i] = j ;
[1974]1547        idx = j ;
1548        break ;
1549      }
1550    }
[2017]1551    if ( tidx[i] == -1 ) {
[2022]1552//       Double tsc = scTime[scnrow-1].get( "s" ).getValue() ;
1553//       Double dt = scInterval[scnrow-1] ;
[2017]1554//       if ( t <= tsc+0.5*dt ) {
1555//         tidx[i] = scnrow-1 ;
1556//       }
1557      tidx[i] = scnrow-1 ;
[1974]1558    }
1559  }
[2004]1560//   double endSec = gettimeofday_sec() ;
1561//   os_ << "end MSFiller::getSysCalTime() endSec=" << endSec << " (" << endSec-startSec << "sec) scnrow = " << scnrow << " tcol.nelements = " << tcol.nelements() << LogIO::POST ;
[1993]1562  return ;
[1974]1563}
1564
[2004]1565Block<uInt> MSFiller::getTcalId( Int fid, Int spwid, MEpoch &t )
1566{
[2002]1567//   double startSec = gettimeofday_sec() ;
[2004]1568//   os_ << "start MSFiller::getTcalId() startSec=" << startSec << LogIO::POST ;
1569  //if ( table_->tcal().table().nrow() == 0 ) {
1570  if ( !isSysCal_ ) {
[1988]1571    os_ << "No TCAL rows" << LogIO::POST ;
[2184]1572    Block<uInt> tcalids( 4, 0 ) ;
[1988]1573    return  tcalids ;
1574  }   
[2004]1575  //String sctime = MVTime( Quantum<Double>(t,"s") ).string(MVTime::YMD) ;
1576  String sctime = MVTime( t.getValue() ).string(MVTime::YMD) ;
[1990]1577  String key = keyTcal( fid, spwid, sctime ) ;
[1988]1578  if ( !tcalrec_.isDefined( key ) ) {
[1974]1579    os_ << "No TCAL rows" << LogIO::POST ;
[2184]1580    Block<uInt> tcalids( 4, 0 ) ;
[1974]1581    return tcalids ;
1582  }
[1988]1583  Vector<uInt> ids = tcalrec_.asArrayuInt( key ) ;
1584  uInt npol = ids[1] - ids[0] + 1 ;
[2002]1585  Block<uInt> tcalids( npol ) ;
[1988]1586  tcalids[0] = ids[0] ;
1587  tcalids[1] = ids[1] ;
1588  for ( uInt ipol = 2 ; ipol < npol ; ipol++ )
1589    tcalids[ipol] = ids[0] + ipol - 1 ;
1590
[2004]1591//   double endSec = gettimeofday_sec() ;
1592//   os_ << "end MSFiller::getTcalId() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
[1974]1593  return tcalids ;
1594}
1595
[1987]1596uInt MSFiller::getDirection( uInt idx, Vector<Double> &dir, Vector<Double> &srate, String &ref, MSPointing &tab, Double t )
[1974]1597{
[2004]1598//   double startSec = gettimeofday_sec() ;
1599//   os_ << "start MSFiller::getDirection() startSec=" << startSec << LogIO::POST ;
[1974]1600  // assume that cols is sorted by TIME
1601  Bool doInterp = False ;
[1987]1602  //uInt nrow = cols.nrow() ;
1603  uInt nrow = tab.nrow() ;
[1974]1604  if ( nrow == 0 )
1605    return 0 ;
[1987]1606  ROScalarMeasColumn<MEpoch> tcol( tab, "TIME" ) ;
1607  ROArrayMeasColumn<MDirection> dmcol( tab, "DIRECTION" ) ;
1608  ROArrayColumn<Double> dcol( tab, "DIRECTION" ) ;
[2003]1609  // binary search if idx == 0
1610  if ( idx == 0 ) {
1611    uInt nrowb = 75000 ;
[2004]1612    if ( nrow > nrowb ) {
[2003]1613      uInt nblock = nrow / nrowb + 1 ;
1614      for ( uInt iblock = 0 ; iblock < nblock ; iblock++ ) {
[2004]1615        uInt high = min( nrowb, nrow-iblock*nrowb ) ;
[2003]1616
1617        if ( tcol( high-1 ).get( "s" ).getValue() < t ) {
[2004]1618          idx = iblock * nrowb ;
[2003]1619          continue ;
1620        }
1621
1622        Vector<MEpoch> tarr( high ) ;
1623        for ( uInt irow = 0 ; irow < high ; irow++ ) {
[2004]1624          tarr[irow] = tcol( iblock*nrowb+irow ) ;
[2003]1625        }
1626
1627        uInt bidx = binarySearch( tarr, t ) ;
1628
[2004]1629        idx = iblock * nrowb + bidx ;
[2003]1630        break ;
1631      }
1632    }
1633    else {
1634      Vector<MEpoch> tarr( nrow ) ;
1635      for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1636        tarr[irow] = tcol( irow ) ;
1637      }
1638      idx = binarySearch( tarr, t ) ;
1639    }
1640  }
[1974]1641  // ensure that tcol(idx) < t
1642  //os_ << "tcol(idx) = " << tcol(idx).get("s").getValue() << " t = " << t << " diff = " << tcol(idx).get("s").getValue()-t << endl ;
1643  while ( tcol(idx).get("s").getValue() > t && idx > 0 )
1644    idx-- ;
1645  //os_ << "idx = " << idx << LogIO::POST ;
1646
1647  // index search
1648  for ( uInt i = idx ; i < nrow ; i++ ) {
1649    Double tref = tcol( i ).get( "s" ).getValue() ;
1650    if ( tref == t ) {
1651      idx = i ;
1652      break ;
1653    }
1654    else if ( tref > t ) {
1655      if ( i == 0 ) {
1656        idx = i ;
1657      }
1658      else {
1659        idx = i-1 ;
1660        doInterp = True ;
1661      }
1662      break ;
1663    }
1664    else {
1665      idx = nrow - 1 ;
1666    }
1667  }
1668  //os_ << "searched idx = " << idx << LogIO::POST ;
1669
1670  //os_ << "dmcol(idx).shape() = " << dmcol(idx).shape() << LogIO::POST ;
1671  IPosition ip( dmcol(idx).shape().nelements(), 0 ) ;
1672  //os_ << "ip = " << ip << LogIO::POST ;
1673  ref = dmcol(idx)(ip).getRefString() ;
1674  //os_ << "ref = " << ref << LogIO::POST ;
1675  if ( doInterp ) {
1676    //os_ << "do interpolation" << LogIO::POST ;
1677    //os_ << "dcol(idx).shape() = " << dcol(idx).shape() << LogIO::POST ;
1678    Double tref0 = tcol(idx).get("s").getValue() ;
1679    Double tref1 = tcol(idx+1).get("s").getValue() ;
[1987]1680    Matrix<Double> mdir0 = dcol( idx ) ;
1681    Matrix<Double> mdir1 = dcol( idx+1 ) ;
1682    Vector<Double> dir0 = mdir0.column( 0 ) ;
[1974]1683    //os_ << "dir0 = " << dir0 << LogIO::POST ;
[1987]1684    Vector<Double> dir1 = mdir1.column( 0 ) ;
[1974]1685    //os_ << "dir1 = " << dir1 << LogIO::POST ;
1686    Double dt0 = t - tref0 ;
1687    Double dt1 = tref1 - t ;
1688    dir.reference( (dt0*dir1+dt1*dir0)/(dt0+dt1) ) ;
[1987]1689    if ( mdir0.ncolumn() > 1 ) {
1690      if ( dt0 >= dt1 )
1691        srate.reference( mdir0.column( 1 ) ) ;
1692      else
1693        srate.reference( mdir1.column( 1 ) ) ;
[1974]1694    }
1695    //os_ << "dir = " << dir << LogIO::POST ;
1696  }
1697  else {
1698    //os_ << "no interpolation" << LogIO::POST ;
[1987]1699    Matrix<Double> mdir0 = dcol( idx ) ;
1700    dir.reference( mdir0.column( 0 ) ) ;
1701    if ( mdir0.ncolumn() > 1 )
1702      srate.reference( mdir0.column( 1 ) ) ;
[1974]1703  }
1704
[2004]1705//   double endSec = gettimeofday_sec() ;
1706//   os_ << "end MSFiller::getDirection() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
[1974]1707  return idx ;
1708}
1709
[1990]1710String MSFiller::keyTcal( Int feedid, Int spwid, String stime )
1711{
1712  String sfeed = "FEED" + String::toString( feedid ) ;
1713  String sspw = "SPW" + String::toString( spwid ) ;
1714  return sfeed+":"+sspw+":"+stime ;
1715}
1716
[2003]1717uInt MSFiller::binarySearch( Vector<MEpoch> &timeList, Double target )
1718{
1719  Int low = 0 ;
1720  Int high = timeList.nelements() ;
1721  uInt idx = 0 ;
1722
1723  while ( low <= high ) {
1724    idx = (Int)( 0.5 * ( low + high ) ) ;
1725    Double t = timeList[idx].get( "s" ).getValue() ;
1726    if ( t < target )
1727      low = idx + 1 ;
1728    else if ( t > target )
1729      high = idx - 1 ;
1730    else
1731      return idx ;
1732  }
1733
1734  idx = max( 0, min( low, high ) ) ;
1735
1736  return idx ;
1737 
1738}
1739
[2217]1740string MSFiller::getFrame()
1741{
1742  MFrequency::Types frame = MFrequency::DEFAULT ;
1743  ROTableColumn numChanCol( mstable_.spectralWindow(), "NUM_CHAN" ) ;
1744  ROTableColumn measFreqRefCol( mstable_.spectralWindow(), "MEAS_FREQ_REF" ) ;
1745  uInt nrow = numChanCol.nrow() ;
1746  Vector<Int> measFreqRef( nrow, MFrequency::DEFAULT ) ;
1747  uInt nref = 0 ;
1748  for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1749    if ( numChanCol.asInt( irow ) != 4 ) { // exclude WVR
1750      measFreqRef[nref] = measFreqRefCol.asInt( irow ) ;
1751      nref++ ;
1752    }
1753  }
1754  if ( nref > 0 )
1755    frame = (MFrequency::Types)measFreqRef[0] ;
1756
1757  return MFrequency::showType( frame ) ;
1758}
[1974]1759} ;
1760
Note: See TracBrowser for help on using the repository browser.