source: branches/casa-prerelease/pre-asap/src/MSFiller.cpp @ 2079

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

New Development: No

JIRA Issue: Yes CAS-2718

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: Yes/No?

Module(s): Module Names change impacts.

Description: Describe your changes here...

Merged bug fix on MSFiller in trunk (r2078).

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