source: trunk/src/MSFiller.cpp @ 2232

Last change on this file since 2232 was 2232, 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...

REFVAL, REFPIX, INCREMENT are calculated only once for each
spectral window.

File size: 63.6 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 = -1 ;
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          uInt freqId ;
564          tcolr = tpoolr->construct( spwtab, "NUM_CHAN" ) ;
565          Int nchan = tcolr->asInt( spwId ) ;
566          Bool iswvr = False ;
567          if ( nchan == 4 ) iswvr = True ;
568          tpoolr->destroy( tcolr ) ;
569          map<Int,uInt>::iterator iter = ifmap.find( spwId ) ;
570          if ( iter == ifmap.end() ) {
571            ROScalarQuantColumn<Double> *tmpQuantCol = new ROScalarQuantColumn<Double>( t3, "TIME" ) ;
572            me = MEpoch( (*tmpQuantCol)( 0 ), MEpoch::UTC ) ;
573            delete tmpQuantCol ;
574            MeasFrame mf( me, mp, md ) ;
575            tcolr = tpoolr->construct( spwtab, "MEAS_FREQ_REF" ) ;
576            MFrequency::Types freqRef = MFrequency::castType((uInt)(tcolr->asInt(spwId))) ;
577            tpoolr->destroy( tcolr ) ;
578            Bool even = False ;
579            if ( (nchan/2)*2 == nchan ) even = True ;
580            sdh.nchan = max( sdh.nchan, nchan ) ;
581            tmpQuantCol = new ROScalarQuantColumn<Double>( spwtab, "TOTAL_BANDWIDTH" ) ;
582            Double totbw = (*tmpQuantCol)( spwId ).getValue( "Hz" ) ;
583            delete tmpQuantCol ;
584            if ( nchan != 4 )
585              sdh.bandwidth = max( sdh.bandwidth, totbw ) ;
586            if ( sdh.freqref == "" && nchan != 4)
587              //sdh.freqref = MFrequency::showType( freqRef ) ;
588              sdh.freqref = "LSRK" ;
589            if ( sdh.reffreq == -1.0 && nchan != 4 ) {
590              tmpQuantCol = new ROScalarQuantColumn<Double>( spwtab, "REF_FREQUENCY" ) ;
591              Quantum<Double> qreffreq = (*tmpQuantCol)( spwId ) ;
592              delete tmpQuantCol ;
593              //             sdh.reffreq = qreffreq.getValue("Hz") ;
594              if ( freqRef == MFrequency::LSRK ) {
595                sdh.reffreq = qreffreq.getValue("Hz") ;
596              }
597              else {
598                MFrequency::Convert tolsr( freqRef, MFrequency::Ref( MFrequency::LSRK, mf ) ) ;
599                sdh.reffreq = tolsr( qreffreq ).get("Hz").getValue() ;
600              }
601            }
602            Int refchan = nchan / 2 ;
603            IPosition refip( 1, refchan ) ;
604            Double refpix = 0.5*(nchan-1) ;
605            Double refval = 0.0 ;
606            sharedQDArrCol = new ROArrayQuantColumn<Double>( spwtab, "CHAN_WIDTH" ) ;
607            Double increment = (*sharedQDArrCol)( spwId )( refip ).getValue( "Hz" ) ;
608            delete sharedQDArrCol ;
609            //           os_ << "nchan = " << nchan << " refchan = " << refchan << "(even=" << even << ") refpix = " << refpix << LogIO::POST ;
610            sharedQDArrCol = new ROArrayQuantColumn<Double>( spwtab, "CHAN_FREQ" ) ;
611            Vector< Quantum<Double> > chanFreqs = (*sharedQDArrCol)( spwId ) ;
612            delete sharedQDArrCol ;
613            if ( nchan > 1 && chanFreqs[0].getValue("Hz") > chanFreqs[1].getValue("Hz") )
614              increment *= -1.0 ;
615            //           if ( even ) {
616            //             IPosition refip0( 1, refchan-1 ) ;
617            //             Double refval0 = chanFreqs(refip0).getValue("Hz") ;
618            //             Double refval1 = chanFreqs(refip).getValue("Hz") ;
619            //             refval = 0.5 * ( refval0 + refval1 ) ;
620            //           }
621            //           else {
622            //             refval = chanFreqs(refip).getValue("Hz") ;
623            //           }
624            if ( freqRef == MFrequency::LSRK ) {
625              if ( even ) {
626                IPosition refip0( 1, refchan-1 ) ;
627                Double refval0 = chanFreqs(refip0).getValue("Hz") ;
628                Double refval1 = chanFreqs(refip).getValue("Hz") ;
629                refval = 0.5 * ( refval0 + refval1 ) ;
630              }
631              else {
632                refval = chanFreqs(refip).getValue("Hz") ;
633              }
634            }
635            else {
636              MFrequency::Convert tolsr( freqRef, MFrequency::Ref( MFrequency::LSRK, mf ) ) ;
637              if ( even ) {
638                IPosition refip0( 1, refchan-1 ) ;
639                Double refval0 = chanFreqs(refip0).getValue("Hz") ;
640                Double refval1 = chanFreqs(refip).getValue("Hz") ;
641                refval = 0.5 * ( refval0 + refval1 ) ;
642                refval = tolsr( refval ).get("Hz").getValue() ;
643              }
644              else {
645                refval = tolsr( chanFreqs(refip) ).get("Hz").getValue() ;
646              }
647            }
648            freqId = table_->frequencies().addEntry( refpix, refval, increment ) ;
649            //if ( ifmap.find( spwId ) == ifmap.end() ) {
650            ifmap.insert( pair<Int, uInt>(spwId,freqId) ) ;
651            //os_ << "added to ifmap: (" << spwId << "," << freqId << ")" << LogIO::POST ;
652          }
653          else {
654            freqId = iter->second ;
655          }
656
657          // FREQ_ID
658          uintRF.attachToRecord( trec, "FREQ_ID" ) ;
659          *uintRF = freqId ;
660
661          // for TSYS and TCAL
662          Vector<MEpoch> scTime ;
663          Vector<Double> scInterval ;
664          ROArrayColumn<Float> scTsysCol ;
665          MSSysCal caltabsel ;
666          if ( isSysCal_ ) {
667            caltabsel = caltab( caltab.col("ANTENNA_ID") == antenna_ && caltab.col("FEED_ID") == feedId && caltab.col("SPECTRAL_WINDOW_ID") == spwId ).sort("TIME") ;
668            ROScalarMeasColumn<MEpoch> scTimeCol( caltabsel, "TIME" ) ;
669            scTime.resize( caltabsel.nrow() ) ;
670            for ( uInt irow = 0 ; irow < caltabsel.nrow() ; irow++ )
671              scTime[irow] = scTimeCol( irow ) ;
672            ROScalarColumn<Double> *scIntervalCol = new ROScalarColumn<Double>( caltabsel, "INTERVAL" ) ;
673            scInterval = scIntervalCol->getColumn() ;
674            delete scIntervalCol ;
675            if ( colTsys_ != "NONE" )
676              scTsysCol.attach( caltabsel, colTsys_ ) ;
677          }
678
679          sdh.npol = max( sdh.npol, npol ) ;
680          if ( !iswvr && sdh.poltype == "" ) sdh.poltype = getPolType( corrtype[0] ) ;
681
682//           time1 = gettimeofday_sec() ;
683//           os_ << "end 3rd iteration init: " << time1 << " (" << time1-time0 << "sec)" << LogIO::POST ;
684          //
685          // ITERATION: SCAN_NUMBER
686          //
687          TableIterator iter4( t3, "SCAN_NUMBER" ) ;
688          while( !iter4.pastEnd() ) {
689//             time0 = gettimeofday_sec() ;
690//             os_ << "start 4th iteration: " << time0 << LogIO::POST ;
691            Table t4 = iter4.table() ;
692            tcolr = tpoolr->construct( t4, "SCAN_NUMBER" ) ;
693            Int scanNum = tcolr->asInt( 0 ) ;
694            tpoolr->destroy( tcolr ) ;
695
696            // SCANNO
697            uintRF.attachToRecord( trec, "SCANNO" ) ;
698            *uintRF = scanNum - 1 ;
699
700//             time1 = gettimeofday_sec() ;
701//             os_ << "end 4th iteration init: " << time1 << " (" << time1-time0 << "sec)" << LogIO::POST ;
702            //
703            // ITERATION: STATE_ID
704            //
705            TableIterator iter5( t4, "STATE_ID" ) ;
706            while( !iter5.pastEnd() ) {
707//               time0 = gettimeofday_sec() ;
708//               os_ << "start 5th iteration: " << time0 << LogIO::POST ;
709              Table t5 = iter5.table() ;
710              tcolr = tpoolr->construct( t5, "STATE_ID" ) ;
711              Int stateId = tcolr->asInt( 0 ) ;
712              tpoolr->destroy( tcolr ) ;
713              tcolr = tpoolr->construct( stattab, "OBS_MODE" ) ;
714              String obstype = tcolr->asString( stateId ) ;
715              tpoolr->destroy( tcolr ) ;
716              if ( sdh.obstype == "" ) sdh.obstype = obstype ;
717
718              Int nrow = t5.nrow() ;
719//               time1 = gettimeofday_sec() ;
720//               os_ << "end 5th iteration init: " << time1 << " (" << time1-time0 << "sec)" << LogIO::POST ;
721
722              uInt cycle = 0 ;
723
724              Cube<Float> spArr ;
725              Cube<Bool> flArr ;
726              if ( isFloatData_ ) {
727                ROArrayColumn<Bool> mFlagCol( t5, "FLAG" ) ;
728                ROArrayColumn<Float> mFloatDataCol( t5, "FLOAT_DATA" ) ;
729                spArr = mFloatDataCol.getColumn() ;
730                flArr = mFlagCol.getColumn() ;
731                if ( sdh.fluxunit == "" ) {
732                  const TableRecord &dataColKeys = mFloatDataCol.keywordSet() ;
733                  if ( dataColKeys.isDefined( "UNIT" ) )
734                    sdh.fluxunit = dataColKeys.asString( "UNIT" ) ;
735                  else if ( dataColKeys.isDefined( "QuantumUnits" ) )
736                    sdh.fluxunit = dataColKeys.asString( "QuantumUnits" ) ;
737                }
738              }
739              else if ( isData_ ) {
740                spArr.resize( npol, nchan, nrow ) ;
741                flArr.resize( npol, nchan, nrow ) ;
742                ROArrayColumn<Bool> mFlagCol( t5, "FLAG" ) ;
743                ROArrayColumn<Complex> mDataCol( t5, "DATA" ) ;
744                for ( Int irow = 0 ; irow < nrow ; irow++ ) {
745                  Bool crossOK = False ;
746                  Matrix<Complex> sp = mDataCol( irow ) ;
747                  Matrix<Bool> fl = mFlagCol( irow ) ;
748                  Matrix<Float> spxy = spArr.xyPlane( irow ) ;
749                  Matrix<Bool> flxy = flArr.xyPlane( irow ) ;
750                  for ( Int ipol = 0 ; ipol < npol ; ipol++ ) {
751                    if ( corrtype[ipol] == Stokes::XY || corrtype[ipol] == Stokes::YX
752                         || corrtype[ipol] == Stokes::RL || corrtype[ipol] == Stokes::LR ) {
753                      if ( !crossOK ) {
754                        spxy.row( ipol ) = real( sp.row( ipol ) ) ;
755                        flxy.row( ipol ) = fl.row( ipol ) ;
756                        if ( corrtype[ipol] == Stokes::XY || corrtype[ipol] == Stokes::RL ) {
757                          spxy.row( ipol+1 ) = imag( sp.row( ipol ) ) ;
758                          flxy.row( ipol+1 ) = fl.row( ipol ) ;
759                        }                       
760                        else {
761                          spxy.row( ipol+1 ) = imag( conj( sp.row( ipol ) ) ) ;
762                          flxy.row( ipol+1 ) = fl.row( ipol ) ;
763                        }
764                        crossOK = True ;
765                      }
766                    }
767                    else {
768                      spxy.row( ipol ) = real( sp.row( ipol ) ) ;
769                      flxy.row( ipol ) = fl.row( ipol ) ;
770                    }
771                  }
772                }
773                if ( sdh.fluxunit == "" ) {
774                  const TableRecord &dataColKeys = mDataCol.keywordSet() ;
775                  if ( dataColKeys.isDefined( "UNIT" ) )
776                    sdh.fluxunit = dataColKeys.asString( "UNIT" ) ;
777                  else if ( dataColKeys.isDefined( "QuantumUnits" ) )
778                    sdh.fluxunit = dataColKeys.asString( "QuantumUnits" ) ;
779                }
780              }
781              ROScalarMeasColumn<MEpoch> *mTimeCol = new ROScalarMeasColumn<MEpoch>( t5, "TIME" ) ;
782              Block<MEpoch> mTimeB( nrow ) ;
783              for ( Int irow = 0 ; irow < nrow ; irow++ )
784                mTimeB[irow] = (*mTimeCol)( irow ) ;
785              ROTableColumn *mIntervalCol = tpoolr->construct( t5, "INTERVAL" ) ;
786              ROTableColumn *mFlagRowCol = tpoolr->construct( t5, "FLAG_ROW" ) ;
787              Block<Int> sysCalIdx( nrow, -1 ) ;
788              if ( isSysCal_ ) {
789                getSysCalTime( scTime, scInterval, mTimeB, sysCalIdx ) ;
790              }
791              delete mTimeCol ;
792              Matrix<Float> defaulttsys( npol, 1, 1.0 ) ;
793              Int srcType = getSrcType( stateId, tpoolr ) ;
794              uInt diridx = 0 ;
795              MDirection::Types dirType ;
796              uInt wid = 0 ;
797              Int pidx = 0 ;
798              Bool crossOK = False ;
799              Block<uInt> polnos( npol, 99 ) ;
800              for ( Int ipol = 0 ; ipol < npol ; ipol++ ) {
801                Block<uInt> p = getPolNo( corrtype[ipol] ) ;
802                if ( p.size() > 1 ) {
803                  if ( crossOK ) continue ;
804                  else {
805                    polnos[pidx] = p[0] ;
806                    pidx++ ;
807                    polnos[pidx] = p[1] ;
808                    pidx++ ;
809                    crossOK = True ;
810                  }
811                }
812                else {
813                  polnos[pidx] = p[0] ;
814                  pidx++ ;
815                }
816              }
817             
818              // SRCTYPE
819              intRF.attachToRecord( trec, "SRCTYPE" ) ;
820              *intRF = srcType ;
821
822              for ( Int irow = 0 ; irow < nrow ; irow++ ) {
823                // CYCLENO
824                *cycleRF = cycle ;
825
826                // FLAGROW
827                *flrRF = (uInt)mFlagRowCol->asBool( irow ) ;
828
829                // SPECTRA, FLAG
830                Matrix<Float> sp = spArr.xyPlane( irow ) ;
831                Matrix<Bool> flb = flArr.xyPlane( irow ) ;
832                Matrix<uChar> fl( flb.shape() ) ;
833                convertArray( fl, flb ) ;
834
835                // TIME
836                *timeRF = mTimeB[irow].get("d").getValue() ;
837
838                // INTERVAL
839                *intervalRF = (Double)(mIntervalCol->asdouble( irow )) ;
840
841                // TSYS
842                Matrix<Float> tsys ;
843                if ( sysCalIdx[irow] != -1 && colTsys_ != "NONE" )
844                  tsys = scTsysCol( sysCalIdx[irow] ) ;
845                else
846                  tsys = defaulttsys ;
847
848                // TCAL_ID
849                Block<uInt> tcalids( npol, 0 ) ;
850                if ( sysCalIdx[irow] != -1 && colTcal_ != "NONE" ) {
851                  tcalids = getTcalId( feedId, spwId, scTime[sysCalIdx[irow]] ) ;
852                }
853
854                // WEATHER_ID
855                if ( isWeather_ )
856                  wid = getWeatherId( wid, mTimeB[irow].get("s").getValue() ) ;
857                *widRF = wid ;
858                 
859
860                // DIRECTION, AZEL, SCANRATE
861                if ( getPt_ ) {
862                  Vector<Double> dir ;
863                  Vector<Double> scanrate ;
864                  String refString ;
865                  diridx = getDirection( diridx, dir, scanrate, refString, pointtab, mTimeB[irow].get("s").getValue() ) ;
866                  MDirection::getType( dirType, refString ) ;
867                  MeasFrame mf( mTimeB[irow], mp ) ;
868                  //mf.resetEpoch( mTimeB[irow] ) ;
869                  //mf.resetDirection( MDirection( MVDirection(dir), dirType ) ) ;
870                  if ( refString == "J2000" ) {
871                    *dirRF = dir ;
872                    MDirection::Convert toazel( dirType, MDirection::Ref( MDirection::AZEL, mf ) ) ;
873                    Vector<Double> azel = toazel( dir ).getAngle("rad").getValue() ;
874                    *azRF = (Float)azel(0) ;
875                    *elRF = (Float)azel(1) ;
876                  }
877                  else if ( refString(0,4) == "AZEL" ) {
878                    *azRF = (Float)dir(0) ;
879                    *elRF = (Float)dir(1) ;
880                    MDirection::Convert toj2000( dirType, MDirection::Ref( MDirection::J2000, mf ) ) ;
881                    Vector<Double> newdir = toj2000( dir ).getAngle("rad").getValue() ;
882                    *dirRF = newdir ;
883                  }
884                  else {
885                    MDirection::Convert toazel( dirType, MDirection::Ref( MDirection::AZEL, mf ) ) ;
886                    Vector<Double> azel = toazel( dir ).getAngle("rad").getValue() ;
887                    MDirection::Convert toj2000( dirType, MDirection::Ref( MDirection::J2000, mf ) ) ;
888                    Vector<Double> newdir = toj2000( dir ).getAngle("rad").getValue() ;
889                    *dirRF = newdir ;
890                    *azRF = (Float)azel(0) ;
891                    *elRF = (Float)azel(1) ;
892                  }
893                  if ( scanrate.size() != 0 ) {
894                    *scrRF = scanrate ;
895                  }
896                  else {
897                    *scrRF = defaultScanrate ;
898                  }
899                }
900                else {
901                  String ref = md.getRefString() ;
902                  //Vector<Double> defaultDir = srcDir ;
903                  MDirection::getType( dirType, "J2000" ) ;
904                  MeasFrame mf( mTimeB[irow], mp ) ;
905                  if ( ref != "J2000" ) {
906                    ROScalarMeasColumn<MEpoch> tmCol( pointtab, "TIME" ) ;
907                    mf.resetEpoch( tmCol( 0 ) ) ;
908                    MDirection::Convert toj2000( dirType, MDirection::Ref( MDirection::J2000, mf ) ) ;
909                    defaultDir = toj2000( defaultDir ).getAngle("rad").getValue() ;
910                  }
911                  mf.resetEpoch( mTimeB[irow] ) ;
912                  MDirection::Convert toazel( dirType, MDirection::Ref( MDirection::AZEL, mf ) ) ;
913                  Vector<Double> azel = toazel( defaultDir ).getAngle("rad").getValue() ;
914                  *azRF = (Float)azel(0) ;
915                  *elRF = (Float)azel(1) ;
916                  *dirRF = defaultDir ;
917                  *scrRF = defaultScanrate ;
918                }
919
920                // Polarization dependent things
921                for ( Int ipol = 0 ; ipol < npol ; ipol++ ) {
922                  // POLNO
923                  *polnoRF = polnos[ipol] ;
924
925                  //*spRF = sp.row( ipol ) ;
926                  //*ucarrRF = fl.row( ipol ) ;
927                  //*tsysRF = tsys.row( ipol ) ;
928                  spRF.define( sp.row( ipol ) ) ;
929                  ucarrRF.define( fl.row( ipol ) ) ;
930                  tsysRF.define( tsys.row( ipol ) ) ;
931                  *tcalidRF = tcalids[ipol] ;
932
933                  // Commit row
934                  stab.addRow() ;
935                  row.put( stab.nrow()-1 ) ;
936                }
937
938                cycle++ ;
939              }
940              tpoolr->destroy( mIntervalCol ) ;
941              tpoolr->destroy( mFlagRowCol ) ;
942
943//               time1 = gettimeofday_sec() ;
944//               os_ << "end 5th iteration: " << time1 << " (" << time1-time0 << "sec)" << LogIO::POST ;
945
946              iter5.next() ;
947            }
948
949
950            iter4.next() ;
951          }
952
953
954          iter3.next() ;
955        }
956
957             
958        iter2.next() ;
959      }
960
961
962      iter1.next() ;
963    }
964    if ( sdh.nbeam < nbeam ) sdh.nbeam = nbeam ;
965
966    iter0.next() ;
967  }
968
969
970  delete tpoolr ;
971
972
973  // Table Keywords
974  sdh.nif = ifmap.size() ;
975  if ( ( telescopeName == "" ) || ( antennaName == telescopeName ) ) {
976    sdh.antennaname = antennaName ;
977  }
978  else {
979    sdh.antennaname = telescopeName + "//" + antennaName ;
980  }
981  if ( stationName != "" && stationName != antennaName ) {
982    sdh.antennaname += "@" + stationName ;
983  }
984  ROArrayColumn<Double> pdirCol( pointtab, "DIRECTION" ) ;
985  String dirref = pdirCol.keywordSet().asRecord("MEASINFO").asString("Ref") ;
986  if ( dirref == "AZELGEO" || dirref == "AZEL" ) {
987    dirref = "J2000" ;
988  }
989  sscanf( dirref.chars()+1, "%f", &sdh.equinox ) ;
990  sdh.epoch = "UTC" ;
991  if (sdh.freqref == "TOPO") {
992    sdh.freqref = "TOPOCENT";
993  } else if (sdh.freqref == "GEO") {
994    sdh.freqref = "GEOCENTR";
995  } else if (sdh.freqref == "BARY") {
996    sdh.freqref = "BARYCENT";
997  } else if (sdh.freqref == "GALACTO") {
998    sdh.freqref = "GALACTOC";
999  } else if (sdh.freqref == "LGROUP") {
1000    sdh.freqref = "LOCALGRP";
1001  } else if (sdh.freqref == "CMB") {
1002    sdh.freqref = "CMBDIPOL";
1003  } else if (sdh.freqref == "REST") {
1004    sdh.freqref = "SOURCE";
1005  }
1006  //if ( sdh.fluxunit == "" )
1007  if ( sdh.fluxunit == "" || sdh.fluxunit == "CNTS" )
1008    sdh.fluxunit = "K" ;
1009  table_->setHeader( sdh ) ;
1010
1011  // save path to POINTING table
1012  // 2011/07/06 TN
1013  // Path to POINTING table in original MS will not be written
1014  // if getPt_ is True
1015  Path datapath( tablename_ ) ;
1016  if ( !getPt_ ) {
1017    String pTabName = datapath.absoluteName() + "/POINTING" ;
1018    stab.rwKeywordSet().define( "POINTING", pTabName ) ;
1019  }
1020
1021  // for GBT
1022  if ( antennaName.contains( "GBT" ) ) {
1023    String goTabName = datapath.absoluteName() + "/GBT_GO" ;
1024    stab.rwKeywordSet().define( "GBT_GO", goTabName ) ;
1025  }
1026
1027  // for MS created from ASDM
1028  //mstable_.keywordSet().print(cout) ;
1029  const TableRecord &msKeys = mstable_.keywordSet() ;
1030  uInt nfields = msKeys.nfields() ;
1031  for ( uInt ifield = 0 ; ifield < nfields ; ifield++ ) {
1032    String name = msKeys.name( ifield ) ;
1033    //os_ << "name = " << name << LogIO::POST ;
1034    if ( name.find( "ASDM" ) != String::npos ) {
1035      String asdmpath = msKeys.asTable( ifield ).tableName() ;
1036      os_ << "ASDM table: " << asdmpath << LogIO::POST ;
1037      stab.rwKeywordSet().define( name, asdmpath ) ;
1038    }
1039  }
1040
1041//   double endSec = gettimeofday_sec() ;
1042//   os_ << "end MSFiller::fill() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1043}
1044
1045void MSFiller::close()
1046{
1047  //tablesel_.closeSubTables() ;
1048  mstable_.closeSubTables() ;
1049  //tablesel_.unlock() ;
1050  mstable_.unlock() ;
1051}
1052
1053Int MSFiller::getSrcType( Int stateId, boost::object_pool<ROTableColumn> *tpool )
1054{
1055//   double startSec = gettimeofday_sec() ;
1056//   os_ << "start MSFiller::getSrcType() startSec=" << startSec << LogIO::POST ;
1057
1058  MSState statetab = mstable_.state() ;
1059  ROTableColumn *sharedCol ;
1060  sharedCol = tpool->construct( statetab, "OBS_MODE" ) ;
1061  String obsMode = sharedCol->asString( stateId ) ;
1062  tpool->destroy( sharedCol ) ;
1063  sharedCol = tpool->construct( statetab, "SIG" ) ;
1064  Bool sig = sharedCol->asBool( stateId ) ;
1065  tpool->destroy( sharedCol ) ;
1066  sharedCol = tpool->construct( statetab, "REF" ) ;
1067  Bool ref = sharedCol->asBool( stateId ) ;
1068  tpool->destroy( sharedCol ) ;
1069  sharedCol = tpool->construct( statetab, "CAL" ) ;
1070  Double cal = (Double)(sharedCol->asdouble( stateId )) ;
1071  tpool->destroy( sharedCol ) ;
1072  //os_ << "OBS_MODE = " << obsMode << LogIO::POST ;
1073
1074  // determine separator
1075  String sep = "" ;
1076  String tmpStr = obsMode.substr( 0, obsMode.find_first_of( "," ) ) ;
1077  //os_ << "tmpStr = " << tmpStr << LogIO::POST ;
1078  //if ( obsMode.find( ":" ) != String::npos ) {
1079  if ( tmpStr.find( ":" ) != String::npos ) {
1080    sep = ":" ;
1081  }
1082  //else if ( obsMode.find( "." ) != String::npos ) {
1083  else if ( tmpStr.find( "." ) != String::npos ) {
1084    sep = "." ;
1085  }
1086  else if ( tmpStr.find( "#" ) != String::npos ) {
1087    sep = "#" ;
1088  }
1089  //else if ( obsMode.find( "_" ) != String::npos ) {
1090  else if ( tmpStr.find( "_" ) != String::npos ) {
1091    sep = "_" ;
1092  }
1093  //os_ << "separator = " << sep << LogIO::POST ;
1094
1095  // determine SRCTYPE
1096  Int srcType = SrcType::NOTYPE ;
1097  if ( sep == ":" ) {
1098    // sep == ":"
1099    //
1100    // GBT case
1101    //
1102    // obsMode1=Nod
1103    //    NOD
1104    // obsMode1=OffOn
1105    //    obsMode2=PSWITCHON:  PSON
1106    //    obsMode2=PSWITCHOFF: PSOFF
1107    // obsMode1=??
1108    //    obsMode2=FSWITCH:
1109    //       SIG=1: FSON
1110    //       REF=1: FSOFF
1111    // Calibration scan if CAL != 0
1112    Int epos = obsMode.find_first_of( sep ) ;
1113    Int nextpos = obsMode.find_first_of( sep, epos+1 ) ;
1114    String obsMode1 = obsMode.substr( 0, epos ) ;
1115    String obsMode2 = obsMode.substr( epos+1, nextpos-epos-1 ) ;
1116    if ( obsMode1 == "Nod" ) {
1117      srcType = SrcType::NOD ;
1118    }
1119    else if ( obsMode1 == "OffOn" ) {
1120      if ( obsMode2 == "PSWITCHON" ) srcType = SrcType::PSON ;
1121      if ( obsMode2 == "PSWITCHOFF" ) srcType = SrcType::PSOFF ;
1122    }
1123    else {
1124      if ( obsMode2 == "FSWITCH" ) {
1125        if ( sig ) srcType = SrcType::FSON ;
1126        if ( ref ) srcType = SrcType::FSOFF ;
1127      }
1128    }
1129    if ( cal > 0.0 ) {
1130      if ( srcType == SrcType::NOD )
1131        srcType = SrcType::NODCAL ;
1132      else if ( srcType == SrcType::PSON )
1133        srcType = SrcType::PONCAL ;
1134      else if ( srcType == SrcType::PSOFF )
1135        srcType = SrcType::POFFCAL ;
1136      else if ( srcType == SrcType::FSON )
1137        srcType = SrcType::FONCAL ;
1138      else if ( srcType == SrcType::FSOFF )
1139        srcType = SrcType::FOFFCAL ;
1140      else
1141        srcType = SrcType::CAL ;
1142    }
1143  }
1144  else if ( sep == "." || sep == "#" ) {
1145    // sep == "." or "#"
1146    //
1147    // ALMA & EVLA case (MS via ASDM) before3.1
1148    //
1149    // obsMode1=CALIBRATE_*
1150    //    obsMode2=ON_SOURCE: PONCAL
1151    //    obsMode2=OFF_SOURCE: POFFCAL
1152    // obsMode1=OBSERVE_TARGET
1153    //    obsMode2=ON_SOURCE: PON
1154    //    obsMode2=OFF_SOURCE: POFF
1155    string substr[2] ;
1156    int numSubstr = split( obsMode, substr, 2, "," ) ;
1157    //os_ << "numSubstr = " << numSubstr << LogIO::POST ;
1158    //for ( int i = 0 ; i < numSubstr ; i++ )
1159    //os_ << "substr[" << i << "] = " << substr[i] << LogIO::POST ;
1160    String obsType( substr[0] ) ;
1161    //os_ << "obsType = " << obsType << LogIO::POST ;
1162    Int epos = obsType.find_first_of( sep ) ;
1163    Int nextpos = obsType.find_first_of( sep, epos+1 ) ;
1164    String obsMode1 = obsType.substr( 0, epos ) ;
1165    String obsMode2 = obsType.substr( epos+1, nextpos-epos-1 ) ;
1166    //os_ << "obsMode1 = " << obsMode1 << LogIO::POST ;
1167    //os_ << "obsMode2 = " << obsMode2 << LogIO::POST ;
1168    if ( obsMode1.find( "CALIBRATE_" ) == 0 ) {
1169      if ( obsMode2 == "ON_SOURCE" ) srcType = SrcType::PONCAL ;
1170      if ( obsMode2 == "OFF_SOURCE" ) srcType = SrcType::POFFCAL ;
1171    }
1172    else if ( obsMode1 == "OBSERVE_TARGET" ) {
1173      if ( obsMode2 == "ON_SOURCE" ) srcType = SrcType::PSON ;
1174      if ( obsMode2 == "OFF_SOURCE" ) srcType = SrcType::PSOFF ;
1175    }
1176  }
1177  else if ( sep == "_" ) {
1178    // sep == "_"
1179    //
1180    // ALMA & EVLA case (MS via ASDM) after 3.2
1181    //
1182    // obsMode1=CALIBRATE_*
1183    //    obsMode2=ON_SOURCE: PONCAL
1184    //    obsMode2=OFF_SOURCE: POFFCAL
1185    // obsMode1=OBSERVE_TARGET
1186    //    obsMode2=ON_SOURCE: PON
1187    //    obsMode2=OFF_SOURCE: POFF
1188    string substr[2] ;
1189    int numSubstr = split( obsMode, substr, 2, "," ) ;
1190    //os_ << "numSubstr = " << numSubstr << LogIO::POST ;
1191    //for ( int i = 0 ; i < numSubstr ; i++ )
1192    //os_ << "substr[" << i << "] = " << substr[i] << LogIO::POST ;
1193    String obsType( substr[0] ) ;
1194    //os_ << "obsType = " << obsType << LogIO::POST ;
1195    string substr2[4] ;
1196    int numSubstr2 = split( obsType, substr2, 4, sep ) ;
1197    //Int epos = obsType.find_first_of( sep ) ;
1198    //Int nextpos = obsType.find_first_of( sep, epos+1 ) ;
1199    //String obsMode1 = obsType.substr( 0, epos ) ;
1200    //String obsMode2 = obsType.substr( epos+1, nextpos-epos-1 ) ;
1201    String obsMode1( substr2[0] ) ;
1202    String obsMode2( substr2[2] ) ;
1203    //os_ << "obsMode1 = " << obsMode1 << LogIO::POST ;
1204    //os_ << "obsMode2 = " << obsMode2 << LogIO::POST ;
1205    if ( obsMode1.find( "CALIBRATE" ) == 0 ) {
1206      if ( obsMode2 == "ON" ) srcType = SrcType::PONCAL ;
1207      if ( obsMode2 == "OFF" ) srcType = SrcType::POFFCAL ;
1208    }
1209    else if ( obsMode1 == "OBSERVE" ) {
1210      if ( obsMode2 == "ON" ) srcType = SrcType::PSON ;
1211      if ( obsMode2 == "OFF" ) srcType = SrcType::PSOFF ;
1212    }
1213  }
1214  else {
1215    if ( sig ) srcType = SrcType::SIG ;
1216    if ( ref ) srcType = SrcType::REF ;
1217  }
1218   
1219  //os_ << "srcType = " << srcType << LogIO::POST ;
1220//   double endSec = gettimeofday_sec() ;
1221//   os_ << "end MSFiller::getSrcType() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1222  return srcType ;
1223}
1224
1225//Vector<uInt> MSFiller::getPolNo( Int corrType )
1226Block<uInt> MSFiller::getPolNo( Int corrType )
1227{
1228//   double startSec = gettimeofday_sec() ;
1229//   os_ << "start MSFiller::getPolNo() startSec=" << startSec << LogIO::POST ;
1230  Block<uInt> polno( 1 ) ;
1231
1232  if ( corrType == Stokes::I || corrType == Stokes::RR || corrType == Stokes::XX ) {
1233    polno = 0 ;
1234  }
1235  else if ( corrType == Stokes::Q || corrType == Stokes::LL || corrType == Stokes::YY ) {
1236    polno = 1 ;
1237  }
1238  else if ( corrType == Stokes::U ) {
1239    polno = 2 ;
1240  }
1241  else if ( corrType == Stokes::V ) {
1242    polno = 3 ;
1243  }
1244  else if ( corrType == Stokes::RL || corrType == Stokes::XY || corrType == Stokes::LR || corrType == Stokes::RL ) {
1245    polno.resize( 2 ) ;
1246    polno[0] = 2 ;
1247    polno[1] = 3 ;
1248  }
1249  else if ( corrType == Stokes::Plinear ) {
1250    polno[0] = 1 ;
1251  }
1252  else if ( corrType == Stokes::Pangle ) {
1253    polno[0] = 2 ;
1254  }
1255  else {
1256    polno = 99 ;
1257  }
1258  //os_ << "polno = " << polno << LogIO::POST ;
1259//   double endSec = gettimeofday_sec() ;
1260//   os_ << "end MSFiller::getPolNo() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1261 
1262  return polno ;
1263}
1264
1265String MSFiller::getPolType( Int corrType )
1266{
1267//   double startSec = gettimeofday_sec() ;
1268//   os_ << "start MSFiller::getPolType() startSec=" << startSec << LogIO::POST ;
1269  String poltype = "" ;
1270
1271  if ( corrType == Stokes::I || corrType == Stokes::Q || corrType == Stokes::U || corrType == Stokes::V )
1272    poltype = "stokes" ;
1273  else if ( corrType == Stokes::XX || corrType == Stokes::YY || corrType == Stokes::XY || corrType == Stokes::YX )
1274    poltype = "linear" ;
1275  else if ( corrType == Stokes::RR || corrType == Stokes::LL || corrType == Stokes::RL || corrType == Stokes::LR )
1276    poltype = "circular" ;
1277  else if ( corrType == Stokes::Plinear || corrType == Stokes::Pangle )
1278    poltype = "linpol" ;
1279
1280//   double endSec = gettimeofday_sec() ;
1281//   os_ << "end MSFiller::getPolType() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1282  return poltype ;
1283}
1284
1285void MSFiller::fillWeather()
1286{
1287//   double startSec = gettimeofday_sec() ;
1288//   os_ << "start MSFiller::fillWeather() startSec=" << startSec << LogIO::POST ;
1289
1290  if ( !isWeather_ ) {
1291    // add dummy row
1292    table_->weather().table().addRow(1,True) ;
1293    return ;
1294  }
1295
1296  Table mWeather = mstable_.weather()  ;
1297  //Table mWeatherSel = mWeather( mWeather.col("ANTENNA_ID") == antenna_ ).sort("TIME") ;
1298  Table mWeatherSel( mWeather( mWeather.col("ANTENNA_ID") == antenna_ ).sort("TIME") ) ;
1299  //os_ << "mWeatherSel.nrow() = " << mWeatherSel.nrow() << LogIO::POST ;
1300  if ( mWeatherSel.nrow() == 0 ) {
1301    os_ << "No rows with ANTENNA_ID = " << antenna_ << " in WEATHER table, Try -1..." << LogIO::POST ;
1302    mWeatherSel = Table( MSWeather( mWeather( mWeather.col("ANTENNA_ID") == -1 ) ) ) ;
1303    if ( mWeatherSel.nrow() == 0 ) {
1304      os_ << "No rows in WEATHER table" << LogIO::POST ;
1305    }
1306  }
1307  uInt wnrow = mWeatherSel.nrow() ;
1308  //os_ << "wnrow = " << wnrow << LogIO::POST ;
1309
1310  if ( wnrow == 0 )
1311    return ;
1312
1313  Table wtab = table_->weather().table() ;
1314  wtab.addRow( wnrow ) ;
1315
1316  ScalarColumn<Float> *fCol ;
1317  ROScalarColumn<Float> *sharedFloatCol ;
1318  if ( mWeatherSel.tableDesc().isColumn( "TEMPERATURE" ) ) {
1319    fCol = new ScalarColumn<Float>( wtab, "TEMPERATURE" ) ;
1320    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "TEMPERATURE" ) ;
1321    fCol->putColumn( *sharedFloatCol ) ;
1322    delete sharedFloatCol ;
1323    delete fCol ;
1324  }
1325  if ( mWeatherSel.tableDesc().isColumn( "PRESSURE" ) ) {
1326    fCol = new ScalarColumn<Float>( wtab, "PRESSURE" ) ;
1327    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "PRESSURE" ) ;
1328    fCol->putColumn( *sharedFloatCol ) ;
1329    delete sharedFloatCol ;
1330    delete fCol ;
1331  }
1332  if ( mWeatherSel.tableDesc().isColumn( "REL_HUMIDITY" ) ) {
1333    fCol = new ScalarColumn<Float>( wtab, "HUMIDITY" ) ;
1334    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "REL_HUMIDITY" ) ;
1335    fCol->putColumn( *sharedFloatCol ) ;
1336    delete sharedFloatCol ;
1337    delete fCol ;
1338  }
1339  if ( mWeatherSel.tableDesc().isColumn( "WIND_SPEED" ) ) { 
1340    fCol = new ScalarColumn<Float>( wtab, "WINDSPEED" ) ;
1341    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "WIND_SPEED" ) ;
1342    fCol->putColumn( *sharedFloatCol ) ;
1343    delete sharedFloatCol ;
1344    delete fCol ;
1345  }
1346  if ( mWeatherSel.tableDesc().isColumn( "WIND_DIRECTION" ) ) {
1347    fCol = new ScalarColumn<Float>( wtab, "WINDAZ" ) ;
1348    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "WIND_DIRECTION" ) ;
1349    fCol->putColumn( *sharedFloatCol ) ;
1350    delete sharedFloatCol ;
1351    delete fCol ;
1352  }
1353  ScalarColumn<uInt> idCol( wtab, "ID" ) ;
1354  for ( uInt irow = 0 ; irow < wnrow ; irow++ )
1355    idCol.put( irow, irow ) ;
1356
1357  ROScalarQuantColumn<Double> tqCol( mWeatherSel, "TIME" ) ;
1358  ROScalarColumn<Double> tCol( mWeatherSel, "TIME" ) ;
1359  String tUnit = tqCol.getUnits() ;
1360  mwTime_ = tCol.getColumn() ;
1361  if ( tUnit == "d" )
1362    mwTime_ *= 86400.0 ;
1363  tqCol.attach( mWeatherSel, "INTERVAL" ) ;
1364  tCol.attach( mWeatherSel, "INTERVAL" ) ;
1365  String iUnit = tqCol.getUnits() ;
1366  mwInterval_ = tCol.getColumn() ;
1367  if ( iUnit == "d" )
1368    mwInterval_ *= 86400.0 ;
1369  //os_ << "mwTime[0] = " << mwTime_[0] << " mwInterval[0] = " << mwInterval_[0] << LogIO::POST ;
1370//   double endSec = gettimeofday_sec() ;
1371//   os_ << "end MSFiller::fillWeather() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1372}
1373
1374void MSFiller::fillFocus()
1375{
1376//   double startSec = gettimeofday_sec() ;
1377//   os_ << "start MSFiller::fillFocus() startSec=" << startSec << LogIO::POST ;
1378  // tentative
1379  table_->focus().addEntry( 0.0, 0.0, 0.0, 0.0 ) ;
1380//   double endSec = gettimeofday_sec() ;
1381//   os_ << "end MSFiller::fillFocus() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1382}
1383
1384void MSFiller::fillTcal( boost::object_pool<ROTableColumn> *tpoolr )
1385{
1386//   double startSec = gettimeofday_sec() ;
1387//   os_ << "start MSFiller::fillTcal() startSec=" << startSec << LogIO::POST ;
1388
1389  if ( !isSysCal_ ) {
1390    // add dummy row
1391    os_ << "No SYSCAL rows" << LogIO::POST ;
1392    table_->tcal().table().addRow(1,True) ;
1393    Vector<Float> defaultTcal( 1, 1.0 ) ;
1394    ArrayColumn<Float> tcalCol( table_->tcal().table(), "TCAL" ) ;
1395    tcalCol.put( 0, defaultTcal ) ;
1396    return ;
1397  }
1398
1399  if ( colTcal_ == "NONE" ) {
1400    // add dummy row
1401    os_ << "No TCAL column" << LogIO::POST ;
1402    table_->tcal().table().addRow(1,True) ;
1403    Vector<Float> defaultTcal( 1, 1.0 ) ;
1404    ArrayColumn<Float> tcalCol( table_->tcal().table(), "TCAL" ) ;
1405    tcalCol.put( 0, defaultTcal ) ;
1406    return ;
1407  }
1408
1409  Table sctab = mstable_.sysCal() ;
1410  if ( sctab.nrow() == 0 ) {
1411    os_ << "No SYSCAL rows" << LogIO::POST ;
1412    return ;
1413  }
1414  Table sctabsel( sctab( sctab.col("ANTENNA_ID") == antenna_ ) ) ;
1415  if ( sctabsel.nrow() == 0 ) {
1416    os_ << "No SYSCAL rows" << LogIO::POST ;
1417    return ;
1418  }
1419  ROArrayColumn<Float> *tmpTcalCol = new ROArrayColumn<Float>( sctabsel, colTcal_ ) ;
1420  // return if any rows without Tcal value exists
1421  Bool notDefined = False ;
1422  for ( uInt irow = 0 ; irow < sctabsel.nrow() ; irow++ ) {
1423    if ( !tmpTcalCol->isDefined( irow ) ) {
1424      notDefined = True ;
1425      break ;
1426    }
1427  }
1428  if ( notDefined ) {
1429    os_ << "No TCAL value" << LogIO::POST ;
1430    delete tmpTcalCol ;
1431    table_->tcal().table().addRow(1,True) ;
1432    Vector<Float> defaultTcal( 1, 1.0 ) ;
1433    ArrayColumn<Float> tcalCol( table_->tcal().table(), "TCAL" ) ;
1434    tcalCol.put( 0, defaultTcal ) ;
1435    return ;
1436  }   
1437  uInt npol = tmpTcalCol->shape( 0 )(0) ;
1438  delete tmpTcalCol ;
1439  //os_ << "fillTcal(): npol = " << npol << LogIO::POST ;
1440  Table tab = table_->tcal().table() ;
1441  ArrayColumn<Float> tcalCol( tab, "TCAL" ) ;
1442  ROTableColumn *sharedCol ;
1443  uInt oldnr = 0 ;
1444  uInt newnr = 0 ;
1445  TableRow row( tab ) ;
1446  TableRecord &trec = row.record() ;
1447  RecordFieldPtr<uInt> idRF( trec, "ID" ) ;
1448  RecordFieldPtr<String> timeRF( trec, "TIME" ) ;
1449  RecordFieldPtr< Array<Float> > tcalRF( trec, "TCAL" ) ;
1450  TableIterator iter0( sctabsel, "FEED_ID" ) ;
1451  while( !iter0.pastEnd() ) {
1452    Table t0 = iter0.table() ;
1453    sharedCol = tpoolr->construct( t0, "FEED_ID" ) ;
1454    Int feedId = sharedCol->asInt( 0 ) ;
1455    tpoolr->destroy( sharedCol ) ;
1456    TableIterator iter1( t0, "SPECTRAL_WINDOW_ID" ) ;
1457    while( !iter1.pastEnd() ) {
1458      Table t1 = iter1.table() ;
1459      sharedCol = tpoolr->construct( t1, "SPECTRAL_WINDOW_ID" ) ;
1460      Int spwId = sharedCol->asInt( 0 ) ;
1461      tpoolr->destroy( sharedCol ) ;
1462      tmpTcalCol = new ROArrayColumn<Float>( t1, colTcal_ ) ;
1463      ROScalarQuantColumn<Double> scTimeCol( t1, "TIME" ) ;
1464      Vector<uInt> idminmax( 2, oldnr ) ;
1465      for ( uInt irow = 0 ; irow < t1.nrow() ; irow++ ) {
1466        String sTime = MVTime( scTimeCol(irow) ).string( MVTime::YMD ) ;
1467        *timeRF = sTime ;
1468        uInt idx = oldnr ;
1469        Matrix<Float> subtcal = (*tmpTcalCol)( irow ) ;
1470        for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1471          *idRF = idx++ ;
1472          //*tcalRF = subtcal.row( ipol ) ;
1473          tcalRF.define( subtcal.row( ipol ) ) ;
1474
1475          // commit row
1476          tab.addRow() ;
1477          row.put( tab.nrow()-1 ) ;
1478
1479          newnr++ ;
1480        }
1481        idminmax[0] = oldnr ;
1482        idminmax[1] = newnr - 1 ;
1483        oldnr = newnr ;
1484
1485        String key = keyTcal( feedId, spwId, sTime ) ;
1486        tcalrec_.define( key, idminmax ) ;
1487      }
1488      delete tmpTcalCol ;
1489      iter1++ ;
1490    }
1491    iter0++ ;
1492  }
1493
1494  //tcalrec_.print( std::cout ) ;
1495//   double endSec = gettimeofday_sec() ;
1496//   os_ << "end MSFiller::fillTcal() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1497}
1498
1499uInt MSFiller::getWeatherId( uInt idx, Double wtime )
1500{
1501//   double startSec = gettimeofday_sec() ;
1502//   os_ << "start MSFiller::getWeatherId() startSec=" << startSec << LogIO::POST ;
1503  uInt nrow = mwTime_.size() ;
1504  if ( nrow < 2 )
1505    return 0 ;
1506  uInt wid = nrow ;
1507  for ( uInt i = idx ; i < nrow-1 ; i++ ) {
1508    Double tStart = mwTime_[i]-0.5*mwInterval_[i] ;
1509    // use of INTERVAL column is problematic
1510    // since there are "blank" time of weather monitoring
1511    //Double tEnd = tStart + mwInterval_[i] ;
1512    Double tEnd = mwTime_[i+1]-0.5*mwInterval_[i+1] ;
1513    //os_ << "tStart = " << tStart << " dtEnd = " << tEnd-tStart << " dwtime = " << wtime-tStart << LogIO::POST ;
1514    if ( wtime >= tStart && wtime <= tEnd ) {
1515      wid = i ;
1516      break ;
1517    }
1518  }
1519  if ( wid == nrow ) {
1520    uInt i = nrow - 1 ;
1521    Double tStart = mwTime_[i-1]+0.5*mwInterval_[i-1] ;
1522    Double tEnd = mwTime_[i]+0.5*mwInterval_[i] ;
1523    //os_ << "tStart = " << tStart << " dtEnd = " << tEnd-tStart << " dwtime = " << wtime-tStart << LogIO::POST ;
1524    if ( wtime >= tStart && wtime <= tEnd )
1525      wid = i-1 ;
1526    else
1527      wid = i ;
1528  }
1529
1530  //if ( wid == nrow )
1531  //os_ << LogIO::WARN << "Couldn't find correct WEATHER_ID for time " << wtime << LogIO::POST ;
1532
1533//   double endSec = gettimeofday_sec() ;
1534//   os_ << "end MSFiller::getWeatherId() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1535  return wid ;
1536}
1537
1538void MSFiller::getSysCalTime( Vector<MEpoch> &scTime, Vector<Double> &scInterval, Block<MEpoch> &tcol, Block<Int> &tidx )
1539{
1540//   double startSec = gettimeofday_sec() ;
1541//   os_ << "start MSFiller::getSysCalTime() startSec=" << startSec << LogIO::POST ;
1542
1543  if ( !isSysCal_ )
1544    return ;
1545
1546  uInt nrow = tidx.nelements() ;
1547  if ( scTime.nelements() == 0 )
1548    return ;
1549  else if ( scTime.nelements() == 1 ) {
1550    tidx[0] = 0 ;
1551    return ;
1552  }
1553  uInt scnrow = scTime.nelements() ;
1554  uInt idx = 0 ;
1555  const Double half = 0.5e0 ;
1556  // execute  binary search
1557  idx = binarySearch( scTime, tcol[0].get( "s" ).getValue() ) ;
1558  if ( idx != 0 )
1559    idx -= 1 ;
1560  for ( uInt i = 0 ; i < nrow ; i++ ) {
1561    Double t = tcol[i].get( "s" ).getValue() ;
1562    Double tsc = scTime[0].get( "s" ).getValue() ;
1563    if ( t < tsc ) {
1564      tidx[i] = 0 ;
1565      continue ;
1566    }
1567    for ( uInt j = idx ; j < scnrow-1 ; j++ ) {
1568      Double tsc1 = scTime[j].get( "s" ).getValue() ;
1569      Double dt1 = scInterval[j] ;
1570      Double tsc2 = scTime[j+1].get( "s" ).getValue() ;
1571      Double dt2 = scInterval[j+1] ;
1572      if ( t > tsc1-half*dt1 && t <= tsc2-half*dt2 ) {
1573        tidx[i] = j ;
1574        idx = j ;
1575        break ;
1576      }
1577    }
1578    if ( tidx[i] == -1 ) {
1579//       Double tsc = scTime[scnrow-1].get( "s" ).getValue() ;
1580//       Double dt = scInterval[scnrow-1] ;
1581//       if ( t <= tsc+0.5*dt ) {
1582//         tidx[i] = scnrow-1 ;
1583//       }
1584      tidx[i] = scnrow-1 ;
1585    }
1586  }
1587//   double endSec = gettimeofday_sec() ;
1588//   os_ << "end MSFiller::getSysCalTime() endSec=" << endSec << " (" << endSec-startSec << "sec) scnrow = " << scnrow << " tcol.nelements = " << tcol.nelements() << LogIO::POST ;
1589  return ;
1590}
1591
1592Block<uInt> MSFiller::getTcalId( Int fid, Int spwid, MEpoch &t )
1593{
1594//   double startSec = gettimeofday_sec() ;
1595//   os_ << "start MSFiller::getTcalId() startSec=" << startSec << LogIO::POST ;
1596  //if ( table_->tcal().table().nrow() == 0 ) {
1597  if ( !isSysCal_ ) {
1598    os_ << "No TCAL rows" << LogIO::POST ;
1599    Block<uInt> tcalids( 4, 0 ) ;
1600    return  tcalids ;
1601  }   
1602  //String sctime = MVTime( Quantum<Double>(t,"s") ).string(MVTime::YMD) ;
1603  String sctime = MVTime( t.getValue() ).string(MVTime::YMD) ;
1604  String key = keyTcal( fid, spwid, sctime ) ;
1605  if ( !tcalrec_.isDefined( key ) ) {
1606    os_ << "No TCAL rows" << LogIO::POST ;
1607    Block<uInt> tcalids( 4, 0 ) ;
1608    return tcalids ;
1609  }
1610  Vector<uInt> ids = tcalrec_.asArrayuInt( key ) ;
1611  uInt npol = ids[1] - ids[0] + 1 ;
1612  Block<uInt> tcalids( npol ) ;
1613  tcalids[0] = ids[0] ;
1614  tcalids[1] = ids[1] ;
1615  for ( uInt ipol = 2 ; ipol < npol ; ipol++ )
1616    tcalids[ipol] = ids[0] + ipol - 1 ;
1617
1618//   double endSec = gettimeofday_sec() ;
1619//   os_ << "end MSFiller::getTcalId() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1620  return tcalids ;
1621}
1622
1623uInt MSFiller::getDirection( uInt idx, Vector<Double> &dir, Vector<Double> &srate, String &ref, MSPointing &tab, Double t )
1624{
1625//   double startSec = gettimeofday_sec() ;
1626//   os_ << "start MSFiller::getDirection() startSec=" << startSec << LogIO::POST ;
1627  // assume that cols is sorted by TIME
1628  Bool doInterp = False ;
1629  //uInt nrow = cols.nrow() ;
1630  uInt nrow = tab.nrow() ;
1631  if ( nrow == 0 )
1632    return 0 ;
1633  ROScalarMeasColumn<MEpoch> tcol( tab, "TIME" ) ;
1634  ROArrayMeasColumn<MDirection> dmcol( tab, "DIRECTION" ) ;
1635  ROArrayColumn<Double> dcol( tab, "DIRECTION" ) ;
1636  // binary search if idx == 0
1637  if ( idx == 0 ) {
1638    uInt nrowb = 75000 ;
1639    if ( nrow > nrowb ) {
1640      uInt nblock = nrow / nrowb + 1 ;
1641      for ( uInt iblock = 0 ; iblock < nblock ; iblock++ ) {
1642        uInt high = min( nrowb, nrow-iblock*nrowb ) ;
1643
1644        if ( tcol( high-1 ).get( "s" ).getValue() < t ) {
1645          idx = iblock * nrowb ;
1646          continue ;
1647        }
1648
1649        Vector<MEpoch> tarr( high ) ;
1650        for ( uInt irow = 0 ; irow < high ; irow++ ) {
1651          tarr[irow] = tcol( iblock*nrowb+irow ) ;
1652        }
1653
1654        uInt bidx = binarySearch( tarr, t ) ;
1655
1656        idx = iblock * nrowb + bidx ;
1657        break ;
1658      }
1659    }
1660    else {
1661      Vector<MEpoch> tarr( nrow ) ;
1662      for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1663        tarr[irow] = tcol( irow ) ;
1664      }
1665      idx = binarySearch( tarr, t ) ;
1666    }
1667  }
1668  // ensure that tcol(idx) < t
1669  //os_ << "tcol(idx) = " << tcol(idx).get("s").getValue() << " t = " << t << " diff = " << tcol(idx).get("s").getValue()-t << endl ;
1670  while ( tcol(idx).get("s").getValue() > t && idx > 0 )
1671    idx-- ;
1672  //os_ << "idx = " << idx << LogIO::POST ;
1673
1674  // index search
1675  for ( uInt i = idx ; i < nrow ; i++ ) {
1676    Double tref = tcol( i ).get( "s" ).getValue() ;
1677    if ( tref == t ) {
1678      idx = i ;
1679      break ;
1680    }
1681    else if ( tref > t ) {
1682      if ( i == 0 ) {
1683        idx = i ;
1684      }
1685      else {
1686        idx = i-1 ;
1687        doInterp = True ;
1688      }
1689      break ;
1690    }
1691    else {
1692      idx = nrow - 1 ;
1693    }
1694  }
1695  //os_ << "searched idx = " << idx << LogIO::POST ;
1696
1697  //os_ << "dmcol(idx).shape() = " << dmcol(idx).shape() << LogIO::POST ;
1698  IPosition ip( dmcol(idx).shape().nelements(), 0 ) ;
1699  //os_ << "ip = " << ip << LogIO::POST ;
1700  ref = dmcol(idx)(ip).getRefString() ;
1701  //os_ << "ref = " << ref << LogIO::POST ;
1702  if ( doInterp ) {
1703    //os_ << "do interpolation" << LogIO::POST ;
1704    //os_ << "dcol(idx).shape() = " << dcol(idx).shape() << LogIO::POST ;
1705    Double tref0 = tcol(idx).get("s").getValue() ;
1706    Double tref1 = tcol(idx+1).get("s").getValue() ;
1707    Matrix<Double> mdir0 = dcol( idx ) ;
1708    Matrix<Double> mdir1 = dcol( idx+1 ) ;
1709    Vector<Double> dir0 = mdir0.column( 0 ) ;
1710    //os_ << "dir0 = " << dir0 << LogIO::POST ;
1711    Vector<Double> dir1 = mdir1.column( 0 ) ;
1712    //os_ << "dir1 = " << dir1 << LogIO::POST ;
1713    Double dt0 = t - tref0 ;
1714    Double dt1 = tref1 - t ;
1715    dir.reference( (dt0*dir1+dt1*dir0)/(dt0+dt1) ) ;
1716    if ( mdir0.ncolumn() > 1 ) {
1717      if ( dt0 >= dt1 )
1718        srate.reference( mdir0.column( 1 ) ) ;
1719      else
1720        srate.reference( mdir1.column( 1 ) ) ;
1721    }
1722    //os_ << "dir = " << dir << LogIO::POST ;
1723  }
1724  else {
1725    //os_ << "no interpolation" << LogIO::POST ;
1726    Matrix<Double> mdir0 = dcol( idx ) ;
1727    dir.reference( mdir0.column( 0 ) ) ;
1728    if ( mdir0.ncolumn() > 1 )
1729      srate.reference( mdir0.column( 1 ) ) ;
1730  }
1731
1732//   double endSec = gettimeofday_sec() ;
1733//   os_ << "end MSFiller::getDirection() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1734  return idx ;
1735}
1736
1737String MSFiller::keyTcal( Int feedid, Int spwid, String stime )
1738{
1739  String sfeed = "FEED" + String::toString( feedid ) ;
1740  String sspw = "SPW" + String::toString( spwid ) ;
1741  return sfeed+":"+sspw+":"+stime ;
1742}
1743
1744uInt MSFiller::binarySearch( Vector<MEpoch> &timeList, Double target )
1745{
1746  Int low = 0 ;
1747  Int high = timeList.nelements() ;
1748  uInt idx = 0 ;
1749
1750  while ( low <= high ) {
1751    idx = (Int)( 0.5 * ( low + high ) ) ;
1752    Double t = timeList[idx].get( "s" ).getValue() ;
1753    if ( t < target )
1754      low = idx + 1 ;
1755    else if ( t > target )
1756      high = idx - 1 ;
1757    else
1758      return idx ;
1759  }
1760
1761  idx = max( 0, min( low, high ) ) ;
1762
1763  return idx ;
1764 
1765}
1766
1767string MSFiller::getFrame()
1768{
1769  MFrequency::Types frame = MFrequency::DEFAULT ;
1770  ROTableColumn numChanCol( mstable_.spectralWindow(), "NUM_CHAN" ) ;
1771  ROTableColumn measFreqRefCol( mstable_.spectralWindow(), "MEAS_FREQ_REF" ) ;
1772  uInt nrow = numChanCol.nrow() ;
1773  Vector<Int> measFreqRef( nrow, MFrequency::DEFAULT ) ;
1774  uInt nref = 0 ;
1775  for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1776    if ( numChanCol.asInt( irow ) != 4 ) { // exclude WVR
1777      measFreqRef[nref] = measFreqRefCol.asInt( irow ) ;
1778      nref++ ;
1779    }
1780  }
1781  if ( nref > 0 )
1782    frame = (MFrequency::Types)measFreqRef[0] ;
1783
1784  return MFrequency::showType( frame ) ;
1785}
1786} ;
1787
Note: See TracBrowser for help on using the repository browser.