source: trunk/src/MSFiller.cpp @ 2224

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

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: Yes/No?

Module(s): Module Names change impacts.

Description: Describe your changes here...

Just added commented out code that are is used to store raw
frequency frame value instead to convert frequency to LSRK value.


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