source: trunk/src/MSWriter.cpp@ 2454

Last change on this file since 2454 was 2337, checked in by Takeshi Nakazato, 13 years ago

New Development: No

JIRA Issue: No

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: List test programs

Put in Release Notes: Yes/No

Module(s): Module Names change impacts.

Description: Describe your changes here...

Fixed a serious bug in the code that fills ANTENNA table.


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