source: trunk/src/MSFiller.cpp @ 2021

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

New Development: No

JIRA Issue: Yes CAS-2718

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...

Bug fix related to ALMA data.

  1. bug fix when NUM_LINES is 0 in SOURCE subtable
  2. support variable number of polarization data (e.g. including WVR data)
  3. bug fix on WEATHER_ID numbering in MSFiller


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