source: trunk/src/MSFiller.cpp @ 2238

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

Improved performance.
Speed up getDirection.


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