source: trunk/src/MSWriter.cpp@ 3063

Last change on this file since 3063 was 3063, checked in by Takeshi Nakazato, 10 years ago

New Development: No

JIRA Issue: Yes CAS-8062

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


Sort output POINTING table by time.

File size: 82.2 KB
Line 
1//
2// C++ Interface: MSWriter
3//
4// Description:
5//
6// This class is specific writer for MS format
7//
8// Takeshi Nakazato <takeshi.nakazato@nao.ac.jp>, (C) 2010
9//
10// Copyright: See COPYING file that comes with this distribution
11//
12//
13#include <assert.h>
14
15#include <set>
16
17#include <casa/OS/File.h>
18#include <casa/OS/RegularFile.h>
19#include <casa/OS/Directory.h>
20#include <casa/OS/SymLink.h>
21#include <casa/BasicSL/String.h>
22#include <casa/Arrays/Cube.h>
23#include <casa/Containers/RecordField.h>
24
25#include <tables/Tables/ExprNode.h>
26#include <tables/Tables/TableDesc.h>
27#include <tables/Tables/SetupNewTab.h>
28#include <tables/Tables/TableIter.h>
29#include <tables/Tables/RefRows.h>
30#include <tables/Tables/TableRow.h>
31
32#include <ms/MeasurementSets/MeasurementSet.h>
33#include <ms/MeasurementSets/MSColumns.h>
34#include <ms/MSSel/MSPolIndex.h>
35#include <ms/MSSel/MSDataDescIndex.h>
36#include <ms/MSSel/MSSourceIndex.h>
37
38#include "MSWriter.h"
39#include "STHeader.h"
40#include "STFrequencies.h"
41#include "STMolecules.h"
42#include "STTcal.h"
43#include "MathUtils.h"
44#include "TableTraverse.h"
45
46using namespace casa ;
47using namespace std ;
48
49namespace asap {
50
51class CorrTypeHandler {
52public:
53 CorrTypeHandler()
54 {}
55 virtual ~CorrTypeHandler() {}
56 virtual Vector<Stokes::StokesTypes> corrType() = 0 ;
57 virtual void reset()
58 {
59 npol = 0 ;
60 }
61 void append( uInt polno )
62 {
63 polnos[npol] = polno ;
64 npol++ ;
65 }
66 uInt nPol() { return npol ; }
67protected:
68 Vector<Stokes::StokesTypes> polmap ;
69 uInt polnos[4] ;
70 uInt npol ;
71};
72
73class LinearHandler : public CorrTypeHandler {
74public:
75 LinearHandler()
76 : CorrTypeHandler()
77 {
78 initMap() ;
79 }
80 virtual ~LinearHandler() {}
81 virtual Vector<Stokes::StokesTypes> corrType()
82 {
83 Vector<Stokes::StokesTypes> ret( npol, Stokes::Undefined ) ;
84 if ( npol < 4 ) {
85 for ( uInt ipol = 0 ; ipol < npol ; ipol++ )
86 ret[ipol] = polmap[polnos[ipol]] ;
87 }
88 else if ( npol == 4 ) {
89 ret[0] = polmap[0] ;
90 ret[1] = polmap[2] ;
91 ret[2] = polmap[3] ;
92 ret[3] = polmap[1] ;
93 }
94 else {
95 throw( AipsError("npol > 4") ) ;
96 }
97 return ret ;
98 }
99protected:
100 void initMap()
101 {
102 polmap.resize( 4 ) ;
103 polmap[0] = Stokes::XX ;
104 polmap[1] = Stokes::YY ;
105 polmap[2] = Stokes::XY ;
106 polmap[3] = Stokes::YX ;
107 }
108};
109class CircularHandler : public CorrTypeHandler {
110public:
111 CircularHandler()
112 : CorrTypeHandler()
113 {
114 initMap() ;
115 }
116 virtual ~CircularHandler() {}
117 virtual Vector<Stokes::StokesTypes> corrType()
118 {
119 Vector<Stokes::StokesTypes> ret( npol, Stokes::Undefined ) ;
120 if ( npol < 4 ) {
121 for ( uInt ipol = 0 ; ipol < npol ; ipol++ )
122 ret[ipol] = polmap[polnos[ipol]] ;
123 }
124 else if ( npol == 4 ) {
125 ret[0] = polmap[0] ;
126 ret[1] = polmap[2] ;
127 ret[2] = polmap[3] ;
128 ret[3] = polmap[1] ;
129 }
130 else {
131 throw( AipsError("npol > 4") ) ;
132 }
133 return ret ;
134 }
135private:
136 void initMap()
137 {
138 polmap.resize( 4 ) ;
139 polmap[0] = Stokes::RR ;
140 polmap[1] = Stokes::LL ;
141 polmap[2] = Stokes::RL ;
142 polmap[3] = Stokes::LR ;
143 }
144};
145class StokesHandler : public CorrTypeHandler {
146public:
147 StokesHandler()
148 : CorrTypeHandler()
149 {
150 initMap() ;
151 }
152 virtual ~StokesHandler() {}
153 virtual Vector<Stokes::StokesTypes> corrType()
154 {
155 Vector<Stokes::StokesTypes> ret( npol, Stokes::Undefined ) ;
156 if ( npol <= 4 ) {
157 for ( uInt ipol = 0 ; ipol < npol ; ipol++ )
158 ret[ipol] = polmap[polnos[ipol]] ;
159 }
160 else {
161 throw( AipsError("npol > 4") ) ;
162 }
163 return ret ;
164 }
165private:
166 void initMap()
167 {
168 polmap.resize( 4 ) ;
169 polmap[0] = Stokes::I ;
170 polmap[1] = Stokes::Q ;
171 polmap[2] = Stokes::U ;
172 polmap[3] = Stokes::V ;
173 }
174};
175class LinPolHandler : public CorrTypeHandler {
176public:
177 LinPolHandler()
178 : CorrTypeHandler()
179 {
180 initMap() ;
181 }
182 virtual ~LinPolHandler() {}
183 virtual Vector<Stokes::StokesTypes> corrType()
184 {
185 Vector<Stokes::StokesTypes> ret( npol, Stokes::Undefined ) ;
186 if ( npol <= 2 ) {
187 for ( uInt ipol = 0 ; ipol < npol ; ipol++ )
188 ret[ipol] = polmap[polnos[ipol]] ;
189 }
190 else {
191 throw( AipsError("npol > 4") ) ;
192 }
193 return ret ;
194 }
195private:
196 void initMap()
197 {
198 polmap.resize( 2 ) ;
199 polmap[0] = Stokes::Plinear ;
200 polmap[1] = Stokes::Pangle ;
201 }
202};
203
204class DataHolder {
205public:
206 DataHolder( TableRow &tableRow, String polType )
207 : row( tableRow )
208 {
209 nchan = 0 ;
210 npol = 0 ;
211 makeCorrTypeHandler( polType ) ;
212 attach() ;
213 flagRow.resize( 4 ) ;
214 reset() ;
215 sigmaTemplate.resize( 4 ) ;
216 sigmaTemplate = 1.0 ;
217 }
218 virtual ~DataHolder() {}
219 void post()
220 {
221 postData() ;
222 postFlag() ;
223 postFlagRow() ;
224 postAuxiliary() ;
225 }
226 virtual void reset()
227 {
228 corr->reset() ;
229 flagRow = False ;
230 npol = 0 ;
231 for ( uInt i = 0 ; i < 4 ; i++ )
232 isFilled[i] = False ;
233 }
234 virtual void accumulate( uInt id, Vector<Float> &sp, Vector<Bool> &fl, Bool &flr )
235 {
236 accumulateCorrType( id ) ;
237 accumulateData( id, sp ) ;
238 accumulateFlag( id, fl ) ;
239 accumulateFlagRow( id, flr ) ;
240 isFilled[id] = True;
241 }
242 uInt nPol() { return npol ; }
243 uInt nChan() { return nchan ; }
244 Vector<Int> corrTypeInt()
245 {
246 Vector<Int> v( npol ) ;
247 convertArray( v, corr->corrType() ) ;
248 return v ;
249 }
250 Vector<Stokes::StokesTypes> corrType() { return corr->corrType() ; }
251 void setNchan( uInt num )
252 {
253 nchan = num ;
254 resize() ;
255 }
256protected:
257 void postAuxiliary()
258 {
259 Vector<Float> w = sigmaTemplate( IPosition(1,0), IPosition(1,npol-1) ) ;
260 sigmaRF.define( w ) ;
261 weightRF.define( w ) ;
262 Cube<Bool> c( npol, nchan, 1, False ) ;
263 flagCategoryRF.define( c ) ;
264 }
265 inline void accumulateCorrType( uInt &id )
266 {
267 corr->append( id ) ;
268 npol = corr->nPol() ;
269 }
270 inline void accumulateFlagRow( uInt &id, Bool &flr )
271 {
272 flagRow[id] = flr ;
273 }
274 void postFlagRow()
275 {
276 // CAS-5545 FLAG_ROW must always be set False
277 //*flagRowRF = anyEQ( flagRow, True ) ;
278 *flagRowRF = False;
279 }
280 inline void accumulateFlag( uInt &id, Vector<Bool> &fl )
281 {
282 flag.row( id ) = fl ;
283 }
284 virtual void postFlag() = 0 ;
285 inline void accumulateData( uInt &id, Vector<Float> &sp )
286 {
287 data.row( id ) = sp ;
288 }
289 uInt filledIndex()
290 {
291 uInt idx = 0;
292 while( idx < 4 && !isFilled[idx] ) ++idx;
293 return idx;
294 }
295 virtual void postData() = 0 ;
296 TableRow &row ;
297 uInt nchan ;
298 uInt npol ;
299 CountedPtr<CorrTypeHandler> corr;
300 RecordFieldPtr< Vector<Float> > sigmaRF ;
301 RecordFieldPtr< Vector<Float> > weightRF ;
302 RecordFieldPtr< Array<Bool> > flagRF ;
303 RecordFieldPtr<Bool> flagRowRF ;
304 RecordFieldPtr< Cube<Bool> > flagCategoryRF ;
305 Vector<Bool> flagRow ;
306 Matrix<Bool> flag ;
307 Matrix<Float> data ;
308 Vector<Float> sigmaTemplate ;
309 Bool isFilled[4] ;
310private:
311 void makeCorrTypeHandler( String &polType )
312 {
313 if ( polType == "linear" )
314 corr = new LinearHandler() ;
315 else if ( polType == "circular" )
316 corr = new CircularHandler() ;
317 else if ( polType == "stokes" )
318 corr = new StokesHandler() ;
319 else if ( polType == "linpol" )
320 corr = new LinPolHandler() ;
321 else
322 throw( AipsError("Invalid polarization type") ) ;
323 }
324 void attach()
325 {
326 TableRecord &rec = row.record() ;
327 sigmaRF.attachToRecord( rec, "SIGMA" ) ;
328 weightRF.attachToRecord( rec, "WEIGHT" ) ;
329 flagRF.attachToRecord( rec, "FLAG" ) ;
330 flagRowRF.attachToRecord( rec, "FLAG_ROW" ) ;
331 flagCategoryRF.attachToRecord( rec, "FLAG_CATEGORY" ) ;
332 }
333 void resize()
334 {
335 flag.resize( 4, nchan ) ;
336 data.resize( 4, nchan ) ;
337 }
338};
339
340class FloatDataHolder : public DataHolder {
341public:
342 FloatDataHolder( TableRow &tableRow, String polType )
343 : DataHolder( tableRow, polType )
344 {
345 attachData() ;
346 }
347 virtual ~FloatDataHolder() {}
348protected:
349 virtual void postFlag()
350 {
351 // CAS-5545 FLAG must all be set True if FLAG_ROW is True
352 for (uInt ipol = 0; ipol < 4; ++ipol) {
353 if (isFilled[ipol] and flagRow[ipol]) {
354 flag(IPosition(2, ipol, 0), IPosition(2, ipol, nchan-1)) = True;
355 }
356 }
357
358 if ( npol == 2 ) {
359 flagRF.define( flag( IPosition( 2, 0, 0 ), IPosition( 2, npol-1, nchan-1 ) ) ) ;
360 }
361 else {
362 // should be npol == 1
363 uInt idx = filledIndex() ;
364 flagRF.define( flag( IPosition( 2, idx, 0 ), IPosition( 2, idx, nchan-1 ) ) ) ;
365 }
366 }
367 virtual void postData()
368 {
369 if ( npol == 2 ) {
370 dataRF.define( data( IPosition( 2, 0, 0 ), IPosition( 2, npol-1, nchan-1 ) ) ) ;
371 }
372 else {
373 // should be npol == 1
374 uInt idx = filledIndex() ;
375 dataRF.define( data( IPosition( 2, idx, 0 ), IPosition( 2, idx, nchan-1 ) ) ) ;
376 }
377 }
378private:
379 void attachData()
380 {
381 dataRF.attachToRecord( row.record(), "FLOAT_DATA" ) ;
382 }
383 RecordFieldPtr< Matrix<Float> > dataRF;
384};
385
386class ComplexDataHolder : public DataHolder {
387public:
388 ComplexDataHolder( TableRow &tableRow, String polType )
389 : DataHolder( tableRow, polType )
390 {
391 attachData() ;
392 }
393 virtual ~ComplexDataHolder() {}
394protected:
395 virtual void postFlag()
396 {
397 // CAS-5545 FLAG must all be set True if FLAG_ROW is True
398 for (uInt ipol = 0; ipol < 4; ++ipol) {
399 if (isFilled[ipol] and flagRow[ipol]) {
400 flag(IPosition(2, ipol, 0), IPosition(2, ipol, nchan-1)) = True;
401 }
402 }
403
404 if ( npol == 4 ) {
405 Vector<Bool> tmp = flag.row( 3 ) ;
406 flag.row( 3 ) = flag.row( 1 ) ;
407 flag.row( 2 ) = flag.row( 2 ) || tmp ;
408 flag.row( 1 ) = flag.row( 2 ) ;
409 flagRF.define( flag ) ;
410 }
411 else if ( npol == 2 ) {
412 flagRF.define( flag( IPosition( 2, 0, 0 ), IPosition( 2, npol-1, nchan-1 ) ) ) ;
413 }
414 else {
415 // should be npol == 1
416 uInt idx = filledIndex() ;
417 flagRF.define( flag( IPosition( 2, idx, 0 ), IPosition( 2, idx, nchan-1 ) ) ) ;
418 }
419 }
420 virtual void postData()
421 {
422 Matrix<Float> tmp( 2, nchan, 0.0 ) ;
423 Matrix<Complex> v( npol, nchan ) ;
424 if ( isFilled[0] ) {
425 tmp.row( 0 ) = data.row( 0 ) ;
426 v.row( 0 ) = RealToComplex( tmp ) ;
427 }
428 if ( isFilled[1] ) {
429 tmp.row( 0 ) = data.row( 1 ) ;
430 v.row( npol-1 ) = RealToComplex( tmp ) ;
431 }
432 if ( isFilled[2] && isFilled[3] ) {
433 tmp.row( 0 ) = data.row( 2 ) ;
434 tmp.row( 1 ) = data.row( 3 ) ;
435 v.row( 1 ) = RealToComplex( tmp ) ;
436 v.row( 2 ) = conj( v.row( 1 ) ) ;
437 }
438 dataRF.define( v ) ;
439 }
440private:
441 void attachData()
442 {
443 dataRF.attachToRecord( row.record(), "DATA" ) ;
444 }
445 RecordFieldPtr< Matrix<Complex> > dataRF;
446};
447
448class BaseMSWriterVisitor: public TableVisitor {
449 const String *lastFieldName;
450 uInt lastRecordNo;
451 uInt lastBeamNo, lastScanNo, lastIfNo, lastPolNo;
452 Int lastSrcType;
453 uInt lastCycleNo;
454 Double lastTime;
455protected:
456 const Table &table;
457 uInt count;
458public:
459 BaseMSWriterVisitor(const Table &table)
460 : table(table)
461 {
462 static const String dummy;
463 lastFieldName = &dummy;
464 count = 0;
465 }
466
467 virtual void enterFieldName(const uInt /*recordNo*/, const String &/*columnValue*/) {
468 }
469 virtual void leaveFieldName(const uInt /*recordNo*/, const String &/*columnValue*/) {
470 }
471 virtual void enterBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
472 virtual void leaveBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
473 virtual void enterScanNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
474 virtual void leaveScanNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
475 virtual void enterIfNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
476 virtual void leaveIfNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
477 virtual void enterSrcType(const uInt /*recordNo*/, Int /*columnValue*/) { }
478 virtual void leaveSrcType(const uInt /*recordNo*/, Int /*columnValue*/) { }
479 virtual void enterCycleNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
480 virtual void leaveCycleNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
481 virtual void enterTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
482 virtual void leaveTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
483 virtual void enterPolNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
484 virtual void leavePolNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
485
486 virtual Bool visitRecord(const uInt /*recordNo*/,
487 const String &/*fieldName*/,
488 const uInt /*beamNo*/,
489 const uInt /*scanNo*/,
490 const uInt /*ifNo*/,
491 const Int /*srcType*/,
492 const uInt /*cycleNo*/,
493 const Double /*time*/,
494 const uInt /*polNo*/) { return True ;}
495
496 virtual Bool visit(Bool isFirst, const uInt recordNo,
497 const uInt nCols, void const *const colValues[]) {
498 const String *fieldName = NULL;
499 uInt beamNo, scanNo, ifNo;
500 Int srcType;
501 uInt cycleNo;
502 Double time;
503 uInt polNo;
504 { // prologue
505 uInt i = 0;
506 {
507 const String *col = (const String*)colValues[i++];
508 fieldName = &col[recordNo];
509 }
510 {
511 const uInt *col = (const uInt *)colValues[i++];
512 beamNo = col[recordNo];
513 }
514 {
515 const uInt *col = (const uInt *)colValues[i++];
516 scanNo = col[recordNo];
517 }
518 {
519 const uInt *col = (const uInt *)colValues[i++];
520 ifNo = col[recordNo];
521 }
522 {
523 const Int *col = (const Int *)colValues[i++];
524 srcType = col[recordNo];
525 }
526 {
527 const uInt *col = (const uInt *)colValues[i++];
528 cycleNo = col[recordNo];
529 }
530 {
531 const Double *col = (const Double *)colValues[i++];
532 time = col[recordNo];
533 }
534 {
535 const Int *col = (const Int *)colValues[i++];
536 polNo = col[recordNo];
537 }
538 assert(nCols == i);
539 }
540
541 if (isFirst) {
542 enterFieldName(recordNo, *fieldName);
543 enterBeamNo(recordNo, beamNo);
544 enterScanNo(recordNo, scanNo);
545 enterIfNo(recordNo, ifNo);
546 enterSrcType(recordNo, srcType);
547 enterCycleNo(recordNo, cycleNo);
548 enterTime(recordNo, time);
549 enterPolNo(recordNo, polNo);
550 } else {
551 if (lastFieldName->compare(*fieldName) != 0) {
552 leavePolNo(lastRecordNo, lastPolNo);
553 leaveTime(lastRecordNo, lastTime);
554 leaveCycleNo(lastRecordNo, lastCycleNo);
555 leaveSrcType(lastRecordNo, lastSrcType);
556 leaveIfNo(lastRecordNo, lastIfNo);
557 leaveScanNo(lastRecordNo, lastScanNo);
558 leaveBeamNo(lastRecordNo, lastBeamNo);
559 leaveFieldName(lastRecordNo, *lastFieldName);
560
561 enterFieldName(recordNo, *fieldName);
562 enterBeamNo(recordNo, beamNo);
563 enterScanNo(recordNo, scanNo);
564 enterIfNo(recordNo, ifNo);
565 enterSrcType(recordNo, srcType);
566 enterCycleNo(recordNo, cycleNo);
567 enterTime(recordNo, time);
568 enterPolNo(recordNo, polNo);
569 } else if (lastBeamNo != beamNo) {
570 leavePolNo(lastRecordNo, lastPolNo);
571 leaveTime(lastRecordNo, lastTime);
572 leaveCycleNo(lastRecordNo, lastCycleNo);
573 leaveSrcType(lastRecordNo, lastSrcType);
574 leaveIfNo(lastRecordNo, lastIfNo);
575 leaveScanNo(lastRecordNo, lastScanNo);
576 leaveBeamNo(lastRecordNo, lastBeamNo);
577
578 enterBeamNo(recordNo, beamNo);
579 enterScanNo(recordNo, scanNo);
580 enterIfNo(recordNo, ifNo);
581 enterSrcType(recordNo, srcType);
582 enterCycleNo(recordNo, cycleNo);
583 enterTime(recordNo, time);
584 enterPolNo(recordNo, polNo);
585 } else if (lastScanNo != scanNo) {
586 leavePolNo(lastRecordNo, lastPolNo);
587 leaveTime(lastRecordNo, lastTime);
588 leaveCycleNo(lastRecordNo, lastCycleNo);
589 leaveSrcType(lastRecordNo, lastSrcType);
590 leaveIfNo(lastRecordNo, lastIfNo);
591 leaveScanNo(lastRecordNo, lastScanNo);
592
593 enterScanNo(recordNo, scanNo);
594 enterIfNo(recordNo, ifNo);
595 enterSrcType(recordNo, srcType);
596 enterCycleNo(recordNo, cycleNo);
597 enterTime(recordNo, time);
598 enterPolNo(recordNo, polNo);
599 } else if (lastIfNo != ifNo) {
600 leavePolNo(lastRecordNo, lastPolNo);
601 leaveTime(lastRecordNo, lastTime);
602 leaveCycleNo(lastRecordNo, lastCycleNo);
603 leaveSrcType(lastRecordNo, lastSrcType);
604 leaveIfNo(lastRecordNo, lastIfNo);
605
606 enterIfNo(recordNo, ifNo);
607 enterSrcType(recordNo, srcType);
608 enterCycleNo(recordNo, cycleNo);
609 enterTime(recordNo, time);
610 enterPolNo(recordNo, polNo);
611 } else if (lastSrcType != srcType) {
612 leavePolNo(lastRecordNo, lastPolNo);
613 leaveTime(lastRecordNo, lastTime);
614 leaveCycleNo(lastRecordNo, lastCycleNo);
615 leaveSrcType(lastRecordNo, lastSrcType);
616
617 enterSrcType(recordNo, srcType);
618 enterCycleNo(recordNo, cycleNo);
619 enterTime(recordNo, time);
620 enterPolNo(recordNo, polNo);
621 } else if (lastCycleNo != cycleNo) {
622 leavePolNo(lastRecordNo, lastPolNo);
623 leaveTime(lastRecordNo, lastTime);
624 leaveCycleNo(lastRecordNo, lastCycleNo);
625
626 enterCycleNo(recordNo, cycleNo);
627 enterTime(recordNo, time);
628 enterPolNo(recordNo, polNo);
629 } else if (lastTime != time) {
630 leavePolNo(lastRecordNo, lastPolNo);
631 leaveTime(lastRecordNo, lastTime);
632
633 enterTime(recordNo, time);
634 enterPolNo(recordNo, polNo);
635 } else if (lastPolNo != polNo) {
636 leavePolNo(lastRecordNo, lastPolNo);
637 enterPolNo(recordNo, polNo);
638 }
639 }
640 count++;
641 Bool result = visitRecord(recordNo, *fieldName, beamNo, scanNo, ifNo, srcType,
642 cycleNo, time, polNo);
643
644 { // epilogue
645 lastRecordNo = recordNo;
646
647 lastFieldName = fieldName;
648 lastBeamNo = beamNo;
649 lastScanNo = scanNo;
650 lastIfNo = ifNo;
651 lastSrcType = srcType;
652 lastCycleNo = cycleNo;
653 lastTime = time;
654 lastPolNo = polNo;
655 }
656 return result ;
657 }
658
659 virtual void finish() {
660 if (count > 0) {
661 leavePolNo(lastRecordNo, lastPolNo);
662 leaveTime(lastRecordNo, lastTime);
663 leaveCycleNo(lastRecordNo, lastCycleNo);
664 leaveSrcType(lastRecordNo, lastSrcType);
665 leaveIfNo(lastRecordNo, lastIfNo);
666 leaveScanNo(lastRecordNo, lastScanNo);
667 leaveBeamNo(lastRecordNo, lastBeamNo);
668 leaveFieldName(lastRecordNo, *lastFieldName);
669 }
670 }
671};
672
673class MSWriterVisitor: public BaseMSWriterVisitor, public MSWriterUtils {
674public:
675 MSWriterVisitor(const Table &table, Table &mstable)
676 : BaseMSWriterVisitor(table),
677 ms(mstable),
678 addScanrate_(False),
679 pointingTimeList_(table.nrow(), -1.0),
680 referenceBeam_(-1)
681 {
682 rowidx = 0 ;
683 fieldName = "" ;
684 defaultFieldId = 0 ;
685 spwId = -1 ;
686 subscan = 1 ;
687 ptName = "" ;
688 srcId = 0 ;
689
690 row = TableRow( ms ) ;
691
692 initPolarization() ;
693 initFrequencies() ;
694
695 //
696 // add rows to MS
697 //
698 uInt addrow = table.nrow() ;
699 ms.addRow( addrow ) ;
700
701 // attach to Scantable columns
702 spectraCol.attach( table, "SPECTRA" ) ;
703 flagtraCol.attach( table, "FLAGTRA" ) ;
704 flagRowCol.attach( table, "FLAGROW" ) ;
705 tcalIdCol.attach( table, "TCAL_ID" ) ;
706 intervalCol.attach( table, "INTERVAL" ) ;
707 directionCol.attach( table, "DIRECTION" ) ;
708 scanRateCol.attach( table, "SCANRATE" ) ;
709 timeCol.attach( table, "TIME" ) ;
710 freqIdCol.attach( table, "FREQ_ID" ) ;
711 sourceNameCol.attach( table, "SRCNAME" ) ;
712 sourceDirectionCol.attach( table, "SRCDIRECTION" ) ;
713 fieldNameCol.attach( table, "FIELDNAME" ) ;
714
715 // MS subtables
716 attachSubtables() ;
717
718 // attach to MS columns
719 attachMain() ;
720 attachPointing() ;
721
722 // decide whether put SCANRATE to MS POINTING column
723 if (anyNE(scanRateCol.getColumn(), (Double)0.0)) {
724 addScanrate_ = True;
725 }
726 }
727
728 virtual void enterFieldName(const uInt recordNo, const String &/*columnValue*/) {
729 //printf("%u: FieldName: %s\n", recordNo, columnValue.c_str());
730 fieldName = fieldNameCol.asString( recordNo ) ;
731 String::size_type pos = fieldName.find( "__" ) ;
732 if ( pos != String::npos ) {
733 fieldId = String::toInt( fieldName.substr( pos+2 ) ) ;
734 fieldName = fieldName.substr( 0, pos ) ;
735 }
736 else {
737 fieldId = defaultFieldId ;
738 defaultFieldId++ ;
739 }
740 Double tSec = timeCol.asdouble( recordNo ) * 86400.0 ;
741 Vector<Double> srcDir = sourceDirectionCol( recordNo ) ;
742 Vector<Double> srate = scanRateCol( recordNo ) ;
743 String srcName = sourceNameCol.asString( recordNo ) ;
744
745 addField( fieldId, fieldName, srcName, srcDir, srate, tSec ) ;
746
747 // put value
748 *fieldIdRF = fieldId ;
749 }
750 virtual void leaveFieldName(const uInt /*recordNo*/, const String &/*columnValue*/) {
751 }
752 virtual void enterBeamNo(const uInt /*recordNo*/, uInt columnValue) {
753 //printf("%u: BeamNo: %u\n", recordNo, columnValue);
754
755 feedId = (Int)columnValue ;
756 if (referenceBeam_ < 0) {
757 referenceBeam_ = feedId;
758 LogIO os;
759 os << "Reference beam is " << referenceBeam_ << LogIO::POST;
760 }
761
762 // put value
763 *feed1RF = feedId ;
764 *feed2RF = feedId ;
765 }
766 virtual void leaveBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/) {
767 }
768 virtual void enterScanNo(const uInt /*recordNo*/, uInt columnValue) {
769 //printf("%u: ScanNo: %u\n", recordNo, columnValue);
770
771 // put value
772 // CAS-5841: SCANNO should be consistent with MS SCAN_NUMBER
773 *scanNumberRF = (Int)columnValue ;
774 }
775 virtual void leaveScanNo(const uInt /*recordNo*/, uInt /*columnValue*/) {
776 subscan = 1 ;
777 }
778 virtual void enterIfNo(const uInt recordNo, uInt columnValue) {
779 //printf("%u: IfNo: %u\n", recordNo, columnValue);
780
781 spwId = (Int)columnValue ;
782 uInt freqId = freqIdCol.asuInt( recordNo ) ;
783
784 Vector<Float> sp = spectraCol( recordNo ) ;
785 uInt nchan = sp.nelements() ;
786 holder->setNchan( nchan ) ;
787
788 addSpectralWindow( spwId, freqId ) ;
789
790 addFeed( feedId, spwId ) ;
791 }
792 virtual void leaveIfNo(const uInt /*recordNo*/, uInt /*columnValue*/) {
793 }
794 virtual void enterSrcType(const uInt /*recordNo*/, Int columnValue) {
795 //printf("%u: SrcType: %d\n", recordNo, columnValue);
796
797 Int stateId = addState( columnValue ) ;
798
799 // put value
800 *stateIdRF = stateId ;
801 }
802 virtual void leaveSrcType(const uInt /*recordNo*/, Int /*columnValue*/) {
803 }
804 virtual void enterCycleNo(const uInt /*recordNo*/, uInt /*columnValue*/) {
805 //printf("%u: CycleNo: %u\n", recordNo, columnValue);
806 }
807 virtual void leaveCycleNo(const uInt /*recordNo*/, uInt /*columnValue*/) {
808 }
809 virtual void enterTime(const uInt recordNo, Double columnValue) {
810 //printf("%u: Time: %f\n", recordNo, columnValue);
811
812 Double timeSec = columnValue * 86400.0 ;
813 Double interval = intervalCol.asdouble( recordNo ) ;
814
815 // add POINTING row only when 1) BEAMNO is 0 and
816 // 2) there is no row corresponding to the current timestamp
817 //LogIO os;
818 //os << "feedId = " << feedId << LogIO::POST;
819 if ( ptName.empty() && feedId == referenceBeam_ &&
820 (potab.nrow() == 0 || allNE(pointingTimeList_(Slice(0, potab.nrow())), timeSec))) {
821 LogIO os;
822 os << LogIO::DEBUGGING << "ROW " << recordNo << " Beam " << feedId
823 << ": adding pointing row, potab.nrow() = " << potab.nrow() << LogIO::POST;
824 pointingTimeList_[potab.nrow()] = timeSec;
825 Vector<Double> dir = directionCol( recordNo ) ;
826 Vector<Double> rate = scanRateCol( recordNo ) ;
827// if (feedId != referenceBeam_) {
828// os << LogIO::DEBUGGING << "TODO: Need to store pointing direction of reference beam"
829// << " if only non-reference beam row is available for certain timestamp" << LogIO::POST;
830// }
831 //if ( anyNE( rate, 0.0 ) ) {
832 if (addScanrate_) {
833 Matrix<Double> msdir( 2, 2 ) ;
834 msdir.column( 0 ) = dir ;
835 msdir.column( 1 ) = rate ;
836 addPointing( timeSec, interval, msdir ) ;
837 }
838 else {
839 Matrix<Double> msdir( 2, 1 ) ;
840 msdir.column( 0 ) = dir ;
841 addPointing( timeSec, interval, msdir ) ;
842 }
843 }
844
845 // put value
846 *timeRF = timeSec ;
847 *timeCentroidRF = timeSec ;
848 *intervalRF = interval ;
849 *exposureRF = interval ;
850 }
851 virtual void leaveTime(const uInt /*recordNo*/, Double /*columnValue*/) {
852 if ( holder->nPol() > 0 ) {
853 Int polId = addPolarization() ;
854 Int ddId = addDataDescription( polId, spwId ) ;
855
856 // put field
857 *dataDescIdRF = ddId ;
858 holder->post() ;
859
860 // commit row
861 row.put( rowidx ) ;
862 rowidx++ ;
863
864 // reset holder
865 holder->reset() ;
866 }
867 }
868 virtual void enterPolNo(const uInt /*recordNo*/, uInt /*columnValue*/) {
869 //printf("%u: PolNo: %d\n", recordNo, columnValue);
870 }
871 virtual void leavePolNo(const uInt /*recordNo*/, uInt /*columnValue*/) {
872 }
873
874 virtual Bool visitRecord(const uInt recordNo,
875 const String &/*fieldName*/,
876 const uInt /*beamNo*/,
877 const uInt /*scanNo*/,
878 const uInt /*ifNo*/,
879 const Int /*srcType*/,
880 const uInt /*cycleNo*/,
881 const Double /*time*/,
882 const uInt polNo) {
883 //printf("%u: %s, %u, %u, %u, %d, %u, %f, %d\n", recordNo,
884 // fieldName.c_str(), beamNo, scanNo, ifNo, srcType, cycleNo, time, polNo);
885
886 Vector<Float> sp = spectraCol( recordNo ) ;
887 Vector<uChar> tmp = flagtraCol( recordNo ) ;
888 Vector<Bool> fl( tmp.shape() ) ;
889 convertArray( fl, tmp ) ;
890 Bool flr = (Bool)flagRowCol.asuInt( recordNo ) ;
891 holder->accumulate( polNo, sp, fl, flr ) ;
892
893 return True ;
894 }
895
896 virtual void finish() {
897 BaseMSWriterVisitor::finish();
898 //printf("Total: %u\n", count);
899
900 // remove rows
901 if ( ms.nrow() > rowidx ) {
902 uInt numRemove = ms.nrow() - rowidx ;
903 //cout << "numRemove = " << numRemove << endl ;
904 Vector<uInt> rows( numRemove ) ;
905 indgen( rows, rowidx ) ;
906 ms.removeRow( rows ) ;
907 }
908
909 // fill empty SPECTRAL_WINDOW rows
910 infillSpectralWindow() ;
911
912 // fill empty FIELD rows
913 infillField() ;
914
915 // sort POINTING rows
916 sortPointing();
917 }
918
919 void dataColumnName( String name )
920 {
921 if ( name == "DATA" )
922 holder = new ComplexDataHolder( row, poltype ) ;
923 else if ( name == "FLOAT_DATA" )
924 holder = new FloatDataHolder( row, poltype ) ;
925 }
926 void pointingTableName( String name ) {
927 ptName = name ;
928 }
929 void setSourceRecord( Record &r ) {
930 srcRec = r ;
931 }
932private:
933 void addField( Int &fid, String &fname, String &srcName,
934 Vector<Double> &sdir, Vector<Double> &srate,
935 Double &tSec )
936 {
937 uInt nrow = fieldtab.nrow() ;
938 while( (Int)nrow <= fid ) {
939 fieldtab.addRow( 1, True ) ;
940 nrow++ ;
941 }
942
943 Matrix<Double> dir ;
944 Int numPoly = 0 ;
945 if ( anyNE( srate, 0.0 ) ) {
946 dir.resize( 2, 2 ) ;
947 dir.column( 0 ) = sdir ;
948 dir.column( 1 ) = srate ;
949 numPoly = 1 ;
950 }
951 else {
952 dir.resize( 2, 1 ) ;
953 dir.column( 0 ) = sdir ;
954 }
955 srcId = srcRec.asInt( srcName ) ;
956
957 TableRow tr( fieldtab ) ;
958 TableRecord &r = tr.record() ;
959 putField( "NAME", r, fname ) ;
960 putField( "NUM_POLY", r, numPoly ) ;
961 putField( "TIME", r, tSec ) ;
962 putField( "SOURCE_ID", r, srcId ) ;
963 defineField( "DELAY_DIR", r, dir ) ;
964 defineField( "REFERENCE_DIR", r, dir ) ;
965 defineField( "PHASE_DIR", r, dir ) ;
966 tr.put( fid ) ;
967
968 // for POINTING table
969 *poNameRF = fname ;
970 }
971 Int addState( Int &id )
972 {
973 String obsMode ;
974 Bool isSignal ;
975 Double tnoise ;
976 Double tload ;
977 queryType( id, obsMode, isSignal, tnoise, tload ) ;
978
979 String key = obsMode+"_"+String::toString( subscan ) ;
980 Int idx = -1 ;
981 uInt nEntry = stateEntry.nelements() ;
982 for ( uInt i = 0 ; i < nEntry ; i++ ) {
983 if ( stateEntry[i] == key ) {
984 idx = i ;
985 break ;
986 }
987 }
988 if ( idx == -1 ) {
989 uInt nrow = statetab.nrow() ;
990 statetab.addRow( 1, True ) ;
991 TableRow tr( statetab ) ;
992 TableRecord &r = tr.record() ;
993 putField( "OBS_MODE", r, obsMode ) ;
994 putField( "SIG", r, isSignal ) ;
995 isSignal = !isSignal ;
996 putField( "REF", r, isSignal ) ;
997 putField( "CAL", r, tnoise ) ;
998 putField( "LOAD", r, tload ) ;
999 tr.put( nrow ) ;
1000 idx = nrow ;
1001
1002 stateEntry.resize( nEntry+1, True ) ;
1003 stateEntry[nEntry] = key ;
1004 }
1005 subscan++ ;
1006
1007 return idx ;
1008 }
1009 void addPointing( Double &tSec, Double &interval, Matrix<Double> &dir )
1010 {
1011 uInt nrow = potab.nrow() ;
1012 potab.addRow() ;
1013
1014 *poNumPolyRF = dir.ncolumn() - 1 ;
1015 *poTimeRF = tSec ;
1016 *poTimeOriginRF = tSec ;
1017 *poIntervalRF = interval ;
1018 poDirectionRF.define( dir ) ;
1019 poTargetRF.define( dir ) ;
1020 porow.put( nrow ) ;
1021 }
1022
1023 void sortPointing()
1024 {
1025 ScalarColumn<Double> timeCol(potab, "TIME");
1026 Vector<Double> originalTime = timeCol.getColumn();
1027 Sort sort;
1028 sort.sortKey(&originalTime[0], TpDouble, 0, Sort::Ascending);
1029 Vector<uInt> sortIndex;
1030 sort.sort(sortIndex, originalTime.nelements());
1031
1032 sortPointingTime(sortIndex);
1033 sortPointingNumPoly(sortIndex);
1034 sortPointingInterval(sortIndex);
1035 sortPointingName(sortIndex);
1036 sortPointingDirection(sortIndex);
1037 }
1038
1039 void sortPointingTime(const Vector<uInt> &sortIndex)
1040 {
1041 sortScalarColumn<Double>("TIME", sortIndex, "TIME_ORIGIN");
1042 }
1043
1044 void sortPointingNumPoly(const Vector<uInt> &sortIndex)
1045 {
1046 sortScalarColumn<Int>("NUM_POLY", sortIndex);
1047 }
1048
1049 void sortPointingInterval(const Vector<uInt> &sortIndex)
1050 {
1051 sortScalarColumn<Double>("INTERVAL", sortIndex);
1052 }
1053
1054 void sortPointingName(const Vector<uInt> &sortIndex)
1055 {
1056 sortScalarColumn<String>("NAME", sortIndex);
1057 }
1058
1059 void sortPointingDirection(const Vector<uInt> &sortIndex)
1060 {
1061 ArrayColumn<Double> col(potab, "DIRECTION");
1062 Cube<Double> data = col.getColumn();
1063 Cube<Double> sortedData(data.shape());
1064 for (size_t i = 0; i < sortIndex.nelements(); ++i) {
1065 sortedData.xyPlane(i) = data.xyPlane(sortIndex[i]);
1066 }
1067
1068 col.putColumn(sortedData);
1069 col.attach(potab, "TARGET");
1070 col.putColumn(sortedData);
1071 }
1072
1073 template<class T>
1074 void sortScalarColumn(const String &columnName, const Vector<uInt> &sortIndex, const String &copyColumnName="")
1075 {
1076 ScalarColumn<T> col(potab, columnName);
1077 Vector<T> data = col.getColumn();
1078 Vector<T> sortedData(data.shape());
1079 for (size_t i = 0; i < sortIndex.nelements(); ++i) {
1080 sortedData[i] = data[sortIndex[i]];
1081 }
1082 col.putColumn(sortedData);
1083 if (copyColumnName.size() > 0) {
1084 col.attach(potab, copyColumnName);
1085 col.putColumn(sortedData);
1086 }
1087 }
1088
1089 Int addPolarization()
1090 {
1091 Int idx = -1 ;
1092 Vector<Int> corrType = holder->corrTypeInt() ;
1093 uInt nEntry = polEntry.size() ;
1094 for ( uInt i = 0 ; i < nEntry ; i++ ) {
1095 if ( polEntry[i].conform( corrType ) && allEQ( polEntry[i], corrType ) ) {
1096 idx = i ;
1097 break ;
1098 }
1099 }
1100
1101 Int numCorr = holder->nPol() ;
1102 Matrix<Int> corrProduct = corrProductTemplate[numCorr].copy() ;
1103 if ( numCorr == 1 && (corrType[0] == Stokes::YY || corrType[0] == Stokes::LL ) ) {
1104 corrProduct = 1;
1105 }
1106
1107 if ( idx == -1 ) {
1108 uInt nrow = poltab.nrow() ;
1109 poltab.addRow( 1, True ) ;
1110 TableRow tr( poltab ) ;
1111 TableRecord &r = tr.record() ;
1112 putField( "NUM_CORR", r, numCorr ) ;
1113 defineField( "CORR_TYPE", r, corrType ) ;
1114 defineField( "CORR_PRODUCT", r, corrProduct ) ;
1115 tr.put( nrow ) ;
1116 idx = nrow ;
1117
1118 polEntry.resize( nEntry+1 ) ;
1119 polEntry[nEntry] = corrType ;
1120 }
1121
1122 return idx ;
1123 }
1124 Int addDataDescription( Int pid, Int sid )
1125 {
1126 Int idx = -1 ;
1127 uInt nItem = 2 ;
1128 uInt len = ddEntry.nelements() ;
1129 uInt nEntry = len / nItem ;
1130 const Int *dd_p = ddEntry.storage() ;
1131 for ( uInt i = 0 ; i < nEntry ; i++ ) {
1132 Int pol = *dd_p ;
1133 dd_p++ ;
1134 Int spw = *dd_p ;
1135 dd_p++ ;
1136 if ( pid == pol && sid == spw ) {
1137 idx = i ;
1138 break ;
1139 }
1140 }
1141
1142 if ( idx == -1 ) {
1143 uInt nrow = ddtab.nrow() ;
1144 ddtab.addRow( 1, True ) ;
1145 TableRow tr( ddtab ) ;
1146 TableRecord &r = tr.record() ;
1147 putField( "POLARIZATION_ID", r, pid ) ;
1148 putField( "SPECTRAL_WINDOW_ID", r, sid ) ;
1149 tr.put( nrow ) ;
1150 idx = nrow ;
1151
1152 ddEntry.resize( len+nItem ) ;
1153 ddEntry[len] = pid ;
1154 ddEntry[len+1] = sid ;
1155 }
1156
1157 return idx ;
1158 }
1159 void infillSpectralWindow()
1160 {
1161 ROScalarColumn<Int> nchanCol( spwtab, "NUM_CHAN" ) ;
1162 Vector<Int> nchan = nchanCol.getColumn() ;
1163 TableRow tr( spwtab ) ;
1164 TableRecord &r = tr.record() ;
1165 Int mfr = freqframe ;
1166 Int oneChan = 1 ;
1167 Vector<Double> dummy( 1, 0.0 ) ;
1168 putField( "MEAS_FREQ_REF", r, mfr ) ;
1169 defineField( "CHAN_FREQ", r, dummy ) ;
1170 defineField( "CHAN_WIDTH", r, dummy ) ;
1171 defineField( "EFFECTIVE_BW", r, dummy ) ;
1172 defineField( "RESOLUTION", r, dummy ) ;
1173 putField( "NUM_CHAN", r, oneChan ) ;
1174
1175 for ( uInt i = 0 ; i < spwtab.nrow() ; i++ ) {
1176 if ( nchan[i] == 0 )
1177 tr.put( i ) ;
1178 }
1179 }
1180 void infillField()
1181 {
1182 ScalarColumn<Int> sourceIdCol(fieldtab, "SOURCE_ID");
1183 ArrayColumn<Double> delayDirCol(fieldtab, "DELAY_DIR");
1184 ArrayColumn<Double> phaseDirCol(fieldtab, "PHASE_DIR");
1185 ArrayColumn<Double> referenceDirCol(fieldtab, "REFERENCE_DIR");
1186 uInt nrow = fieldtab.nrow();
1187 Matrix<Double> dummy(IPosition(2, 2, 1), 0.0);
1188 for (uInt irow = 0; irow < nrow; ++irow) {
1189 if (!phaseDirCol.isDefined(irow)) {
1190 delayDirCol.put(irow, dummy);
1191 phaseDirCol.put(irow, dummy);
1192 referenceDirCol.put(irow, dummy);
1193 sourceIdCol.put(irow, -1);
1194 }
1195 }
1196 }
1197 void addSpectralWindow( Int sid, uInt fid )
1198 {
1199 if (processedFreqId.find((uInt)fid) == processedFreqId.end()
1200 || processedIFNO.find((uInt)sid) == processedIFNO.end() ) {
1201 uInt nrow = spwtab.nrow() ;
1202 while( (Int)nrow <= sid ) {
1203 spwtab.addRow( 1, True ) ;
1204 nrow++ ;
1205 }
1206 processedFreqId.insert((uInt)fid);
1207 processedIFNO.insert((uInt)sid);
1208 }
1209 else {
1210 return ;
1211 }
1212
1213
1214 Double rp = refpix[fid] ;
1215 Double rv = refval[fid] ;
1216 Double ic = increment[fid] ;
1217
1218 Int mfrInt = (Int)freqframe ;
1219 Int nchan = holder->nChan() ;
1220 Double bw = nchan * abs( ic ) ;
1221 Double reffreq = rv - rp * ic ;
1222 Int netsb = 0 ; // USB->0, LSB->1
1223 if ( ic < 0 )
1224 netsb = 1 ;
1225 Vector<Double> res( nchan, abs(ic) ) ;
1226 Vector<Double> cw( nchan, ic ) ;
1227 Vector<Double> chanf( nchan ) ;
1228 indgen( chanf, reffreq, ic ) ;
1229
1230 TableRow tr( spwtab ) ;
1231 TableRecord &r = tr.record() ;
1232 putField( "MEAS_FREQ_REF", r, mfrInt ) ;
1233 putField( "NUM_CHAN", r, nchan ) ;
1234 putField( "TOTAL_BANDWIDTH", r, bw ) ;
1235 putField( "REF_FREQUENCY", r, reffreq ) ;
1236 putField( "NET_SIDEBAND", r, netsb ) ;
1237 defineField( "RESOLUTION", r, res ) ;
1238// defineField( "CHAN_WIDTH", r, res ) ;
1239 defineField( "CHAN_WIDTH", r, cw ) ;
1240 defineField( "EFFECTIVE_BW", r, res ) ;
1241 defineField( "CHAN_FREQ", r, chanf ) ;
1242 tr.put( sid ) ;
1243 }
1244 void addFeed( Int fid, Int sid )
1245 {
1246 Int idx = -1 ;
1247 uInt nItem = 2 ;
1248 uInt len = feedEntry.nelements() ;
1249 uInt nEntry = len / nItem ;
1250 const Int *fe_p = feedEntry.storage() ;
1251 for ( uInt i = 0 ; i < nEntry ; i++ ) {
1252 Int feed = *fe_p ;
1253 fe_p++ ;
1254 Int spw = *fe_p ;
1255 fe_p++ ;
1256 if ( fid == feed && sid == spw ) {
1257 idx = i ;
1258 break ;
1259 }
1260 }
1261
1262
1263 if ( idx == -1 ) {
1264 uInt nrow = feedtab.nrow() ;
1265 feedtab.addRow( 1, True ) ;
1266 Int numReceptors = 2 ;
1267 Vector<String> polType( numReceptors ) ;
1268 Matrix<Double> beamOffset( 2, numReceptors, 0.0 ) ;
1269 Vector<Double> receptorAngle( numReceptors, 0.0 ) ;
1270 if ( poltype == "linear" ) {
1271 polType[0] = "X" ;
1272 polType[1] = "Y" ;
1273 }
1274 else if ( poltype == "circular" ) {
1275 polType[0] = "R" ;
1276 polType[1] = "L" ;
1277 }
1278 else {
1279 polType[0] = "X" ;
1280 polType[1] = "Y" ;
1281 }
1282 Matrix<Complex> polResponse( numReceptors, numReceptors, 0.0 ) ;
1283
1284 TableRow tr( feedtab ) ;
1285 TableRecord &r = tr.record() ;
1286 putField( "FEED_ID", r, fid ) ;
1287 putField( "BEAM_ID", r, fid ) ;
1288 Int tmp = 0 ;
1289 putField( "ANTENNA_ID", r, tmp ) ;
1290 putField( "SPECTRAL_WINDOW_ID", r, sid ) ;
1291 putField( "NUM_RECEPTORS", r, numReceptors ) ;
1292 defineField( "POLARIZATION_TYPE", r, polType ) ;
1293 defineField( "BEAM_OFFSET", r, beamOffset ) ;
1294 defineField( "RECEPTOR_ANGLE", r, receptorAngle ) ;
1295 defineField( "POL_RESPONSE", r, polResponse ) ;
1296 tr.put( nrow ) ;
1297
1298 feedEntry.resize( len+nItem ) ;
1299 feedEntry[len] = fid ;
1300 feedEntry[len+1] = sid ;
1301 }
1302 }
1303 void initPolarization()
1304 {
1305 const TableRecord &keys = table.keywordSet() ;
1306 poltype = keys.asString( "POLTYPE" ) ;
1307
1308 initCorrProductTemplate() ;
1309 }
1310 void initFrequencies()
1311 {
1312 const TableRecord &keys = table.keywordSet() ;
1313 Table tab = keys.asTable( "FREQUENCIES" ) ;
1314 ROScalarColumn<uInt> idcol( tab, "ID" ) ;
1315 ROScalarColumn<Double> rpcol( tab, "REFPIX" ) ;
1316 ROScalarColumn<Double> rvcol( tab, "REFVAL" ) ;
1317 ROScalarColumn<Double> iccol( tab, "INCREMENT" ) ;
1318 Vector<uInt> id = idcol.getColumn() ;
1319 Vector<Double> rp = rpcol.getColumn() ;
1320 Vector<Double> rv = rvcol.getColumn() ;
1321 Vector<Double> ic = iccol.getColumn() ;
1322 for ( uInt i = 0 ; i < id.nelements() ; i++ ) {
1323 refpix.insert( pair<uInt,Double>( id[i], rp[i] ) ) ;
1324 refval.insert( pair<uInt,Double>( id[i], rv[i] ) ) ;
1325 increment.insert( pair<uInt,Double>( id[i], ic[i] ) ) ;
1326 }
1327 String frameStr = tab.keywordSet().asString( "BASEFRAME" ) ;
1328 MFrequency::getType( freqframe, frameStr ) ;
1329 }
1330 void attachSubtables()
1331 {
1332 //const TableRecord &keys = table.keywordSet() ;
1333 TableRecord &mskeys = ms.rwKeywordSet() ;
1334
1335 // FIELD table
1336 fieldtab = mskeys.asTable( "FIELD" ) ;
1337
1338 // SPECTRAL_WINDOW table
1339 spwtab = mskeys.asTable( "SPECTRAL_WINDOW" ) ;
1340
1341 // POINTING table
1342 potab = mskeys.asTable( "POINTING" ) ;
1343
1344 // POLARIZATION table
1345 poltab = mskeys.asTable( "POLARIZATION" ) ;
1346
1347 // DATA_DESCRIPTION table
1348 ddtab = mskeys.asTable( "DATA_DESCRIPTION" ) ;
1349
1350 // STATE table
1351 statetab = mskeys.asTable( "STATE" ) ;
1352
1353 // FEED table
1354 feedtab = mskeys.asTable( "FEED" ) ;
1355 }
1356 void attachMain()
1357 {
1358 TableRecord &r = row.record() ;
1359 dataDescIdRF.attachToRecord( r, "DATA_DESC_ID" ) ;
1360 timeRF.attachToRecord( r, "TIME" ) ;
1361 timeCentroidRF.attachToRecord( r, "TIME_CENTROID" ) ;
1362 intervalRF.attachToRecord( r, "INTERVAL" ) ;
1363 exposureRF.attachToRecord( r, "EXPOSURE" ) ;
1364 fieldIdRF.attachToRecord( r, "FIELD_ID" ) ;
1365 feed1RF.attachToRecord( r, "FEED1" ) ;
1366 feed2RF.attachToRecord( r, "FEED2" ) ;
1367 scanNumberRF.attachToRecord( r, "SCAN_NUMBER" ) ;
1368 stateIdRF.attachToRecord( r, "STATE_ID" ) ;
1369
1370 // constant values
1371 //Int id = 0 ;
1372 RecordFieldPtr<Int> intRF( r, "OBSERVATION_ID" ) ;
1373 *intRF = 0 ;
1374 intRF.attachToRecord( r, "ANTENNA1" ) ;
1375 *intRF = 0 ;
1376 intRF.attachToRecord( r, "ANTENNA2" ) ;
1377 *intRF = 0 ;
1378 intRF.attachToRecord( r, "ARRAY_ID" ) ;
1379 *intRF = 0 ;
1380 intRF.attachToRecord( r, "PROCESSOR_ID" ) ;
1381 *intRF = 0 ;
1382 RecordFieldPtr< Vector<Double> > arrayRF( r, "UVW" ) ;
1383 arrayRF.define( Vector<Double>( 3, 0.0 ) ) ;
1384 }
1385 void attachPointing()
1386 {
1387 porow = TableRow( potab ) ;
1388 TableRecord &r = porow.record() ;
1389 poNumPolyRF.attachToRecord( r, "NUM_POLY" ) ;
1390 poTimeRF.attachToRecord( r, "TIME" ) ;
1391 poTimeOriginRF.attachToRecord( r, "TIME_ORIGIN" ) ;
1392 poIntervalRF.attachToRecord( r, "INTERVAL" ) ;
1393 poNameRF.attachToRecord( r, "NAME" ) ;
1394 poDirectionRF.attachToRecord( r, "DIRECTION" ) ;
1395 poTargetRF.attachToRecord( r, "TARGET" ) ;
1396
1397 // constant values
1398 RecordFieldPtr<Int> antIdRF( r, "ANTENNA_ID" ) ;
1399 *antIdRF = 0 ;
1400 RecordFieldPtr<Bool> trackingRF( r, "TRACKING" ) ;
1401 *trackingRF = True ;
1402 }
1403 void queryType( Int type, String &stype, Bool &b, Double &t, Double &l )
1404 {
1405 t = 0.0 ;
1406 l = 0.0 ;
1407
1408 String sep1="#" ;
1409 String sep2="," ;
1410 String target="OBSERVE_TARGET" ;
1411 String atmcal="CALIBRATE_TEMPERATURE" ;
1412 String onstr="ON_SOURCE" ;
1413 String offstr="OFF_SOURCE" ;
1414 String pswitch="POSITION_SWITCH" ;
1415 String nod="NOD" ;
1416 String fswitch="FREQUENCY_SWITCH" ;
1417 String sigstr="SIG" ;
1418 String refstr="REF" ;
1419 String unspecified="UNSPECIFIED" ;
1420 String ftlow="LOWER" ;
1421 String fthigh="HIGHER" ;
1422 switch ( type ) {
1423 case SrcType::PSON:
1424 stype = target+sep1+onstr+sep2+pswitch ;
1425 b = True ;
1426 break ;
1427 case SrcType::PSOFF:
1428 stype = target+sep1+offstr+sep2+pswitch ;
1429 b = False ;
1430 break ;
1431 case SrcType::NOD:
1432 stype = target+sep1+onstr+sep2+nod ;
1433 b = True ;
1434 break ;
1435 case SrcType::FSON:
1436 stype = target+sep1+onstr+sep2+fswitch+sep1+sigstr ;
1437 b = True ;
1438 break ;
1439 case SrcType::FSOFF:
1440 stype = target+sep1+onstr+sep2+fswitch+sep1+refstr ;
1441 b = False ;
1442 break ;
1443 case SrcType::SKY:
1444 stype = atmcal+sep1+offstr+sep2+unspecified ;
1445 b = False ;
1446 break ;
1447 case SrcType::HOT:
1448 stype = atmcal+sep1+offstr+sep2+unspecified ;
1449 b = False ;
1450 break ;
1451 case SrcType::WARM:
1452 stype = atmcal+sep1+offstr+sep2+unspecified ;
1453 b = False ;
1454 break ;
1455 case SrcType::COLD:
1456 stype = atmcal+sep1+offstr+sep2+unspecified ;
1457 b = False ;
1458 break ;
1459 case SrcType::PONCAL:
1460 stype = atmcal+sep1+onstr+sep2+pswitch ;
1461 b = True ;
1462 break ;
1463 case SrcType::POFFCAL:
1464 stype = atmcal+sep1+offstr+sep2+pswitch ;
1465 b = False ;
1466 break ;
1467 case SrcType::NODCAL:
1468 stype = atmcal+sep1+onstr+sep2+nod ;
1469 b = True ;
1470 break ;
1471 case SrcType::FONCAL:
1472 stype = atmcal+sep1+onstr+sep2+fswitch+sep1+sigstr ;
1473 b = True ;
1474 break ;
1475 case SrcType::FOFFCAL:
1476 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+refstr ;
1477 b = False ;
1478 break ;
1479 case SrcType::FSLO:
1480 stype = target+sep1+onstr+sep2+fswitch+sep1+ftlow ;
1481 b = True ;
1482 break ;
1483 case SrcType::FLOOFF:
1484 stype = target+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1485 b = False ;
1486 break ;
1487 case SrcType::FLOSKY:
1488 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1489 b = False ;
1490 break ;
1491 case SrcType::FLOHOT:
1492 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1493 b = False ;
1494 break ;
1495 case SrcType::FLOWARM:
1496 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1497 b = False ;
1498 break ;
1499 case SrcType::FLOCOLD:
1500 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1501 b = False ;
1502 break ;
1503 case SrcType::FSHI:
1504 stype = target+sep1+onstr+sep2+fswitch+sep1+fthigh ;
1505 b = True ;
1506 break ;
1507 case SrcType::FHIOFF:
1508 stype = target+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1509 b = False ;
1510 break ;
1511 case SrcType::FHISKY:
1512 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1513 b = False ;
1514 break ;
1515 case SrcType::FHIHOT:
1516 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1517 b = False ;
1518 break ;
1519 case SrcType::FHIWARM:
1520 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1521 b = False ;
1522 break ;
1523 case SrcType::FHICOLD:
1524 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1525 b = False ;
1526 break ;
1527 case SrcType::SIG:
1528 stype = target+sep1+onstr+sep2+unspecified ;
1529 b = True ;
1530 break ;
1531 case SrcType::REF:
1532 stype = target+sep1+offstr+sep2+unspecified ;
1533 b = False ;
1534 break ;
1535 default:
1536 stype = unspecified ;
1537 b = True ;
1538 break ;
1539 }
1540 }
1541 void initCorrProductTemplate()
1542 {
1543 Int n = 1 ;
1544 {
1545 Matrix<Int> c( 2, n, 0 ) ;
1546 corrProductTemplate[n] = c ;
1547 }
1548 n = 2 ;
1549 {
1550 Matrix<Int> c( 2, n, 0 ) ;
1551 c.column( 1 ) = 1 ;
1552 corrProductTemplate[n] = c ;
1553 }
1554 n = 4 ;
1555 {
1556 Matrix<Int> c( 2, n, 0 ) ;
1557 c( 0, 2 ) = 1 ;
1558 c( 0, 3 ) = 1 ;
1559 c( 1, 1 ) = 1 ;
1560 c( 1, 3 ) = 1 ;
1561 corrProductTemplate[n] = c ;
1562 }
1563 }
1564
1565 Table &ms;
1566 TableRow row;
1567 uInt rowidx;
1568 String fieldName;
1569 Int fieldId;
1570 Int srcId;
1571 Int defaultFieldId;
1572 Int spwId;
1573 Int feedId;
1574 Int subscan;
1575 CountedPtr<DataHolder> holder;
1576 String ptName;
1577 Bool useFloat;
1578 String poltype;
1579 Bool addScanrate_;
1580
1581 // MS subtables
1582 Table spwtab;
1583 Table statetab;
1584 Table ddtab;
1585 Table poltab;
1586 Table fieldtab;
1587 Table feedtab;
1588 Table potab;
1589
1590 // Scantable MAIN columns
1591 ROArrayColumn<Float> spectraCol;
1592 ROArrayColumn<Double> directionCol,scanRateCol,sourceDirectionCol;
1593 ROArrayColumn<uChar> flagtraCol;
1594 ROTableColumn tcalIdCol,intervalCol,flagRowCol,timeCol,freqIdCol,
1595 sourceNameCol,fieldNameCol;
1596
1597 // MS MAIN columns
1598 RecordFieldPtr<Int> dataDescIdRF,fieldIdRF,feed1RF,feed2RF,
1599 scanNumberRF,stateIdRF;
1600 RecordFieldPtr<Double> timeRF,timeCentroidRF,intervalRF,exposureRF;
1601
1602 // MS POINTING columns
1603 TableRow porow;
1604 RecordFieldPtr<Int> poNumPolyRF ;
1605 RecordFieldPtr<Double> poTimeRF,
1606 poTimeOriginRF,
1607 poIntervalRF ;
1608 RecordFieldPtr<String> poNameRF ;
1609 RecordFieldPtr< Matrix<Double> > poDirectionRF,
1610 poTargetRF ;
1611
1612 Vector<String> stateEntry;
1613 Block<Int> ddEntry;
1614 Block<Int> feedEntry;
1615 vector< Vector<Int> > polEntry;
1616 set<uInt> processedFreqId;
1617 set<uInt> processedIFNO;
1618 map<uInt,Double> refpix;
1619 map<uInt,Double> refval;
1620 map<uInt,Double> increment;
1621 MFrequency::Types freqframe;
1622 Record srcRec;
1623 map< Int, Matrix<Int> > corrProductTemplate;
1624 Vector<Double> pointingTimeList_;
1625 Int referenceBeam_;
1626};
1627
1628class BaseMSSysCalVisitor: public TableVisitor {
1629 uInt lastRecordNo;
1630 uInt lastBeamNo, lastIfNo, lastPolNo;
1631 Double lastTime;
1632protected:
1633 const Table &table;
1634 uInt count;
1635public:
1636 BaseMSSysCalVisitor(const Table &table)
1637 : table(table)
1638 {
1639 count = 0;
1640 }
1641
1642 virtual void enterBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1643 virtual void leaveBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1644 virtual void enterIfNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1645 virtual void leaveIfNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1646 virtual void enterPolNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1647 virtual void leavePolNo(const uInt /*recordNo*/, uInt /*columnValue*/) { }
1648 virtual void enterTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
1649 virtual void leaveTime(const uInt /*recordNo*/, Double /*columnValue*/) { }
1650
1651 virtual Bool visitRecord(const uInt /*recordNo*/,
1652 const uInt /*beamNo*/,
1653 const uInt /*ifNo*/,
1654 const uInt /*polNo*/,
1655 const Double /*time*/) { return True ;}
1656
1657 virtual Bool visit(Bool isFirst, const uInt recordNo,
1658 const uInt nCols, void const *const colValues[]) {
1659 uInt beamNo, ifNo, polNo;
1660 Double time;
1661 { // prologue
1662 uInt i = 0;
1663 {
1664 const uInt *col = (const uInt *)colValues[i++];
1665 beamNo = col[recordNo];
1666 }
1667 {
1668 const uInt *col = (const uInt *)colValues[i++];
1669 ifNo = col[recordNo];
1670 }
1671 {
1672 const Double *col = (const Double *)colValues[i++];
1673 time = col[recordNo];
1674 }
1675 {
1676 const uInt *col = (const uInt *)colValues[i++];
1677 polNo = col[recordNo];
1678 }
1679 assert(nCols == i);
1680 }
1681
1682 if (isFirst) {
1683 enterBeamNo(recordNo, beamNo);
1684 enterIfNo(recordNo, ifNo);
1685 enterTime(recordNo, time);
1686 enterPolNo(recordNo, polNo);
1687 } else {
1688 if (lastBeamNo != beamNo) {
1689 leavePolNo(lastRecordNo, lastPolNo);
1690 leaveTime(lastRecordNo, lastTime);
1691 leaveIfNo(lastRecordNo, lastIfNo);
1692 leaveBeamNo(lastRecordNo, lastBeamNo);
1693
1694 enterBeamNo(recordNo, beamNo);
1695 enterIfNo(recordNo, ifNo);
1696 enterTime(recordNo, time);
1697 enterPolNo(recordNo, polNo);
1698 } else if (lastIfNo != ifNo) {
1699 leavePolNo(lastRecordNo, lastPolNo);
1700 leaveTime(lastRecordNo, lastTime);
1701 leaveIfNo(lastRecordNo, lastIfNo);
1702
1703 enterIfNo(recordNo, ifNo);
1704 enterTime(recordNo, time);
1705 enterPolNo(recordNo, polNo);
1706 } else if (lastTime != time) {
1707 leavePolNo(lastRecordNo, lastPolNo);
1708 leaveTime(lastRecordNo, lastTime);
1709
1710 enterTime(recordNo, time);
1711 enterPolNo(recordNo, polNo);
1712 } else if (lastPolNo != polNo) {
1713 leavePolNo(lastRecordNo, lastPolNo);
1714 enterPolNo(recordNo, polNo);
1715 }
1716 }
1717 count++;
1718 Bool result = visitRecord(recordNo, beamNo, ifNo, polNo, time);
1719
1720 { // epilogue
1721 lastRecordNo = recordNo;
1722
1723 lastBeamNo = beamNo;
1724 lastIfNo = ifNo;
1725 lastPolNo = polNo;
1726 lastTime = time;
1727 }
1728 return result ;
1729 }
1730
1731 virtual void finish() {
1732 if (count > 0) {
1733 leavePolNo(lastRecordNo, lastPolNo);
1734 leaveTime(lastRecordNo, lastTime);
1735 leaveIfNo(lastRecordNo, lastIfNo);
1736 leaveBeamNo(lastRecordNo, lastBeamNo);
1737 }
1738 }
1739};
1740
1741class BaseTsysHolder
1742{
1743public:
1744 BaseTsysHolder( ROArrayColumn<Float> &tsysCol )
1745 : col( tsysCol ),
1746 nchan(0)
1747 {
1748 reset() ;
1749 }
1750 virtual ~BaseTsysHolder() {}
1751 virtual Array<Float> getTsys() = 0 ;
1752 void setNchan( uInt n ) { nchan = n ; }
1753 void appendTsys( uInt row )
1754 {
1755 Vector<Float> v = col( row ) ;
1756 uInt len = tsys.nrow() ;
1757 tsys.resize( len+1, nchan, True ) ;
1758 if ( v.nelements() == nchan )
1759 tsys.row( len ) = v ;
1760 else
1761 tsys.row( len ) = v[0] ;
1762 }
1763 void setTsys( uInt row, uInt idx )
1764 {
1765 if ( idx >= nrow() )
1766 appendTsys( row ) ;
1767 else {
1768 Vector<Float> v = col( row ) ;
1769 if ( v.nelements() == nchan )
1770 tsys.row( idx ) = v ;
1771 else
1772 tsys.row( idx ) = v[0] ;
1773 }
1774 }
1775 void reset()
1776 {
1777 tsys.resize() ;
1778 }
1779 uInt nrow() { return tsys.nrow() ; }
1780 Bool isEffective()
1781 {
1782 return ( !(tsys.empty()) && anyNE( tsys, (Float)1.0 ) ) ;
1783 }
1784 BaseTsysHolder &operator= ( const BaseTsysHolder &v )
1785 {
1786 if ( this != &v )
1787 tsys.assign( v.tsys ) ;
1788 return *this ;
1789 }
1790protected:
1791 ROArrayColumn<Float> col ;
1792 Matrix<Float> tsys ;
1793 uInt nchan ;
1794};
1795
1796class TsysHolder : public BaseTsysHolder
1797{
1798public:
1799 TsysHolder( ROArrayColumn<Float> &tsysCol )
1800 : BaseTsysHolder( tsysCol )
1801 {}
1802 virtual ~TsysHolder() {}
1803 virtual Array<Float> getTsys()
1804 {
1805 return tsys.column( 0 ) ;
1806 }
1807};
1808
1809class TsysSpectrumHolder : public BaseTsysHolder
1810{
1811public:
1812 TsysSpectrumHolder( ROArrayColumn<Float> &tsysCol )
1813 : BaseTsysHolder( tsysCol )
1814 {}
1815 virtual ~TsysSpectrumHolder() {}
1816 virtual Array<Float> getTsys()
1817 {
1818 return tsys ;
1819 }
1820};
1821
1822class BaseTcalProcessor
1823{
1824public:
1825 BaseTcalProcessor( ROArrayColumn<Float> &tcalCol )
1826 : col_( tcalCol )
1827 {}
1828 virtual ~BaseTcalProcessor() {}
1829 void setTcalId( Vector<uInt> &tcalId ) { id_.assign( tcalId ) ; }
1830 virtual Array<Float> getTcal() = 0 ;
1831protected:
1832 ROArrayColumn<Float> col_ ;
1833 Vector<uInt> id_ ;
1834};
1835
1836class TcalProcessor : public BaseTcalProcessor
1837{
1838public:
1839 TcalProcessor( ROArrayColumn<Float> &tcalCol )
1840 : BaseTcalProcessor( tcalCol )
1841 {}
1842 virtual ~TcalProcessor() {}
1843 virtual Array<Float> getTcal()
1844 {
1845 uInt npol = id_.nelements() ;
1846 Vector<Float> tcal( npol ) ;
1847 for ( uInt ipol = 0 ; ipol < npol ; ipol++ )
1848 tcal[ipol] = col_( id_[ipol] ).data()[0] ;
1849 //cout << "TcalProcessor: tcal = " << tcal << endl ;
1850 return tcal ;
1851 }
1852};
1853
1854class TcalSpectrumProcessor : public BaseTcalProcessor
1855{
1856public:
1857 TcalSpectrumProcessor( ROArrayColumn<Float> &tcalCol )
1858 : BaseTcalProcessor( tcalCol )
1859 {}
1860 virtual ~TcalSpectrumProcessor() {}
1861 virtual Array<Float> getTcal()
1862 {
1863 uInt npol = id_.nelements() ;
1864 //Vector<Float> tcal0 = col_( 0 ) ;
1865 Vector<Float> tcal0 = col_( id_[0] ) ;
1866 uInt nchan = tcal0.nelements() ;
1867 Matrix<Float> tcal( npol, nchan ) ;
1868 tcal.row( 0 ) = tcal0 ;
1869 for ( uInt ipol = 1 ; ipol < npol ; ipol++ )
1870 tcal.row( ipol ) = col_( id_[ipol] ) ;
1871 return tcal ;
1872 }
1873};
1874
1875class MSSysCalVisitor : public BaseMSSysCalVisitor
1876{
1877public:
1878 MSSysCalVisitor( const Table &from, Table &to )
1879 : BaseMSSysCalVisitor( from ),
1880 sctab( to ),
1881 rowidx( 0 ),
1882 polno_()
1883 {
1884 scrow = TableRow( sctab ) ;
1885
1886 lastTcalId.resize() ;
1887 theTcalId.resize() ;
1888 startTime = 0.0 ;
1889 endTime = 0.0 ;
1890
1891 const TableRecord &keys = table.keywordSet() ;
1892 Table tcalTable = keys.asTable( "TCAL" ) ;
1893 tcalCol.attach( tcalTable, "TCAL" ) ;
1894 tsysCol.attach( table, "TSYS" ) ;
1895 tcalIdCol.attach( table, "TCAL_ID" ) ;
1896 intervalCol.attach( table, "INTERVAL" ) ;
1897 effectiveTcal.resize( tcalTable.nrow() ) ;
1898 for ( uInt irow = 0 ; irow < tcalTable.nrow() ; irow++ ) {
1899 if ( allEQ( tcalCol( irow ), (Float)1.0 ) )
1900 effectiveTcal[irow] = False ;
1901 else
1902 effectiveTcal[irow] = True ;
1903 }
1904
1905 TableRecord &r = scrow.record() ;
1906 RecordFieldPtr<Int> antennaIdRF( r, "ANTENNA_ID" ) ;
1907 *antennaIdRF = 0 ;
1908 feedIdRF.attachToRecord( r, "FEED_ID" ) ;
1909 specWinIdRF.attachToRecord( r, "SPECTRAL_WINDOW_ID" ) ;
1910 timeRF.attachToRecord( r, "TIME" ) ;
1911 intervalRF.attachToRecord( r, "INTERVAL" ) ;
1912 if ( r.isDefined( "TCAL" ) ) {
1913 tcalRF.attachToRecord( r, "TCAL" ) ;
1914 tcalProcessor = new TcalProcessor( tcalCol ) ;
1915 }
1916 else if ( r.isDefined( "TCAL_SPECTRUM" ) ) {
1917 tcalRF.attachToRecord( r, "TCAL_SPECTRUM" ) ;
1918 tcalProcessor = new TcalSpectrumProcessor( tcalCol ) ;
1919 }
1920 if ( r.isDefined( "TSYS" ) ) {
1921 tsysRF.attachToRecord( r, "TSYS" ) ;
1922 theTsys = new TsysHolder( tsysCol ) ;
1923 lastTsys = new TsysHolder( tsysCol ) ;
1924 }
1925 else {
1926 tsysRF.attachToRecord( r, "TSYS_SPECTRUM" ) ;
1927 theTsys = new TsysSpectrumHolder( tsysCol ) ;
1928 lastTsys = new TsysSpectrumHolder( tsysCol ) ;
1929 }
1930
1931 }
1932
1933 virtual void enterBeamNo(const uInt /*recordNo*/, uInt columnValue)
1934 {
1935 *feedIdRF = (Int)columnValue ;
1936 }
1937 virtual void leaveBeamNo(const uInt /*recordNo*/, uInt /*columnValue*/)
1938 {
1939 }
1940 virtual void enterIfNo(const uInt recordNo, uInt columnValue)
1941 {
1942 //cout << "enterIfNo" << endl ;
1943 ROArrayColumn<Float> sp( table, "SPECTRA" ) ;
1944 uInt nchan = sp( recordNo ).nelements() ;
1945 theTsys->setNchan( nchan ) ;
1946 lastTsys->setNchan( nchan ) ;
1947
1948 *specWinIdRF = (Int)columnValue ;
1949 }
1950 virtual void leaveIfNo(const uInt /*recordNo*/, uInt /*columnValue*/)
1951 {
1952 //cout << "leaveIfNo" << endl ;
1953 post() ;
1954 reset(true);
1955 startTime = 0.0 ;
1956 endTime = 0.0 ;
1957 }
1958 virtual void enterTime(const uInt recordNo, Double columnValue)
1959 {
1960 //cout << "enterTime" << endl ;
1961 interval = intervalCol.asdouble( recordNo ) ;
1962 // start time and end time
1963 if ( startTime == 0.0 ) {
1964 startTime = columnValue * 86400.0 - 0.5 * interval ;
1965 endTime = columnValue * 86400.0 + 0.5 * interval ;
1966 }
1967 }
1968 virtual void leaveTime(const uInt /*recordNo*/, Double columnValue)
1969 {
1970 //cout << "leaveTime" << endl ;
1971 if ( isUpdated() ) {
1972 post() ;
1973 *lastTsys = *theTsys ;
1974 lastTcalId = theTcalId ;
1975 reset(false);
1976 startTime = columnValue * 86400.0 - 0.5 * interval ;
1977 endTime = columnValue * 86400.0 + 0.5 * interval ;
1978 }
1979 else {
1980 endTime = columnValue * 86400.0 + 0.5 * interval ;
1981 }
1982 }
1983 virtual void enterPolNo(const uInt recordNo, uInt columnValue)
1984 {
1985 //cout << "enterPolNo" << endl ;
1986 Vector<Float> tsys = tsysCol( recordNo ) ;
1987 uInt tcalId = tcalIdCol.asuInt( recordNo ) ;
1988 polno_.insert( columnValue ) ;
1989 uInt numPol = polno_.size() ;
1990 if ( lastTsys->nrow() < numPol )
1991 lastTsys->appendTsys( recordNo ) ;
1992 if ( lastTcalId.nelements() <= numPol )
1993 appendTcalId( lastTcalId, tcalId, numPol-1 ) ;
1994 if ( theTsys->nrow() < numPol )
1995 theTsys->appendTsys( recordNo ) ;
1996 else {
1997 theTsys->setTsys( recordNo, numPol-1 ) ;
1998 }
1999 if ( theTcalId.nelements() < numPol )
2000 appendTcalId( theTcalId, tcalId, numPol-1 ) ;
2001 else
2002 setTcalId( theTcalId, tcalId, numPol-1 ) ;
2003 }
2004 virtual void leavePolNo( const uInt /*recordNo*/, uInt /*columnValue*/ )
2005 {
2006 }
2007
2008private:
2009 void reset(bool completely)
2010 {
2011 if (completely) {
2012 lastTsys->reset() ;
2013 lastTcalId.resize() ;
2014 }
2015 theTsys->reset() ;
2016 theTcalId.resize() ;
2017 polno_.clear();
2018 }
2019 void appendTcalId( Vector<uInt> &v, uInt &elem, uInt polId )
2020 {
2021 v.resize( polId+1, True ) ;
2022 v[polId] = elem ;
2023 }
2024 void setTcalId( Vector<uInt> &v, uInt &elem, uInt polId )
2025 {
2026 v[polId] = elem ;
2027 }
2028 void post()
2029 {
2030 // check if given Tcal and Tsys is effective
2031 Bool isEffective = False ;
2032 for ( uInt ipol = 0 ; ipol < lastTcalId.nelements() ; ipol++ ) {
2033 if ( effectiveTcal[lastTcalId[ipol]] ) {
2034 isEffective = True ;
2035 break ;
2036 }
2037 }
2038 if ( !isEffective ) {
2039 if ( !(lastTsys->isEffective()) )
2040 return ;
2041 }
2042
2043 //cout << " interval: " << (endTime-startTime) << " lastTcalId = " << lastTcalId << endl ;
2044 Double midTime = 0.5 * ( startTime + endTime ) ;
2045 Double interval = endTime - startTime ;
2046 *timeRF = midTime ;
2047 *intervalRF = interval ;
2048 tcalProcessor->setTcalId( lastTcalId ) ;
2049 Array<Float> tcal = tcalProcessor->getTcal() ;
2050 Array<Float> tsys = lastTsys->getTsys() ;
2051 tcalRF.define( tcal ) ;
2052 tsysRF.define( tsys ) ;
2053 sctab.addRow( 1, True ) ;
2054 scrow.put( rowidx ) ;
2055 rowidx++ ;
2056 }
2057
2058 Bool isUpdated()
2059 {
2060 Bool ret = (anyNE( theTcalId, lastTcalId ) || anyNE( theTsys->getTsys(), lastTsys->getTsys() )) ;
2061 return ret ;
2062 }
2063
2064 Table &sctab;
2065 TableRow scrow;
2066 uInt rowidx;
2067
2068 Double startTime,endTime,interval;
2069
2070 CountedPtr<BaseTsysHolder> lastTsys,theTsys;
2071 Vector<uInt> lastTcalId,theTcalId;
2072 set<uInt> polno_;
2073 CountedPtr<BaseTcalProcessor> tcalProcessor ;
2074 Vector<Bool> effectiveTcal;
2075
2076 RecordFieldPtr<Int> feedIdRF,specWinIdRF;
2077 RecordFieldPtr<Double> timeRF,intervalRF;
2078 RecordFieldPtr< Array<Float> > tcalRF,tsysRF;
2079
2080 ROArrayColumn<Float> tsysCol,tcalCol;
2081 ROTableColumn tcalIdCol,intervalCol;
2082};
2083
2084MSWriter::MSWriter(CountedPtr<Scantable> stable)
2085 : table_(stable),
2086 mstable_(NULL),
2087 isWeather_(False),
2088 tcalSpec_(False),
2089 tsysSpec_(False),
2090 ptTabName_("")
2091{
2092 os_ = LogIO() ;
2093 os_.origin( LogOrigin( "MSWriter", "MSWriter()", WHERE ) ) ;
2094// os_ << "MSWriter::MSWriter()" << LogIO::POST ;
2095
2096 // initialize writer
2097 init() ;
2098}
2099
2100MSWriter::~MSWriter()
2101{
2102 os_.origin( LogOrigin( "MSWriter", "~MSWriter()", WHERE ) ) ;
2103// os_ << "MSWriter::~MSWriter()" << LogIO::POST ;
2104
2105 if ( mstable_ != 0 )
2106 delete mstable_ ;
2107}
2108
2109bool MSWriter::write(const string& filename, const Record& rec)
2110{
2111 os_.origin( LogOrigin( "MSWriter", "write()", WHERE ) ) ;
2112 //double startSec = mathutil::gettimeofday_sec() ;
2113 //os_ << "start MSWriter::write() startSec=" << startSec << LogIO::POST ;
2114
2115 filename_ = filename ;
2116
2117 // parsing MS options
2118 Bool overwrite = False ;
2119 if ( rec.isDefined( "ms" ) ) {
2120 Record msrec = rec.asRecord( "ms" ) ;
2121 if ( msrec.isDefined( "overwrite" ) ) {
2122 overwrite = msrec.asBool( "overwrite" ) ;
2123 }
2124 }
2125
2126 os_ << "Parsing MS options" << endl ;
2127 os_ << " overwrite = " << overwrite << LogIO::POST ;
2128
2129 File file( filename_ ) ;
2130 if ( file.exists() ) {
2131 if ( overwrite ) {
2132 os_ << filename_ << " exists. Overwrite existing data... " << LogIO::POST ;
2133 if ( file.isRegular() ) RegularFile(file).remove() ;
2134 else if ( file.isDirectory() ) Directory(file).removeRecursive() ;
2135 else SymLink(file).remove() ;
2136 }
2137 else {
2138 os_ << LogIO::SEVERE << "ERROR: " << filename_ << " exists..." << LogIO::POST ;
2139 return False ;
2140 }
2141 }
2142
2143 // set up MS
2144 setupMS() ;
2145
2146 // subtables
2147 // OBSERVATION
2148 fillObservation() ;
2149
2150 // ANTENNA
2151 fillAntenna() ;
2152
2153 // PROCESSOR
2154 fillProcessor() ;
2155
2156 // SOURCE
2157 fillSource() ;
2158
2159 // WEATHER
2160 if ( isWeather_ )
2161 fillWeather() ;
2162
2163 // SYSCAL
2164 fillSysCal() ;
2165
2166 /***
2167 * Start iteration using TableVisitor
2168 ***/
2169 {
2170 static const char *cols[] = {
2171 "FIELDNAME", "BEAMNO", "SCANNO", "IFNO", "SRCTYPE", "CYCLENO", "TIME",
2172 "POLNO",
2173 NULL
2174 };
2175 static const TypeManagerImpl<uInt> tmUInt;
2176 static const TypeManagerImpl<Int> tmInt;
2177 static const TypeManagerImpl<Double> tmDouble;
2178 static const TypeManagerImpl<String> tmString;
2179 static const TypeManager *const tms[] = {
2180 &tmString, &tmUInt, &tmUInt, &tmUInt, &tmInt, &tmUInt, &tmDouble, &tmUInt, NULL
2181 };
2182 //double t0 = mathutil::gettimeofday_sec() ;
2183 MSWriterVisitor myVisitor(table_->table(),*mstable_);
2184 //double t1 = mathutil::gettimeofday_sec() ;
2185 //cout << "MSWriterVisitor(): elapsed time " << t1-t0 << " sec" << endl ;
2186 String dataColName = "FLOAT_DATA" ;
2187 if ( useData_ )
2188 dataColName = "DATA" ;
2189 myVisitor.dataColumnName( dataColName ) ;
2190 myVisitor.pointingTableName( ptTabName_ ) ;
2191 myVisitor.setSourceRecord( srcRec_ ) ;
2192 //double t2 = mathutil::gettimeofday_sec() ;
2193 traverseTable(table_->table(), cols, tms, &myVisitor);
2194 //double t3 = mathutil::gettimeofday_sec() ;
2195 //cout << "traverseTable(): elapsed time " << t3-t2 << " sec" << endl ;
2196 }
2197 /***
2198 * End iteration using TableVisitor
2199 ***/
2200
2201 // ASDM tables
2202 const TableRecord &stKeys = table_->table().keywordSet() ;
2203 TableRecord &msKeys = mstable_->rwKeywordSet() ;
2204 uInt nfields = stKeys.nfields() ;
2205 for ( uInt ifield = 0 ; ifield < nfields ; ifield++ ) {
2206 String kname = stKeys.name( ifield ) ;
2207 if ( kname.find( "ASDM" ) != String::npos ) {
2208 String asdmpath = stKeys.asString( ifield ) ;
2209 os_ << "found ASDM table: " << asdmpath << LogIO::POST ;
2210 if ( Table::isReadable( asdmpath ) ) {
2211 Table newAsdmTab( asdmpath, Table::Old ) ;
2212 newAsdmTab.copy( filename_+"/"+kname, Table::New ) ;
2213 os_ << "add subtable: " << kname << LogIO::POST ;
2214 msKeys.defineTable( kname, Table( filename_+"/"+kname, Table::Old ) ) ;
2215 }
2216 }
2217 }
2218
2219 // replace POINTING table with original one if exists
2220 if ( ptTabName_ != "" ) {
2221 delete mstable_ ;
2222 mstable_ = 0 ;
2223 Table newPtTab( ptTabName_, Table::Old ) ;
2224 newPtTab.copy( filename_+"/POINTING", Table::New ) ;
2225 }
2226
2227 //double endSec = mathutil::gettimeofday_sec() ;
2228 //os_ << "end MSWriter::write() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2229
2230 os_ << "Exported data as MS" << LogIO::POST ;
2231
2232 return True ;
2233}
2234
2235void MSWriter::init()
2236{
2237// os_.origin( LogOrigin( "MSWriter", "init()", WHERE ) ) ;
2238// double startSec = mathutil::gettimeofday_sec() ;
2239// os_ << "start MSWriter::init() startSec=" << startSec << LogIO::POST ;
2240
2241 // access to scantable
2242 header_ = table_->getHeader() ;
2243
2244 // FLOAT_DATA? or DATA?
2245 if ( header_.npol > 2 ) {
2246 useFloatData_ = False ;
2247 useData_ = True ;
2248 }
2249 else {
2250 useFloatData_ = True ;
2251 useData_ = False ;
2252 }
2253
2254 // polarization type
2255 polType_ = header_.poltype ;
2256 if ( polType_ == "" )
2257 polType_ = "stokes" ;
2258 else if ( polType_.find( "linear" ) != String::npos )
2259 polType_ = "linear" ;
2260 else if ( polType_.find( "circular" ) != String::npos )
2261 polType_ = "circular" ;
2262 else if ( polType_.find( "stokes" ) != String::npos )
2263 polType_ = "stokes" ;
2264 else if ( polType_.find( "linpol" ) != String::npos )
2265 polType_ = "linpol" ;
2266 else
2267 polType_ = "notype" ;
2268
2269 // Check if some subtables are exists
2270 Bool isTcal = False ;
2271 if ( table_->tcal().table().nrow() != 0 ) {
2272 ROTableColumn col( table_->tcal().table(), "TCAL" ) ;
2273 if ( col.isDefined( 0 ) ) {
2274 os_ << "TCAL table exists: nrow=" << table_->tcal().table().nrow() << LogIO::POST ;
2275 isTcal = True ;
2276 }
2277 else {
2278 os_ << "No TCAL rows" << LogIO::POST ;
2279 }
2280 }
2281 else {
2282 os_ << "No TCAL rows" << LogIO::POST ;
2283 }
2284 if ( table_->weather().table().nrow() != 0 ) {
2285 ROTableColumn col( table_->weather().table(), "TEMPERATURE" ) ;
2286 if ( col.isDefined( 0 ) ) {
2287 os_ << "WEATHER table exists: nrow=" << table_->weather().table().nrow() << LogIO::POST ;
2288 isWeather_ =True ;
2289 }
2290 else {
2291 os_ << "No WEATHER rows" << LogIO::POST ;
2292 }
2293 }
2294 else {
2295 os_ << "No WEATHER rows" << LogIO::POST ;
2296 }
2297
2298 // Are TCAL_SPECTRUM and TSYS_SPECTRUM necessary?
2299 if ( header_.nchan != 1 ) {
2300 if ( isTcal ) {
2301 // examine TCAL subtable
2302 Table tcaltab = table_->tcal().table() ;
2303 ROArrayColumn<Float> tcalCol( tcaltab, "TCAL" ) ;
2304 for ( uInt irow = 0 ; irow < tcaltab.nrow() ; irow++ ) {
2305 if ( tcalCol( irow ).size() != 1 )
2306 tcalSpec_ = True ;
2307 }
2308 }
2309 // examine spectral data
2310 TableIterator iter0( table_->table(), "IFNO" ) ;
2311 while( !iter0.pastEnd() ) {
2312 Table t0( iter0.table() ) ;
2313 ROArrayColumn<Float> sharedFloatArrCol( t0, "SPECTRA" ) ;
2314 uInt len = sharedFloatArrCol( 0 ).size() ;
2315 if ( len != 1 ) {
2316 sharedFloatArrCol.attach( t0, "TSYS" ) ;
2317 if ( sharedFloatArrCol( 0 ).size() != 1 )
2318 tsysSpec_ = True ;
2319 }
2320 iter0.next() ;
2321 }
2322 }
2323
2324 // check if reference for POINTING table exists
2325 const TableRecord &rec = table_->table().keywordSet() ;
2326 if ( rec.isDefined( "POINTING" ) ) {
2327 ptTabName_ = rec.asString( "POINTING" ) ;
2328 if ( !Table::isReadable( ptTabName_ ) ) {
2329 ptTabName_ = "" ;
2330 }
2331 }
2332
2333// double endSec = mathutil::gettimeofday_sec() ;
2334// os_ << "end MSWriter::init() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2335}
2336
2337void MSWriter::setupMS()
2338{
2339// os_.origin( LogOrigin( "MSWriter", "setupMS()", WHERE ) ) ;
2340// double startSec = mathutil::gettimeofday_sec() ;
2341// os_ << "start MSWriter::setupMS() startSec=" << startSec << LogIO::POST ;
2342
2343 String dunit = table_->getHeader().fluxunit ;
2344
2345 TableDesc msDesc = MeasurementSet::requiredTableDesc() ;
2346 if ( useFloatData_ )
2347 MeasurementSet::addColumnToDesc( msDesc, MSMainEnums::FLOAT_DATA, 2 ) ;
2348 else if ( useData_ )
2349 MeasurementSet::addColumnToDesc( msDesc, MSMainEnums::DATA, 2 ) ;
2350
2351 SetupNewTable newtab( filename_, msDesc, Table::New ) ;
2352
2353 mstable_ = new MeasurementSet( newtab ) ;
2354
2355 TableColumn col ;
2356 if ( useFloatData_ )
2357 col.attach( *mstable_, "FLOAT_DATA" ) ;
2358 else if ( useData_ )
2359 col.attach( *mstable_, "DATA" ) ;
2360 col.rwKeywordSet().define( "UNIT", dunit ) ;
2361
2362 // create subtables
2363 TableDesc antennaDesc = MSAntenna::requiredTableDesc() ;
2364 SetupNewTable antennaTab( mstable_->antennaTableName(), antennaDesc, Table::New ) ;
2365 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::ANTENNA ), Table( antennaTab ) ) ;
2366
2367 TableDesc dataDescDesc = MSDataDescription::requiredTableDesc() ;
2368 SetupNewTable dataDescTab( mstable_->dataDescriptionTableName(), dataDescDesc, Table::New ) ;
2369 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::DATA_DESCRIPTION ), Table( dataDescTab ) ) ;
2370
2371 TableDesc dopplerDesc = MSDoppler::requiredTableDesc() ;
2372 SetupNewTable dopplerTab( mstable_->dopplerTableName(), dopplerDesc, Table::New ) ;
2373 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::DOPPLER ), Table( dopplerTab ) ) ;
2374
2375 TableDesc feedDesc = MSFeed::requiredTableDesc() ;
2376 SetupNewTable feedTab( mstable_->feedTableName(), feedDesc, Table::New ) ;
2377 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FEED ), Table( feedTab ) ) ;
2378
2379 TableDesc fieldDesc = MSField::requiredTableDesc() ;
2380 SetupNewTable fieldTab( mstable_->fieldTableName(), fieldDesc, Table::New ) ;
2381 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FIELD ), Table( fieldTab ) ) ;
2382
2383 TableDesc flagCmdDesc = MSFlagCmd::requiredTableDesc() ;
2384 SetupNewTable flagCmdTab( mstable_->flagCmdTableName(), flagCmdDesc, Table::New ) ;
2385 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FLAG_CMD ), Table( flagCmdTab ) ) ;
2386
2387 TableDesc freqOffsetDesc = MSFreqOffset::requiredTableDesc() ;
2388 SetupNewTable freqOffsetTab( mstable_->freqOffsetTableName(), freqOffsetDesc, Table::New ) ;
2389 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FREQ_OFFSET ), Table( freqOffsetTab ) ) ;
2390
2391 TableDesc historyDesc = MSHistory::requiredTableDesc() ;
2392 SetupNewTable historyTab( mstable_->historyTableName(), historyDesc, Table::New ) ;
2393 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::HISTORY ), Table( historyTab ) ) ;
2394
2395 TableDesc observationDesc = MSObservation::requiredTableDesc() ;
2396 SetupNewTable observationTab( mstable_->observationTableName(), observationDesc, Table::New ) ;
2397 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::OBSERVATION ), Table( observationTab ) ) ;
2398
2399 TableDesc pointingDesc = MSPointing::requiredTableDesc() ;
2400 SetupNewTable pointingTab( mstable_->pointingTableName(), pointingDesc, Table::New ) ;
2401 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::POINTING ), Table( pointingTab ) ) ;
2402
2403 TableDesc polarizationDesc = MSPolarization::requiredTableDesc() ;
2404 SetupNewTable polarizationTab( mstable_->polarizationTableName(), polarizationDesc, Table::New ) ;
2405 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::POLARIZATION ), Table( polarizationTab ) ) ;
2406
2407 TableDesc processorDesc = MSProcessor::requiredTableDesc() ;
2408 SetupNewTable processorTab( mstable_->processorTableName(), processorDesc, Table::New ) ;
2409 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::PROCESSOR ), Table( processorTab ) ) ;
2410
2411 TableDesc sourceDesc = MSSource::requiredTableDesc() ;
2412 MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::TRANSITION, 1 ) ;
2413 MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::REST_FREQUENCY, 1 ) ;
2414 MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::SYSVEL, 1 ) ;
2415 SetupNewTable sourceTab( mstable_->sourceTableName(), sourceDesc, Table::New ) ;
2416 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SOURCE ), Table( sourceTab ) ) ;
2417
2418 TableDesc spwDesc = MSSpectralWindow::requiredTableDesc() ;
2419 SetupNewTable spwTab( mstable_->spectralWindowTableName(), spwDesc, Table::New ) ;
2420 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SPECTRAL_WINDOW ), Table( spwTab ) ) ;
2421
2422 TableDesc stateDesc = MSState::requiredTableDesc() ;
2423 SetupNewTable stateTab( mstable_->stateTableName(), stateDesc, Table::New ) ;
2424 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::STATE ), Table( stateTab ) ) ;
2425
2426 TableDesc sysCalDesc = MSSysCal::requiredTableDesc() ;
2427 if ( tcalSpec_ )
2428 MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TCAL_SPECTRUM, 2 ) ;
2429 else
2430 MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TCAL, 1 ) ;
2431 if ( tsysSpec_ )
2432 MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TSYS_SPECTRUM, 2 ) ;
2433 else
2434 MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TSYS, 1 ) ;
2435 SetupNewTable sysCalTab( mstable_->sysCalTableName(), sysCalDesc, Table::New ) ;
2436 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SYSCAL ), Table( sysCalTab ) ) ;
2437
2438 TableDesc weatherDesc = MSWeather::requiredTableDesc() ;
2439 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::TEMPERATURE ) ;
2440 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::PRESSURE ) ;
2441 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::REL_HUMIDITY ) ;
2442 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::WIND_SPEED ) ;
2443 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::WIND_DIRECTION ) ;
2444 SetupNewTable weatherTab( mstable_->weatherTableName(), weatherDesc, Table::New ) ;
2445 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::WEATHER ), Table( weatherTab ) ) ;
2446
2447 mstable_->initRefs() ;
2448
2449// double endSec = mathutil::gettimeofday_sec() ;
2450// os_ << "end MSWriter::setupMS() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2451}
2452
2453void MSWriter::fillObservation()
2454{
2455 //double startSec = mathutil::gettimeofday_sec() ;
2456 //os_ << "start MSWriter::fillObservation() startSec=" << startSec << LogIO::POST ;
2457
2458 // only 1 row
2459 mstable_->observation().addRow( 1, True ) ;
2460 MSObservationColumns msObsCols( mstable_->observation() ) ;
2461 msObsCols.observer().put( 0, header_.observer ) ;
2462 // tentatively put antennaname (from ANTENNA subtable)
2463 String hAntennaName = header_.antennaname ;
2464 String::size_type pos = hAntennaName.find( "//" ) ;
2465 String telescopeName ;
2466 if ( pos != String::npos ) {
2467 telescopeName = hAntennaName.substr( 0, pos ) ;
2468 }
2469 else {
2470 pos = hAntennaName.find( "@" ) ;
2471 telescopeName = hAntennaName.substr( 0, pos ) ;
2472 }
2473// os_ << "telescopeName = " << telescopeName << LogIO::POST ;
2474 msObsCols.telescopeName().put( 0, telescopeName ) ;
2475 msObsCols.project().put( 0, header_.project ) ;
2476 //ScalarMeasColumn<MEpoch> timeCol( table_->table().sort("TIME"), "TIME" ) ;
2477 Table sortedtable = table_->table().sort("TIME") ;
2478 ScalarMeasColumn<MEpoch> timeCol( sortedtable, "TIME" ) ;
2479 Vector<MEpoch> trange( 2 ) ;
2480 trange[0] = timeCol( 0 ) ;
2481 trange[1] = timeCol( table_->nrow()-1 ) ;
2482 msObsCols.timeRangeMeas().put( 0, trange ) ;
2483
2484 //double endSec = mathutil::gettimeofday_sec() ;
2485 //os_ << "end MSWriter::fillObservation() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2486}
2487
2488void MSWriter::antennaProperty( String &name, String &m, String &t, Double &d )
2489{
2490 name.upcase() ;
2491
2492 m = "ALT-AZ" ;
2493 t = "GROUND-BASED" ;
2494 if ( name.matches( Regex( "DV[0-9]+$" ) )
2495 || name.matches( Regex( "DA[0-9]+$" ) )
2496 || name.matches( Regex( "PM[0-9]+$" ) ) )
2497 d = 12.0 ;
2498 else if ( name.matches( Regex( "CM[0-9]+$" ) ) )
2499 d = 7.0 ;
2500 else if ( name.contains( "GBT" ) )
2501 d = 104.9 ;
2502 else if ( name.contains( "MOPRA" ) )
2503 d = 22.0 ;
2504 else if ( name.contains( "PKS" ) || name.contains( "PARKS" ) )
2505 d = 64.0 ;
2506 else if ( name.contains( "TIDBINBILLA" ) )
2507 d = 70.0 ;
2508 else if ( name.contains( "CEDUNA" ) )
2509 d = 30.0 ;
2510 else if ( name.contains( "HOBART" ) )
2511 d = 26.0 ;
2512 else if ( name.contains( "APEX" ) )
2513 d = 12.0 ;
2514 else if ( name.contains( "ASTE" ) )
2515 d = 10.0 ;
2516 else if ( name.contains( "NRO" ) )
2517 d = 45.0 ;
2518 else
2519 d = 1.0 ;
2520}
2521
2522void MSWriter::fillAntenna()
2523{
2524 //double startSec = mathutil::gettimeofday_sec() ;
2525 //os_ << "start MSWriter::fillAntenna() startSec=" << startSec << LogIO::POST ;
2526
2527 // only 1 row
2528 Table anttab = mstable_->antenna() ;
2529 anttab.addRow( 1, True ) ;
2530
2531 Table &table = table_->table() ;
2532 const TableRecord &keys = table.keywordSet() ;
2533 String hAntName = keys.asString( "AntennaName" ) ;
2534 String::size_type pos = hAntName.find( "//" ) ;
2535 String antennaName ;
2536 String stationName ;
2537 if ( pos != String::npos ) {
2538 stationName = hAntName.substr( 0, pos ) ;
2539 hAntName = hAntName.substr( pos+2 ) ;
2540 }
2541 pos = hAntName.find( "@" ) ;
2542 if ( pos != String::npos ) {
2543 antennaName = hAntName.substr( 0, pos ) ;
2544 stationName = hAntName.substr( pos+1 ) ;
2545 }
2546 else {
2547 antennaName = hAntName ;
2548 }
2549 Vector<Double> antpos = keys.asArrayDouble( "AntennaPosition" ) ;
2550
2551 String mount, atype ;
2552 Double diameter ;
2553 antennaProperty( antennaName, mount, atype, diameter ) ;
2554
2555 TableRow tr( anttab ) ;
2556 TableRecord &r = tr.record() ;
2557 RecordFieldPtr<String> nameRF( r, "NAME" ) ;
2558 RecordFieldPtr<String> stationRF( r, "STATION" ) ;
2559 RecordFieldPtr<String> mountRF( r, "MOUNT" ) ;
2560 RecordFieldPtr<String> typeRF( r, "TYPE" ) ;
2561 RecordFieldPtr<Double> dishDiameterRF( r, "DISH_DIAMETER" ) ;
2562 RecordFieldPtr< Vector<Double> > positionRF( r, "POSITION" ) ;
2563 *nameRF = antennaName ;
2564 *mountRF = mount ;
2565 *typeRF = atype ;
2566 *dishDiameterRF = diameter ;
2567 *positionRF = antpos ;
2568 *stationRF = stationName ;
2569
2570 tr.put( 0 ) ;
2571
2572 //double endSec = mathutil::gettimeofday_sec() ;
2573 //os_ << "end MSWriter::fillAntenna() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2574}
2575
2576void MSWriter::fillProcessor()
2577{
2578// double startSec = mathutil::gettimeofday_sec() ;
2579// os_ << "start MSWriter::fillProcessor() startSec=" << startSec << LogIO::POST ;
2580
2581 // only add empty 1 row
2582 MSProcessor msProc = mstable_->processor() ;
2583 msProc.addRow( 1, True ) ;
2584
2585// double endSec = mathutil::gettimeofday_sec() ;
2586// os_ << "end MSWriter::fillProcessor() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2587}
2588
2589void MSWriter::fillSource()
2590{
2591// double startSec = mathutil::gettimeofday_sec() ;
2592// os_ << "start MSWriter::fillSource() startSec=" << startSec << LogIO::POST ;
2593
2594 // access to MS SOURCE subtable
2595 MSSource msSrc = mstable_->source() ;
2596
2597 // access to MOLECULE subtable
2598 STMolecules stm = table_->molecules() ;
2599
2600 Int srcId = 0 ;
2601
2602 // row based
2603 TableRow row( msSrc ) ;
2604 TableRecord &rec = row.record() ;
2605 RecordFieldPtr<Int> srcidRF( rec, "SOURCE_ID" ) ;
2606 RecordFieldPtr<String> nameRF( rec, "NAME" ) ;
2607 RecordFieldPtr< Array<Double> > srcpmRF( rec, "PROPER_MOTION" ) ;
2608 RecordFieldPtr< Array<Double> > srcdirRF( rec, "DIRECTION" ) ;
2609 RecordFieldPtr<Int> numlineRF( rec, "NUM_LINES" ) ;
2610 RecordFieldPtr< Array<Double> > restfreqRF( rec, "REST_FREQUENCY" ) ;
2611 RecordFieldPtr< Array<Double> > sysvelRF( rec, "SYSVEL" ) ;
2612 RecordFieldPtr< Array<String> > transitionRF( rec, "TRANSITION" ) ;
2613 RecordFieldPtr<Double> timeRF( rec, "TIME" ) ;
2614 RecordFieldPtr<Double> intervalRF( rec, "INTERVAL" ) ;
2615 RecordFieldPtr<Int> spwidRF( rec, "SPECTRAL_WINDOW_ID" ) ;
2616
2617 //
2618 // ITERATION: SRCNAME
2619 //
2620 TableIterator iter0( table_->table(), "SRCNAME" ) ;
2621 while( !iter0.pastEnd() ) {
2622 //Table t0( iter0.table() ) ;
2623 Table t0 = iter0.table() ;
2624
2625 // get necessary information
2626 ROScalarColumn<String> srcNameCol( t0, "SRCNAME" ) ;
2627 String srcName = srcNameCol( 0 ) ;
2628 ROArrayColumn<Double> sharedDArrRCol( t0, "SRCPROPERMOTION" ) ;
2629 Vector<Double> srcPM = sharedDArrRCol( 0 ) ;
2630 sharedDArrRCol.attach( t0, "SRCDIRECTION" ) ;
2631 Vector<Double> srcDir = sharedDArrRCol( 0 ) ;
2632 ROScalarColumn<Double> srcVelCol( t0, "SRCVELOCITY" ) ;
2633 Double srcVel = srcVelCol( 0 ) ;
2634 srcRec_.define( srcName, srcId ) ;
2635
2636 // NAME
2637 *nameRF = srcName ;
2638
2639 // SOURCE_ID
2640 *srcidRF = srcId ;
2641
2642 // PROPER_MOTION
2643 *srcpmRF = srcPM ;
2644
2645 // DIRECTION
2646 *srcdirRF = srcDir ;
2647
2648 //
2649 // ITERATION: MOLECULE_ID
2650 //
2651 TableIterator iter1( t0, "MOLECULE_ID" ) ;
2652 while( !iter1.pastEnd() ) {
2653 //Table t1( iter1.table() ) ;
2654 Table t1 = iter1.table() ;
2655
2656 // get necessary information
2657 Vector<Double> restFreq ;
2658 Vector<String> molName ;
2659 Vector<String> fMolName ;
2660 ROScalarColumn<uInt> molIdCol( t1, "MOLECULE_ID" ) ;
2661 uInt molId = molIdCol( 0 ) ;
2662 stm.getEntry( restFreq, molName, fMolName, molId ) ;
2663
2664 uInt numFreq = restFreq.size() ;
2665
2666 // NUM_LINES
2667 *numlineRF = numFreq ;
2668
2669 // REST_FREQUENCY
2670 restfreqRF.define(restFreq);
2671
2672 // TRANSITION
2673 Vector<String> transition ;
2674 if ( fMolName.size() != 0 ) {
2675 transition = fMolName ;
2676 }
2677 else if ( molName.size() != 0 ) {
2678 transition = molName ;
2679 }
2680 else {
2681 transition.resize( numFreq ) ;
2682 transition = "" ;
2683 }
2684 transitionRF.define(transition);
2685
2686 // SYSVEL
2687 Vector<Double> sysvelArr( numFreq, srcVel ) ;
2688 sysvelRF.define(sysvelArr);
2689
2690 //
2691 // ITERATION: IFNO
2692 //
2693 TableIterator iter2( t1, "IFNO" ) ;
2694 while( !iter2.pastEnd() ) {
2695 //Table t2( iter2.table() ) ;
2696 Table t2 = iter2.table() ;
2697 uInt nrow = msSrc.nrow() ;
2698
2699 // get necessary information
2700 ROScalarColumn<uInt> ifNoCol( t2, "IFNO" ) ;
2701 uInt ifno = ifNoCol( 0 ) ; // IFNO = SPECTRAL_WINDOW_ID
2702 Double midTime ;
2703 Double interval ;
2704 getValidTimeRange( midTime, interval, t2 ) ;
2705
2706 // fill SPECTRAL_WINDOW_ID
2707 *spwidRF = ifno ;
2708
2709 // fill TIME, INTERVAL
2710 *timeRF = midTime ;
2711 *intervalRF = interval ;
2712
2713 // add row
2714 msSrc.addRow( 1, True ) ;
2715 row.put( nrow ) ;
2716
2717 iter2.next() ;
2718 }
2719
2720 iter1.next() ;
2721 }
2722
2723 // increment srcId if SRCNAME changed
2724 srcId++ ;
2725
2726 iter0.next() ;
2727 }
2728
2729// double endSec = mathutil::gettimeofday_sec() ;
2730// os_ << "end MSWriter::fillSource() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2731}
2732
2733void MSWriter::fillWeather()
2734{
2735// double startSec = mathutil::gettimeofday_sec() ;
2736// os_ << "start MSWriter::fillWeather() startSec=" << startSec << LogIO::POST ;
2737
2738 // access to MS WEATHER subtable
2739 MSWeather msw = mstable_->weather() ;
2740
2741 // access to WEATHER subtable
2742 Table stw = table_->weather().table() ;
2743 uInt nrow = stw.nrow() ;
2744
2745 if ( nrow == 0 )
2746 return ;
2747
2748 msw.addRow( nrow, True ) ;
2749 MSWeatherColumns mswCols( msw ) ;
2750
2751 // ANTENNA_ID is always 0
2752 Vector<Int> antIdArr( nrow, 0 ) ;
2753 mswCols.antennaId().putColumn( antIdArr ) ;
2754
2755 // fill weather status
2756 ROScalarColumn<Float> sharedFloatCol( stw, "TEMPERATURE" ) ;
2757 mswCols.temperature().putColumn( sharedFloatCol ) ;
2758 sharedFloatCol.attach( stw, "PRESSURE" ) ;
2759 mswCols.pressure().putColumn( sharedFloatCol ) ;
2760 sharedFloatCol.attach( stw, "HUMIDITY" ) ;
2761 mswCols.relHumidity().putColumn( sharedFloatCol ) ;
2762 sharedFloatCol.attach( stw, "WINDSPEED" ) ;
2763 mswCols.windSpeed().putColumn( sharedFloatCol ) ;
2764 sharedFloatCol.attach( stw, "WINDAZ" ) ;
2765 mswCols.windDirection().putColumn( sharedFloatCol ) ;
2766
2767 // fill TIME and INTERVAL
2768 Double midTime ;
2769 Double interval ;
2770 Vector<Double> intervalArr( nrow, 0.0 ) ;
2771 TableIterator iter( table_->table(), "WEATHER_ID" ) ;
2772 while( !iter.pastEnd() ) {
2773 //Table tab( iter.table() ) ;
2774 Table tab = iter.table() ;
2775
2776 ROScalarColumn<uInt> widCol( tab, "WEATHER_ID" ) ;
2777 uInt wid = widCol( 0 ) ;
2778
2779 getValidTimeRange( midTime, interval, tab ) ;
2780 mswCols.time().put( wid, midTime ) ;
2781 intervalArr[wid] = interval ;
2782
2783 iter.next() ;
2784 }
2785 mswCols.interval().putColumn( intervalArr ) ;
2786
2787// double endSec = mathutil::gettimeofday_sec() ;
2788// os_ << "end MSWriter::fillWeather() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2789}
2790
2791void MSWriter::fillSysCal()
2792{
2793 Table mssc = mstable_->sysCal() ;
2794
2795 if (table_->tcal().table().nrow() > 0) {
2796 static const char *cols[] = {
2797 "BEAMNO", "IFNO", "TIME", "POLNO",
2798 NULL
2799 };
2800 static const TypeManagerImpl<uInt> tmUInt;
2801 static const TypeManagerImpl<Double> tmDouble;
2802 static const TypeManager *const tms[] = {
2803 &tmUInt, &tmUInt, &tmDouble, &tmUInt, NULL
2804 };
2805 //double t0 = mathutil::gettimeofday_sec() ;
2806 MSSysCalVisitor myVisitor(table_->table(),mssc);
2807 //double t1 = mathutil::gettimeofday_sec() ;
2808 //cout << "MSWriterVisitor(): elapsed time " << t1-t0 << " sec" << endl ;
2809 traverseTable(table_->table(), cols, tms, &myVisitor);
2810 //double t3 = mathutil::gettimeofday_sec() ;
2811 //cout << "traverseTable(): elapsed time " << t3-t2 << " sec" << endl ;
2812 }
2813
2814}
2815
2816void MSWriter::getValidTimeRange( Double &me, Double &interval, Table &tab )
2817{
2818// double startSec = mathutil::gettimeofday_sec() ;
2819// os_ << "start MSWriter::getVaridTimeRange() startSec=" << startSec << LogIO::POST ;
2820
2821 // sort table
2822 //Table stab = tab.sort( "TIME" ) ;
2823
2824 ROScalarColumn<Double> timeCol( tab, "TIME" ) ;
2825 Vector<Double> timeArr = timeCol.getColumn() ;
2826 Double minTime ;
2827 Double maxTime ;
2828 minMax( minTime, maxTime, timeArr ) ;
2829 Double midTime = 0.5 * ( minTime + maxTime ) * 86400.0 ;
2830 // unit for TIME
2831 // Scantable: "d"
2832 // MS: "s"
2833 me = midTime ;
2834 interval = ( maxTime - minTime ) * 86400.0 ;
2835
2836// double endSec = mathutil::gettimeofday_sec() ;
2837// os_ << "end MSWriter::getValidTimeRange() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2838}
2839
2840void MSWriter::getValidTimeRange( Double &me, Double &interval, Vector<Double> &atime, Vector<Double> &ainterval )
2841{
2842// double startSec = mathutil::gettimeofday_sec() ;
2843// os_ << "start MSWriter::getVaridTimeRange() startSec=" << startSec << LogIO::POST ;
2844
2845 // sort table
2846 //Table stab = tab.sort( "TIME" ) ;
2847
2848 Double minTime ;
2849 Double maxTime ;
2850 minMax( minTime, maxTime, atime ) ;
2851 Double midTime = 0.5 * ( minTime + maxTime ) * 86400.0 ;
2852 // unit for TIME
2853 // Scantable: "d"
2854 // MS: "s"
2855 me = midTime ;
2856 interval = ( maxTime - minTime ) * 86400.0 + mean( ainterval ) ;
2857
2858// double endSec = mathutil::gettimeofday_sec() ;
2859// os_ << "end MSWriter::getValidTimeRange() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2860}
2861
2862}
Note: See TracBrowser for help on using the repository browser.