source: trunk/src/MSFiller.cpp @ 2234

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

Consider weather station when filling weather table.


File size: 65.9 KB
Line 
1//
2// C++ Interface: MSFiller
3//
4// Description:
5//
6// This class is specific filler for MS format
7//
8// Takeshi Nakazato <takeshi.nakazato@nao.ac.jp>, (C) 2010
9//
10// Copyright: See COPYING file that comes with this distribution
11//
12//
13
14#include <iostream>
15#include <map>
16
17#include <tables/Tables/ExprNode.h>
18#include <tables/Tables/TableIter.h>
19#include <tables/Tables/TableColumn.h>
20#include <tables/Tables/ScalarColumn.h>
21#include <tables/Tables/ArrayColumn.h>
22#include <tables/Tables/TableParse.h>
23#include <tables/Tables/TableRow.h>
24
25#include <casa/Containers/RecordField.h>
26#include <casa/Logging/LogIO.h>
27#include <casa/Arrays/Slicer.h>
28#include <casa/Quanta/MVTime.h>
29#include <casa/OS/Path.h>
30
31#include <measures/Measures/Stokes.h>
32#include <measures/Measures/MEpoch.h>
33#include <measures/Measures/MCEpoch.h>
34#include <measures/Measures/MFrequency.h>
35#include <measures/Measures/MCFrequency.h>
36#include <measures/Measures/MPosition.h>
37#include <measures/Measures/MCPosition.h>
38#include <measures/Measures/MDirection.h>
39#include <measures/Measures/MCDirection.h>
40#include <measures/Measures/MeasConvert.h>
41#include <measures/TableMeasures/ScalarMeasColumn.h>
42#include <measures/TableMeasures/ArrayMeasColumn.h>
43#include <measures/TableMeasures/ScalarQuantColumn.h>
44#include <measures/TableMeasures/ArrayQuantColumn.h>
45
46#include <ms/MeasurementSets/MSAntennaIndex.h>
47
48#include <atnf/PKSIO/SrcType.h>
49
50#include "MSFiller.h"
51#include "STHeader.h"
52
53#include <ctime>
54#include <sys/time.h>
55
56using namespace casa ;
57using namespace std ;
58
59namespace asap {
60double MSFiller::gettimeofday_sec()
61{
62  struct timeval tv ;
63  gettimeofday( &tv, NULL ) ;
64  return tv.tv_sec + (double)tv.tv_usec*1.0e-6 ;
65}
66
67MSFiller::MSFiller( casa::CountedPtr<Scantable> stable )
68  : table_( stable ),
69    tablename_( "" ),
70    antenna_( -1 ),
71    antennaStr_(""),
72    getPt_( True ),
73    isFloatData_( False ),
74    isData_( False ),
75    isDoppler_( False ),
76    isFlagCmd_( False ),
77    isFreqOffset_( False ),
78    isHistory_( False ),
79    isProcessor_( False ),
80    isSysCal_( False ),
81    isWeather_( False ),
82    colTsys_( "TSYS_SPECTRUM" ),
83    colTcal_( "TCAL_SPECTRUM" )
84{
85  os_ = LogIO() ;
86  os_.origin( LogOrigin( "MSFiller", "MSFiller()", WHERE ) ) ;
87}
88
89MSFiller::~MSFiller()
90{
91  os_.origin( LogOrigin( "MSFiller", "~MSFiller()", WHERE ) ) ;
92}
93
94bool MSFiller::open( const std::string &filename, const casa::Record &rec )
95{
96  os_.origin( LogOrigin( "MSFiller", "open()", WHERE ) ) ;
97//   double startSec = gettimeofday_sec() ;
98//   os_ << "start MSFiller::open() startsec=" << startSec << LogIO::POST ;
99  //os_ << "   filename = " << filename << endl ;
100
101  // parsing MS options
102  if ( rec.isDefined( "ms" ) ) {
103    Record msrec = rec.asRecord( "ms" ) ;
104    if ( msrec.isDefined( "getpt" ) ) {
105      getPt_ = msrec.asBool( "getpt" ) ;
106    }
107    if ( msrec.isDefined( "antenna" ) ) {
108      if ( msrec.type( msrec.fieldNumber( "antenna" ) ) == TpInt ) {
109        antenna_ = msrec.asInt( "antenna" ) ;
110      }
111      else {
112        //antenna_ = atoi( msrec.asString( "antenna" ).c_str() ) ;
113        antennaStr_ = msrec.asString( "antenna" ) ;
114      }
115    }
116    else {
117      antenna_ = 0 ;
118    }
119  }
120
121  MeasurementSet *tmpMS = new MeasurementSet( filename, Table::Old ) ;
122  //mstable_ = (*tmpMS)( tmpMS->col("ANTENNA1") == antenna_
123  //                     && tmpMS->col("ANTENNA1") == tmpMS->col("ANTENNA2") ) ;
124  tablename_ = tmpMS->tableName() ;
125  if ( antenna_ == -1 && antennaStr_.size() > 0 ) {
126    MSAntennaIndex msAntIdx( tmpMS->antenna() ) ;
127    Vector<Int> id = msAntIdx.matchAntennaName( antennaStr_ ) ;
128    if ( id.size() > 0 )
129      antenna_ = id[0] ;
130  }
131
132  os_ << "Parsing MS options" << endl ;
133  os_ << "   getPt = " << getPt_ << endl ;
134  os_ << "   antenna = " << antenna_ << endl ;
135  os_ << "   antennaStr = " << antennaStr_ << LogIO::POST ;
136
137  mstable_ = MeasurementSet( (*tmpMS)( tmpMS->col("ANTENNA1") == antenna_
138                                       && tmpMS->col("ANTENNA1") == tmpMS->col("ANTENNA2") ) ) ;
139//   stringstream ss ;
140//   ss << "SELECT FROM $1 WHERE ANTENNA1 == ANTENNA2 && ANTENNA1 == " << antenna_ ;
141//   String taql( ss.str() ) ;
142//   mstable_ = MeasurementSet( tableCommand( taql, *tmpMS ) ) ;
143  delete tmpMS ;
144
145  // check which data column exists
146  isFloatData_ = mstable_.tableDesc().isColumn( "FLOAT_DATA" ) ;
147  isData_ = mstable_.tableDesc().isColumn( "DATA" ) ;
148
149//   double endSec = gettimeofday_sec() ;
150//   os_ << "end MSFiller::open() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
151  return true ;
152}
153
154void MSFiller::fill()
155{
156  os_.origin( LogOrigin( "MSFiller", "fill()", WHERE ) ) ;
157//   double startSec = gettimeofday_sec() ;
158//   os_ << "start MSFiller::fill() startSec=" << startSec << LogIO::POST ;
159
160//   double time0 = gettimeofday_sec() ;
161//   os_ << "start init fill: " << time0 << LogIO::POST ;
162
163  // Initialize header
164  STHeader sdh ; 
165  sdh.nchan = 0 ;
166  sdh.npol = 0 ;
167  sdh.nif = 0 ;
168  sdh.nbeam = 0 ;
169  sdh.observer = "" ;
170  sdh.project = "" ;
171  sdh.obstype = "" ;
172  sdh.antennaname = "" ;
173  sdh.antennaposition.resize( 0 ) ;
174  sdh.equinox = 0.0 ;
175  sdh.freqref = "" ;
176  sdh.reffreq = -1.0 ;
177  sdh.bandwidth = 0.0 ;
178  sdh.utc = 0.0 ;
179  sdh.fluxunit = "" ;
180  sdh.epoch = "" ;
181  sdh.poltype = "" ;
182 
183  // check if optional table exists
184  //const TableRecord msrec = tablesel_.keywordSet() ;
185  const TableRecord msrec = mstable_.keywordSet() ;
186  isDoppler_ = msrec.isDefined( "DOPPLER" ) ;
187  if ( isDoppler_ )
188    if ( mstable_.doppler().nrow() == 0 )
189      isDoppler_ = False ;
190  isFlagCmd_ = msrec.isDefined( "FLAG_CMD" ) ;
191  if ( isFlagCmd_ )
192    if ( mstable_.flagCmd().nrow() == 0 )
193      isFlagCmd_ = False ;
194  isFreqOffset_ = msrec.isDefined( "FREQ_OFFSET" ) ;
195  if ( isFreqOffset_ )
196    if ( mstable_.freqOffset().nrow() == 0 )
197      isFreqOffset_ = False ;
198  isHistory_ = msrec.isDefined( "HISTORY" ) ;
199  if ( isHistory_ )
200    if ( mstable_.history().nrow() == 0 )
201      isHistory_ = False ;
202  isProcessor_ = msrec.isDefined( "PROCESSOR" ) ;
203  if ( isProcessor_ )
204    if ( mstable_.processor().nrow() == 0 )
205      isProcessor_ = False ;
206  isSysCal_ = msrec.isDefined( "SYSCAL" ) ;
207  if ( isSysCal_ )
208    if ( mstable_.sysCal().nrow() == 0 )
209      isSysCal_ = False ;
210  isWeather_ = msrec.isDefined( "WEATHER" ) ;
211  if ( isWeather_ )
212    if ( mstable_.weather().nrow() == 0 )
213      isWeather_ = False ;
214
215  // Access to MS subtables
216  MSField fieldtab = mstable_.field() ;
217  MSPolarization poltab = mstable_.polarization() ;
218  MSDataDescription ddtab = mstable_.dataDescription() ;
219  MSObservation obstab = mstable_.observation() ;
220  MSSource srctab = mstable_.source() ;
221  MSSpectralWindow spwtab = mstable_.spectralWindow() ;
222  MSSysCal caltab = mstable_.sysCal() ;
223  if ( caltab.nrow() == 0 )
224    isSysCal_ = False ;
225  else {
226    if ( !caltab.tableDesc().isColumn( colTcal_ ) ) {
227      colTcal_ = "TCAL" ;
228      if ( !caltab.tableDesc().isColumn( colTcal_ ) )
229        colTcal_ = "NONE" ;
230    }
231    if ( !caltab.tableDesc().isColumn( colTsys_ ) ) {
232      colTsys_ = "TSYS" ;
233      if ( !caltab.tableDesc().isColumn( colTcal_ ) )
234        colTsys_ = "NONE" ;
235    }
236  }
237//   colTcal_ = "TCAL" ;
238//   colTsys_ = "TSYS" ;
239  MSPointing pointtab = mstable_.pointing() ;
240  if ( mstable_.weather().nrow() == 0 )
241    isWeather_ = False ;
242  MSState stattab = mstable_.state() ;
243  MSAntenna anttab = mstable_.antenna() ;
244
245  // TEST
246  // memory allocation by boost::object_pool
247  boost::object_pool<ROTableColumn> *tpoolr = new boost::object_pool<ROTableColumn> ;
248  //
249
250  // SUBTABLES: FREQUENCIES
251  //string freqFrame = getFrame() ;
252  string freqFrame = "LSRK" ;
253  table_->frequencies().setFrame( freqFrame ) ;
254  table_->frequencies().setFrame( freqFrame, True ) ;
255
256  // SUBTABLES: WEATHER
257  fillWeather() ;
258
259  // SUBTABLES: FOCUS
260  fillFocus() ;
261
262  // SUBTABLES: TCAL
263  fillTcal( tpoolr ) ;
264
265  // SUBTABLES: FIT
266  //fillFit() ;
267
268  // SUBTABLES: HISTORY
269  //fillHistory() ;
270
271  // shared pointers
272  ROTableColumn *tcolr ;
273
274  // MAIN
275  // Iterate over several ids
276  map<Int, uInt> ifmap ; // (IFNO, FREQ_ID) pair
277  ROArrayQuantColumn<Double> *sharedQDArrCol = new ROArrayQuantColumn<Double>( anttab, "POSITION" ) ;
278  Vector< Quantum<Double> > antpos = (*sharedQDArrCol)( antenna_ ) ;
279  delete sharedQDArrCol ;
280  MPosition mp( MVPosition( antpos ), MPosition::ITRF ) ;
281  if ( getPt_ ) {
282    //pointtab = pointtab( pointtab.col("ANTENNA_ID")==antenna_ ).sort("TIME") ;
283    pointtab = MSPointing( pointtab( pointtab.col("ANTENNA_ID")==antenna_ ).sort("TIME") ) ;
284  }
285  tcolr = tpoolr->construct( anttab, "STATION" ) ;
286  String stationName = tcolr->asString( antenna_ ) ;
287  tpoolr->destroy( tcolr ) ;
288  tcolr = tpoolr->construct( anttab, "NAME" ) ;
289  String antennaName = tcolr->asString( antenna_ ) ;
290  tpoolr->destroy( tcolr ) ;
291  sdh.antennaposition.resize( 3 ) ;
292  for ( int i = 0 ; i < 3 ; i++ )
293    sdh.antennaposition[i] = antpos[i].getValue( "m" ) ;
294  String telescopeName = "" ;
295
296//   double time1 = gettimeofday_sec() ;
297//   os_ << "end fill init: " << time1 << " (" << time1-time0 << "sec)" << LogIO::POST ;
298
299  // row based
300  Table &stab = table_->table() ;
301  TableRow row( stab ) ;
302  TableRecord &trec = row.record() ;
303  RecordFieldPtr< Array<Float> > spRF( trec, "SPECTRA" ) ;
304  RecordFieldPtr< Array<uChar> > ucarrRF( trec, "FLAGTRA" ) ;
305  RecordFieldPtr<Double> timeRF( trec, "TIME" ) ;
306  RecordFieldPtr< Array<Float> > tsysRF( trec, "TSYS" ) ;
307  RecordFieldPtr<Double> intervalRF( trec, "INTERVAL" ) ;
308  RecordFieldPtr< Array<Double> > dirRF( trec, "DIRECTION" ) ;
309  RecordFieldPtr<Float> azRF( trec, "AZIMUTH" ) ;
310  RecordFieldPtr<Float> elRF( trec, "ELEVATION" ) ;
311  RecordFieldPtr< Array<Double> > scrRF( trec, "SCANRATE" ) ;
312  RecordFieldPtr<uInt> cycleRF( trec, "CYCLENO" ) ;
313  RecordFieldPtr<uInt> flrRF( trec, "FLAGROW" ) ;
314  RecordFieldPtr<uInt> tcalidRF( trec, "TCAL_ID" ) ;
315  RecordFieldPtr<uInt> widRF( trec, "WEATHER_ID" ) ;
316  RecordFieldPtr<uInt> polnoRF( trec, "POLNO" ) ;
317
318
319  // REFBEAMNO
320  RecordFieldPtr<Int> intRF( trec, "REFBEAMNO" ) ;
321  *intRF = -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 = mwIndex_[wid] ;
858                }
859                else {
860                  *widRF = wid ;
861                }
862                 
863
864                // DIRECTION, AZEL, SCANRATE
865                if ( getPt_ ) {
866                  Vector<Double> dir ;
867                  Vector<Double> scanrate ;
868                  String refString ;
869                  diridx = getDirection( diridx, dir, scanrate, refString, pointtab, mTimeB[irow].get("s").getValue() ) ;
870                  MDirection::getType( dirType, refString ) ;
871                  MeasFrame mf( mTimeB[irow], mp ) ;
872                  //mf.resetEpoch( mTimeB[irow] ) ;
873                  //mf.resetDirection( MDirection( MVDirection(dir), dirType ) ) ;
874                  if ( refString == "J2000" ) {
875                    *dirRF = dir ;
876                    MDirection::Convert toazel( dirType, MDirection::Ref( MDirection::AZEL, mf ) ) ;
877                    Vector<Double> azel = toazel( dir ).getAngle("rad").getValue() ;
878                    *azRF = (Float)azel(0) ;
879                    *elRF = (Float)azel(1) ;
880                  }
881                  else if ( refString(0,4) == "AZEL" ) {
882                    *azRF = (Float)dir(0) ;
883                    *elRF = (Float)dir(1) ;
884                    MDirection::Convert toj2000( dirType, MDirection::Ref( MDirection::J2000, mf ) ) ;
885                    Vector<Double> newdir = toj2000( dir ).getAngle("rad").getValue() ;
886                    *dirRF = newdir ;
887                  }
888                  else {
889                    MDirection::Convert toazel( dirType, MDirection::Ref( MDirection::AZEL, mf ) ) ;
890                    Vector<Double> azel = toazel( dir ).getAngle("rad").getValue() ;
891                    MDirection::Convert toj2000( dirType, MDirection::Ref( MDirection::J2000, mf ) ) ;
892                    Vector<Double> newdir = toj2000( dir ).getAngle("rad").getValue() ;
893                    *dirRF = newdir ;
894                    *azRF = (Float)azel(0) ;
895                    *elRF = (Float)azel(1) ;
896                  }
897                  if ( scanrate.size() != 0 ) {
898                    *scrRF = scanrate ;
899                  }
900                  else {
901                    *scrRF = defaultScanrate ;
902                  }
903                }
904                else {
905                  String ref = md.getRefString() ;
906                  //Vector<Double> defaultDir = srcDir ;
907                  MDirection::getType( dirType, "J2000" ) ;
908                  MeasFrame mf( mTimeB[irow], mp ) ;
909                  if ( ref != "J2000" ) {
910                    ROScalarMeasColumn<MEpoch> tmCol( pointtab, "TIME" ) ;
911                    mf.resetEpoch( tmCol( 0 ) ) ;
912                    MDirection::Convert toj2000( dirType, MDirection::Ref( MDirection::J2000, mf ) ) ;
913                    defaultDir = toj2000( defaultDir ).getAngle("rad").getValue() ;
914                  }
915                  mf.resetEpoch( mTimeB[irow] ) ;
916                  MDirection::Convert toazel( dirType, MDirection::Ref( MDirection::AZEL, mf ) ) ;
917                  Vector<Double> azel = toazel( defaultDir ).getAngle("rad").getValue() ;
918                  *azRF = (Float)azel(0) ;
919                  *elRF = (Float)azel(1) ;
920                  *dirRF = defaultDir ;
921                  *scrRF = defaultScanrate ;
922                }
923
924                // Polarization dependent things
925                for ( Int ipol = 0 ; ipol < npol ; ipol++ ) {
926                  // POLNO
927                  *polnoRF = polnos[ipol] ;
928
929                  //*spRF = sp.row( ipol ) ;
930                  //*ucarrRF = fl.row( ipol ) ;
931                  //*tsysRF = tsys.row( ipol ) ;
932                  spRF.define( sp.row( ipol ) ) ;
933                  ucarrRF.define( fl.row( ipol ) ) ;
934                  tsysRF.define( tsys.row( ipol ) ) ;
935                  *tcalidRF = tcalids[ipol] ;
936
937                  // Commit row
938                  stab.addRow() ;
939                  row.put( stab.nrow()-1 ) ;
940                }
941
942                cycle++ ;
943              }
944              tpoolr->destroy( mIntervalCol ) ;
945              tpoolr->destroy( mFlagRowCol ) ;
946
947//               time1 = gettimeofday_sec() ;
948//               os_ << "end 5th iteration: " << time1 << " (" << time1-time0 << "sec)" << LogIO::POST ;
949
950              iter5.next() ;
951            }
952
953
954            iter4.next() ;
955          }
956
957
958          iter3.next() ;
959        }
960
961             
962        iter2.next() ;
963      }
964
965
966      iter1.next() ;
967    }
968    if ( sdh.nbeam < nbeam ) sdh.nbeam = nbeam ;
969
970    iter0.next() ;
971  }
972
973
974  delete tpoolr ;
975
976
977  // Table Keywords
978  sdh.nif = ifmap.size() ;
979  if ( ( telescopeName == "" ) || ( antennaName == telescopeName ) ) {
980    sdh.antennaname = antennaName ;
981  }
982  else {
983    sdh.antennaname = telescopeName + "//" + antennaName ;
984  }
985  if ( stationName != "" && stationName != antennaName ) {
986    sdh.antennaname += "@" + stationName ;
987  }
988  ROArrayColumn<Double> pdirCol( pointtab, "DIRECTION" ) ;
989  String dirref = pdirCol.keywordSet().asRecord("MEASINFO").asString("Ref") ;
990  if ( dirref == "AZELGEO" || dirref == "AZEL" ) {
991    dirref = "J2000" ;
992  }
993  sscanf( dirref.chars()+1, "%f", &sdh.equinox ) ;
994  sdh.epoch = "UTC" ;
995  if (sdh.freqref == "TOPO") {
996    sdh.freqref = "TOPOCENT";
997  } else if (sdh.freqref == "GEO") {
998    sdh.freqref = "GEOCENTR";
999  } else if (sdh.freqref == "BARY") {
1000    sdh.freqref = "BARYCENT";
1001  } else if (sdh.freqref == "GALACTO") {
1002    sdh.freqref = "GALACTOC";
1003  } else if (sdh.freqref == "LGROUP") {
1004    sdh.freqref = "LOCALGRP";
1005  } else if (sdh.freqref == "CMB") {
1006    sdh.freqref = "CMBDIPOL";
1007  } else if (sdh.freqref == "REST") {
1008    sdh.freqref = "SOURCE";
1009  }
1010  //if ( sdh.fluxunit == "" )
1011  if ( sdh.fluxunit == "" || sdh.fluxunit == "CNTS" )
1012    sdh.fluxunit = "K" ;
1013  table_->setHeader( sdh ) ;
1014
1015  // save path to POINTING table
1016  // 2011/07/06 TN
1017  // Path to POINTING table in original MS will not be written
1018  // if getPt_ is True
1019  Path datapath( tablename_ ) ;
1020  if ( !getPt_ ) {
1021    String pTabName = datapath.absoluteName() + "/POINTING" ;
1022    stab.rwKeywordSet().define( "POINTING", pTabName ) ;
1023  }
1024
1025  // for GBT
1026  if ( antennaName.contains( "GBT" ) ) {
1027    String goTabName = datapath.absoluteName() + "/GBT_GO" ;
1028    stab.rwKeywordSet().define( "GBT_GO", goTabName ) ;
1029  }
1030
1031  // for MS created from ASDM
1032  //mstable_.keywordSet().print(cout) ;
1033  const TableRecord &msKeys = mstable_.keywordSet() ;
1034  uInt nfields = msKeys.nfields() ;
1035  for ( uInt ifield = 0 ; ifield < nfields ; ifield++ ) {
1036    String name = msKeys.name( ifield ) ;
1037    //os_ << "name = " << name << LogIO::POST ;
1038    if ( name.find( "ASDM" ) != String::npos ) {
1039      String asdmpath = msKeys.asTable( ifield ).tableName() ;
1040      os_ << "ASDM table: " << asdmpath << LogIO::POST ;
1041      stab.rwKeywordSet().define( name, asdmpath ) ;
1042    }
1043  }
1044
1045//   double endSec = gettimeofday_sec() ;
1046//   os_ << "end MSFiller::fill() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1047}
1048
1049void MSFiller::close()
1050{
1051  //tablesel_.closeSubTables() ;
1052  mstable_.closeSubTables() ;
1053  //tablesel_.unlock() ;
1054  mstable_.unlock() ;
1055}
1056
1057Int MSFiller::getSrcType( Int stateId, boost::object_pool<ROTableColumn> *tpool )
1058{
1059//   double startSec = gettimeofday_sec() ;
1060//   os_ << "start MSFiller::getSrcType() startSec=" << startSec << LogIO::POST ;
1061
1062  MSState statetab = mstable_.state() ;
1063  ROTableColumn *sharedCol ;
1064  sharedCol = tpool->construct( statetab, "OBS_MODE" ) ;
1065  String obsMode = sharedCol->asString( stateId ) ;
1066  tpool->destroy( sharedCol ) ;
1067  sharedCol = tpool->construct( statetab, "SIG" ) ;
1068  Bool sig = sharedCol->asBool( stateId ) ;
1069  tpool->destroy( sharedCol ) ;
1070  sharedCol = tpool->construct( statetab, "REF" ) ;
1071  Bool ref = sharedCol->asBool( stateId ) ;
1072  tpool->destroy( sharedCol ) ;
1073  sharedCol = tpool->construct( statetab, "CAL" ) ;
1074  Double cal = (Double)(sharedCol->asdouble( stateId )) ;
1075  tpool->destroy( sharedCol ) ;
1076  //os_ << "OBS_MODE = " << obsMode << LogIO::POST ;
1077
1078  // determine separator
1079  String sep = "" ;
1080  String tmpStr = obsMode.substr( 0, obsMode.find_first_of( "," ) ) ;
1081  //os_ << "tmpStr = " << tmpStr << LogIO::POST ;
1082  //if ( obsMode.find( ":" ) != String::npos ) {
1083  if ( tmpStr.find( ":" ) != String::npos ) {
1084    sep = ":" ;
1085  }
1086  //else if ( obsMode.find( "." ) != String::npos ) {
1087  else if ( tmpStr.find( "." ) != String::npos ) {
1088    sep = "." ;
1089  }
1090  else if ( tmpStr.find( "#" ) != String::npos ) {
1091    sep = "#" ;
1092  }
1093  //else if ( obsMode.find( "_" ) != String::npos ) {
1094  else if ( tmpStr.find( "_" ) != String::npos ) {
1095    sep = "_" ;
1096  }
1097  //os_ << "separator = " << sep << LogIO::POST ;
1098
1099  // determine SRCTYPE
1100  Int srcType = SrcType::NOTYPE ;
1101  if ( sep == ":" ) {
1102    // sep == ":"
1103    //
1104    // GBT case
1105    //
1106    // obsMode1=Nod
1107    //    NOD
1108    // obsMode1=OffOn
1109    //    obsMode2=PSWITCHON:  PSON
1110    //    obsMode2=PSWITCHOFF: PSOFF
1111    // obsMode1=??
1112    //    obsMode2=FSWITCH:
1113    //       SIG=1: FSON
1114    //       REF=1: FSOFF
1115    // Calibration scan if CAL != 0
1116    Int epos = obsMode.find_first_of( sep ) ;
1117    Int nextpos = obsMode.find_first_of( sep, epos+1 ) ;
1118    String obsMode1 = obsMode.substr( 0, epos ) ;
1119    String obsMode2 = obsMode.substr( epos+1, nextpos-epos-1 ) ;
1120    if ( obsMode1 == "Nod" ) {
1121      srcType = SrcType::NOD ;
1122    }
1123    else if ( obsMode1 == "OffOn" ) {
1124      if ( obsMode2 == "PSWITCHON" ) srcType = SrcType::PSON ;
1125      if ( obsMode2 == "PSWITCHOFF" ) srcType = SrcType::PSOFF ;
1126    }
1127    else {
1128      if ( obsMode2 == "FSWITCH" ) {
1129        if ( sig ) srcType = SrcType::FSON ;
1130        if ( ref ) srcType = SrcType::FSOFF ;
1131      }
1132    }
1133    if ( cal > 0.0 ) {
1134      if ( srcType == SrcType::NOD )
1135        srcType = SrcType::NODCAL ;
1136      else if ( srcType == SrcType::PSON )
1137        srcType = SrcType::PONCAL ;
1138      else if ( srcType == SrcType::PSOFF )
1139        srcType = SrcType::POFFCAL ;
1140      else if ( srcType == SrcType::FSON )
1141        srcType = SrcType::FONCAL ;
1142      else if ( srcType == SrcType::FSOFF )
1143        srcType = SrcType::FOFFCAL ;
1144      else
1145        srcType = SrcType::CAL ;
1146    }
1147  }
1148  else if ( sep == "." || sep == "#" ) {
1149    // sep == "." or "#"
1150    //
1151    // ALMA & EVLA case (MS via ASDM) before3.1
1152    //
1153    // obsMode1=CALIBRATE_*
1154    //    obsMode2=ON_SOURCE: PONCAL
1155    //    obsMode2=OFF_SOURCE: POFFCAL
1156    // obsMode1=OBSERVE_TARGET
1157    //    obsMode2=ON_SOURCE: PON
1158    //    obsMode2=OFF_SOURCE: POFF
1159    string substr[2] ;
1160    int numSubstr = split( obsMode, substr, 2, "," ) ;
1161    //os_ << "numSubstr = " << numSubstr << LogIO::POST ;
1162    //for ( int i = 0 ; i < numSubstr ; i++ )
1163    //os_ << "substr[" << i << "] = " << substr[i] << LogIO::POST ;
1164    String obsType( substr[0] ) ;
1165    //os_ << "obsType = " << obsType << LogIO::POST ;
1166    Int epos = obsType.find_first_of( sep ) ;
1167    Int nextpos = obsType.find_first_of( sep, epos+1 ) ;
1168    String obsMode1 = obsType.substr( 0, epos ) ;
1169    String obsMode2 = obsType.substr( epos+1, nextpos-epos-1 ) ;
1170    //os_ << "obsMode1 = " << obsMode1 << LogIO::POST ;
1171    //os_ << "obsMode2 = " << obsMode2 << LogIO::POST ;
1172    if ( obsMode1.find( "CALIBRATE_" ) == 0 ) {
1173      if ( obsMode2 == "ON_SOURCE" ) srcType = SrcType::PONCAL ;
1174      if ( obsMode2 == "OFF_SOURCE" ) srcType = SrcType::POFFCAL ;
1175    }
1176    else if ( obsMode1 == "OBSERVE_TARGET" ) {
1177      if ( obsMode2 == "ON_SOURCE" ) srcType = SrcType::PSON ;
1178      if ( obsMode2 == "OFF_SOURCE" ) srcType = SrcType::PSOFF ;
1179    }
1180  }
1181  else if ( sep == "_" ) {
1182    // sep == "_"
1183    //
1184    // ALMA & EVLA case (MS via ASDM) after 3.2
1185    //
1186    // obsMode1=CALIBRATE_*
1187    //    obsMode2=ON_SOURCE: PONCAL
1188    //    obsMode2=OFF_SOURCE: POFFCAL
1189    // obsMode1=OBSERVE_TARGET
1190    //    obsMode2=ON_SOURCE: PON
1191    //    obsMode2=OFF_SOURCE: POFF
1192    string substr[2] ;
1193    int numSubstr = split( obsMode, substr, 2, "," ) ;
1194    //os_ << "numSubstr = " << numSubstr << LogIO::POST ;
1195    //for ( int i = 0 ; i < numSubstr ; i++ )
1196    //os_ << "substr[" << i << "] = " << substr[i] << LogIO::POST ;
1197    String obsType( substr[0] ) ;
1198    //os_ << "obsType = " << obsType << LogIO::POST ;
1199    string substr2[4] ;
1200    int numSubstr2 = split( obsType, substr2, 4, sep ) ;
1201    //Int epos = obsType.find_first_of( sep ) ;
1202    //Int nextpos = obsType.find_first_of( sep, epos+1 ) ;
1203    //String obsMode1 = obsType.substr( 0, epos ) ;
1204    //String obsMode2 = obsType.substr( epos+1, nextpos-epos-1 ) ;
1205    String obsMode1( substr2[0] ) ;
1206    String obsMode2( substr2[2] ) ;
1207    //os_ << "obsMode1 = " << obsMode1 << LogIO::POST ;
1208    //os_ << "obsMode2 = " << obsMode2 << LogIO::POST ;
1209    if ( obsMode1.find( "CALIBRATE" ) == 0 ) {
1210      if ( obsMode2 == "ON" ) srcType = SrcType::PONCAL ;
1211      if ( obsMode2 == "OFF" ) srcType = SrcType::POFFCAL ;
1212    }
1213    else if ( obsMode1 == "OBSERVE" ) {
1214      if ( obsMode2 == "ON" ) srcType = SrcType::PSON ;
1215      if ( obsMode2 == "OFF" ) srcType = SrcType::PSOFF ;
1216    }
1217  }
1218  else {
1219    if ( sig ) srcType = SrcType::SIG ;
1220    if ( ref ) srcType = SrcType::REF ;
1221  }
1222   
1223  //os_ << "srcType = " << srcType << LogIO::POST ;
1224//   double endSec = gettimeofday_sec() ;
1225//   os_ << "end MSFiller::getSrcType() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1226  return srcType ;
1227}
1228
1229//Vector<uInt> MSFiller::getPolNo( Int corrType )
1230Block<uInt> MSFiller::getPolNo( Int corrType )
1231{
1232//   double startSec = gettimeofday_sec() ;
1233//   os_ << "start MSFiller::getPolNo() startSec=" << startSec << LogIO::POST ;
1234  Block<uInt> polno( 1 ) ;
1235
1236  if ( corrType == Stokes::I || corrType == Stokes::RR || corrType == Stokes::XX ) {
1237    polno = 0 ;
1238  }
1239  else if ( corrType == Stokes::Q || corrType == Stokes::LL || corrType == Stokes::YY ) {
1240    polno = 1 ;
1241  }
1242  else if ( corrType == Stokes::U ) {
1243    polno = 2 ;
1244  }
1245  else if ( corrType == Stokes::V ) {
1246    polno = 3 ;
1247  }
1248  else if ( corrType == Stokes::RL || corrType == Stokes::XY || corrType == Stokes::LR || corrType == Stokes::RL ) {
1249    polno.resize( 2 ) ;
1250    polno[0] = 2 ;
1251    polno[1] = 3 ;
1252  }
1253  else if ( corrType == Stokes::Plinear ) {
1254    polno[0] = 1 ;
1255  }
1256  else if ( corrType == Stokes::Pangle ) {
1257    polno[0] = 2 ;
1258  }
1259  else {
1260    polno = 99 ;
1261  }
1262  //os_ << "polno = " << polno << LogIO::POST ;
1263//   double endSec = gettimeofday_sec() ;
1264//   os_ << "end MSFiller::getPolNo() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1265 
1266  return polno ;
1267}
1268
1269String MSFiller::getPolType( Int corrType )
1270{
1271//   double startSec = gettimeofday_sec() ;
1272//   os_ << "start MSFiller::getPolType() startSec=" << startSec << LogIO::POST ;
1273  String poltype = "" ;
1274
1275  if ( corrType == Stokes::I || corrType == Stokes::Q || corrType == Stokes::U || corrType == Stokes::V )
1276    poltype = "stokes" ;
1277  else if ( corrType == Stokes::XX || corrType == Stokes::YY || corrType == Stokes::XY || corrType == Stokes::YX )
1278    poltype = "linear" ;
1279  else if ( corrType == Stokes::RR || corrType == Stokes::LL || corrType == Stokes::RL || corrType == Stokes::LR )
1280    poltype = "circular" ;
1281  else if ( corrType == Stokes::Plinear || corrType == Stokes::Pangle )
1282    poltype = "linpol" ;
1283
1284//   double endSec = gettimeofday_sec() ;
1285//   os_ << "end MSFiller::getPolType() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1286  return poltype ;
1287}
1288
1289void MSFiller::fillWeather()
1290{
1291//   double startSec = gettimeofday_sec() ;
1292//   os_ << "start MSFiller::fillWeather() startSec=" << startSec << LogIO::POST ;
1293
1294  if ( !isWeather_ ) {
1295    // add dummy row
1296    table_->weather().table().addRow(1,True) ;
1297    return ;
1298  }
1299
1300  Table mWeather = mstable_.weather()  ;
1301  //Table mWeatherSel = mWeather( mWeather.col("ANTENNA_ID") == antenna_ ).sort("TIME") ;
1302  Table mWeatherSel( mWeather( mWeather.col("ANTENNA_ID") == antenna_ ).sort("TIME") ) ;
1303  //os_ << "mWeatherSel.nrow() = " << mWeatherSel.nrow() << LogIO::POST ;
1304  if ( mWeatherSel.nrow() == 0 ) {
1305    os_ << "No rows with ANTENNA_ID = " << antenna_ << " in WEATHER table, Try -1..." << LogIO::POST ;
1306    mWeatherSel = Table( MSWeather( mWeather( mWeather.col("ANTENNA_ID") == -1 ) ) ) ;
1307    if ( mWeatherSel.nrow() == 0 ) {
1308      os_ << "No rows in WEATHER table" << LogIO::POST ;
1309    }
1310  }
1311  uInt wnrow = mWeatherSel.nrow() ;
1312  //os_ << "wnrow = " << wnrow << LogIO::POST ;
1313
1314  if ( wnrow == 0 )
1315    return ;
1316
1317  Table wtab = table_->weather().table() ;
1318  wtab.addRow( wnrow ) ;
1319
1320  Bool stationInfoExists = mWeatherSel.tableDesc().isColumn( "NS_WX_STATION_ID" ) ;
1321  Int stationId = -1 ;
1322  if ( stationInfoExists ) {
1323    // determine which station is closer
1324    ROScalarColumn<Int> stationCol( mWeatherSel, "NS_WX_STATION_ID" ) ;
1325    ROArrayColumn<Double> stationPosCol( mWeatherSel, "NS_WX_STATION_POSITION" ) ;
1326    Vector<Int> stationIds = stationCol.getColumn() ;
1327    Vector<Int> stationIdList( 0 ) ;
1328    Matrix<Double> stationPosList( 0, 3, 0.0 ) ;
1329    uInt numStation = 0 ;
1330    for ( uInt i = 0 ; i < stationIds.size() ; i++ ) {
1331      if ( !anyEQ( stationIdList, stationIds[i] ) ) {
1332        numStation++ ;
1333        stationIdList.resize( numStation, True ) ;
1334        stationIdList[numStation-1] = stationIds[i] ;
1335        stationPosList.resize( numStation, 3, True ) ;
1336        stationPosList.row( numStation-1 ) = stationPosCol( i ) ;
1337      }
1338    }
1339    //os_ << "staionIdList = " << stationIdList << endl ;
1340    Table mAntenna = mstable_.antenna() ;
1341    ROArrayColumn<Double> antposCol( mAntenna, "POSITION" ) ;
1342    Vector<Double> antpos = antposCol( antenna_ ) ;
1343    Double minDiff = -1.0 ;
1344    for ( uInt i = 0 ; i < stationIdList.size() ; i++ ) {
1345      Double diff = sum( square( antpos - stationPosList.row( i ) ) ) ;
1346      if ( minDiff < 0.0 || minDiff > diff ) {
1347        minDiff = diff ;
1348        stationId = stationIdList[i] ;
1349      }
1350    }
1351  }
1352  //os_ << "stationId = " << stationId << endl ;
1353 
1354  ScalarColumn<Float> *fCol ;
1355  ROScalarColumn<Float> *sharedFloatCol ;
1356  if ( mWeatherSel.tableDesc().isColumn( "TEMPERATURE" ) ) {
1357    fCol = new ScalarColumn<Float>( wtab, "TEMPERATURE" ) ;
1358    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "TEMPERATURE" ) ;
1359    fCol->putColumn( *sharedFloatCol ) ;
1360    delete sharedFloatCol ;
1361    delete fCol ;
1362  }
1363  if ( mWeatherSel.tableDesc().isColumn( "PRESSURE" ) ) {
1364    fCol = new ScalarColumn<Float>( wtab, "PRESSURE" ) ;
1365    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "PRESSURE" ) ;
1366    fCol->putColumn( *sharedFloatCol ) ;
1367    delete sharedFloatCol ;
1368    delete fCol ;
1369  }
1370  if ( mWeatherSel.tableDesc().isColumn( "REL_HUMIDITY" ) ) {
1371    fCol = new ScalarColumn<Float>( wtab, "HUMIDITY" ) ;
1372    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "REL_HUMIDITY" ) ;
1373    fCol->putColumn( *sharedFloatCol ) ;
1374    delete sharedFloatCol ;
1375    delete fCol ;
1376  }
1377  if ( mWeatherSel.tableDesc().isColumn( "WIND_SPEED" ) ) { 
1378    fCol = new ScalarColumn<Float>( wtab, "WINDSPEED" ) ;
1379    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "WIND_SPEED" ) ;
1380    fCol->putColumn( *sharedFloatCol ) ;
1381    delete sharedFloatCol ;
1382    delete fCol ;
1383  }
1384  if ( mWeatherSel.tableDesc().isColumn( "WIND_DIRECTION" ) ) {
1385    fCol = new ScalarColumn<Float>( wtab, "WINDAZ" ) ;
1386    sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "WIND_DIRECTION" ) ;
1387    fCol->putColumn( *sharedFloatCol ) ;
1388    delete sharedFloatCol ;
1389    delete fCol ;
1390  }
1391  ScalarColumn<uInt> idCol( wtab, "ID" ) ;
1392  for ( uInt irow = 0 ; irow < wnrow ; irow++ )
1393    idCol.put( irow, irow ) ;
1394
1395  ROScalarQuantColumn<Double> tqCol( mWeatherSel, "TIME" ) ;
1396  ROScalarColumn<Double> tCol( mWeatherSel, "TIME" ) ;
1397  String tUnit = tqCol.getUnits() ;
1398  Vector<Double> mwTime = tCol.getColumn() ;
1399  if ( tUnit == "d" )
1400    mwTime *= 86400.0 ;
1401  tqCol.attach( mWeatherSel, "INTERVAL" ) ;
1402  tCol.attach( mWeatherSel, "INTERVAL" ) ;
1403  String iUnit = tqCol.getUnits() ;
1404  Vector<Double> mwInterval = tCol.getColumn() ;
1405  if ( iUnit == "d" )
1406    mwInterval *= 86400.0 ;
1407
1408  if ( stationId > 0 ) {
1409    ROScalarColumn<Int> stationCol( mWeatherSel, "NS_WX_STATION_ID" ) ;
1410    Vector<Int> stationVec = stationCol.getColumn() ;
1411    uInt wsnrow = ntrue( stationVec == stationId ) ;
1412    mwTime_.resize( wsnrow ) ;
1413    mwInterval_.resize( wsnrow ) ;
1414    mwIndex_.resize( wsnrow ) ;
1415    uInt wsidx = 0 ;
1416    for ( uInt irow = 0 ; irow < wnrow ; irow++ ) {
1417      if ( stationId == stationVec[irow] ) {
1418        mwTime_[wsidx] = mwTime[irow] ;
1419        mwInterval_[wsidx] = mwInterval[irow] ;
1420        mwIndex_[wsidx] = irow ;
1421        wsidx++ ;
1422      }
1423    }
1424  }
1425  else {
1426    mwTime_ = mwTime ;
1427    mwInterval_ = mwInterval ;
1428    mwIndex_.resize( mwTime_.size() ) ;
1429    indgen( mwIndex_ ) ;
1430  }
1431  //os_ << "mwTime[0] = " << mwTime_[0] << " mwInterval[0] = " << mwInterval_[0] << LogIO::POST ;
1432//   double endSec = gettimeofday_sec() ;
1433//   os_ << "end MSFiller::fillWeather() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1434}
1435
1436void MSFiller::fillFocus()
1437{
1438//   double startSec = gettimeofday_sec() ;
1439//   os_ << "start MSFiller::fillFocus() startSec=" << startSec << LogIO::POST ;
1440  // tentative
1441  table_->focus().addEntry( 0.0, 0.0, 0.0, 0.0 ) ;
1442//   double endSec = gettimeofday_sec() ;
1443//   os_ << "end MSFiller::fillFocus() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1444}
1445
1446void MSFiller::fillTcal( boost::object_pool<ROTableColumn> *tpoolr )
1447{
1448//   double startSec = gettimeofday_sec() ;
1449//   os_ << "start MSFiller::fillTcal() startSec=" << startSec << LogIO::POST ;
1450
1451  if ( !isSysCal_ ) {
1452    // add dummy row
1453    os_ << "No SYSCAL rows" << LogIO::POST ;
1454    table_->tcal().table().addRow(1,True) ;
1455    Vector<Float> defaultTcal( 1, 1.0 ) ;
1456    ArrayColumn<Float> tcalCol( table_->tcal().table(), "TCAL" ) ;
1457    tcalCol.put( 0, defaultTcal ) ;
1458    return ;
1459  }
1460
1461  if ( colTcal_ == "NONE" ) {
1462    // add dummy row
1463    os_ << "No TCAL column" << LogIO::POST ;
1464    table_->tcal().table().addRow(1,True) ;
1465    Vector<Float> defaultTcal( 1, 1.0 ) ;
1466    ArrayColumn<Float> tcalCol( table_->tcal().table(), "TCAL" ) ;
1467    tcalCol.put( 0, defaultTcal ) ;
1468    return ;
1469  }
1470
1471  Table sctab = mstable_.sysCal() ;
1472  if ( sctab.nrow() == 0 ) {
1473    os_ << "No SYSCAL rows" << LogIO::POST ;
1474    return ;
1475  }
1476  Table sctabsel( sctab( sctab.col("ANTENNA_ID") == antenna_ ) ) ;
1477  if ( sctabsel.nrow() == 0 ) {
1478    os_ << "No SYSCAL rows" << LogIO::POST ;
1479    return ;
1480  }
1481  ROArrayColumn<Float> *tmpTcalCol = new ROArrayColumn<Float>( sctabsel, colTcal_ ) ;
1482  // return if any rows without Tcal value exists
1483  Bool notDefined = False ;
1484  for ( uInt irow = 0 ; irow < sctabsel.nrow() ; irow++ ) {
1485    if ( !tmpTcalCol->isDefined( irow ) ) {
1486      notDefined = True ;
1487      break ;
1488    }
1489  }
1490  if ( notDefined ) {
1491    os_ << "No TCAL value" << LogIO::POST ;
1492    delete tmpTcalCol ;
1493    table_->tcal().table().addRow(1,True) ;
1494    Vector<Float> defaultTcal( 1, 1.0 ) ;
1495    ArrayColumn<Float> tcalCol( table_->tcal().table(), "TCAL" ) ;
1496    tcalCol.put( 0, defaultTcal ) ;
1497    return ;
1498  }   
1499  uInt npol = tmpTcalCol->shape( 0 )(0) ;
1500  delete tmpTcalCol ;
1501  //os_ << "fillTcal(): npol = " << npol << LogIO::POST ;
1502  Table tab = table_->tcal().table() ;
1503  ArrayColumn<Float> tcalCol( tab, "TCAL" ) ;
1504  ROTableColumn *sharedCol ;
1505  uInt oldnr = 0 ;
1506  uInt newnr = 0 ;
1507  TableRow row( tab ) ;
1508  TableRecord &trec = row.record() ;
1509  RecordFieldPtr<uInt> idRF( trec, "ID" ) ;
1510  RecordFieldPtr<String> timeRF( trec, "TIME" ) ;
1511  RecordFieldPtr< Array<Float> > tcalRF( trec, "TCAL" ) ;
1512  TableIterator iter0( sctabsel, "FEED_ID" ) ;
1513  while( !iter0.pastEnd() ) {
1514    Table t0 = iter0.table() ;
1515    sharedCol = tpoolr->construct( t0, "FEED_ID" ) ;
1516    Int feedId = sharedCol->asInt( 0 ) ;
1517    tpoolr->destroy( sharedCol ) ;
1518    TableIterator iter1( t0, "SPECTRAL_WINDOW_ID" ) ;
1519    while( !iter1.pastEnd() ) {
1520      Table t1 = iter1.table() ;
1521      sharedCol = tpoolr->construct( t1, "SPECTRAL_WINDOW_ID" ) ;
1522      Int spwId = sharedCol->asInt( 0 ) ;
1523      tpoolr->destroy( sharedCol ) ;
1524      tmpTcalCol = new ROArrayColumn<Float>( t1, colTcal_ ) ;
1525      ROScalarQuantColumn<Double> scTimeCol( t1, "TIME" ) ;
1526      Vector<uInt> idminmax( 2, oldnr ) ;
1527      for ( uInt irow = 0 ; irow < t1.nrow() ; irow++ ) {
1528        String sTime = MVTime( scTimeCol(irow) ).string( MVTime::YMD ) ;
1529        *timeRF = sTime ;
1530        uInt idx = oldnr ;
1531        Matrix<Float> subtcal = (*tmpTcalCol)( irow ) ;
1532        for ( uInt ipol = 0 ; ipol < npol ; ipol++ ) {
1533          *idRF = idx++ ;
1534          //*tcalRF = subtcal.row( ipol ) ;
1535          tcalRF.define( subtcal.row( ipol ) ) ;
1536
1537          // commit row
1538          tab.addRow() ;
1539          row.put( tab.nrow()-1 ) ;
1540
1541          newnr++ ;
1542        }
1543        idminmax[0] = oldnr ;
1544        idminmax[1] = newnr - 1 ;
1545        oldnr = newnr ;
1546
1547        String key = keyTcal( feedId, spwId, sTime ) ;
1548        tcalrec_.define( key, idminmax ) ;
1549      }
1550      delete tmpTcalCol ;
1551      iter1++ ;
1552    }
1553    iter0++ ;
1554  }
1555
1556  //tcalrec_.print( std::cout ) ;
1557//   double endSec = gettimeofday_sec() ;
1558//   os_ << "end MSFiller::fillTcal() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1559}
1560
1561uInt MSFiller::getWeatherId( uInt idx, Double wtime )
1562{
1563//   double startSec = gettimeofday_sec() ;
1564//   os_ << "start MSFiller::getWeatherId() startSec=" << startSec << LogIO::POST ;
1565  uInt nrow = mwTime_.size() ;
1566  if ( nrow < 2 )
1567    return 0 ;
1568  uInt wid = nrow ;
1569  if ( idx == 0 ) {
1570    wid = 0 ;
1571    Double tStart = mwTime_[wid]-0.5*mwInterval_[wid] ;
1572    if ( wtime < tStart )
1573      return wid ;
1574  }
1575  for ( uInt i = idx ; i < nrow-1 ; i++ ) {
1576    Double tStart = mwTime_[i]-0.5*mwInterval_[i] ;
1577    // use of INTERVAL column is problematic
1578    // since there are "blank" time of weather monitoring
1579    //Double tEnd = tStart + mwInterval_[i] ;
1580    Double tEnd = mwTime_[i+1]-0.5*mwInterval_[i+1] ;
1581    //os_ << "tStart = " << tStart << " dtEnd = " << tEnd-tStart << " dwtime = " << wtime-tStart << LogIO::POST ;
1582    if ( wtime >= tStart && wtime <= tEnd ) {
1583      wid = i ;
1584      break ;
1585    }
1586  }
1587  if ( wid == nrow ) {
1588    uInt i = nrow - 1 ;
1589    Double tStart = mwTime_[i-1]+0.5*mwInterval_[i-1] ;
1590    Double tEnd = mwTime_[i]+0.5*mwInterval_[i] ;
1591    //os_ << "tStart = " << tStart << " dtEnd = " << tEnd-tStart << " dwtime = " << wtime-tStart << LogIO::POST ;
1592    if ( wtime >= tStart && wtime <= tEnd )
1593      wid = i-1 ;
1594    else
1595      wid = i ;
1596  }
1597
1598  //if ( wid == nrow )
1599  //os_ << LogIO::WARN << "Couldn't find correct WEATHER_ID for time " << wtime << LogIO::POST ;
1600
1601//   double endSec = gettimeofday_sec() ;
1602//   os_ << "end MSFiller::getWeatherId() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1603  return wid ;
1604}
1605
1606void MSFiller::getSysCalTime( Vector<MEpoch> &scTime, Vector<Double> &scInterval, Block<MEpoch> &tcol, Block<Int> &tidx )
1607{
1608//   double startSec = gettimeofday_sec() ;
1609//   os_ << "start MSFiller::getSysCalTime() startSec=" << startSec << LogIO::POST ;
1610
1611  if ( !isSysCal_ )
1612    return ;
1613
1614  uInt nrow = tidx.nelements() ;
1615  if ( scTime.nelements() == 0 )
1616    return ;
1617  else if ( scTime.nelements() == 1 ) {
1618    tidx[0] = 0 ;
1619    return ;
1620  }
1621  uInt scnrow = scTime.nelements() ;
1622  uInt idx = 0 ;
1623  const Double half = 0.5e0 ;
1624  // execute  binary search
1625  idx = binarySearch( scTime, tcol[0].get( "s" ).getValue() ) ;
1626  if ( idx != 0 )
1627    idx -= 1 ;
1628  for ( uInt i = 0 ; i < nrow ; i++ ) {
1629    Double t = tcol[i].get( "s" ).getValue() ;
1630    Double tsc = scTime[0].get( "s" ).getValue() ;
1631    if ( t < tsc ) {
1632      tidx[i] = 0 ;
1633      continue ;
1634    }
1635    for ( uInt j = idx ; j < scnrow-1 ; j++ ) {
1636      Double tsc1 = scTime[j].get( "s" ).getValue() ;
1637      Double dt1 = scInterval[j] ;
1638      Double tsc2 = scTime[j+1].get( "s" ).getValue() ;
1639      Double dt2 = scInterval[j+1] ;
1640      if ( t > tsc1-half*dt1 && t <= tsc2-half*dt2 ) {
1641        tidx[i] = j ;
1642        idx = j ;
1643        break ;
1644      }
1645    }
1646    if ( tidx[i] == -1 ) {
1647//       Double tsc = scTime[scnrow-1].get( "s" ).getValue() ;
1648//       Double dt = scInterval[scnrow-1] ;
1649//       if ( t <= tsc+0.5*dt ) {
1650//         tidx[i] = scnrow-1 ;
1651//       }
1652      tidx[i] = scnrow-1 ;
1653    }
1654  }
1655//   double endSec = gettimeofday_sec() ;
1656//   os_ << "end MSFiller::getSysCalTime() endSec=" << endSec << " (" << endSec-startSec << "sec) scnrow = " << scnrow << " tcol.nelements = " << tcol.nelements() << LogIO::POST ;
1657  return ;
1658}
1659
1660Block<uInt> MSFiller::getTcalId( Int fid, Int spwid, MEpoch &t )
1661{
1662//   double startSec = gettimeofday_sec() ;
1663//   os_ << "start MSFiller::getTcalId() startSec=" << startSec << LogIO::POST ;
1664  //if ( table_->tcal().table().nrow() == 0 ) {
1665  if ( !isSysCal_ ) {
1666    os_ << "No TCAL rows" << LogIO::POST ;
1667    Block<uInt> tcalids( 4, 0 ) ;
1668    return  tcalids ;
1669  }   
1670  //String sctime = MVTime( Quantum<Double>(t,"s") ).string(MVTime::YMD) ;
1671  String sctime = MVTime( t.getValue() ).string(MVTime::YMD) ;
1672  String key = keyTcal( fid, spwid, sctime ) ;
1673  if ( !tcalrec_.isDefined( key ) ) {
1674    os_ << "No TCAL rows" << LogIO::POST ;
1675    Block<uInt> tcalids( 4, 0 ) ;
1676    return tcalids ;
1677  }
1678  Vector<uInt> ids = tcalrec_.asArrayuInt( key ) ;
1679  uInt npol = ids[1] - ids[0] + 1 ;
1680  Block<uInt> tcalids( npol ) ;
1681  tcalids[0] = ids[0] ;
1682  tcalids[1] = ids[1] ;
1683  for ( uInt ipol = 2 ; ipol < npol ; ipol++ )
1684    tcalids[ipol] = ids[0] + ipol - 1 ;
1685
1686//   double endSec = gettimeofday_sec() ;
1687//   os_ << "end MSFiller::getTcalId() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1688  return tcalids ;
1689}
1690
1691uInt MSFiller::getDirection( uInt idx, Vector<Double> &dir, Vector<Double> &srate, String &ref, MSPointing &tab, Double t )
1692{
1693//   double startSec = gettimeofday_sec() ;
1694//   os_ << "start MSFiller::getDirection() startSec=" << startSec << LogIO::POST ;
1695  // assume that cols is sorted by TIME
1696  Bool doInterp = False ;
1697  //uInt nrow = cols.nrow() ;
1698  uInt nrow = tab.nrow() ;
1699  if ( nrow == 0 )
1700    return 0 ;
1701  ROScalarMeasColumn<MEpoch> tcol( tab, "TIME" ) ;
1702  ROArrayMeasColumn<MDirection> dmcol( tab, "DIRECTION" ) ;
1703  ROArrayColumn<Double> dcol( tab, "DIRECTION" ) ;
1704  // binary search if idx == 0
1705  if ( idx == 0 ) {
1706    uInt nrowb = 75000 ;
1707    if ( nrow > nrowb ) {
1708      uInt nblock = nrow / nrowb + 1 ;
1709      for ( uInt iblock = 0 ; iblock < nblock ; iblock++ ) {
1710        uInt high = min( nrowb, nrow-iblock*nrowb ) ;
1711
1712        if ( tcol( high-1 ).get( "s" ).getValue() < t ) {
1713          idx = iblock * nrowb ;
1714          continue ;
1715        }
1716
1717        Vector<MEpoch> tarr( high ) ;
1718        for ( uInt irow = 0 ; irow < high ; irow++ ) {
1719          tarr[irow] = tcol( iblock*nrowb+irow ) ;
1720        }
1721
1722        uInt bidx = binarySearch( tarr, t ) ;
1723
1724        idx = iblock * nrowb + bidx ;
1725        break ;
1726      }
1727    }
1728    else {
1729      Vector<MEpoch> tarr( nrow ) ;
1730      for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1731        tarr[irow] = tcol( irow ) ;
1732      }
1733      idx = binarySearch( tarr, t ) ;
1734    }
1735  }
1736  // ensure that tcol(idx) < t
1737  //os_ << "tcol(idx) = " << tcol(idx).get("s").getValue() << " t = " << t << " diff = " << tcol(idx).get("s").getValue()-t << endl ;
1738  while ( tcol(idx).get("s").getValue() > t && idx > 0 )
1739    idx-- ;
1740  //os_ << "idx = " << idx << LogIO::POST ;
1741
1742  // index search
1743  for ( uInt i = idx ; i < nrow ; i++ ) {
1744    Double tref = tcol( i ).get( "s" ).getValue() ;
1745    if ( tref == t ) {
1746      idx = i ;
1747      break ;
1748    }
1749    else if ( tref > t ) {
1750      if ( i == 0 ) {
1751        idx = i ;
1752      }
1753      else {
1754        idx = i-1 ;
1755        doInterp = True ;
1756      }
1757      break ;
1758    }
1759    else {
1760      idx = nrow - 1 ;
1761    }
1762  }
1763  //os_ << "searched idx = " << idx << LogIO::POST ;
1764
1765  //os_ << "dmcol(idx).shape() = " << dmcol(idx).shape() << LogIO::POST ;
1766  IPosition ip( dmcol(idx).shape().nelements(), 0 ) ;
1767  //os_ << "ip = " << ip << LogIO::POST ;
1768  ref = dmcol(idx)(ip).getRefString() ;
1769  //os_ << "ref = " << ref << LogIO::POST ;
1770  if ( doInterp ) {
1771    //os_ << "do interpolation" << LogIO::POST ;
1772    //os_ << "dcol(idx).shape() = " << dcol(idx).shape() << LogIO::POST ;
1773    Double tref0 = tcol(idx).get("s").getValue() ;
1774    Double tref1 = tcol(idx+1).get("s").getValue() ;
1775    Matrix<Double> mdir0 = dcol( idx ) ;
1776    Matrix<Double> mdir1 = dcol( idx+1 ) ;
1777    Vector<Double> dir0 = mdir0.column( 0 ) ;
1778    //os_ << "dir0 = " << dir0 << LogIO::POST ;
1779    Vector<Double> dir1 = mdir1.column( 0 ) ;
1780    //os_ << "dir1 = " << dir1 << LogIO::POST ;
1781    Double dt0 = t - tref0 ;
1782    Double dt1 = tref1 - t ;
1783    dir.reference( (dt0*dir1+dt1*dir0)/(dt0+dt1) ) ;
1784    if ( mdir0.ncolumn() > 1 ) {
1785      if ( dt0 >= dt1 )
1786        srate.reference( mdir0.column( 1 ) ) ;
1787      else
1788        srate.reference( mdir1.column( 1 ) ) ;
1789    }
1790    //os_ << "dir = " << dir << LogIO::POST ;
1791  }
1792  else {
1793    //os_ << "no interpolation" << LogIO::POST ;
1794    Matrix<Double> mdir0 = dcol( idx ) ;
1795    dir.reference( mdir0.column( 0 ) ) ;
1796    if ( mdir0.ncolumn() > 1 )
1797      srate.reference( mdir0.column( 1 ) ) ;
1798  }
1799
1800//   double endSec = gettimeofday_sec() ;
1801//   os_ << "end MSFiller::getDirection() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1802  return idx ;
1803}
1804
1805String MSFiller::keyTcal( Int feedid, Int spwid, String stime )
1806{
1807  String sfeed = "FEED" + String::toString( feedid ) ;
1808  String sspw = "SPW" + String::toString( spwid ) ;
1809  return sfeed+":"+sspw+":"+stime ;
1810}
1811
1812uInt MSFiller::binarySearch( Vector<MEpoch> &timeList, Double target )
1813{
1814  Int low = 0 ;
1815  Int high = timeList.nelements() ;
1816  uInt idx = 0 ;
1817
1818  while ( low <= high ) {
1819    idx = (Int)( 0.5 * ( low + high ) ) ;
1820    Double t = timeList[idx].get( "s" ).getValue() ;
1821    if ( t < target )
1822      low = idx + 1 ;
1823    else if ( t > target )
1824      high = idx - 1 ;
1825    else
1826      return idx ;
1827  }
1828
1829  idx = max( 0, min( low, high ) ) ;
1830
1831  return idx ;
1832 
1833}
1834
1835string MSFiller::getFrame()
1836{
1837  MFrequency::Types frame = MFrequency::DEFAULT ;
1838  ROTableColumn numChanCol( mstable_.spectralWindow(), "NUM_CHAN" ) ;
1839  ROTableColumn measFreqRefCol( mstable_.spectralWindow(), "MEAS_FREQ_REF" ) ;
1840  uInt nrow = numChanCol.nrow() ;
1841  Vector<Int> measFreqRef( nrow, MFrequency::DEFAULT ) ;
1842  uInt nref = 0 ;
1843  for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1844    if ( numChanCol.asInt( irow ) != 4 ) { // exclude WVR
1845      measFreqRef[nref] = measFreqRefCol.asInt( irow ) ;
1846      nref++ ;
1847    }
1848  }
1849  if ( nref > 0 )
1850    frame = (MFrequency::Types)measFreqRef[0] ;
1851
1852  return MFrequency::showType( frame ) ;
1853}
1854} ;
1855
Note: See TracBrowser for help on using the repository browser.