source: trunk/src/MSFiller.cpp@ 3099

Last change on this file since 3099 was 3084, checked in by Takeshi Nakazato, 9 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: Yes/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...


Get rid of warnings from table module that warns the change of the location of some header files.

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// New version that is implemented using TableVisitor instead of TableIterator
8//
9// Takeshi Nakazato <takeshi.nakazato@nao.ac.jp>, (C) 2011
10//
11// Copyright: See COPYING file that comes with this distribution
12//
13//
14
15#include <assert.h>
16#include <iostream>
17#include <map>
18#include <set>
19
20#include <tables/TaQL/ExprNode.h>
21#include <tables/Tables/TableIter.h>
22#include <tables/Tables/TableColumn.h>
23#include <tables/Tables/ScalarColumn.h>
24#include <tables/Tables/ArrayColumn.h>
25#include <tables/TaQL/TableParse.h>
26#include <tables/Tables/TableRow.h>
27
28#include <casa/Containers/RecordField.h>
29#include <casa/Logging/LogIO.h>
30#include <casa/Arrays/Slicer.h>
31#include <casa/Quanta/MVTime.h>
32#include <casa/OS/Path.h>
33
34#include <measures/Measures/Stokes.h>
35#include <measures/Measures/MEpoch.h>
36#include <measures/Measures/MCEpoch.h>
37#include <measures/Measures/MFrequency.h>
38#include <measures/Measures/MCFrequency.h>
39#include <measures/Measures/MPosition.h>
40#include <measures/Measures/MCPosition.h>
41#include <measures/Measures/MDirection.h>
42#include <measures/Measures/MCDirection.h>
43#include <measures/Measures/MeasConvert.h>
44#include <measures/TableMeasures/ScalarMeasColumn.h>
45#include <measures/TableMeasures/ArrayMeasColumn.h>
46#include <measures/TableMeasures/ScalarQuantColumn.h>
47#include <measures/TableMeasures/ArrayQuantColumn.h>
48
49#include <ms/MSSel/MSAntennaIndex.h>
50
51#include <atnf/PKSIO/SrcType.h>
52
53#include "MSFiller.h"
54#include "STHeader.h"
55
56#include "MathUtils.h"
57
58using namespace casa ;
59using namespace std ;
60
61namespace asap {
62
63class BaseMSFillerVisitor: public TableVisitor {
64 uInt lastRecordNo ;
65 Int lastObservationId ;
66 Int lastFeedId ;
67 Int lastFieldId ;
68 Int lastDataDescId ;
69 Int lastScanNo ;
70 Int lastStateId ;
71 Double lastTime ;
72protected:
73 const Table &table;
74 uInt count;
75public:
76 BaseMSFillerVisitor(const Table &table)
77 : table(table)
78 {
79 count = 0;
80 }
81
82 virtual void enterObservationId(const uInt /*recordNo*/, Int /*columnValue*/) { }
83 virtual void leaveObservationId(const uInt /*recordNo*/, Int /*columnValue*/) { }
84 virtual void enterFeedId(const uInt /*recordNo*/, Int /*columnValue*/) { }
85 virtual void leaveFeedId(const uInt /*recordNo*/, Int /*columnValue*/) { }
86 virtual void enterFieldId(const uInt /*recordNo*/, Int /*columnValue*/) { }
87 virtual void leaveFieldId(const uInt /*recordNo*/, Int /*columnValue*/) { }
88 virtual void enterDataDescId(const uInt /*recordNo*/, Int /*columnValue*/) { }
89 virtual void leaveDataDescId(const uInt /*recordNo*/, Int /*columnValue*/) { }
90 virtual void enterScanNo(const uInt /*recordNo*/, Int /*columnValue*/) { }
91 virtual void leaveScanNo(const uInt /*recordNo*/, Int /*columnValue*/) { }
92 virtual void enterStateId(const uInt /*recordNo*/, Int /*columnValue*/) { }
93 virtual void leaveStateId(const uInt /*recordNo*/, Int /*columnValue*/) { }
94 virtual void enterTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
95 virtual void leaveTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
96
97 virtual Bool visitRecord(const uInt /*recordNo*/,
98 const Int /*ObservationId*/,
99 const Int /*feedId*/,
100 const Int /*fieldId*/,
101 const Int /*dataDescId*/,
102 const Int /*scanNo*/,
103 const Int /*stateId*/,
104 const Double /*time*/) { return True ; }
105
106 virtual Bool visit(Bool isFirst, const uInt recordNo,
107 const uInt nCols, void const *const colValues[]) {
108 (void)nCols;
109 Int observationId, feedId, fieldId, dataDescId, scanNo, stateId;
110 Double time;
111 { // prologue
112 uInt i = 0;
113 {
114 const Int *col = (const Int *)colValues[i++];
115 observationId = col[recordNo];
116 }
117 {
118 const Int *col = (const Int *)colValues[i++];
119 feedId = col[recordNo];
120 }
121 {
122 const Int *col = (const Int *)colValues[i++];
123 fieldId = col[recordNo];
124 }
125 {
126 const Int *col = (const Int *)colValues[i++];
127 dataDescId = col[recordNo];
128 }
129 {
130 const Int *col = (const Int *)colValues[i++];
131 scanNo = col[recordNo];
132 }
133 {
134 const Int *col = (const Int *)colValues[i++];
135 stateId = col[recordNo];
136 }
137 {
138 const Double *col = (const Double *)colValues[i++];
139 time = col[recordNo];
140 }
141 assert(nCols == i);
142 }
143
144 if (isFirst) {
145 enterObservationId(recordNo, observationId);
146 enterFeedId(recordNo, feedId);
147 enterFieldId(recordNo, fieldId);
148 enterDataDescId(recordNo, dataDescId);
149 enterScanNo(recordNo, scanNo);
150 enterStateId(recordNo, stateId);
151 enterTime(recordNo, time);
152 } else {
153 if (lastObservationId != observationId) {
154 leaveTime(lastRecordNo, lastTime);
155 leaveStateId(lastRecordNo, lastStateId);
156 leaveScanNo(lastRecordNo, lastScanNo);
157 leaveDataDescId(lastRecordNo, lastDataDescId);
158 leaveFieldId(lastRecordNo, lastFieldId);
159 leaveFeedId(lastRecordNo, lastFeedId);
160 leaveObservationId(lastRecordNo, lastObservationId);
161
162 enterObservationId(recordNo, observationId);
163 enterFeedId(recordNo, feedId);
164 enterFieldId(recordNo, fieldId);
165 enterDataDescId(recordNo, dataDescId);
166 enterScanNo(recordNo, scanNo);
167 enterStateId(recordNo, stateId);
168 enterTime(recordNo, time);
169 } else if (lastFeedId != feedId) {
170 leaveTime(lastRecordNo, lastTime);
171 leaveStateId(lastRecordNo, lastStateId);
172 leaveScanNo(lastRecordNo, lastScanNo);
173 leaveDataDescId(lastRecordNo, lastDataDescId);
174 leaveFieldId(lastRecordNo, lastFieldId);
175 leaveFeedId(lastRecordNo, lastFeedId);
176
177 enterFeedId(recordNo, feedId);
178 enterFieldId(recordNo, fieldId);
179 enterDataDescId(recordNo, dataDescId);
180 enterScanNo(recordNo, scanNo);
181 enterStateId(recordNo, stateId);
182 enterTime(recordNo, time);
183 } else if (lastFieldId != fieldId) {
184 leaveTime(lastRecordNo, lastTime);
185 leaveStateId(lastRecordNo, lastStateId);
186 leaveScanNo(lastRecordNo, lastScanNo);
187 leaveDataDescId(lastRecordNo, lastDataDescId);
188 leaveFieldId(lastRecordNo, lastFieldId);
189
190 enterFieldId(recordNo, fieldId);
191 enterDataDescId(recordNo, dataDescId);
192 enterScanNo(recordNo, scanNo);
193 enterStateId(recordNo, stateId);
194 enterTime(recordNo, time);
195 } else if (lastDataDescId != dataDescId) {
196 leaveTime(lastRecordNo, lastTime);
197 leaveStateId(lastRecordNo, lastStateId);
198 leaveScanNo(lastRecordNo, lastScanNo);
199 leaveDataDescId(lastRecordNo, lastDataDescId);
200
201 enterDataDescId(recordNo, dataDescId);
202 enterScanNo(recordNo, scanNo);
203 enterStateId(recordNo, stateId);
204 enterTime(recordNo, time);
205 } else if (lastScanNo != scanNo) {
206 leaveTime(lastRecordNo, lastTime);
207 leaveStateId(lastRecordNo, lastStateId);
208 leaveScanNo(lastRecordNo, lastScanNo);
209
210 enterScanNo(recordNo, scanNo);
211 enterStateId(recordNo, stateId);
212 enterTime(recordNo, time);
213 } else if (lastStateId != stateId) {
214 leaveTime(lastRecordNo, lastTime);
215 leaveStateId(lastRecordNo, lastStateId);
216
217 enterStateId(recordNo, stateId);
218 enterTime(recordNo, time);
219 } else if (lastTime != time) {
220 leaveTime(lastRecordNo, lastTime);
221 enterTime(recordNo, time);
222 }
223 }
224 count++;
225 Bool result = visitRecord(recordNo, observationId, feedId, fieldId, dataDescId,
226 scanNo, stateId, time);
227
228 { // epilogue
229 lastRecordNo = recordNo;
230
231 lastObservationId = observationId;
232 lastFeedId = feedId;
233 lastFieldId = fieldId;
234 lastDataDescId = dataDescId;
235 lastScanNo = scanNo;
236 lastStateId = stateId;
237 lastTime = time;
238 }
239 return result ;
240 }
241
242 virtual void finish() {
243 if (count > 0) {
244 leaveTime(lastRecordNo, lastTime);
245 leaveStateId(lastRecordNo, lastStateId);
246 leaveScanNo(lastRecordNo, lastScanNo);
247 leaveDataDescId(lastRecordNo, lastDataDescId);
248 leaveFieldId(lastRecordNo, lastFieldId);
249 leaveFeedId(lastRecordNo, lastFeedId);
250 leaveObservationId(lastRecordNo, lastObservationId);
251 }
252 }
253};
254
255class MSFillerVisitor: public BaseMSFillerVisitor, public MSFillerUtils {
256public:
257 MSFillerVisitor(const Table &from, Scantable &to)
258 : BaseMSFillerVisitor(from),
259 scantable(to)
260 {
261 antennaId = 0 ;
262 rowidx = 0 ;
263 tablerow = TableRow( scantable.table() ) ;
264 feedEntry = Vector<Int>( 64, -1 ) ;
265 nbeam = 0 ;
266 ifmap.clear() ;
267 const TableDesc &desc = table.tableDesc() ;
268 if ( desc.isColumn( "DATA" ) )
269 dataColumnName = "DATA" ;
270 else if ( desc.isColumn( "FLOAT_DATA" ) )
271 dataColumnName = "FLOAT_DATA" ;
272 getpt = False ;
273 isWeather_ = False ;
274 isSysCal = False ;
275 isTcal = False ;
276 cycleNo = 0 ;
277 numSysCalRow = 0 ;
278 header = scantable.getHeader() ;
279 fluxUnit( header.fluxunit ) ;
280
281 // MS subtables
282 const TableRecord &hdr = table.keywordSet();
283 obstab = hdr.asTable( "OBSERVATION" ) ;
284 spwtab = hdr.asTable( "SPECTRAL_WINDOW" ) ;
285 statetab = hdr.asTable( "STATE" ) ;
286 ddtab = hdr.asTable( "DATA_DESCRIPTION" ) ;
287 poltab = hdr.asTable( "POLARIZATION" ) ;
288 fieldtab = hdr.asTable( "FIELD" ) ;
289 anttab = hdr.asTable( "ANTENNA" ) ;
290 if ( hdr.isDefined( "SYSCAL" ) )
291 sctab = hdr.asTable( "SYSCAL" ) ;
292 if ( hdr.isDefined( "SOURCE" ) )
293 srctab = hdr.asTable( "SOURCE" ) ;
294
295 // attach to columns
296 // MS MAIN
297 intervalCol.attach( table, "INTERVAL" ) ;
298 flagRowCol.attach( table, "FLAG_ROW" ) ;
299 flagCol.attach( table, "FLAG" ) ;
300 if ( dataColumnName.compare( "DATA" ) == 0 )
301 dataCol.attach( table, dataColumnName ) ;
302 else
303 floatDataCol.attach( table, dataColumnName ) ;
304
305 // set dummy epoch
306 mf.set( currentTime ) ;
307
308 //
309 // add rows to scantable
310 //
311 // number of polarization is up to 4
312 uInt addrow = table.nrow() * maxNumPol() ;
313 scantable.table().addRow( addrow ) ;
314
315 // attach to columns
316 // Scantable MAIN
317 TableRecord &r = tablerow.record() ;
318 timeRF.attachToRecord( r, "TIME" ) ;
319 intervalRF.attachToRecord( r, "INTERVAL" ) ;
320 directionRF.attachToRecord( r, "DIRECTION" ) ;
321 azimuthRF.attachToRecord( r, "AZIMUTH" ) ;
322 elevationRF.attachToRecord( r, "ELEVATION" ) ;
323 scanRateRF.attachToRecord( r, "SCANRATE" ) ;
324 weatherIdRF.attachToRecord( r, "WEATHER_ID" ) ;
325 cycleNoRF.attachToRecord( r, "CYCLENO" ) ;
326 flagRowRF.attachToRecord( r, "FLAGROW" ) ;
327 polNoRF.attachToRecord( r, "POLNO" ) ;
328 tcalIdRF.attachToRecord( r, "TCAL_ID" ) ;
329 spectraRF.attachToRecord( r, "SPECTRA" ) ;
330 flagtraRF.attachToRecord( r, "FLAGTRA" ) ;
331 tsysRF.attachToRecord( r, "TSYS" ) ;
332 beamNoRF.attachToRecord( r, "BEAMNO" ) ;
333 ifNoRF.attachToRecord( r, "IFNO" ) ;
334 freqIdRF.attachToRecord( r, "FREQ_ID" ) ;
335 moleculeIdRF.attachToRecord( r, "MOLECULE_ID" ) ;
336 sourceNameRF.attachToRecord( r, "SRCNAME" ) ;
337 sourceProperMotionRF.attachToRecord( r, "SRCPROPERMOTION" ) ;
338 sourceDirectionRF.attachToRecord( r, "SRCDIRECTION" ) ;
339 sourceVelocityRF.attachToRecord( r, "SRCVELOCITY" ) ;
340 focusIdRF.attachToRecord( r, "FOCUS_ID" ) ;
341 fieldNameRF.attachToRecord( r, "FIELDNAME" ) ;
342 sourceTypeRF.attachToRecord( r, "SRCTYPE" ) ;
343 scanNoRF.attachToRecord( r, "SCANNO" ) ;
344
345 // put values
346 RecordFieldPtr<Int> refBeamNoRF( r, "REFBEAMNO" ) ;
347 *refBeamNoRF = -1 ;
348 RecordFieldPtr<Int> fitIdRF( r, "FIT_ID" ) ;
349 *fitIdRF = -1 ;
350 RecordFieldPtr<Float> opacityRF( r, "OPACITY" ) ;
351 *opacityRF = 0.0 ;
352 }
353
354 virtual void enterObservationId(const uInt /*recordNo*/, Int columnValue) {
355 //printf("%u: ObservationId: %d\n", recordNo, columnValue);
356 // update header
357 if ( header.observer.empty() )
358 getScalar( String("OBSERVER"), (uInt)columnValue, obstab, header.observer ) ;
359 if ( header.project.empty() )
360 getScalar( "PROJECT", (uInt)columnValue, obstab, header.project ) ;
361 if ( header.utc == 0.0 ) {
362 Vector<MEpoch> amp ;
363 getArrayMeas( "TIME_RANGE", (uInt)columnValue, obstab, amp ) ;
364 obsEpoch = amp[0];
365 header.utc = obsEpoch.get( "d" ).getValue() ;
366 }
367 if ( header.antennaname.empty() )
368 getScalar( "TELESCOPE_NAME", (uInt)columnValue, obstab, header.antennaname ) ;
369 }
370 virtual void leaveObservationId(const uInt /*recordNo*/, Int /*columnValue*/) {
371 // update header
372 header.nbeam = max( header.nbeam, (Int)nbeam ) ;
373
374 nbeam = 0 ;
375 feedEntry = -1 ;
376 }
377 virtual void enterFeedId(const uInt /*recordNo*/, Int columnValue) {
378 //printf("%u: FeedId: %d\n", recordNo, columnValue);
379
380 // update feed entry
381 if ( allNE( feedEntry, columnValue ) ) {
382 feedEntry[nbeam] = columnValue ;
383 nbeam++ ;
384 }
385
386 // put values
387 *beamNoRF = (uInt)columnValue ;
388 *focusIdRF = (uInt)0 ;
389 }
390 virtual void leaveFeedId(const uInt /*recordNo*/, Int /*columnValue*/) {
391 uInt nelem = feedEntry.nelements() ;
392 if ( nbeam > nelem ) {
393 feedEntry.resize( nelem+64, True ) ;
394 Slicer slice( IPosition( 1, nelem ), IPosition( 1, feedEntry.nelements()-1 ) ) ;
395 feedEntry( slice ) = -1 ;
396 }
397 }
398 virtual void enterFieldId(const uInt /*recordNo*/, Int columnValue) {
399 //printf("%u: FieldId: %d\n", recordNo, columnValue);
400 // update sourceId and fieldName
401 getScalar( "SOURCE_ID", (uInt)columnValue, fieldtab, sourceId ) ;
402 String fieldName ;
403 getScalar( "NAME", (uInt)columnValue, fieldtab, fieldName ) ;
404 fieldName += "__" + String::toString( columnValue ) ;
405
406 // put values
407 *fieldNameRF = fieldName ;
408 }
409 virtual void leaveFieldId(const uInt /*recordNo*/, Int /*columnValue*/) {
410 sourceId = -1 ;
411 }
412 virtual void enterDataDescId(const uInt /*recordNo*/, Int columnValue) {
413 //printf("%u: DataDescId: %d\n", recordNo, columnValue);
414 // update polarization and spectral window ids
415 getScalar( "POLARIZATION_ID", (uInt)columnValue, ddtab, polId ) ;
416 getScalar( "SPECTRAL_WINDOW_ID", (uInt)columnValue, ddtab, spwId ) ;
417
418 // polarization setup
419 getScalar( "NUM_CORR", (uInt)polId, poltab, npol ) ;
420 Vector<Int> corrtype ;
421 getArray( "CORR_TYPE", (uInt)polId, poltab, corrtype ) ;
422 polnos = getPolNos( corrtype ) ;
423
424 // process SOURCE table
425 String sourceName ;
426 Vector<Double> sourcePM, restFreqs, sysVels ;
427 Vector<String> transition ;
428 processSource( sourceId, spwId, sourceName, sourceDir, sourcePM,
429 restFreqs, transition, sysVels ) ;
430
431 // spectral setup
432 uInt freqId ;
433 Double reffreq, bandwidth ;
434 String freqref ;
435 getScalar( "NUM_CHAN", (uInt)spwId, spwtab, nchan ) ;
436 Bool iswvr = (Bool)(nchan == 4) ;
437 map<Int,uInt>::iterator iter = ifmap.find( spwId ) ;
438 if ( iter == ifmap.end() ) {
439 //MEpoch me ;
440 //getScalarMeas( "TIME", recordNo, table, me ) ;
441 //spectralSetup( spwId, me, antpos, sourceDir,
442 spectralSetup(spwId, obsEpoch, antpos, sourceDir,
443 freqId, nchan,
444 freqref, reffreq, bandwidth);
445 ifmap.insert( pair<Int,uInt>(spwId,freqId) ) ;
446 }
447 else {
448 freqId = iter->second ;
449 }
450 sp.resize( npol, nchan ) ;
451 fl.resize( npol, nchan ) ;
452
453
454 // molecular setup
455 STMolecules mtab = scantable.molecules() ;
456 uInt molId = mtab.addEntry( restFreqs, transition, transition ) ;
457
458 // process SYSCAL table
459 if ( isSysCal )
460 processSysCal( spwId ) ;
461
462 // update header
463 if ( !iswvr ) {
464 header.nchan = max( header.nchan, nchan ) ;
465 header.bandwidth = max( header.bandwidth, bandwidth ) ;
466 if ( header.reffreq == -1.0 )
467 header.reffreq = reffreq ;
468 header.npol = max( header.npol, npol ) ;
469 if ( header.poltype.empty() )
470 header.poltype = getPolType( corrtype[0] ) ;
471 if ( header.freqref.empty() )
472 header.freqref = freqref ;
473 }
474
475 // put values
476 *ifNoRF = (uInt)spwId ;
477 *freqIdRF = freqId ;
478 *moleculeIdRF = molId ;
479 *sourceNameRF = sourceName ;
480 sourceProperMotionRF.define( sourcePM ) ;
481 Vector<Double> srcD = sourceDir.getAngle().getValue( "rad" ) ;
482 sourceDirectionRF.define( srcD ) ;
483 if ( !sysVels.empty() )
484 *sourceVelocityRF = sysVels[0] ;
485 else {
486 *sourceVelocityRF = (Double)0.0 ;
487 }
488 }
489 virtual void leaveDataDescId(const uInt /*recordNo*/, Int /*columnValue*/) {
490 npol = 0 ;
491 nchan = 0 ;
492 numSysCalRow = 0 ;
493 }
494 virtual void enterScanNo(const uInt /*recordNo*/, Int columnValue) {
495 //printf("%u: ScanNo: %d\n", recordNo, columnValue);
496 // put value
497 // CAS-5841: SCANNO should be consistent with MS SCAN_NUMBER
498 *scanNoRF = (uInt)columnValue ;
499 }
500 virtual void leaveScanNo(const uInt /*recordNo*/, Int /*columnValue*/) {
501 cycleNo = 0 ;
502 }
503 virtual void enterStateId(const uInt /*recordNo*/, Int columnValue) {
504 //printf("%u: StateId: %d\n", recordNo, columnValue);
505 // SRCTYPE
506 Int srcType = getSrcType( columnValue ) ;
507
508 // update header
509 if ( header.obstype.empty() )
510 getScalar( "OBS_MODE", (uInt)columnValue, statetab, header.obstype ) ;
511
512 // put value
513 *sourceTypeRF = srcType ;
514 }
515 virtual void leaveStateId(const uInt /*recordNo*/, Int /*columnValue*/) { }
516 virtual void enterTime(const uInt recordNo, Double columnValue) {
517 //printf("%u: Time: %f\n", recordNo, columnValue);
518 currentTime = MEpoch( Quantity( columnValue, "s" ), MEpoch::UTC ) ;
519
520 // DIRECTION, AZEL, and SCANRATE
521 Vector<Double> direction, azel ;
522 Vector<Double> scanrate( 2, 0.0 ) ;
523 if ( getpt )
524 getDirection( direction, azel, scanrate ) ;
525 else
526 getSourceDirection( direction, azel, scanrate ) ;
527
528 // INTERVAL
529 Double interval = intervalCol.asdouble( recordNo ) ;
530
531 // WEATHER_ID
532 uInt wid = 0 ;
533 if ( isWeather_ )
534 wid = getWeatherId() ;
535
536 // put value
537 Double t = currentTime.get( "d" ).getValue() ;
538 *timeRF = t ;
539 *intervalRF = interval ;
540 directionRF.define( direction ) ;
541 *azimuthRF = (Float)azel[0] ;
542 *elevationRF = (Float)azel[1] ;
543 scanRateRF.define( scanrate ) ;
544 *weatherIdRF = wid ;
545 }
546 virtual void leaveTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
547 virtual Bool visitRecord(const uInt recordNo,
548 const Int /*observationId*/,
549 const Int /*feedId*/,
550 const Int /*fieldId*/,
551 const Int /*dataDescId*/,
552 const Int /*scanNo*/,
553 const Int /*stateId*/,
554 const Double /*time*/)
555 {
556 //printf("%u: %d, %d, %d, %d, %d, %d, %f\n", recordNo,
557 //observationId, feedId, fieldId, dataDescId, scanNo, stateId, time);
558
559 // SPECTRA and FLAGTRA
560 //Matrix<Float> sp;
561 //Matrix<uChar> fl;
562 spectraAndFlagtra( recordNo, sp, fl ) ;
563
564 // FLAGROW
565 Bool flr = flagRowCol.asBool( recordNo ) ;
566
567 // TSYS
568 Matrix<Float> tsys ;
569 uInt scIdx = getSysCalIndex() ;
570 if ( numSysCalRow > 0 ) {
571 tsys = sysCalTsysCol( syscalRow[scIdx] ) ;
572 }
573 else {
574 tsys.resize( npol, 1 ) ;
575 tsys = 1.0 ;
576 }
577
578 // TCAL_ID
579 Block<uInt> tcalids( npol, 0 ) ;
580 if ( numSysCalRow > 0 ) {
581 tcalids = getTcalId( syscalTime[scIdx] ) ;
582 }
583 else {
584 tcalids = getDummyTcalId( spwId ) ;
585 }
586
587 // put value
588 *cycleNoRF = cycleNo ;
589 *flagRowRF = (uInt)flr ;
590
591 // for each polarization component
592 for ( Int ipol = 0 ; ipol < npol ; ipol++ ) {
593 // put value depending on polarization component
594 *polNoRF = polnos[ipol] ;
595 *tcalIdRF = tcalids[ipol] ;
596 spectraRF.define( sp.row( ipol ) ) ;
597 flagtraRF.define( fl.row( ipol ) ) ;
598 tsysRF.define( tsys.row( ipol ) ) ;
599
600 // commit row
601 tablerow.put( rowidx ) ;
602 rowidx++ ;
603 }
604
605 // increment CYCLENO
606 cycleNo++ ;
607
608 return True ;
609 }
610 virtual void finish()
611 {
612 BaseMSFillerVisitor::finish();
613 //printf("Total: %u\n", count);
614 // remove redundant rows
615 //cout << "filled " << rowidx << " rows out of " << scantable.nrow() << " rows" << endl ;
616 if ( scantable.nrow() > (Int)rowidx ) {
617 uInt numRemove = scantable.nrow() - rowidx ;
618 //cout << "numRemove = " << numRemove << endl ;
619 Vector<uInt> rows( numRemove ) ;
620 indgen( rows, rowidx ) ;
621 scantable.table().removeRow( rows ) ;
622 }
623
624 // antenna name and station name
625 String antennaName ;
626 getScalar( "NAME", (uInt)antennaId, anttab, antennaName ) ;
627 String stationName ;
628 getScalar( "STATION", (uInt)antennaId, anttab, stationName ) ;
629
630 // update header
631 header.nif = ifmap.size() ;
632 header.antennaposition = antpos.get( "m" ).getValue() ;
633 if ( header.antennaname.empty() || header.antennaname == antennaName )
634 header.antennaname = antennaName ;
635 else
636 header.antennaname += "//" + antennaName ;
637 if ( !stationName.empty() && stationName != antennaName )
638 header.antennaname += "@" + stationName ;
639 if ( header.fluxunit.empty() || header.fluxunit == "CNTS" )
640 header.fluxunit = "K" ;
641 header.epoch = "UTC" ;
642 header.equinox = 2000.0 ;
643 if (header.freqref == "TOPO") {
644 header.freqref = "TOPOCENT";
645 } else if (header.freqref == "GEO") {
646 header.freqref = "GEOCENTR";
647 } else if (header.freqref == "BARY") {
648 header.freqref = "BARYCENT";
649 } else if (header.freqref == "GALACTO") {
650 header.freqref = "GALACTOC";
651 } else if (header.freqref == "LGROUP") {
652 header.freqref = "LOCALGRP";
653 } else if (header.freqref == "CMB") {
654 header.freqref = "CMBDIPOL";
655 } else if (header.freqref == "REST") {
656 header.freqref = "SOURCE";
657 }
658 scantable.setHeader( header ) ;
659 }
660 void setAntenna( Int id )
661 {
662 antennaId = id ;
663
664 Vector< Quantum<Double> > pos ;
665 getArrayQuant( "POSITION", (uInt)antennaId, anttab, pos ) ;
666 antpos = MPosition( MVPosition( pos ), MPosition::ITRF ) ;
667 mf.set( antpos ) ;
668 }
669 void setPointingTable( const Table &tab, String columnToUse="DIRECTION" )
670 {
671 // input POINTING table must be
672 // 1) selected by antenna
673 // 2) sorted by TIME
674 ROScalarColumn<Double> tcol( tab, "TIME" ) ;
675 ROArrayColumn<Double> dcol( tab, columnToUse ) ;
676 tcol.getColumn( pointingTime ) ;
677 dcol.getColumn( pointingDirection ) ;
678 const TableRecord &rec = dcol.keywordSet() ;
679 String pointingRef = rec.asRecord( "MEASINFO" ).asString( "Ref" ) ;
680 MDirection::getType( dirType, pointingRef ) ;
681 getpt = True ;
682
683 // initialize toj2000 and toazel
684 initConvert() ;
685 }
686 void setWeatherTime( const Vector<Double> &t, const Vector<Double> &it,
687 const Vector<uInt> &idx )
688 {
689 isWeather_ = True ;
690 weatherTime_ = t ;
691 weatherInterval_ = it ;
692 weatherIndex_ = idx;
693 }
694 void setSysCalRecord( const Record &r )
695 //void setSysCalRecord( const map< String,Vector<uInt> > &r )
696 {
697 isSysCal = True ;
698 isTcal = True ;
699 syscalRecord = r ;
700 if ( syscalRecord.nfields() == 0 )
701 isTcal = False ;
702
703 const TableDesc &desc = sctab.tableDesc() ;
704 uInt nrow = sctab.nrow() ;
705 syscalRow.resize( nrow ) ;
706 syscalTime.resize( nrow ) ;
707 syscalInterval.resize( nrow ) ;
708 String tsysCol = "NONE" ;
709 Vector<String> tsysCols = stringToVector( "TSYS_SPECTRUM,TSYS" ) ;
710 for ( uInt i = 0 ; i < tsysCols.nelements() ; i++ ) {
711 if ( tsysCol == "NONE" && desc.isColumn( tsysCols[i] ) )
712 tsysCol = tsysCols[i] ;
713 }
714 sysCalTsysCol.attach( sctab, tsysCol ) ;
715 }
716 STHeader getHeader() { return header ; }
717 uInt getNumBeam() { return nbeam ; }
718 uInt getFilledRowNum() { return rowidx ; }
719private:
720 void initConvert()
721 {
722 toj2000 = MDirection::Convert( dirType, MDirection::Ref( MDirection::J2000, mf ) ) ;
723 toazel = MDirection::Convert( dirType, MDirection::Ref( MDirection::AZELGEO, mf ) ) ;
724 }
725
726 void fluxUnit( String &u )
727 {
728 ROTableColumn col( table, dataColumnName ) ;
729 const TableRecord &rec = col.keywordSet() ;
730 if ( rec.isDefined( "UNIT" ) )
731 u = rec.asString( "UNIT" ) ;
732 else if ( rec.isDefined( "QuantumUnits" ) )
733 u = rec.asString( "QuantumUnits" ) ;
734 if ( u.empty() )
735 u = "K" ;
736 }
737 void processSource( Int sourceId, Int spwId,
738 String &name, MDirection &dir, Vector<Double> &pm,
739 Vector<Double> &rf, Vector<String> &trans, Vector<Double> &vel )
740 {
741 // find row
742 uInt nrow = srctab.nrow() ;
743 Int idx = -1 ;
744 ROTableRow row( srctab ) ;
745 for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
746 const TableRecord &r = row.get( irow ) ;
747 if ( r.asInt( "SOURCE_ID" ) == sourceId ) {
748 Int tmpSpwId = r.asInt( "SPECTRAL_WINDOW_ID" ) ;
749 if ( tmpSpwId == spwId || tmpSpwId == -1 ) {
750 idx = (Int)irow ;
751 break ;
752 }
753 }
754 }
755
756 // fill
757 Int numLines = 0 ;
758 if ( idx != -1 ) {
759 const TableRecord &r = row.get( idx ) ;
760 name = r.asString( "NAME" ) ;
761 getScalarMeas( "DIRECTION", idx, srctab, dir ) ;
762 pm = r.toArrayDouble( "PROPER_MOTION" ) ;
763 numLines = r.asInt( "NUM_LINES" ) ;
764 }
765 else {
766 name = "" ;
767 pm = Vector<Double>( 2, 0.0 ) ;
768 dir = MDirection( Quantum<Double>(0.0,Unit("rad")), Quantum<Double>(0.0,Unit("rad")) ) ;
769 }
770 if ( !getpt ) {
771 String ref = dir.getRefString() ;
772 MDirection::getType( dirType, ref ) ;
773
774 // initialize toj2000 and toazel
775 initConvert() ;
776 }
777
778 rf.resize( numLines ) ;
779 trans.resize( numLines ) ;
780 vel.resize( numLines ) ;
781 if ( numLines > 0 ) {
782 Block<Bool> isDefined = row.getDefined() ;
783 Vector<String> colNames = row.columnNames() ;
784 Vector<Int> indexes( 3, -1 ) ;
785 Vector<String> cols = stringToVector( "REST_FREQUENCY,TRANSITION,SYSVEL" ) ;
786 for ( uInt icol = 0 ; icol < colNames.nelements() ; icol++ ) {
787 if ( anyEQ( indexes, -1 ) ) {
788 for ( uInt jcol = 0 ; jcol < cols.nelements() ; jcol++ ) {
789 if ( colNames[icol] == cols[jcol] )
790 indexes[jcol] = icol ;
791 }
792 }
793 }
794 if ( indexes[0] != -1 && isDefined[indexes[0]] == True ) {
795 Vector< Quantum<Double> > qrf ;
796 getArrayQuant( "REST_FREQUENCY", idx, srctab, qrf ) ;
797 for ( int i = 0 ; i < numLines ; i++ )
798 rf[i] = qrf[i].getValue( "Hz" ) ;
799 }
800 if ( indexes[1] != -1 && isDefined[indexes[1]] == True ) {
801 getArray( "TRANSITION", idx, srctab, trans ) ;
802 }
803 if ( indexes[2] != -1 && isDefined[indexes[2]] == True ) {
804 Vector< Quantum<Double> > qsv ;
805 getArrayQuant( "SYSVEL", idx, srctab, qsv ) ;
806 for ( int i = 0 ; i < numLines ; i++ )
807 vel[i] = qsv[i].getValue( "m/s" ) ;
808 }
809 }
810 }
811 void spectralSetup( Int &spwId, MEpoch &/*me*/, MPosition &/*mp*/, MDirection &/*md*/,
812 uInt &freqId, Int &nchan,
813 String &freqref, Double &reffreq, Double &bandwidth )
814 {
815 // fill
816 Int measFreqRef ;
817 getScalar( "MEAS_FREQ_REF", spwId, spwtab, measFreqRef ) ;
818 //MFrequency::Types freqRef = MFrequency::castType( measFreqRef ) ;
819 //freqref = MFrequency::showType( freqRef ) ;
820 //freqref = "LSRK" ;
821 freqref = "TOPO";
822 Quantum<Double> q ;
823 getScalarQuant( "TOTAL_BANDWIDTH", spwId, spwtab, q ) ;
824 bandwidth = q.getValue( "Hz" ) ;
825 getScalarQuant( "REF_FREQUENCY", spwId, spwtab, q ) ;
826 reffreq = q.getValue( "Hz" ) ;
827 Double refpix = 0.5 * ( (Double)nchan-1.0 ) ;
828 Int refchan = ( nchan - 1 ) / 2 ;
829 Bool even = (Bool)( nchan % 2 == 0 ) ;
830 Vector< Quantum<Double> > qa ;
831 getArrayQuant( "CHAN_WIDTH", spwId, spwtab, qa ) ;
832// Double increment = qa[refchan].getValue( "Hz" ) ;
833 Double increment = abs(qa[refchan].getValue( "Hz" )) ;
834 getArrayQuant( "CHAN_FREQ", spwId, spwtab, qa ) ;
835 if ( nchan == 1 ) {
836 Int netSideband ;
837 getScalar( "NET_SIDEBAND", spwId, spwtab, netSideband ) ;
838 if ( netSideband == 1 ) increment *= -1.0 ;
839 }
840 else {
841 if ( qa[0].getValue( "Hz" ) > qa[1].getValue( "Hz" ) )
842 increment *= -1.0 ;
843 }
844 Double refval = qa[refchan].getValue( "Hz" ) ;
845 if ( even )
846 refval = 0.5 * ( refval + qa[refchan+1].getValue( "Hz" ) ) ;
847
848 // add new row to FREQUENCIES
849 Table ftab = scantable.frequencies().table() ;
850 freqId = ftab.nrow() ;
851 ftab.addRow() ;
852 TableRow row( ftab ) ;
853 TableRecord &r = row.record() ;
854 RecordFieldPtr<uInt> idRF( r, "ID" ) ;
855 *idRF = freqId ;
856 RecordFieldPtr<Double> refpixRF( r, "REFPIX" ) ;
857 RecordFieldPtr<Double> refvalRF( r, "REFVAL" ) ;
858 RecordFieldPtr<Double> incrRF( r, "INCREMENT" ) ;
859 *refpixRF = refpix ;
860 *refvalRF = refval ;
861 *incrRF = increment ;
862 row.put( freqId ) ;
863 }
864 void spectraAndFlagtra( uInt recordNo, Matrix<Float> &sp, Matrix<uChar> &fl )
865 {
866 Matrix<Bool> b = flagCol( recordNo ) ;
867 if ( dataColumnName.compare( "FLOAT_DATA" ) == 0 ) {
868 sp = floatDataCol( recordNo ) ;
869 convertArray( fl, b ) ;
870 }
871 else {
872 Bool notyet = True ;
873 Matrix<Complex> c = dataCol( recordNo ) ;
874 for ( Int ipol = 0 ; ipol < npol ; ipol++ ) {
875 if ( ( header.poltype == "linear" || header.poltype == "circular" )
876 && ( polnos[ipol] == 2 || polnos[ipol] == 3 ) ) {
877 if ( notyet ) {
878 Vector<Float> tmp = ComplexToReal( c.row( ipol ) ) ;
879 IPosition start( 1, 0 ) ;
880 IPosition end( 1, 2*nchan-1 ) ;
881 IPosition inc( 1, 2 ) ;
882 if ( polnos[ipol] == 2 ) {
883 sp.row( ipol ) = tmp( start, end, inc ) ;
884 Vector<Bool> br = b.row( ipol ) ;
885 Vector<uChar> flr = fl.row( ipol ) ;
886 convertArray( flr, br ) ;
887 start = IPosition( 1, 1 ) ;
888 Int jpol = ipol+1 ;
889 while( polnos[jpol] != 3 && jpol < npol )
890 jpol++ ;
891 sp.row( jpol ) = tmp( start, end, inc ) ;
892 flr.reference( fl.row( jpol ) ) ;
893 convertArray( flr, br ) ;
894 }
895 else if ( polnos[ipol] == 3 ) {
896 sp.row( ipol ) = sp.row( ipol ) * (Float)(-1.0) ;
897 Int jpol = ipol+1 ;
898 while( polnos[jpol] != 2 && jpol < npol )
899 jpol++ ;
900 Vector<Bool> br = b.row( ipol ) ;
901 Vector<uChar> flr = fl.row( jpol ) ;
902 sp.row( jpol ) = tmp( start, end, inc ) ;
903 convertArray( flr, br ) ;
904 start = IPosition( 1, 1 ) ;
905 sp.row( ipol ) = tmp( start, end, inc ) * (Float)(-1.0) ;
906 flr.reference( fl.row( ipol ) ) ;
907 convertArray( flr, br ) ;
908 }
909 notyet = False ;
910 }
911 }
912 else {
913 Vector<Float> tmp = ComplexToReal( c.row( ipol ) ) ;
914 IPosition start( 1, 0 ) ;
915 IPosition end( 1, 2*nchan-1 ) ;
916 IPosition inc( 1, 2 ) ;
917 sp.row( ipol ) = tmp( start, end, inc ) ;
918 Vector<Bool> br = b.row( ipol ) ;
919 Vector<uChar> flr = fl.row( ipol ) ;
920 convertArray( flr, br ) ;
921 }
922 }
923 }
924 }
925 uInt binarySearch( Vector<Double> &timeList, Double target )
926 {
927 Int low = 0 ;
928 Int high = timeList.nelements() ;
929 uInt idx = 0 ;
930
931 while ( low <= high ) {
932 idx = (Int)( 0.5 * ( low + high ) ) ;
933 Double t = timeList[idx] ;
934 if ( t < target )
935 low = idx + 1 ;
936 else if ( t > target )
937 high = idx - 1 ;
938 else {
939 return idx ;
940 }
941 }
942
943 idx = max( 0, min( low, high ) ) ;
944 return idx ;
945 }
946 void getDirection( Vector<Double> &dir, Vector<Double> &azel, Vector<Double> &srate )
947 {
948 // @todo At the moment, do binary search every time
949 // if this is bottleneck, frequency of binary search must be reduced
950 Double t = currentTime.get( "s" ).getValue() ;
951 uInt idx = min( binarySearch( pointingTime, t ), pointingTime.nelements()-1 ) ;
952 Matrix<Double> d ;
953 if ( pointingTime[idx] == t )
954 d = pointingDirection.xyPlane( idx ) ;
955 else if ( pointingTime[idx] < t ) {
956 if ( idx == pointingTime.nelements()-1 )
957 d = pointingDirection.xyPlane( idx ) ;
958 else
959 d = interp( pointingTime[idx], pointingTime[idx+1], t,
960 pointingDirection.xyPlane( idx ), pointingDirection.xyPlane( idx+1 ) ) ;
961 }
962 else {
963 if ( idx == 0 )
964 d = pointingDirection.xyPlane( idx ) ;
965 else
966 d = interp( pointingTime[idx-1], pointingTime[idx], t,
967 pointingDirection.xyPlane( idx-1 ), pointingDirection.xyPlane( idx ) ) ;
968 }
969 mf.set( currentTime ) ;
970 Quantum< Vector<Double> > tmp( d.column( 0 ), Unit( "rad" ) ) ;
971 if ( dirType != MDirection::J2000 ) {
972 dir = toj2000( tmp ).getAngle( "rad" ).getValue() ;
973 }
974 else {
975 dir = d.column( 0 ) ;
976 }
977 if ( dirType != MDirection::AZELGEO ) {
978 azel = toazel( tmp ).getAngle( "rad" ).getValue() ;
979 }
980 else {
981 azel = d.column( 0 ) ;
982 }
983 if ( d.ncolumn() > 1 )
984 srate = d.column( 1 ) ;
985 }
986 void getSourceDirection( Vector<Double> &dir, Vector<Double> &azel, Vector<Double> &/*srate*/ )
987 {
988 dir = sourceDir.getAngle( "rad" ).getValue() ;
989 mf.set( currentTime ) ;
990 azel = toazel( Quantum< Vector<Double> >( dir, Unit("rad") ) ).getAngle( "rad" ).getValue() ;
991 if ( dirType != MDirection::J2000 ) {
992 dir = toj2000( Quantum< Vector<Double> >( dir, Unit("rad") ) ).getAngle( "rad" ).getValue() ;
993 }
994 }
995 String detectSeparator( String &s )
996 {
997 String tmp = s.substr( 0, s.find_first_of( "," ) ) ;
998 const Char *separators[] = { ":", "#", ".", "_" } ;
999 uInt nsep = 4 ;
1000 for ( uInt i = 0 ; i < nsep ; i++ ) {
1001 if ( tmp.find( separators[i] ) != String::npos )
1002 return separators[i] ;
1003 }
1004 return "" ;
1005 }
1006 Int getSrcType( Int stateId )
1007 {
1008 // get values
1009 Bool sig ;
1010 getScalar( "SIG", stateId, statetab, sig ) ;
1011 Bool ref ;
1012 getScalar( "REF", stateId, statetab, ref ) ;
1013 Double cal ;
1014 getScalar( "CAL", stateId, statetab, cal ) ;
1015 String obsmode ;
1016 getScalar( "OBS_MODE", stateId, statetab, obsmode ) ;
1017 String sep = detectSeparator( obsmode ) ;
1018
1019 Int srcType = SrcType::NOTYPE ;
1020 if ( sep == ":" )
1021 srcTypeGBT( srcType, sep, obsmode, sig, ref, cal ) ;
1022 else if ( sep == "." || sep == "#" )
1023 srcTypeALMA( srcType, sep, obsmode ) ;
1024 else if ( sep == "_" )
1025 srcTypeOldALMA( srcType, sep, obsmode, sig, ref ) ;
1026 else
1027 srcTypeDefault( srcType, sig, ref ) ;
1028
1029 return srcType ;
1030 }
1031 void srcTypeDefault( Int &st, Bool &sig, Bool &ref )
1032 {
1033 if ( sig ) st = SrcType::SIG ;
1034 else if ( ref ) st = SrcType::REF ;
1035 }
1036 void srcTypeGBT( Int &st, String &sep, String &mode, Bool &sig, Bool &ref, Double &cal )
1037 {
1038 Int epos = mode.find_first_of( sep ) ;
1039 Int nextpos = mode.find_first_of( sep, epos+1 ) ;
1040 String m1 = mode.substr( 0, epos ) ;
1041 String m2 = mode.substr( epos+1, nextpos-epos-1 ) ;
1042 if ( m1 == "Nod" ) {
1043 st = SrcType::NOD ;
1044 }
1045 else if ( m1 == "OffOn" ) {
1046 if ( m2 == "PSWITCHON" ) st = SrcType::PSON ;
1047 if ( m2 == "PSWITCHOFF" ) st = SrcType::PSOFF ;
1048 }
1049 else {
1050 if ( m2 == "FSWITCH" ) {
1051 if ( sig ) st = SrcType::FSON ;
1052 else if ( ref ) st = SrcType::FSOFF ;
1053 }
1054 }
1055 if ( cal > 0.0 ) {
1056 if ( st == SrcType::NOD )
1057 st = SrcType::NODCAL ;
1058 else if ( st == SrcType::PSON )
1059 st = SrcType::PONCAL ;
1060 else if ( st == SrcType::PSOFF )
1061 st = SrcType::POFFCAL ;
1062 else if ( st == SrcType::FSON )
1063 st = SrcType::FONCAL ;
1064 else if ( st == SrcType::FSOFF )
1065 st = SrcType::FOFFCAL ;
1066 else
1067 st = SrcType::CAL ;
1068 }
1069 }
1070 void srcTypeALMA( Int &st, String &sep, String &mode )
1071 {
1072 Int epos = mode.find_first_of( "," ) ;
1073 String first = mode.substr( 0, epos ) ;
1074 epos = first.find_first_of( sep ) ;
1075 Int nextpos = first.find_first_of( sep, epos+1 ) ;
1076 String m1 = first.substr( 0, epos ) ;
1077 String m2 = first.substr( epos+1, nextpos-epos-1 ) ;
1078 if ( m1.find( "CALIBRATE_ATMOSPHERE" ) == 0 ) {
1079 if (m2.find( "ON_SOURCE" ) == 0 || m2.find("HOT") == 0 || m2.find("AMBIENT") == 0)
1080 st = SrcType::PONCAL ;
1081 else if ( m2.find( "OFF_SOURCE" ) == 0 )
1082 st = SrcType::POFFCAL ;
1083 }
1084 else if ( m1.find( "CALIBRATE_" ) == 0 ) {
1085 st = SrcType::CAL ;
1086 }
1087 else if ( m1.find( "OBSERVE_TARGET" ) == 0 ) {
1088 if ( m2.find( "ON_SOURCE" ) == 0 )
1089 st = SrcType::PSON ;
1090 else if ( m2.find( "OFF_SOURCE" ) == 0 )
1091 st = SrcType::PSOFF ;
1092 }
1093 }
1094 void srcTypeOldALMA( Int &st, String &sep, String &mode, Bool &sig, Bool &ref )
1095 {
1096 Int epos = mode.find_first_of( "," ) ;
1097 String first = mode.substr( 0, epos ) ;
1098 string substr[4] ;
1099 int numSubstr = split( first, substr, 4, sep ) ;
1100 String m1( substr[0] ) ;
1101 String m2( substr[2] ) ;
1102 if ( numSubstr == 4 ) {
1103 if ( m1.find( "CALIBRATE" ) == 0 ) {
1104 if ( m2.find( "ON" ) == 0 )
1105 st = SrcType::PONCAL ;
1106 else if ( m2.find( "OFF" ) == 0 )
1107 st = SrcType::POFFCAL ;
1108 }
1109 else if ( m1.find( "OBSERVE" ) == 0 ) {
1110 if ( m2.find( "ON" ) == 0 )
1111 st = SrcType::PSON ;
1112 else if ( m2.find( "OFF" ) == 0 )
1113 st = SrcType::PSOFF ;
1114 }
1115 }
1116 else {
1117 if ( sig ) st = SrcType::SIG ;
1118 else if ( ref ) st = SrcType::REF ;
1119 }
1120 }
1121 Block<uInt> getPolNos( Vector<Int> &corr )
1122 {
1123 Block<uInt> polnos( npol ) ;
1124 for ( Int ipol = 0 ; ipol < npol ; ipol++ ) {
1125 if ( corr[ipol] == Stokes::I || corr[ipol] == Stokes::RR || corr[ipol] == Stokes::XX )
1126 polnos[ipol] = 0 ;
1127 else if ( corr[ipol] == Stokes::Q || corr[ipol] == Stokes::LL || corr[ipol] == Stokes::YY )
1128 polnos[ipol] = 1 ;
1129 else if ( corr[ipol] == Stokes::U || corr[ipol] == Stokes::RL || corr[ipol] == Stokes::XY )
1130 polnos[ipol] = 2 ;
1131 else if ( corr[ipol] == Stokes::V || corr[ipol] == Stokes::LR || corr[ipol] == Stokes::YX )
1132 polnos[ipol] = 3 ;
1133 }
1134 return polnos ;
1135 }
1136 String getPolType( Int &corr )
1137 {
1138 String poltype = "" ;
1139 if ( corr == Stokes::I || corr == Stokes::Q || corr == Stokes::U || corr == Stokes::V )
1140 poltype = "stokes" ;
1141 else if ( corr == Stokes::XX || corr == Stokes::YY || corr == Stokes::XY || corr == Stokes::YX )
1142 poltype = "linear" ;
1143 else if ( corr == Stokes::RR || corr == Stokes::LL || corr == Stokes::RL || corr == Stokes::LR )
1144 poltype = "circular" ;
1145 else if ( corr == Stokes::Plinear || corr == Stokes::Pangle )
1146 poltype = "linpol" ;
1147 return poltype ;
1148 }
1149 uInt getWeatherId()
1150 {
1151 // if only one row, return 0
1152 if ( weatherTime_.nelements() == 1 )
1153 return 0 ;
1154
1155 // @todo At the moment, do binary search every time
1156 // if this is bottleneck, frequency of binary search must be reduced
1157 Double t = currentTime.get( "s" ).getValue() ;
1158 uInt idx = min( binarySearch( weatherTime_, t ), weatherTime_.nelements()-1 ) ;
1159 if ( weatherTime_[idx] < t ) {
1160 if ( idx != weatherTime_.nelements()-1 ) {
1161 if ( weatherTime_[idx+1] - t < 0.5 * weatherInterval_[idx+1] )
1162 idx++ ;
1163 }
1164 }
1165 else if ( weatherTime_[idx] > t ) {
1166 if ( idx != 0 ) {
1167 if ( weatherTime_[idx] - t > 0.5 * weatherInterval_[idx] )
1168 idx-- ;
1169 }
1170 }
1171 return weatherIndex_[idx] ;
1172 }
1173 void processSysCal( Int &spwId )
1174 {
1175 // get feedId from row
1176 Int feedId = (Int)tablerow.record().asuInt( "BEAMNO" ) ;
1177
1178 uInt nrow = sctab.nrow() ;
1179 ROScalarColumn<Int> col( sctab, "ANTENNA_ID" ) ;
1180 Vector<Int> aids = col.getColumn() ;
1181 col.attach( sctab, "FEED_ID" ) ;
1182 Vector<Int> fids = col.getColumn() ;
1183 col.attach( sctab, "SPECTRAL_WINDOW_ID" ) ;
1184 Vector<Int> sids = col.getColumn() ;
1185 ROScalarColumn<Double> timeCol( sctab, "TIME" ) ;
1186 ROScalarColumn<Double> intCol( sctab, "INTERVAL" ) ;
1187 for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
1188 if ( aids[irow] == antennaId
1189 && fids[irow] == feedId
1190 && sids[irow] == spwId ) {
1191 syscalRow[numSysCalRow] = irow ;
1192 syscalTime[numSysCalRow] = timeCol( irow ) ;
1193 syscalInterval[numSysCalRow] = intCol( irow ) ;
1194 numSysCalRow++ ;
1195 }
1196 }
1197 }
1198 uInt getSysCalIndex()
1199 {
1200 // if only one row, return 0
1201 if ( numSysCalRow == 1 || !isSysCal )
1202 return 0 ;
1203
1204 // @todo At the moment, do binary search every time
1205 // if this is bottleneck, frequency of binary search must be reduced
1206 Double t = currentTime.get( "s" ).getValue() ;
1207 Vector<Double> tslice = syscalTime( Slice(0, numSysCalRow) ) ;
1208 uInt idx = min( binarySearch( tslice, t ), numSysCalRow-1 ) ;
1209 if ( syscalTime[idx] < t ) {
1210 if ( idx != numSysCalRow-1 ) {
1211 if ( syscalTime[idx+1] - t < 0.5 * syscalInterval[idx+1] )
1212 idx++ ;
1213 }
1214 }
1215 else if ( syscalTime[idx] > t ) {
1216 if ( idx != 0 ) {
1217 if ( syscalTime[idx] - t > 0.5 * syscalInterval[idx] )
1218 idx-- ;
1219 }
1220 }
1221 return idx ;
1222 }
1223 Block<uInt> getTcalId( Double &t )
1224 {
1225 // return 0 if no SysCal table
1226 if ( !isSysCal or !isTcal ) {
1227 return Block<uInt>( 4, 0 ) ;
1228 }
1229
1230 // get feedId from row
1231 Int feedId = (Int)tablerow.record().asuInt( "BEAMNO" ) ;
1232
1233 // key
1234 String key = keyTcal( feedId, spwId, t ) ;
1235
1236 // retrieve ids
1237 Vector<uInt> ids = syscalRecord.asArrayuInt( key ) ;
1238 //Vector<uInt> ids = syscalRecord[key] ;
1239 uInt np = ids[1] - ids[0] + 1 ;
1240 Block<uInt> tcalids( np ) ;
1241 if ( np > 0 ) {
1242 tcalids[0] = ids[0] ;
1243 if ( np > 1 ) {
1244 tcalids[1] = ids[1] ;
1245 for ( uInt ip = 2 ; ip < np ; ip++ )
1246 tcalids[ip] = ids[0] + ip - 1 ;
1247 }
1248 }
1249 return tcalids ;
1250 }
1251 Block<uInt> getDummyTcalId( Int spwId )
1252 {
1253 Block<uInt> idList(4, 0);
1254 uInt nfields = syscalRecord.nfields();
1255 Int idx = -1;
1256 for (uInt i = 0; i< nfields ; i++ ) {
1257 String spw = "SPW" + String::toString(spwId);
1258 if (syscalRecord.name(i).find(spw) != String::npos) {
1259 idx = i;
1260 break;
1261 }
1262 }
1263 if ( idx > -1) {
1264 Vector<uInt> tmp = syscalRecord.asArrayuInt(idx);
1265 for (uInt j = 0 ; j < 4 ; j++) {
1266 idList[j] = tmp[0];
1267 }
1268 }
1269 return idList;
1270 }
1271 uInt maxNumPol()
1272 {
1273 ROScalarColumn<Int> numCorrCol( poltab, "NUM_CORR" ) ;
1274 return max( numCorrCol.getColumn() ) ;
1275 }
1276
1277 Scantable &scantable;
1278 Int antennaId;
1279 uInt rowidx;
1280 String dataColumnName;
1281 TableRow tablerow;
1282 STHeader header;
1283 Vector<Int> feedEntry;
1284 uInt nbeam;
1285 Int npol;
1286 Int nchan;
1287 Int sourceId;
1288 Int polId;
1289 Int spwId;
1290 uInt cycleNo;
1291 MDirection sourceDir;
1292 MPosition antpos;
1293 MEpoch currentTime;
1294 MEpoch obsEpoch;
1295 MeasFrame mf;
1296 MDirection::Convert toj2000;
1297 MDirection::Convert toazel;
1298 map<Int,uInt> ifmap;
1299 Block<uInt> polnos;
1300 Bool getpt;
1301 Vector<Double> pointingTime;
1302 Cube<Double> pointingDirection;
1303 MDirection::Types dirType;
1304 Bool isWeather_;
1305 Vector<Double> weatherTime_;
1306 Vector<Double> weatherInterval_;
1307 Vector<uInt> weatherIndex_;
1308 Bool isSysCal;
1309 Bool isTcal;
1310 Record syscalRecord;
1311 //map< String,Vector<uInt> > syscalRecord;
1312 uInt numSysCalRow ;
1313 Vector<uInt> syscalRow;
1314 Vector<Double> syscalTime;
1315 Vector<Double> syscalInterval;
1316 //String tsysCol;
1317 //String tcalCol;
1318
1319 // MS subtables
1320 Table obstab;
1321 Table sctab;
1322 Table spwtab;
1323 Table statetab;
1324 Table ddtab;
1325 Table poltab;
1326 Table fieldtab;
1327 Table anttab;
1328 Table srctab;
1329 Matrix<Float> sp;
1330 Matrix<uChar> fl;
1331
1332 // MS MAIN columns
1333 ROTableColumn intervalCol;
1334 ROTableColumn flagRowCol;
1335 ROArrayColumn<Float> floatDataCol;
1336 ROArrayColumn<Complex> dataCol;
1337 ROArrayColumn<Bool> flagCol;
1338
1339 // MS SYSCAL columns
1340 ROArrayColumn<Float> sysCalTsysCol;
1341
1342 // Scantable MAIN columns
1343 RecordFieldPtr<Double> timeRF,intervalRF,sourceVelocityRF;
1344 RecordFieldPtr< Vector<Double> > directionRF,scanRateRF,
1345 sourceProperMotionRF,sourceDirectionRF;
1346 RecordFieldPtr<Float> azimuthRF,elevationRF;
1347 RecordFieldPtr<uInt> weatherIdRF,cycleNoRF,flagRowRF,polNoRF,tcalIdRF,
1348 ifNoRF,freqIdRF,moleculeIdRF,beamNoRF,focusIdRF,scanNoRF;
1349 RecordFieldPtr< Vector<Float> > spectraRF,tsysRF;
1350 RecordFieldPtr< Vector<uChar> > flagtraRF;
1351 RecordFieldPtr<String> sourceNameRF,fieldNameRF;
1352 RecordFieldPtr<Int> sourceTypeRF;
1353};
1354
1355class BaseTcalVisitor: public TableVisitor {
1356 uInt lastRecordNo ;
1357 Int lastAntennaId ;
1358 Int lastFeedId ;
1359 Int lastSpwId ;
1360 Double lastTime ;
1361protected:
1362 const Table &table;
1363 uInt count;
1364public:
1365 BaseTcalVisitor(const Table &table)
1366 : table(table)
1367 {
1368 count = 0;
1369 }
1370
1371 virtual void enterAntennaId(const uInt /*recordNo*/, Int /*columnValue*/) { }
1372 virtual void leaveAntennaId(const uInt /*recordNo*/, Int /*columnValue*/) { }
1373 virtual void enterFeedId(const uInt /*recordNo*/, Int /*columnValue*/) { }
1374 virtual void leaveFeedId(const uInt /*recordNo*/, Int /*columnValue*/) { }
1375 virtual void enterSpwId(const uInt /*recordNo*/, Int /*columnValue*/) { }
1376 virtual void leaveSpwId(const uInt /*recordNo*/, Int /*columnValue*/) { }
1377 virtual void enterTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
1378 virtual void leaveTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
1379
1380 virtual Bool visitRecord(const uInt /*recordNo*/,
1381 const Int /*antennaId*/,
1382 const Int /*feedId*/,
1383 const Int /*spwId*/,
1384 const Double /*time*/) { return True ; }
1385
1386 virtual Bool visit(Bool isFirst, const uInt recordNo,
1387 const uInt nCols, void const *const colValues[]) {
1388 (void)nCols;
1389 Int antennaId, feedId, spwId;
1390 Double time;
1391 { // prologue
1392 uInt i = 0;
1393 {
1394 const Int *col = (const Int *)colValues[i++];
1395 antennaId = col[recordNo];
1396 }
1397 {
1398 const Int *col = (const Int *)colValues[i++];
1399 feedId = col[recordNo];
1400 }
1401 {
1402 const Int *col = (const Int *)colValues[i++];
1403 spwId = col[recordNo];
1404 }
1405 {
1406 const Double *col = (const Double *)colValues[i++];
1407 time = col[recordNo];
1408 }
1409 assert(nCols == i);
1410 }
1411
1412 if (isFirst) {
1413 enterAntennaId(recordNo, antennaId);
1414 enterFeedId(recordNo, feedId);
1415 enterSpwId(recordNo, spwId);
1416 enterTime(recordNo, time);
1417 } else {
1418 if ( lastAntennaId != antennaId ) {
1419 leaveTime(lastRecordNo, lastTime);
1420 leaveSpwId(lastRecordNo, lastSpwId);
1421 leaveFeedId(lastRecordNo, lastFeedId);
1422 leaveAntennaId(lastRecordNo, lastAntennaId);
1423
1424 enterAntennaId(recordNo, antennaId);
1425 enterFeedId(recordNo, feedId);
1426 enterSpwId(recordNo, spwId);
1427 enterTime(recordNo, time);
1428 }
1429 else if (lastFeedId != feedId) {
1430 leaveTime(lastRecordNo, lastTime);
1431 leaveSpwId(lastRecordNo, lastSpwId);
1432 leaveFeedId(lastRecordNo, lastFeedId);
1433
1434 enterFeedId(recordNo, feedId);
1435 enterSpwId(recordNo, spwId);
1436 enterTime(recordNo, time);
1437 } else if (lastSpwId != spwId) {
1438 leaveTime(lastRecordNo, lastTime);
1439 leaveSpwId(lastRecordNo, lastSpwId);
1440
1441 enterSpwId(recordNo, spwId);
1442 enterTime(recordNo, time);
1443 } else if (lastTime != time) {
1444 leaveTime(lastRecordNo, lastTime);
1445 enterTime(recordNo, time);
1446 }
1447 }
1448 count++;
1449 Bool result = visitRecord(recordNo, antennaId, feedId, spwId, time);
1450
1451 { // epilogue
1452 lastRecordNo = recordNo;
1453
1454 lastAntennaId = antennaId;
1455 lastFeedId = feedId;
1456 lastSpwId = spwId;
1457 lastTime = time;
1458 }
1459 return result ;
1460 }
1461
1462 virtual void finish() {
1463 if (count > 0) {
1464 leaveTime(lastRecordNo, lastTime);
1465 leaveSpwId(lastRecordNo, lastSpwId);
1466 leaveFeedId(lastRecordNo, lastFeedId);
1467 leaveAntennaId(lastRecordNo, lastAntennaId);
1468 }
1469 }
1470};
1471
1472class TcalVisitor: public BaseTcalVisitor, public MSFillerUtils {
1473public:
1474 TcalVisitor(const Table &table, Table &tcaltab, Record &r, Int aid )
1475 //TcalVisitor(const Table &table, Table &tcaltab, map< String,Vector<uInt> > &r, Int aid )
1476 : BaseTcalVisitor( table ),
1477 tcal(tcaltab),
1478 rec(r),
1479 antenna(aid)
1480 {
1481 process = False ;
1482 rowidx = 0 ;
1483
1484 // attach to SYSCAL columns
1485 timeCol.attach( table, "TIME" ) ;
1486
1487 // add rows
1488 uInt addrow = table.nrow() * 4 ;
1489 tcal.addRow( addrow ) ;
1490
1491 // attach to TCAL columns
1492 row = TableRow( tcal ) ;
1493 TableRecord &trec = row.record() ;
1494 idRF.attachToRecord( trec, "ID" ) ;
1495 timeRF.attachToRecord( trec, "TIME" ) ;
1496 tcalRF.attachToRecord( trec, "TCAL" ) ;
1497 }
1498
1499 virtual void enterAntennaId(const uInt /*recordNo*/, Int columnValue) {
1500 if ( columnValue == antenna )
1501 process = True ;
1502 }
1503 virtual void leaveAntennaId(const uInt /*recordNo*/, Int /*columnValue*/) {
1504 process = False ;
1505 }
1506 virtual void enterFeedId(const uInt /*recordNo*/, Int /*columnValue*/) { }
1507 virtual void leaveFeedId(const uInt /*recordNo*/, Int /*columnValue*/) { }
1508 virtual void enterSpwId(const uInt /*recordNo*/, Int /*columnValue*/) { }
1509 virtual void leaveSpwId(const uInt /*recordNo*/, Int /*columnValue*/) { }
1510 virtual void enterTime(const uInt recordNo, Double /*columnValue*/) {
1511 qtime = timeCol( recordNo ) ;
1512 }
1513 virtual void leaveTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
1514 virtual Bool visitRecord(const uInt recordNo,
1515 const Int /*antennaId*/,
1516 const Int feedId,
1517 const Int spwId,
1518 const Double /*time*/)
1519 {
1520 //cout << "(" << recordNo << "," << antennaId << "," << feedId << "," << spwId << ")" << endl ;
1521 if ( process ) {
1522 String sTime = MVTime( qtime ).string( MVTime::YMD ) ;
1523 *timeRF = sTime ;
1524 uInt oldidx = rowidx ;
1525 Matrix<Float> subtcal = tcalCol( recordNo ) ;
1526 Vector<uInt> idminmax( 2 ) ;
1527 for ( uInt ipol = 0 ; ipol < subtcal.nrow() ; ipol++ ) {
1528 *idRF = rowidx ;
1529 tcalRF.define( subtcal.row( ipol ) ) ;
1530
1531 // commit row
1532 row.put( rowidx ) ;
1533 rowidx++ ;
1534 }
1535
1536 idminmax[0] = oldidx ;
1537 idminmax[1] = rowidx - 1 ;
1538
1539 String key = keyTcal( feedId, spwId, sTime ) ;
1540 rec.define( key, idminmax ) ;
1541 //rec[key] = idminmax ;
1542 }
1543 return True ;
1544 }
1545 virtual void finish()
1546 {
1547 BaseTcalVisitor::finish() ;
1548
1549 if ( tcal.nrow() > rowidx ) {
1550 uInt numRemove = tcal.nrow() - rowidx ;
1551 //cout << "numRemove = " << numRemove << endl ;
1552 Vector<uInt> rows( numRemove ) ;
1553 indgen( rows, rowidx ) ;
1554 tcal.removeRow( rows ) ;
1555 }
1556
1557 }
1558 void setTcalColumn( String &col )
1559 {
1560 //colName = col ;
1561 tcalCol.attach( table, col ) ;
1562 }
1563private:
1564 Table &tcal;
1565 Record &rec;
1566 //map< String,Vector<uInt> > &rec;
1567 Int antenna;
1568 uInt rowidx;
1569 Bool process;
1570 Quantum<Double> qtime;
1571 TableRow row;
1572 String colName;
1573
1574 // MS SYSCAL columns
1575 ROScalarQuantColumn<Double> timeCol;
1576 ROArrayColumn<Float> tcalCol;
1577
1578 // TCAL columns
1579 RecordFieldPtr<uInt> idRF;
1580 RecordFieldPtr<String> timeRF;
1581 RecordFieldPtr< Vector<Float> > tcalRF;
1582};
1583
1584MSFiller::MSFiller( casa::CountedPtr<Scantable> stable )
1585 : table_( stable ),
1586 tablename_( "" ),
1587 antenna_( -1 ),
1588 antennaStr_(""),
1589 getPt_( True ),
1590 isFloatData_( False ),
1591 isData_( False ),
1592 isDoppler_( False ),
1593 isFlagCmd_( False ),
1594 isFreqOffset_( False ),
1595 isHistory_( False ),
1596 isProcessor_( False ),
1597 isSysCal_( False ),
1598 isWeather_( False ),
1599 colTsys_( "TSYS_SPECTRUM" ),
1600 colTcal_( "TCAL_SPECTRUM" )
1601{
1602 os_ = LogIO() ;
1603 os_.origin( LogOrigin( "MSFiller", "MSFiller()", WHERE ) ) ;
1604}
1605
1606MSFiller::~MSFiller()
1607{
1608 os_.origin( LogOrigin( "MSFiller", "~MSFiller()", WHERE ) ) ;
1609}
1610
1611bool MSFiller::open( const std::string &filename, const casa::Record &rec )
1612{
1613 os_.origin( LogOrigin( "MSFiller", "open()", WHERE ) ) ;
1614 //double startSec = mathutil::gettimeofday_sec() ;
1615 //os_ << "start MSFiller::open() startsec=" << startSec << LogIO::POST ;
1616 //os_ << " filename = " << filename << endl ;
1617
1618 // parsing MS options
1619 if ( rec.isDefined( "ms" ) ) {
1620 Record msrec = rec.asRecord( "ms" ) ;
1621 if ( msrec.isDefined( "getpt" ) ) {
1622 getPt_ = msrec.asBool( "getpt" ) ;
1623 }
1624 if ( msrec.isDefined( "antenna" ) ) {
1625 if ( msrec.type( msrec.fieldNumber( "antenna" ) ) == TpInt ) {
1626 antenna_ = msrec.asInt( "antenna" ) ;
1627 }
1628 else {
1629 //antenna_ = atoi( msrec.asString( "antenna" ).c_str() ) ;
1630 antennaStr_ = msrec.asString( "antenna" ) ;
1631 }
1632 }
1633 else {
1634 antenna_ = 0 ;
1635 }
1636 }
1637
1638 MeasurementSet *tmpMS = new MeasurementSet( filename, Table::Old ) ;
1639 tablename_ = tmpMS->tableName() ;
1640 if ( antenna_ == -1 && antennaStr_.size() > 0 ) {
1641 MSAntennaIndex msAntIdx( tmpMS->antenna() ) ;
1642 Vector<Int> id = msAntIdx.matchAntennaName( antennaStr_ ) ;
1643 if ( id.size() > 0 )
1644 antenna_ = id[0] ;
1645 else {
1646 delete tmpMS ;
1647 //throw( AipsError( "Antenna " + antennaStr_ + " doesn't exist." ) ) ;
1648 os_ << LogIO::SEVERE << "Antenna " << antennaStr_ << " doesn't exist." << LogIO::POST ;
1649 return False ;
1650 }
1651 }
1652
1653 os_ << "Parsing MS options" << endl ;
1654 os_ << " getPt = " << (getPt_ ? "True" : "False") << endl ;
1655 os_ << " antenna = " << antenna_ << endl ;
1656 os_ << " antennaStr = " << antennaStr_ << LogIO::POST;
1657
1658 mstable_ = MeasurementSet( (*tmpMS)( tmpMS->col("ANTENNA1") == antenna_
1659 && tmpMS->col("ANTENNA1") == tmpMS->col("ANTENNA2") ) ) ;
1660
1661 delete tmpMS ;
1662
1663 // check which data column exists
1664 isFloatData_ = mstable_.tableDesc().isColumn( "FLOAT_DATA" ) ;
1665 isData_ = mstable_.tableDesc().isColumn( "DATA" ) ;
1666
1667 //double endSec = mathutil::gettimeofday_sec() ;
1668 //os_ << "end MSFiller::open() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1669 return true ;
1670}
1671
1672void MSFiller::fill()
1673{
1674 //double startSec = mathutil::gettimeofday_sec() ;
1675 //os_ << "start MSFiller::fill() startSec=" << startSec << LogIO::POST ;
1676
1677 os_.origin( LogOrigin( "MSFiller", "fill()", WHERE ) ) ;
1678
1679 // Initialize header
1680 STHeader sdh ;
1681 initHeader( sdh ) ;
1682 table_->setHeader( sdh ) ;
1683
1684 // check if optional table exists
1685 const TableRecord &msrec = mstable_.keywordSet() ;
1686 isDoppler_ = msrec.isDefined( "DOPPLER" ) ;
1687 if ( isDoppler_ )
1688 if ( mstable_.doppler().nrow() == 0 )
1689 isDoppler_ = False ;
1690 isFlagCmd_ = msrec.isDefined( "FLAG_CMD" ) ;
1691 if ( isFlagCmd_ )
1692 if ( mstable_.flagCmd().nrow() == 0 )
1693 isFlagCmd_ = False ;
1694 isFreqOffset_ = msrec.isDefined( "FREQ_OFFSET" ) ;
1695 if ( isFreqOffset_ )
1696 if ( mstable_.freqOffset().nrow() == 0 )
1697 isFreqOffset_ = False ;
1698 isHistory_ = msrec.isDefined( "HISTORY" ) ;
1699 if ( isHistory_ )
1700 if ( mstable_.history().nrow() == 0 )
1701 isHistory_ = False ;
1702 isProcessor_ = msrec.isDefined( "PROCESSOR" ) ;
1703 if ( isProcessor_ )
1704 if ( mstable_.processor().nrow() == 0 )
1705 isProcessor_ = False ;
1706 isSysCal_ = msrec.isDefined( "SYSCAL" ) ;
1707 if ( isSysCal_ )
1708 if ( mstable_.sysCal().nrow() == 0 )
1709 isSysCal_ = False ;
1710 isWeather_ = msrec.isDefined( "WEATHER" ) ;
1711 if ( isWeather_ )
1712 if ( mstable_.weather().nrow() == 0 )
1713 isWeather_ = False ;
1714
1715 // column name for Tsys and Tcal
1716 if ( isSysCal_ ) {
1717 const MSSysCal &caltab = mstable_.sysCal() ;
1718 if ( !caltab.tableDesc().isColumn( colTcal_ ) ) {
1719 colTcal_ = "TCAL" ;
1720 if ( !caltab.tableDesc().isColumn( colTcal_ ) )
1721 colTcal_ = "NONE" ;
1722 }
1723 if ( !caltab.tableDesc().isColumn( colTsys_ ) ) {
1724 colTsys_ = "TSYS" ;
1725 if ( !caltab.tableDesc().isColumn( colTcal_ ) )
1726 colTsys_ = "NONE" ;
1727 }
1728 }
1729 else {
1730 colTcal_ = "NONE" ;
1731 colTsys_ = "NONE" ;
1732 }
1733
1734 // Access to MS subtables
1735 //MSField &fieldtab = mstable_.field() ;
1736 //MSPolarization &poltab = mstable_.polarization() ;
1737 //MSDataDescription &ddtab = mstable_.dataDescription() ;
1738 //MSObservation &obstab = mstable_.observation() ;
1739 //MSSource &srctab = mstable_.source() ;
1740 //MSSpectralWindow &spwtab = mstable_.spectralWindow() ;
1741 //MSSysCal &caltab = mstable_.sysCal() ;
1742 MSPointing &pointtab = mstable_.pointing() ;
1743 //MSState &stattab = mstable_.state() ;
1744 //MSAntenna &anttab = mstable_.antenna() ;
1745
1746 // SUBTABLES: FREQUENCIES
1747 //string freqFrame = getFrame() ;
1748 string baseFrame = frameFromSpwTable() ;
1749 table_->frequencies().setFrame( baseFrame ) ;
1750 table_->frequencies().setFrame( baseFrame, True ) ;
1751
1752 // SUBTABLES: WEATHER
1753 fillWeather() ;
1754
1755 // SUBTABLES: FOCUS
1756 fillFocus() ;
1757
1758 // SUBTABLES: TCAL
1759 fillTcal() ;
1760
1761 // SUBTABLES: FIT
1762 //fillFit() ;
1763
1764 // SUBTABLES: HISTORY
1765 //fillHistory() ;
1766
1767 /***
1768 * Start iteration using TableVisitor
1769 ***/
1770 Table stab = table_->table() ;
1771 {
1772 static const char *cols[] = {
1773 "OBSERVATION_ID", "FEED1", "FIELD_ID", "DATA_DESC_ID", "SCAN_NUMBER",
1774 "STATE_ID", "TIME",
1775 NULL
1776 };
1777 static const TypeManagerImpl<Int> tmInt;
1778 static const TypeManagerImpl<Double> tmDouble;
1779 static const TypeManager *const tms[] = {
1780 &tmInt, &tmInt, &tmInt, &tmInt, &tmInt, &tmInt, &tmDouble, NULL
1781 };
1782 //double t0 = mathutil::gettimeofday_sec() ;
1783 MSFillerVisitor myVisitor(mstable_, *table_ );
1784 //double t1 = mathutil::gettimeofday_sec() ;
1785 //cout << "MSFillerVisitor(): elapsed time " << t1-t0 << " sec" << endl ;
1786 myVisitor.setAntenna( antenna_ ) ;
1787 //myVisitor.setHeader( sdh ) ;
1788 if ( getPt_ ) {
1789 Table ptsel = pointtab( pointtab.col("ANTENNA_ID")==antenna_ ).sort( "TIME" ) ;
1790 myVisitor.setPointingTable( ptsel ) ;
1791 }
1792 if ( isWeather_ )
1793 myVisitor.setWeatherTime( mwTime_, mwInterval_, mwIndex_ ) ;
1794 if ( isSysCal_ )
1795 myVisitor.setSysCalRecord( tcalrec_ ) ;
1796
1797 //double t2 = mathutil::gettimeofday_sec() ;
1798 traverseTable(mstable_, cols, tms, &myVisitor);
1799 //double t3 = mathutil::gettimeofday_sec() ;
1800 //cout << "traverseTable(): elapsed time " << t3-t2 << " sec" << endl ;
1801
1802 sdh = myVisitor.getHeader() ;
1803 }
1804 /***
1805 * End iteration using TableVisitor
1806 ***/
1807
1808 // set header
1809 //sdh = myVisitor.getHeader() ;
1810 //table_->setHeader( sdh ) ;
1811
1812 // save path to POINTING table
1813 // 2011/07/06 TN
1814 // Path to POINTING table in original MS will not be written
1815 // if getPt_ is True
1816 Path datapath( tablename_ ) ;
1817 if ( !getPt_ ) {
1818 String pTabName = datapath.absoluteName() + "/POINTING" ;
1819 stab.rwKeywordSet().define( "POINTING", pTabName ) ;
1820 }
1821
1822 // for GBT
1823 if ( sdh.antennaname.contains( "GBT" ) ) {
1824 String goTabName = datapath.absoluteName() + "/GBT_GO" ;
1825 stab.rwKeywordSet().define( "GBT_GO", goTabName ) ;
1826 }
1827
1828 // for MS created from ASDM
1829 const TableRecord &msKeys = mstable_.keywordSet() ;
1830 uInt nfields = msKeys.nfields() ;
1831 for ( uInt ifield = 0 ; ifield < nfields ; ifield++ ) {
1832 String name = msKeys.name( ifield ) ;
1833 //os_ << "name = " << name << LogIO::POST ;
1834 if ( name.find( "ASDM" ) != String::npos ) {
1835 String asdmpath = msKeys.asTable( ifield ).tableName() ;
1836 os_ << "ASDM table: " << asdmpath << LogIO::POST ;
1837 stab.rwKeywordSet().define( name, asdmpath ) ;
1838 }
1839 }
1840
1841 //double endSec = mathutil::gettimeofday_sec() ;
1842 //os_ << "end MSFiller::fill() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1843}
1844
1845void MSFiller::close()
1846{
1847 //tablesel_.closeSubTables() ;
1848 mstable_.closeSubTables() ;
1849 //tablesel_.unlock() ;
1850 mstable_.unlock() ;
1851}
1852
1853void MSFiller::fillWeather()
1854{
1855 //double startSec = mathutil::gettimeofday_sec() ;
1856 //os_ << "start MSFiller::fillWeather() startSec=" << startSec << LogIO::POST ;
1857
1858 if ( !isWeather_ ) {
1859 // add dummy row
1860 table_->weather().table().addRow(1,True) ;
1861 return ;
1862 }
1863
1864 Table mWeather = mstable_.weather() ;
1865 //Table mWeatherSel = mWeather( mWeather.col("ANTENNA_ID") == antenna_ ).sort("TIME") ;
1866 Table mWeatherSel( mWeather( mWeather.col("ANTENNA_ID") == antenna_ ).sort("TIME") ) ;
1867 //os_ << "mWeatherSel.nrow() = " << mWeatherSel.nrow() << LogIO::POST ;
1868 if ( mWeatherSel.nrow() == 0 ) {
1869 os_ << "No rows with ANTENNA_ID = " << antenna_ << " in WEATHER table, Try -1..." << LogIO::POST ;
1870 mWeatherSel = Table( MSWeather( mWeather( mWeather.col("ANTENNA_ID") == -1 ) ) ) ;
1871 if ( mWeatherSel.nrow() == 0 ) {
1872 os_ << "No rows in WEATHER table" << LogIO::POST ;
1873 }
1874 }
1875 uInt wnrow = mWeatherSel.nrow() ;
1876 //os_ << "wnrow = " << wnrow << LogIO::POST ;
1877
1878 if ( wnrow == 0 )
1879 return ;
1880
1881 Table wtab = table_->weather().table() ;
1882 wtab.addRow( wnrow ) ;
1883
1884 Bool stationInfoExists = mWeatherSel.tableDesc().isColumn( "NS_WX_STATION_ID" ) ;
1885 Int stationId = -1 ;
1886 if ( stationInfoExists ) {
1887 // determine which station is closer
1888 ROScalarColumn<Int> stationCol( mWeatherSel, "NS_WX_STATION_ID" ) ;
1889 ROArrayColumn<Double> stationPosCol( mWeatherSel, "NS_WX_STATION_POSITION" ) ;
1890 Vector<Int> stationIds = stationCol.getColumn() ;
1891 Vector<Int> stationIdList( 0 ) ;
1892 Matrix<Double> stationPosList( 0, 3, 0.0 ) ;
1893 uInt numStation = 0 ;
1894 for ( uInt i = 0 ; i < stationIds.size() ; i++ ) {
1895 if ( !anyEQ( stationIdList, stationIds[i] ) ) {
1896 numStation++ ;
1897 stationIdList.resize( numStation, True ) ;
1898 stationIdList[numStation-1] = stationIds[i] ;
1899 stationPosList.resize( numStation, 3, True ) ;
1900 stationPosList.row( numStation-1 ) = stationPosCol( i ) ;
1901 }
1902 }
1903 //os_ << "staionIdList = " << stationIdList << endl ;
1904 Table mAntenna = mstable_.antenna() ;
1905 ROArrayColumn<Double> antposCol( mAntenna, "POSITION" ) ;
1906 Vector<Double> antpos = antposCol( antenna_ ) ;
1907 Double minDiff = -1.0 ;
1908 for ( uInt i = 0 ; i < stationIdList.size() ; i++ ) {
1909 Double diff = sum( square( antpos - stationPosList.row( i ) ) ) ;
1910 if ( minDiff < 0.0 || minDiff > diff ) {
1911 minDiff = diff ;
1912 stationId = stationIdList[i] ;
1913 }
1914 }
1915 }
1916 //os_ << "stationId = " << stationId << endl ;
1917
1918 ScalarColumn<Float> *fCol ;
1919 ROScalarColumn<Float> *sharedFloatCol ;
1920 if ( mWeatherSel.tableDesc().isColumn( "TEMPERATURE" ) ) {
1921 fCol = new ScalarColumn<Float>( wtab, "TEMPERATURE" ) ;
1922 sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "TEMPERATURE" ) ;
1923 fCol->putColumn( *sharedFloatCol ) ;
1924 delete sharedFloatCol ;
1925 delete fCol ;
1926 }
1927 if ( mWeatherSel.tableDesc().isColumn( "PRESSURE" ) ) {
1928 fCol = new ScalarColumn<Float>( wtab, "PRESSURE" ) ;
1929 sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "PRESSURE" ) ;
1930 fCol->putColumn( *sharedFloatCol ) ;
1931 delete sharedFloatCol ;
1932 delete fCol ;
1933 }
1934 if ( mWeatherSel.tableDesc().isColumn( "REL_HUMIDITY" ) ) {
1935 fCol = new ScalarColumn<Float>( wtab, "HUMIDITY" ) ;
1936 sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "REL_HUMIDITY" ) ;
1937 fCol->putColumn( *sharedFloatCol ) ;
1938 delete sharedFloatCol ;
1939 delete fCol ;
1940 }
1941 if ( mWeatherSel.tableDesc().isColumn( "WIND_SPEED" ) ) {
1942 fCol = new ScalarColumn<Float>( wtab, "WINDSPEED" ) ;
1943 sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "WIND_SPEED" ) ;
1944 fCol->putColumn( *sharedFloatCol ) ;
1945 delete sharedFloatCol ;
1946 delete fCol ;
1947 }
1948 if ( mWeatherSel.tableDesc().isColumn( "WIND_DIRECTION" ) ) {
1949 fCol = new ScalarColumn<Float>( wtab, "WINDAZ" ) ;
1950 sharedFloatCol = new ROScalarColumn<Float>( mWeatherSel, "WIND_DIRECTION" ) ;
1951 fCol->putColumn( *sharedFloatCol ) ;
1952 delete sharedFloatCol ;
1953 delete fCol ;
1954 }
1955 ScalarColumn<uInt> idCol( wtab, "ID" ) ;
1956 for ( uInt irow = 0 ; irow < wnrow ; irow++ )
1957 idCol.put( irow, irow ) ;
1958
1959 ROScalarQuantColumn<Double> tqCol( mWeatherSel, "TIME" ) ;
1960 ROScalarColumn<Double> tCol( mWeatherSel, "TIME" ) ;
1961 String tUnit = tqCol.getUnits() ;
1962 Vector<Double> mwTime = tCol.getColumn() ;
1963 if ( tUnit == "d" )
1964 mwTime *= 86400.0 ;
1965 tqCol.attach( mWeatherSel, "INTERVAL" ) ;
1966 tCol.attach( mWeatherSel, "INTERVAL" ) ;
1967 String iUnit = tqCol.getUnits() ;
1968 Vector<Double> mwInterval = tCol.getColumn() ;
1969 if ( iUnit == "d" )
1970 mwInterval *= 86400.0 ;
1971
1972 if ( stationId > 0 ) {
1973 ROScalarColumn<Int> stationCol( mWeatherSel, "NS_WX_STATION_ID" ) ;
1974 Vector<Int> stationVec = stationCol.getColumn() ;
1975 uInt wsnrow = ntrue( stationVec == stationId ) ;
1976 mwTime_.resize( wsnrow ) ;
1977 mwInterval_.resize( wsnrow ) ;
1978 mwIndex_.resize( wsnrow ) ;
1979 uInt wsidx = 0 ;
1980 for ( uInt irow = 0 ; irow < wnrow ; irow++ ) {
1981 if ( stationId == stationVec[irow] ) {
1982 mwTime_[wsidx] = mwTime[irow] ;
1983 mwInterval_[wsidx] = mwInterval[irow] ;
1984 mwIndex_[wsidx] = irow ;
1985 wsidx++ ;
1986 }
1987 }
1988 }
1989 else {
1990 mwTime_ = mwTime ;
1991 mwInterval_ = mwInterval ;
1992 mwIndex_.resize( mwTime_.size() ) ;
1993 indgen( mwIndex_ ) ;
1994 }
1995 //os_ << "mwTime[0] = " << mwTime_[0] << " mwInterval[0] = " << mwInterval_[0] << LogIO::POST ;
1996 //os_ << "mwIndex_=" << mwIndex_ << LogIO::POST;
1997 //double endSec = mathutil::gettimeofday_sec() ;
1998 //os_ << "end MSFiller::fillWeather() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
1999}
2000
2001void MSFiller::fillFocus()
2002{
2003 //double startSec = mathutil::gettimeofday_sec() ;
2004 //os_ << "start MSFiller::fillFocus() startSec=" << startSec << LogIO::POST ;
2005 // tentative
2006 table_->focus().addEntry( 0.0, 0.0, 0.0, 0.0 ) ;
2007 //double endSec = mathutil::gettimeofday_sec() ;
2008 //os_ << "end MSFiller::fillFocus() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2009}
2010
2011void MSFiller::fillTcal()
2012{
2013 //double startSec = mathutil::gettimeofday_sec() ;
2014 //os_ << "start MSFiller::fillTcal() startSec=" << startSec << LogIO::POST ;
2015
2016 if ( !isSysCal_ ) {
2017 // add dummy row
2018 os_ << "No SYSCAL rows" << LogIO::POST ;
2019 table_->tcal().table().addRow(1,True) ;
2020 Vector<Float> defaultTcal( 1, 1.0 ) ;
2021 ArrayColumn<Float> tcalCol( table_->tcal().table(), "TCAL" ) ;
2022 tcalCol.put( 0, defaultTcal ) ;
2023 return ;
2024 }
2025
2026 if ( colTcal_ == "NONE" ) {
2027 // add dummy row
2028 os_ << "No TCAL column" << LogIO::POST ;
2029 table_->tcal().table().addRow(1,True) ;
2030 Vector<Float> defaultTcal( 1, 1.0 ) ;
2031 ArrayColumn<Float> tcalCol( table_->tcal().table(), "TCAL" ) ;
2032 tcalCol.put( 0, defaultTcal ) ;
2033 return ;
2034 }
2035
2036 Table &sctab = mstable_.sysCal() ;
2037 if ( sctab.nrow() == 0 ) {
2038 os_ << "No SYSCAL rows" << LogIO::POST ;
2039 return ;
2040 }
2041 ROScalarColumn<Int> antCol( sctab, "ANTENNA_ID" ) ;
2042 Vector<Int> ant = antCol.getColumn() ;
2043 if ( allNE( ant, antenna_ ) ) {
2044 os_ << "No SYSCAL rows" << LogIO::POST ;
2045 return ;
2046 }
2047 ROTableColumn tcalCol( sctab, colTcal_ ) ;
2048 Bool notDefined = False ;
2049 for ( uInt irow = 0 ; irow < sctab.nrow() ; irow++ ) {
2050 if ( ant[irow] == antenna_ && !tcalCol.isDefined( irow ) ) {
2051 notDefined = True ;
2052 break ;
2053 }
2054 }
2055 if ( notDefined ) {
2056 os_ << "No TCAL value" << LogIO::POST ;
2057 table_->tcal().table().addRow(1,True) ;
2058 Vector<Float> defaultTcal( 1, 1.0 ) ;
2059 ArrayColumn<Float> tcalCol( table_->tcal().table(), "TCAL" ) ;
2060 tcalCol.put( 0, defaultTcal ) ;
2061 return ;
2062 }
2063
2064 static const char *cols[] = {
2065 "ANTENNA_ID", "FEED_ID", "SPECTRAL_WINDOW_ID", "TIME",
2066 NULL
2067 };
2068 static const TypeManagerImpl<Int> tmInt;
2069 static const TypeManagerImpl<Double> tmDouble;
2070 static const TypeManager *const tms[] = {
2071 &tmInt, &tmInt, &tmInt, &tmDouble, NULL
2072 };
2073 Table tab = table_->tcal().table() ;
2074 TcalVisitor visitor( sctab, tab, tcalrec_, antenna_ ) ;
2075 visitor.setTcalColumn( colTcal_ ) ;
2076
2077 traverseTable(sctab, cols, tms, &visitor);
2078
2079 infillTcal();
2080
2081 //tcalrec_.print( std::cout ) ;
2082 //double endSec = mathutil::gettimeofday_sec() ;
2083 //os_ << "end MSFiller::fillTcal() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2084}
2085
2086void MSFiller::infillTcal()
2087{
2088 uInt nfields = tcalrec_.nfields() ;
2089 set<Int> spwAvailable;
2090 for (uInt i = 0; i < nfields; i++) {
2091 String name = tcalrec_.name(i);
2092 size_t pos1 = name.find(':') + 4;
2093 size_t pos2 = name.find(':',pos1);
2094 Int spwid = String::toInt(name.substr(pos1,pos2-pos1));
2095 //cout << "spwid=" << spwid << endl;
2096 spwAvailable.insert(spwid);
2097 }
2098 Table spwtab = mstable_.spectralWindow();
2099 Table tcaltab = table_->tcal().table();
2100 ScalarColumn<uInt> idCol(tcaltab, "ID");
2101 ScalarColumn<String> timeCol(tcaltab, "TIME");
2102 ArrayColumn<Float> tcalCol(tcaltab, "TCAL");
2103 ROScalarColumn<Int> numChanCol(spwtab, "NUM_CHAN");
2104 Int numSpw = spwtab.nrow();
2105 Int dummyFeed = 0;
2106 Double dummyTime = 0.0;
2107 Vector<uInt> idminmax(2);
2108 for (Int i = 0; i < numSpw; i++) {
2109 if (spwAvailable.find(i) == spwAvailable.end()) {
2110 String key = keyTcal(dummyFeed, i, dummyTime);
2111 Vector<Float> tcal(numChanCol(i), 1.0);
2112 uInt nrow = tcaltab.nrow();
2113 tcaltab.addRow(1);
2114 idCol.put(nrow, nrow);
2115 timeCol.put(nrow, "");
2116 tcalCol.put(nrow, tcal);
2117 idminmax = nrow;
2118 tcalrec_.define(key, idminmax);
2119 }
2120 }
2121 //tcalrec_.print(cout);
2122}
2123
2124string MSFiller::getFrame()
2125{
2126 MFrequency::Types frame = MFrequency::DEFAULT ;
2127 ROTableColumn numChanCol( mstable_.spectralWindow(), "NUM_CHAN" ) ;
2128 ROTableColumn measFreqRefCol( mstable_.spectralWindow(), "MEAS_FREQ_REF" ) ;
2129 uInt nrow = numChanCol.nrow() ;
2130 Vector<Int> measFreqRef( nrow, MFrequency::DEFAULT ) ;
2131 uInt nref = 0 ;
2132 for ( uInt irow = 0 ; irow < nrow ; irow++ ) {
2133 if ( numChanCol.asInt( irow ) != 4 ) { // exclude WVR
2134 measFreqRef[nref] = measFreqRefCol.asInt( irow ) ;
2135 nref++ ;
2136 }
2137 }
2138 if ( nref > 0 )
2139 frame = (MFrequency::Types)measFreqRef[0] ;
2140
2141 return MFrequency::showType( frame ) ;
2142}
2143
2144void MSFiller::initHeader( STHeader &header )
2145{
2146 header.nchan = 0 ;
2147 header.npol = 0 ;
2148 header.nif = 0 ;
2149 header.nbeam = 0 ;
2150 header.observer = "" ;
2151 header.project = "" ;
2152 header.obstype = "" ;
2153 header.antennaname = "" ;
2154 header.antennaposition.resize( 3 ) ;
2155 header.equinox = 0.0 ;
2156 header.freqref = "" ;
2157 header.reffreq = -1.0 ;
2158 header.bandwidth = 0.0 ;
2159 header.utc = 0.0 ;
2160 header.fluxunit = "" ;
2161 header.epoch = "" ;
2162 header.poltype = "" ;
2163}
2164
2165string MSFiller::frameFromSpwTable()
2166{
2167 string frameString;
2168 Table tab = mstable_.spectralWindow();
2169 ROScalarColumn<Int> mfrCol(tab, "MEAS_FREQ_REF");
2170 Vector<Int> mfr = mfrCol.getColumn();
2171 if (allEQ(mfr,mfr[0])) {
2172 frameString = MFrequency::showType(mfr[0]);
2173 //cout << "all rows have same frame: " << frameString << endl;
2174 }
2175 else {
2176 mfrCol.attach(tab, "NUM_CHAN");
2177 for (uInt i = 0; i < tab.nrow(); i++) {
2178 if (mfrCol(i) != 4) {
2179 frameString = MFrequency::showType(mfr[i]);
2180 break;
2181 }
2182 }
2183 if (frameString.size() == 0) {
2184 frameString = "TOPO";
2185 }
2186 }
2187
2188 //cout << "frameString = " << frameString << endl;
2189
2190 return frameString;
2191}
2192
2193};
Note: See TracBrowser for help on using the repository browser.