source: trunk/src/MSFiller.cpp @ 2017

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

New Development: No

JIRA Issue: Yes CAS-2718

Ready for Test: Yes/No?

Interface Changes: Yes/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...

Defined gettimeofday_sec() as private method of the class.

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