source: trunk/src/MSFiller.cpp @ 2185

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

New Development: No

JIRA Issue: Yes ASAP Trac #242

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

Fixed two issues in MSFiller/Writer:

  • flux unit wasn't correctly handled in MSWriter
  • fixed wrong antenna name when telescope name and station name are not available or equivalent with antenna name


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