source: trunk/src/MSFiller.cpp @ 2237

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

Refactoring MSFiller::fill() to detect bottle neck of the process.
There are no changes effectively.


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