source: trunk/src/MSFiller.cpp @ 2223

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

Excludes WVR spectral window to evaluate bandwidth and reference frequency
in MAIN table keyword.


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