source: trunk/src/MSFiller.cpp@ 3072

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

New Development: No

JIRA Issue: Yes CAS-8097

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...


More strict intent mapping. Only CALIBRATE_ATMOSPHERE#* intents are mapped into Srctype::PONCAL or SrcType::POFFCAL. Other CALIBRATE_* intents such as POINTING are separated from ATMOSPHERE and mapped into SrcType::CAL.

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