source: trunk/src/MSWriter.cpp@ 2569

Last change on this file since 2569 was 2555, checked in by Takeshi Nakazato, 12 years ago

New Development: No

JIRA Issue: Yes CAS-4223

Ready for Test: Yes

Interface Changes: No

What Interface Changed: Please list interface changes

Test Programs: new unit test will be added soon

Put in Release Notes: No

Module(s): Module Names change impacts.

Description: Describe your changes here...

CHAN_WIDTH is negative when frequency increment is negative.


File size: 76.4 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> cw( nchan, ic ) ;
1066 Vector<Double> chanf( nchan ) ;
1067 indgen( chanf, reffreq, ic ) ;
1068
1069 TableRow tr( spwtab ) ;
1070 TableRecord &r = tr.record() ;
1071 putField( "MEAS_FREQ_REF", r, mfrInt ) ;
1072 putField( "NUM_CHAN", r, nchan ) ;
1073 putField( "TOTAL_BANDWIDTH", r, bw ) ;
1074 putField( "REF_FREQUENCY", r, reffreq ) ;
1075 putField( "NET_SIDEBAND", r, netsb ) ;
1076 defineField( "RESOLUTION", r, res ) ;
1077// defineField( "CHAN_WIDTH", r, res ) ;
1078 defineField( "CHAN_WIDTH", r, cw ) ;
1079 defineField( "EFFECTIVE_BW", r, res ) ;
1080 defineField( "CHAN_FREQ", r, chanf ) ;
1081 tr.put( sid ) ;
1082 }
1083 void addFeed( Int fid, Int sid )
1084 {
1085 Int idx = -1 ;
1086 uInt nEntry = feedEntry.nrow() ;
1087 Vector<Int> key( 2 ) ;
1088 key[0] = fid ;
1089 key[1] = sid ;
1090 for ( uInt i = 0 ; i < nEntry ; i++ ) {
1091 if ( allEQ( feedEntry.row(i), key ) ) {
1092 idx = i ;
1093 break ;
1094 }
1095 }
1096
1097 if ( idx == -1 ) {
1098 uInt nrow = feedtab.nrow() ;
1099 feedtab.addRow( 1, True ) ;
1100 Int numReceptors = 2 ;
1101 Vector<String> polType( numReceptors ) ;
1102 Matrix<Double> beamOffset( 2, numReceptors, 0.0 ) ;
1103 Vector<Double> receptorAngle( numReceptors, 0.0 ) ;
1104 if ( poltype == "linear" ) {
1105 polType[0] = "X" ;
1106 polType[1] = "Y" ;
1107 }
1108 else if ( poltype == "circular" ) {
1109 polType[0] = "R" ;
1110 polType[1] = "L" ;
1111 }
1112 else {
1113 polType[0] = "X" ;
1114 polType[1] = "Y" ;
1115 }
1116 Matrix<Complex> polResponse( numReceptors, numReceptors, 0.0 ) ;
1117
1118 TableRow tr( feedtab ) ;
1119 TableRecord &r = tr.record() ;
1120 putField( "FEED_ID", r, fid ) ;
1121 putField( "BEAM_ID", r, fid ) ;
1122 Int tmp = 0 ;
1123 putField( "ANTENNA_ID", r, tmp ) ;
1124 putField( "SPECTRAL_WINDOW_ID", r, sid ) ;
1125 putField( "NUM_RECEPTORS", r, numReceptors ) ;
1126 defineField( "POLARIZATION_TYPE", r, polType ) ;
1127 defineField( "BEAM_OFFSET", r, beamOffset ) ;
1128 defineField( "RECEPTOR_ANGLE", r, receptorAngle ) ;
1129 defineField( "POL_RESPONSE", r, polResponse ) ;
1130 tr.put( nrow ) ;
1131
1132 feedEntry.resize( nEntry+1, 2, True ) ;
1133 feedEntry.row( nEntry ) = key ;
1134 }
1135 }
1136 void initPolarization()
1137 {
1138 const TableRecord &keys = table.keywordSet() ;
1139 poltype = keys.asString( "POLTYPE" ) ;
1140
1141 initCorrProductTemplate() ;
1142 }
1143 void initFrequencies()
1144 {
1145 const TableRecord &keys = table.keywordSet() ;
1146 Table tab = keys.asTable( "FREQUENCIES" ) ;
1147 ROScalarColumn<uInt> idcol( tab, "ID" ) ;
1148 ROScalarColumn<Double> rpcol( tab, "REFPIX" ) ;
1149 ROScalarColumn<Double> rvcol( tab, "REFVAL" ) ;
1150 ROScalarColumn<Double> iccol( tab, "INCREMENT" ) ;
1151 Vector<uInt> id = idcol.getColumn() ;
1152 Vector<Double> rp = rpcol.getColumn() ;
1153 Vector<Double> rv = rvcol.getColumn() ;
1154 Vector<Double> ic = iccol.getColumn() ;
1155 for ( uInt i = 0 ; i < id.nelements() ; i++ ) {
1156 processedFreqId.insert( pair<uInt,Bool>( id[i], False ) ) ;
1157 refpix.insert( pair<uInt,Double>( id[i], rp[i] ) ) ;
1158 refval.insert( pair<uInt,Double>( id[i], rv[i] ) ) ;
1159 increment.insert( pair<uInt,Double>( id[i], ic[i] ) ) ;
1160 }
1161 String frameStr = tab.keywordSet().asString( "BASEFRAME" ) ;
1162 MFrequency::getType( freqframe, frameStr ) ;
1163 }
1164 void attachSubtables()
1165 {
1166 const TableRecord &keys = table.keywordSet() ;
1167 TableRecord &mskeys = ms.rwKeywordSet() ;
1168
1169 // FIELD table
1170 fieldtab = mskeys.asTable( "FIELD" ) ;
1171
1172 // SPECTRAL_WINDOW table
1173 spwtab = mskeys.asTable( "SPECTRAL_WINDOW" ) ;
1174
1175 // POINTING table
1176 potab = mskeys.asTable( "POINTING" ) ;
1177
1178 // POLARIZATION table
1179 poltab = mskeys.asTable( "POLARIZATION" ) ;
1180
1181 // DATA_DESCRIPTION table
1182 ddtab = mskeys.asTable( "DATA_DESCRIPTION" ) ;
1183
1184 // STATE table
1185 statetab = mskeys.asTable( "STATE" ) ;
1186
1187 // FEED table
1188 feedtab = mskeys.asTable( "FEED" ) ;
1189 }
1190 void attachMain()
1191 {
1192 TableRecord &r = row.record() ;
1193 dataDescIdRF.attachToRecord( r, "DATA_DESC_ID" ) ;
1194 timeRF.attachToRecord( r, "TIME" ) ;
1195 timeCentroidRF.attachToRecord( r, "TIME_CENTROID" ) ;
1196 intervalRF.attachToRecord( r, "INTERVAL" ) ;
1197 exposureRF.attachToRecord( r, "EXPOSURE" ) ;
1198 fieldIdRF.attachToRecord( r, "FIELD_ID" ) ;
1199 feed1RF.attachToRecord( r, "FEED1" ) ;
1200 feed2RF.attachToRecord( r, "FEED2" ) ;
1201 scanNumberRF.attachToRecord( r, "SCAN_NUMBER" ) ;
1202 stateIdRF.attachToRecord( r, "STATE_ID" ) ;
1203
1204 // constant values
1205 Int id = 0 ;
1206 RecordFieldPtr<Int> intRF( r, "OBSERVATION_ID" ) ;
1207 *intRF = 0 ;
1208 intRF.attachToRecord( r, "ANTENNA1" ) ;
1209 *intRF = 0 ;
1210 intRF.attachToRecord( r, "ANTENNA2" ) ;
1211 *intRF = 0 ;
1212 intRF.attachToRecord( r, "ARRAY_ID" ) ;
1213 *intRF = 0 ;
1214 intRF.attachToRecord( r, "PROCESSOR_ID" ) ;
1215 *intRF = 0 ;
1216 RecordFieldPtr< Vector<Double> > arrayRF( r, "UVW" ) ;
1217 arrayRF.define( Vector<Double>( 3, 0.0 ) ) ;
1218 }
1219 void attachPointing()
1220 {
1221 porow = TableRow( potab ) ;
1222 TableRecord &r = porow.record() ;
1223 poNumPolyRF.attachToRecord( r, "NUM_POLY" ) ;
1224 poTimeRF.attachToRecord( r, "TIME" ) ;
1225 poTimeOriginRF.attachToRecord( r, "TIME_ORIGIN" ) ;
1226 poIntervalRF.attachToRecord( r, "INTERVAL" ) ;
1227 poNameRF.attachToRecord( r, "NAME" ) ;
1228 poDirectionRF.attachToRecord( r, "DIRECTION" ) ;
1229 poTargetRF.attachToRecord( r, "TARGET" ) ;
1230
1231 // constant values
1232 RecordFieldPtr<Int> antIdRF( r, "ANTENNA_ID" ) ;
1233 *antIdRF = 0 ;
1234 RecordFieldPtr<Bool> trackingRF( r, "TRACKING" ) ;
1235 *trackingRF = True ;
1236 }
1237 void queryType( Int type, String &stype, Bool &b, Double &t, Double &l )
1238 {
1239 t = 0.0 ;
1240 l = 0.0 ;
1241
1242 String sep1="#" ;
1243 String sep2="," ;
1244 String target="OBSERVE_TARGET" ;
1245 String atmcal="CALIBRATE_TEMPERATURE" ;
1246 String onstr="ON_SOURCE" ;
1247 String offstr="OFF_SOURCE" ;
1248 String pswitch="POSITION_SWITCH" ;
1249 String nod="NOD" ;
1250 String fswitch="FREQUENCY_SWITCH" ;
1251 String sigstr="SIG" ;
1252 String refstr="REF" ;
1253 String unspecified="UNSPECIFIED" ;
1254 String ftlow="LOWER" ;
1255 String fthigh="HIGHER" ;
1256 switch ( type ) {
1257 case SrcType::PSON:
1258 stype = target+sep1+onstr+sep2+pswitch ;
1259 b = True ;
1260 break ;
1261 case SrcType::PSOFF:
1262 stype = target+sep1+offstr+sep2+pswitch ;
1263 b = False ;
1264 break ;
1265 case SrcType::NOD:
1266 stype = target+sep1+onstr+sep2+nod ;
1267 b = True ;
1268 break ;
1269 case SrcType::FSON:
1270 stype = target+sep1+onstr+sep2+fswitch+sep1+sigstr ;
1271 b = True ;
1272 break ;
1273 case SrcType::FSOFF:
1274 stype = target+sep1+onstr+sep2+fswitch+sep1+refstr ;
1275 b = False ;
1276 break ;
1277 case SrcType::SKY:
1278 stype = atmcal+sep1+offstr+sep2+unspecified ;
1279 b = False ;
1280 break ;
1281 case SrcType::HOT:
1282 stype = atmcal+sep1+offstr+sep2+unspecified ;
1283 b = False ;
1284 break ;
1285 case SrcType::WARM:
1286 stype = atmcal+sep1+offstr+sep2+unspecified ;
1287 b = False ;
1288 break ;
1289 case SrcType::COLD:
1290 stype = atmcal+sep1+offstr+sep2+unspecified ;
1291 b = False ;
1292 break ;
1293 case SrcType::PONCAL:
1294 stype = atmcal+sep1+onstr+sep2+pswitch ;
1295 b = True ;
1296 break ;
1297 case SrcType::POFFCAL:
1298 stype = atmcal+sep1+offstr+sep2+pswitch ;
1299 b = False ;
1300 break ;
1301 case SrcType::NODCAL:
1302 stype = atmcal+sep1+onstr+sep2+nod ;
1303 b = True ;
1304 break ;
1305 case SrcType::FONCAL:
1306 stype = atmcal+sep1+onstr+sep2+fswitch+sep1+sigstr ;
1307 b = True ;
1308 break ;
1309 case SrcType::FOFFCAL:
1310 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+refstr ;
1311 b = False ;
1312 break ;
1313 case SrcType::FSLO:
1314 stype = target+sep1+onstr+sep2+fswitch+sep1+ftlow ;
1315 b = True ;
1316 break ;
1317 case SrcType::FLOOFF:
1318 stype = target+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1319 b = False ;
1320 break ;
1321 case SrcType::FLOSKY:
1322 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1323 b = False ;
1324 break ;
1325 case SrcType::FLOHOT:
1326 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1327 b = False ;
1328 break ;
1329 case SrcType::FLOWARM:
1330 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1331 b = False ;
1332 break ;
1333 case SrcType::FLOCOLD:
1334 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+ftlow ;
1335 b = False ;
1336 break ;
1337 case SrcType::FSHI:
1338 stype = target+sep1+onstr+sep2+fswitch+sep1+fthigh ;
1339 b = True ;
1340 break ;
1341 case SrcType::FHIOFF:
1342 stype = target+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1343 b = False ;
1344 break ;
1345 case SrcType::FHISKY:
1346 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1347 b = False ;
1348 break ;
1349 case SrcType::FHIHOT:
1350 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1351 b = False ;
1352 break ;
1353 case SrcType::FHIWARM:
1354 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1355 b = False ;
1356 break ;
1357 case SrcType::FHICOLD:
1358 stype = atmcal+sep1+offstr+sep2+fswitch+sep1+fthigh ;
1359 b = False ;
1360 break ;
1361 case SrcType::SIG:
1362 stype = target+sep1+onstr+sep2+unspecified ;
1363 b = True ;
1364 break ;
1365 case SrcType::REF:
1366 stype = target+sep1+offstr+sep2+unspecified ;
1367 b = False ;
1368 break ;
1369 default:
1370 stype = unspecified ;
1371 b = True ;
1372 break ;
1373 }
1374 }
1375 void initCorrProductTemplate()
1376 {
1377 Int n = 1 ;
1378 {
1379 Matrix<Int> c( 2, n, 0 ) ;
1380 corrProductTemplate[n] = c ;
1381 }
1382 n = 2 ;
1383 {
1384 Matrix<Int> c( 2, n, 0 ) ;
1385 c.column( 1 ) = 1 ;
1386 corrProductTemplate[n] = c ;
1387 }
1388 n = 4 ;
1389 {
1390 Matrix<Int> c( 2, n, 0 ) ;
1391 c( 0, 2 ) = 1 ;
1392 c( 0, 3 ) = 1 ;
1393 c( 1, 1 ) = 1 ;
1394 c( 1, 3 ) = 1 ;
1395 corrProductTemplate[n] = c ;
1396 }
1397 }
1398
1399 Table &ms;
1400 TableRow row;
1401 uInt rowidx;
1402 String fieldName;
1403 Int fieldId;
1404 Int srcId;
1405 Int defaultFieldId;
1406 Int spwId;
1407 Int feedId;
1408 Int subscan;
1409 CountedPtr<DataHolder> holder;
1410 String ptName;
1411 Bool useFloat;
1412 String poltype;
1413
1414 // MS subtables
1415 Table spwtab;
1416 Table statetab;
1417 Table ddtab;
1418 Table poltab;
1419 Table fieldtab;
1420 Table feedtab;
1421 Table potab;
1422
1423 // Scantable MAIN columns
1424 ROArrayColumn<Float> spectraCol;
1425 ROArrayColumn<Double> directionCol,scanRateCol,sourceDirectionCol;
1426 ROArrayColumn<uChar> flagtraCol;
1427 ROTableColumn tcalIdCol,intervalCol,flagRowCol,timeCol,freqIdCol,
1428 sourceNameCol,fieldNameCol;
1429
1430 // MS MAIN columns
1431 RecordFieldPtr<Int> dataDescIdRF,fieldIdRF,feed1RF,feed2RF,
1432 scanNumberRF,stateIdRF;
1433 RecordFieldPtr<Double> timeRF,timeCentroidRF,intervalRF,exposureRF;
1434
1435 // MS POINTING columns
1436 TableRow porow;
1437 RecordFieldPtr<Int> poNumPolyRF ;
1438 RecordFieldPtr<Double> poTimeRF,
1439 poTimeOriginRF,
1440 poIntervalRF ;
1441 RecordFieldPtr<String> poNameRF ;
1442 RecordFieldPtr< Matrix<Double> > poDirectionRF,
1443 poTargetRF ;
1444
1445 Vector<String> stateEntry;
1446 Matrix<Int> ddEntry;
1447 Matrix<Int> feedEntry;
1448 vector< Vector<Int> > polEntry;
1449 map<uInt,Bool> processedFreqId;
1450 map<uInt,Double> refpix;
1451 map<uInt,Double> refval;
1452 map<uInt,Double> increment;
1453 MFrequency::Types freqframe;
1454 Record srcRec;
1455 map< Int, Matrix<Int> > corrProductTemplate;
1456};
1457
1458class BaseMSSysCalVisitor: public TableVisitor {
1459 uInt lastRecordNo;
1460 uInt lastBeamNo, lastIfNo, lastPolNo;
1461 Double lastTime;
1462protected:
1463 const Table &table;
1464 uInt count;
1465public:
1466 BaseMSSysCalVisitor(const Table &table)
1467 : table(table)
1468 {
1469 count = 0;
1470 }
1471
1472 virtual void enterBeamNo(const uInt recordNo, uInt columnValue) { }
1473 virtual void leaveBeamNo(const uInt recordNo, uInt columnValue) { }
1474 virtual void enterIfNo(const uInt recordNo, uInt columnValue) { }
1475 virtual void leaveIfNo(const uInt recordNo, uInt columnValue) { }
1476 virtual void enterPolNo(const uInt recordNo, uInt columnValue) { }
1477 virtual void leavePolNo(const uInt recordNo, uInt columnValue) { }
1478 virtual void enterTime(const uInt recordNo, Double columnValue) { }
1479 virtual void leaveTime(const uInt recordNo, Double columnValue) { }
1480
1481 virtual Bool visitRecord(const uInt recordNo,
1482 const uInt beamNo,
1483 const uInt ifNo,
1484 const uInt polNo,
1485 const Double time) { return True ;}
1486
1487 virtual Bool visit(Bool isFirst, const uInt recordNo,
1488 const uInt nCols, void const *const colValues[]) {
1489 uInt beamNo, ifNo, polNo;
1490 Double time;
1491 { // prologue
1492 uInt i = 0;
1493 {
1494 const uInt *col = (const uInt *)colValues[i++];
1495 beamNo = col[recordNo];
1496 }
1497 {
1498 const uInt *col = (const uInt *)colValues[i++];
1499 ifNo = col[recordNo];
1500 }
1501 {
1502 const Double *col = (const Double *)colValues[i++];
1503 time = col[recordNo];
1504 }
1505 {
1506 const uInt *col = (const uInt *)colValues[i++];
1507 polNo = col[recordNo];
1508 }
1509 assert(nCols == i);
1510 }
1511
1512 if (isFirst) {
1513 enterBeamNo(recordNo, beamNo);
1514 enterIfNo(recordNo, ifNo);
1515 enterTime(recordNo, time);
1516 enterPolNo(recordNo, polNo);
1517 } else {
1518 if (lastBeamNo != beamNo) {
1519 leavePolNo(lastRecordNo, lastPolNo);
1520 leaveTime(lastRecordNo, lastTime);
1521 leaveIfNo(lastRecordNo, lastIfNo);
1522 leaveBeamNo(lastRecordNo, lastBeamNo);
1523
1524 enterBeamNo(recordNo, beamNo);
1525 enterIfNo(recordNo, ifNo);
1526 enterTime(recordNo, time);
1527 enterPolNo(recordNo, polNo);
1528 } else if (lastIfNo != ifNo) {
1529 leavePolNo(lastRecordNo, lastPolNo);
1530 leaveTime(lastRecordNo, lastTime);
1531 leaveIfNo(lastRecordNo, lastIfNo);
1532
1533 enterIfNo(recordNo, ifNo);
1534 enterTime(recordNo, time);
1535 enterPolNo(recordNo, polNo);
1536 } else if (lastTime != time) {
1537 leavePolNo(lastRecordNo, lastPolNo);
1538 leaveTime(lastRecordNo, lastTime);
1539
1540 enterTime(recordNo, time);
1541 enterPolNo(recordNo, polNo);
1542 } else if (lastPolNo != polNo) {
1543 leavePolNo(lastRecordNo, lastPolNo);
1544 enterPolNo(recordNo, polNo);
1545 }
1546 }
1547 count++;
1548 Bool result = visitRecord(recordNo, beamNo, ifNo, polNo, time);
1549
1550 { // epilogue
1551 lastRecordNo = recordNo;
1552
1553 lastBeamNo = beamNo;
1554 lastIfNo = ifNo;
1555 lastPolNo = polNo;
1556 lastTime = time;
1557 }
1558 return result ;
1559 }
1560
1561 virtual void finish() {
1562 if (count > 0) {
1563 leavePolNo(lastRecordNo, lastPolNo);
1564 leaveTime(lastRecordNo, lastTime);
1565 leaveIfNo(lastRecordNo, lastIfNo);
1566 leaveBeamNo(lastRecordNo, lastBeamNo);
1567 }
1568 }
1569};
1570
1571class BaseTsysHolder
1572{
1573public:
1574 BaseTsysHolder( ROArrayColumn<Float> &tsysCol )
1575 : col( tsysCol ),
1576 nchan(0)
1577 {
1578 reset() ;
1579 }
1580 virtual ~BaseTsysHolder() {}
1581 virtual Array<Float> getTsys() = 0 ;
1582 void setNchan( uInt n ) { nchan = n ; }
1583 void appendTsys( uInt row )
1584 {
1585 Vector<Float> v = col( row ) ;
1586 uInt len = tsys.nrow() ;
1587 tsys.resize( len+1, nchan, True ) ;
1588 if ( v.nelements() == nchan )
1589 tsys.row( len ) = v ;
1590 else
1591 tsys.row( len ) = v[0] ;
1592 }
1593 void setTsys( uInt row, uInt idx )
1594 {
1595 if ( idx >= nrow() )
1596 appendTsys( row ) ;
1597 else {
1598 Vector<Float> v = col( row ) ;
1599 if ( v.nelements() == nchan )
1600 tsys.row( idx ) = v ;
1601 else
1602 tsys.row( idx ) = v[0] ;
1603 }
1604 }
1605 void reset()
1606 {
1607 tsys.resize() ;
1608 }
1609 uInt nrow() { return tsys.nrow() ; }
1610 Bool isEffective()
1611 {
1612 return ( !(tsys.empty()) && anyNE( tsys, (Float)1.0 ) ) ;
1613 }
1614 BaseTsysHolder &operator= ( const BaseTsysHolder &v )
1615 {
1616 if ( this != &v )
1617 tsys.assign( v.tsys ) ;
1618 return *this ;
1619 }
1620protected:
1621 ROArrayColumn<Float> col ;
1622 Matrix<Float> tsys ;
1623 uInt nchan ;
1624};
1625
1626class TsysHolder : public BaseTsysHolder
1627{
1628public:
1629 TsysHolder( ROArrayColumn<Float> &tsysCol )
1630 : BaseTsysHolder( tsysCol )
1631 {}
1632 virtual ~TsysHolder() {}
1633 virtual Array<Float> getTsys()
1634 {
1635 return tsys.column( 0 ) ;
1636 }
1637};
1638
1639class TsysSpectrumHolder : public BaseTsysHolder
1640{
1641public:
1642 TsysSpectrumHolder( ROArrayColumn<Float> &tsysCol )
1643 : BaseTsysHolder( tsysCol )
1644 {}
1645 virtual ~TsysSpectrumHolder() {}
1646 virtual Array<Float> getTsys()
1647 {
1648 return tsys ;
1649 }
1650};
1651
1652class BaseTcalProcessor
1653{
1654public:
1655 BaseTcalProcessor( ROArrayColumn<Float> &tcalCol )
1656 : col( tcalCol )
1657 {}
1658 virtual ~BaseTcalProcessor() {}
1659 void setTcalId( Vector<uInt> &tcalId ) { id.assign( tcalId ) ; }
1660 virtual Array<Float> getTcal() = 0 ;
1661protected:
1662 ROArrayColumn<Float> col ;
1663 Vector<uInt> id ;
1664};
1665
1666class TcalProcessor : public BaseTcalProcessor
1667{
1668public:
1669 TcalProcessor( ROArrayColumn<Float> &tcalCol )
1670 : BaseTcalProcessor( tcalCol )
1671 {}
1672 virtual ~TcalProcessor() {}
1673 virtual Array<Float> getTcal()
1674 {
1675 uInt npol = id.nelements() ;
1676 Vector<Float> tcal( npol ) ;
1677 for ( uInt ipol = 0 ; ipol < npol ; ipol++ )
1678 tcal[ipol] = col( id[ipol] ).data()[0] ;
1679 //cout << "TcalProcessor: tcal = " << tcal << endl ;
1680 return tcal ;
1681 }
1682};
1683
1684class TcalSpectrumProcessor : public BaseTcalProcessor
1685{
1686public:
1687 TcalSpectrumProcessor( ROArrayColumn<Float> &tcalCol )
1688 : BaseTcalProcessor( tcalCol )
1689 {}
1690 virtual ~TcalSpectrumProcessor() {}
1691 virtual Array<Float> getTcal()
1692 {
1693 uInt npol = id.nelements() ;
1694 Vector<Float> tcal0 = col( 0 ) ;
1695 uInt nchan = tcal0.nelements() ;
1696 Matrix<Float> tcal( npol, nchan ) ;
1697 tcal.row( 0 ) = tcal0 ;
1698 for ( uInt ipol = 1 ; ipol < npol ; ipol++ )
1699 tcal.row( ipol ) = col( id[ipol] ) ;
1700 return tcal ;
1701 }
1702};
1703
1704class MSSysCalVisitor : public BaseMSSysCalVisitor
1705{
1706public:
1707 MSSysCalVisitor( const Table &from, Table &to )
1708 : BaseMSSysCalVisitor( from ),
1709 sctab( to ),
1710 rowidx( 0 )
1711 {
1712 scrow = TableRow( sctab ) ;
1713
1714 lastTcalId.resize() ;
1715 theTcalId.resize() ;
1716 startTime = 0.0 ;
1717 endTime = 0.0 ;
1718
1719 const TableRecord &keys = table.keywordSet() ;
1720 Table tcalTable = keys.asTable( "TCAL" ) ;
1721 tcalCol.attach( tcalTable, "TCAL" ) ;
1722 tsysCol.attach( table, "TSYS" ) ;
1723 tcalIdCol.attach( table, "TCAL_ID" ) ;
1724 intervalCol.attach( table, "INTERVAL" ) ;
1725 effectiveTcal.resize( tcalTable.nrow() ) ;
1726 for ( uInt irow = 0 ; irow < tcalTable.nrow() ; irow++ ) {
1727 if ( allEQ( tcalCol( irow ), (Float)1.0 ) )
1728 effectiveTcal[irow] = False ;
1729 else
1730 effectiveTcal[irow] = True ;
1731 }
1732
1733 TableRecord &r = scrow.record() ;
1734 RecordFieldPtr<Int> antennaIdRF( r, "ANTENNA_ID" ) ;
1735 *antennaIdRF = 0 ;
1736 feedIdRF.attachToRecord( r, "FEED_ID" ) ;
1737 specWinIdRF.attachToRecord( r, "SPECTRAL_WINDOW_ID" ) ;
1738 timeRF.attachToRecord( r, "TIME" ) ;
1739 intervalRF.attachToRecord( r, "INTERVAL" ) ;
1740 if ( r.isDefined( "TCAL" ) ) {
1741 tcalRF.attachToRecord( r, "TCAL" ) ;
1742 tcalProcessor = new TcalProcessor( tcalCol ) ;
1743 }
1744 else if ( r.isDefined( "TCAL_SPECTRUM" ) ) {
1745 tcalRF.attachToRecord( r, "TCAL_SPECTRUM" ) ;
1746 tcalProcessor = new TcalSpectrumProcessor( tcalCol ) ;
1747 }
1748 if ( r.isDefined( "TSYS" ) ) {
1749 tsysRF.attachToRecord( r, "TSYS" ) ;
1750 theTsys = new TsysHolder( tsysCol ) ;
1751 lastTsys = new TsysHolder( tsysCol ) ;
1752 }
1753 else {
1754 tsysRF.attachToRecord( r, "TSYS_SPECTRUM" ) ;
1755 theTsys = new TsysSpectrumHolder( tsysCol ) ;
1756 lastTsys = new TsysSpectrumHolder( tsysCol ) ;
1757 }
1758
1759 }
1760
1761 virtual void enterBeamNo(const uInt recordNo, uInt columnValue)
1762 {
1763 *feedIdRF = (Int)columnValue ;
1764 }
1765 virtual void leaveBeamNo(const uInt recordNo, uInt columnValue)
1766 {
1767 }
1768 virtual void enterIfNo(const uInt recordNo, uInt columnValue)
1769 {
1770 //cout << "enterIfNo" << endl ;
1771 ROArrayColumn<Float> sp( table, "SPECTRA" ) ;
1772 uInt nchan = sp( recordNo ).nelements() ;
1773 theTsys->setNchan( nchan ) ;
1774 lastTsys->setNchan( nchan ) ;
1775
1776 *specWinIdRF = (Int)columnValue ;
1777 }
1778 virtual void leaveIfNo(const uInt recordNo, uInt columnValue)
1779 {
1780 //cout << "leaveIfNo" << endl ;
1781 post() ;
1782 lastTsys->reset() ;
1783 lastTcalId.resize() ;
1784 theTsys->reset() ;
1785 theTcalId.resize() ;
1786 startTime = 0.0 ;
1787 endTime = 0.0 ;
1788 }
1789 virtual void enterTime(const uInt recordNo, Double columnValue)
1790 {
1791 //cout << "enterTime" << endl ;
1792 interval = intervalCol.asdouble( recordNo ) ;
1793 // start time and end time
1794 if ( startTime == 0.0 ) {
1795 startTime = columnValue * 86400.0 - 0.5 * interval ;
1796 endTime = columnValue * 86400.0 + 0.5 * interval ;
1797 }
1798 }
1799 virtual void leaveTime(const uInt recordNo, Double columnValue)
1800 {
1801 //cout << "leaveTime" << endl ;
1802 if ( isUpdated() ) {
1803 post() ;
1804 *lastTsys = *theTsys ;
1805 lastTcalId = theTcalId ;
1806 theTsys->reset() ;
1807 theTcalId.resize() ;
1808 startTime = columnValue * 86400.0 - 0.5 * interval ;
1809 endTime = columnValue * 86400.0 + 0.5 * interval ;
1810 }
1811 else {
1812 endTime = columnValue * 86400.0 + 0.5 * interval ;
1813 }
1814 }
1815 virtual void enterPolNo(const uInt recordNo, uInt columnValue)
1816 {
1817 //cout << "enterPolNo" << endl ;
1818 Vector<Float> tsys = tsysCol( recordNo ) ;
1819 uInt tcalId = tcalIdCol.asuInt( recordNo ) ;
1820 // lastTsys.nrow() must be npol
1821 if ( lastTsys->nrow() == columnValue )
1822 lastTsys->appendTsys( recordNo ) ;
1823 // lastTcalId.nelements() must be npol
1824 if ( lastTcalId.nelements() == columnValue )
1825 appendTcalId( lastTcalId, tcalId, columnValue ) ;
1826 // theTsys.nrow() must be npol
1827 if ( theTsys->nrow() == columnValue )
1828 theTsys->appendTsys( recordNo ) ;
1829 else {
1830 theTsys->setTsys( recordNo, columnValue ) ;
1831 }
1832 if ( theTcalId.nelements() == columnValue )
1833 appendTcalId( theTcalId, tcalId, columnValue ) ;
1834 else
1835 setTcalId( theTcalId, tcalId, columnValue ) ;
1836 }
1837 virtual void leavePolNo( const uInt recordNo, uInt columnValue )
1838 {
1839 }
1840
1841private:
1842 void appendTcalId( Vector<uInt> &v, uInt &elem, uInt &polId )
1843 {
1844 v.resize( polId+1, True ) ;
1845 v[polId] = elem ;
1846 }
1847 void setTcalId( Vector<uInt> &v, uInt &elem, uInt &polId )
1848 {
1849 v[polId] = elem ;
1850 }
1851 void post()
1852 {
1853 // check if given Tcal and Tsys is effective
1854 Bool isEffective = False ;
1855 for ( uInt ipol = 0 ; ipol < lastTcalId.nelements() ; ipol++ ) {
1856 if ( effectiveTcal[lastTcalId[ipol]] ) {
1857 isEffective = True ;
1858 break ;
1859 }
1860 }
1861 if ( !isEffective ) {
1862 if ( !(lastTsys->isEffective()) )
1863 return ;
1864 }
1865
1866 //cout << " interval: " << (endTime-startTime) << " lastTcalId = " << lastTcalId << endl ;
1867 Double midTime = 0.5 * ( startTime + endTime ) ;
1868 Double interval = endTime - startTime ;
1869 *timeRF = midTime ;
1870 *intervalRF = interval ;
1871 tcalProcessor->setTcalId( lastTcalId ) ;
1872 Array<Float> tcal = tcalProcessor->getTcal() ;
1873 tcalRF.define( tcal ) ;
1874 tsysRF.define( lastTsys->getTsys() ) ;
1875 sctab.addRow( 1, True ) ;
1876 scrow.put( rowidx ) ;
1877 rowidx++ ;
1878 }
1879
1880 Bool isUpdated()
1881 {
1882 Bool ret = False ;
1883 ret = anyNE( theTcalId, lastTcalId ) ;
1884 if ( !ret )
1885 ret = anyNE( theTsys->getTsys(), lastTsys->getTsys() ) ;
1886 return ret ;
1887 }
1888
1889 Table &sctab;
1890 TableRow scrow;
1891 uInt rowidx;
1892
1893 Double startTime,endTime,interval;
1894
1895 CountedPtr<BaseTsysHolder> lastTsys,theTsys;
1896 Vector<uInt> lastTcalId,theTcalId;
1897 CountedPtr<BaseTcalProcessor> tcalProcessor ;
1898 Vector<Bool> effectiveTcal;
1899
1900 RecordFieldPtr<Int> feedIdRF,specWinIdRF;
1901 RecordFieldPtr<Double> timeRF,intervalRF;
1902 RecordFieldPtr< Array<Float> > tcalRF,tsysRF;
1903
1904 ROArrayColumn<Float> tsysCol,tcalCol;
1905 ROTableColumn tcalIdCol,intervalCol;
1906};
1907
1908MSWriter::MSWriter(CountedPtr<Scantable> stable)
1909 : table_(stable),
1910 isWeather_(False),
1911 tcalSpec_(False),
1912 tsysSpec_(False),
1913 ptTabName_("")
1914{
1915 os_ = LogIO() ;
1916 os_.origin( LogOrigin( "MSWriter", "MSWriter()", WHERE ) ) ;
1917// os_ << "MSWriter::MSWriter()" << LogIO::POST ;
1918
1919 // initialize writer
1920 init() ;
1921}
1922
1923MSWriter::~MSWriter()
1924{
1925 os_.origin( LogOrigin( "MSWriter", "~MSWriter()", WHERE ) ) ;
1926// os_ << "MSWriter::~MSWriter()" << LogIO::POST ;
1927
1928 if ( mstable_ != 0 )
1929 delete mstable_ ;
1930}
1931
1932bool MSWriter::write(const string& filename, const Record& rec)
1933{
1934 os_.origin( LogOrigin( "MSWriter", "write()", WHERE ) ) ;
1935 //double startSec = mathutil::gettimeofday_sec() ;
1936 //os_ << "start MSWriter::write() startSec=" << startSec << LogIO::POST ;
1937
1938 filename_ = filename ;
1939
1940 // parsing MS options
1941 Bool overwrite = False ;
1942 if ( rec.isDefined( "ms" ) ) {
1943 Record msrec = rec.asRecord( "ms" ) ;
1944 if ( msrec.isDefined( "overwrite" ) ) {
1945 overwrite = msrec.asBool( "overwrite" ) ;
1946 }
1947 }
1948
1949 os_ << "Parsing MS options" << endl ;
1950 os_ << " overwrite = " << overwrite << LogIO::POST ;
1951
1952 File file( filename_ ) ;
1953 if ( file.exists() ) {
1954 if ( overwrite ) {
1955 os_ << filename_ << " exists. Overwrite existing data... " << LogIO::POST ;
1956 if ( file.isRegular() ) RegularFile(file).remove() ;
1957 else if ( file.isDirectory() ) Directory(file).removeRecursive() ;
1958 else SymLink(file).remove() ;
1959 }
1960 else {
1961 os_ << LogIO::SEVERE << "ERROR: " << filename_ << " exists..." << LogIO::POST ;
1962 return False ;
1963 }
1964 }
1965
1966 // set up MS
1967 setupMS() ;
1968
1969 // subtables
1970 // OBSERVATION
1971 fillObservation() ;
1972
1973 // ANTENNA
1974 fillAntenna() ;
1975
1976 // PROCESSOR
1977 fillProcessor() ;
1978
1979 // SOURCE
1980 fillSource() ;
1981
1982 // WEATHER
1983 if ( isWeather_ )
1984 fillWeather() ;
1985
1986 // SYSCAL
1987 fillSysCal() ;
1988
1989 /***
1990 * Start iteration using TableVisitor
1991 ***/
1992 {
1993 static const char *cols[] = {
1994 "FIELDNAME", "BEAMNO", "SCANNO", "IFNO", "SRCTYPE", "CYCLENO", "TIME",
1995 "POLNO",
1996 NULL
1997 };
1998 static const TypeManagerImpl<uInt> tmUInt;
1999 static const TypeManagerImpl<Int> tmInt;
2000 static const TypeManagerImpl<Double> tmDouble;
2001 static const TypeManagerImpl<String> tmString;
2002 static const TypeManager *const tms[] = {
2003 &tmString, &tmUInt, &tmUInt, &tmUInt, &tmInt, &tmUInt, &tmDouble, &tmUInt, NULL
2004 };
2005 //double t0 = mathutil::gettimeofday_sec() ;
2006 MSWriterVisitor myVisitor(table_->table(),*mstable_);
2007 //double t1 = mathutil::gettimeofday_sec() ;
2008 //cout << "MSWriterVisitor(): elapsed time " << t1-t0 << " sec" << endl ;
2009 String dataColName = "FLOAT_DATA" ;
2010 if ( useData_ )
2011 dataColName = "DATA" ;
2012 myVisitor.dataColumnName( dataColName ) ;
2013 myVisitor.pointingTableName( ptTabName_ ) ;
2014 myVisitor.setSourceRecord( srcRec_ ) ;
2015 //double t2 = mathutil::gettimeofday_sec() ;
2016 traverseTable(table_->table(), cols, tms, &myVisitor);
2017 //double t3 = mathutil::gettimeofday_sec() ;
2018 //cout << "traverseTable(): elapsed time " << t3-t2 << " sec" << endl ;
2019 }
2020 /***
2021 * End iteration using TableVisitor
2022 ***/
2023
2024 // ASDM tables
2025 const TableRecord &stKeys = table_->table().keywordSet() ;
2026 TableRecord &msKeys = mstable_->rwKeywordSet() ;
2027 uInt nfields = stKeys.nfields() ;
2028 for ( uInt ifield = 0 ; ifield < nfields ; ifield++ ) {
2029 String kname = stKeys.name( ifield ) ;
2030 if ( kname.find( "ASDM" ) != String::npos ) {
2031 String asdmpath = stKeys.asString( ifield ) ;
2032 os_ << "found ASDM table: " << asdmpath << LogIO::POST ;
2033 if ( Table::isReadable( asdmpath ) ) {
2034 Table newAsdmTab( asdmpath, Table::Old ) ;
2035 newAsdmTab.copy( filename_+"/"+kname, Table::New ) ;
2036 os_ << "add subtable: " << kname << LogIO::POST ;
2037 msKeys.defineTable( kname, Table( filename_+"/"+kname, Table::Old ) ) ;
2038 }
2039 }
2040 }
2041
2042 // replace POINTING table with original one if exists
2043 if ( ptTabName_ != "" ) {
2044 delete mstable_ ;
2045 mstable_ = 0 ;
2046 Table newPtTab( ptTabName_, Table::Old ) ;
2047 newPtTab.copy( filename_+"/POINTING", Table::New ) ;
2048 }
2049
2050 //double endSec = mathutil::gettimeofday_sec() ;
2051 //os_ << "end MSWriter::write() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2052
2053 return True ;
2054}
2055
2056void MSWriter::init()
2057{
2058// os_.origin( LogOrigin( "MSWriter", "init()", WHERE ) ) ;
2059// double startSec = mathutil::gettimeofday_sec() ;
2060// os_ << "start MSWriter::init() startSec=" << startSec << LogIO::POST ;
2061
2062 // access to scantable
2063 header_ = table_->getHeader() ;
2064
2065 // FLOAT_DATA? or DATA?
2066 if ( header_.npol > 2 ) {
2067 useFloatData_ = False ;
2068 useData_ = True ;
2069 }
2070 else {
2071 useFloatData_ = True ;
2072 useData_ = False ;
2073 }
2074
2075 // polarization type
2076 polType_ = header_.poltype ;
2077 if ( polType_ == "" )
2078 polType_ = "stokes" ;
2079 else if ( polType_.find( "linear" ) != String::npos )
2080 polType_ = "linear" ;
2081 else if ( polType_.find( "circular" ) != String::npos )
2082 polType_ = "circular" ;
2083 else if ( polType_.find( "stokes" ) != String::npos )
2084 polType_ = "stokes" ;
2085 else if ( polType_.find( "linpol" ) != String::npos )
2086 polType_ = "linpol" ;
2087 else
2088 polType_ = "notype" ;
2089
2090 // Check if some subtables are exists
2091 Bool isTcal = False ;
2092 if ( table_->tcal().table().nrow() != 0 ) {
2093 ROTableColumn col( table_->tcal().table(), "TCAL" ) ;
2094 if ( col.isDefined( 0 ) ) {
2095 os_ << "TCAL table exists: nrow=" << table_->tcal().table().nrow() << LogIO::POST ;
2096 isTcal = True ;
2097 }
2098 else {
2099 os_ << "No TCAL rows" << LogIO::POST ;
2100 }
2101 }
2102 else {
2103 os_ << "No TCAL rows" << LogIO::POST ;
2104 }
2105 if ( table_->weather().table().nrow() != 0 ) {
2106 ROTableColumn col( table_->weather().table(), "TEMPERATURE" ) ;
2107 if ( col.isDefined( 0 ) ) {
2108 os_ << "WEATHER table exists: nrow=" << table_->weather().table().nrow() << LogIO::POST ;
2109 isWeather_ =True ;
2110 }
2111 else {
2112 os_ << "No WEATHER rows" << LogIO::POST ;
2113 }
2114 }
2115 else {
2116 os_ << "No WEATHER rows" << LogIO::POST ;
2117 }
2118
2119 // Are TCAL_SPECTRUM and TSYS_SPECTRUM necessary?
2120 if ( header_.nchan != 1 ) {
2121 if ( isTcal ) {
2122 // examine TCAL subtable
2123 Table tcaltab = table_->tcal().table() ;
2124 ROArrayColumn<Float> tcalCol( tcaltab, "TCAL" ) ;
2125 for ( uInt irow = 0 ; irow < tcaltab.nrow() ; irow++ ) {
2126 if ( tcalCol( irow ).size() != 1 )
2127 tcalSpec_ = True ;
2128 }
2129 }
2130 // examine spectral data
2131 TableIterator iter0( table_->table(), "IFNO" ) ;
2132 while( !iter0.pastEnd() ) {
2133 Table t0( iter0.table() ) ;
2134 ROArrayColumn<Float> sharedFloatArrCol( t0, "SPECTRA" ) ;
2135 uInt len = sharedFloatArrCol( 0 ).size() ;
2136 if ( len != 1 ) {
2137 sharedFloatArrCol.attach( t0, "TSYS" ) ;
2138 if ( sharedFloatArrCol( 0 ).size() != 1 )
2139 tsysSpec_ = True ;
2140 }
2141 iter0.next() ;
2142 }
2143 }
2144
2145 // check if reference for POINTING table exists
2146 const TableRecord &rec = table_->table().keywordSet() ;
2147 if ( rec.isDefined( "POINTING" ) ) {
2148 ptTabName_ = rec.asString( "POINTING" ) ;
2149 if ( !Table::isReadable( ptTabName_ ) ) {
2150 ptTabName_ = "" ;
2151 }
2152 }
2153
2154// double endSec = mathutil::gettimeofday_sec() ;
2155// os_ << "end MSWriter::init() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2156}
2157
2158void MSWriter::setupMS()
2159{
2160// os_.origin( LogOrigin( "MSWriter", "setupMS()", WHERE ) ) ;
2161// double startSec = mathutil::gettimeofday_sec() ;
2162// os_ << "start MSWriter::setupMS() startSec=" << startSec << LogIO::POST ;
2163
2164 String dunit = table_->getHeader().fluxunit ;
2165
2166 TableDesc msDesc = MeasurementSet::requiredTableDesc() ;
2167 if ( useFloatData_ )
2168 MeasurementSet::addColumnToDesc( msDesc, MSMainEnums::FLOAT_DATA, 2 ) ;
2169 else if ( useData_ )
2170 MeasurementSet::addColumnToDesc( msDesc, MSMainEnums::DATA, 2 ) ;
2171
2172 SetupNewTable newtab( filename_, msDesc, Table::New ) ;
2173
2174 mstable_ = new MeasurementSet( newtab ) ;
2175
2176 TableColumn col ;
2177 if ( useFloatData_ )
2178 col.attach( *mstable_, "FLOAT_DATA" ) ;
2179 else if ( useData_ )
2180 col.attach( *mstable_, "DATA" ) ;
2181 col.rwKeywordSet().define( "UNIT", dunit ) ;
2182
2183 // create subtables
2184 TableDesc antennaDesc = MSAntenna::requiredTableDesc() ;
2185 SetupNewTable antennaTab( mstable_->antennaTableName(), antennaDesc, Table::New ) ;
2186 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::ANTENNA ), Table( antennaTab ) ) ;
2187
2188 TableDesc dataDescDesc = MSDataDescription::requiredTableDesc() ;
2189 SetupNewTable dataDescTab( mstable_->dataDescriptionTableName(), dataDescDesc, Table::New ) ;
2190 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::DATA_DESCRIPTION ), Table( dataDescTab ) ) ;
2191
2192 TableDesc dopplerDesc = MSDoppler::requiredTableDesc() ;
2193 SetupNewTable dopplerTab( mstable_->dopplerTableName(), dopplerDesc, Table::New ) ;
2194 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::DOPPLER ), Table( dopplerTab ) ) ;
2195
2196 TableDesc feedDesc = MSFeed::requiredTableDesc() ;
2197 SetupNewTable feedTab( mstable_->feedTableName(), feedDesc, Table::New ) ;
2198 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FEED ), Table( feedTab ) ) ;
2199
2200 TableDesc fieldDesc = MSField::requiredTableDesc() ;
2201 SetupNewTable fieldTab( mstable_->fieldTableName(), fieldDesc, Table::New ) ;
2202 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FIELD ), Table( fieldTab ) ) ;
2203
2204 TableDesc flagCmdDesc = MSFlagCmd::requiredTableDesc() ;
2205 SetupNewTable flagCmdTab( mstable_->flagCmdTableName(), flagCmdDesc, Table::New ) ;
2206 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FLAG_CMD ), Table( flagCmdTab ) ) ;
2207
2208 TableDesc freqOffsetDesc = MSFreqOffset::requiredTableDesc() ;
2209 SetupNewTable freqOffsetTab( mstable_->freqOffsetTableName(), freqOffsetDesc, Table::New ) ;
2210 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::FREQ_OFFSET ), Table( freqOffsetTab ) ) ;
2211
2212 TableDesc historyDesc = MSHistory::requiredTableDesc() ;
2213 SetupNewTable historyTab( mstable_->historyTableName(), historyDesc, Table::New ) ;
2214 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::HISTORY ), Table( historyTab ) ) ;
2215
2216 TableDesc observationDesc = MSObservation::requiredTableDesc() ;
2217 SetupNewTable observationTab( mstable_->observationTableName(), observationDesc, Table::New ) ;
2218 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::OBSERVATION ), Table( observationTab ) ) ;
2219
2220 TableDesc pointingDesc = MSPointing::requiredTableDesc() ;
2221 SetupNewTable pointingTab( mstable_->pointingTableName(), pointingDesc, Table::New ) ;
2222 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::POINTING ), Table( pointingTab ) ) ;
2223
2224 TableDesc polarizationDesc = MSPolarization::requiredTableDesc() ;
2225 SetupNewTable polarizationTab( mstable_->polarizationTableName(), polarizationDesc, Table::New ) ;
2226 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::POLARIZATION ), Table( polarizationTab ) ) ;
2227
2228 TableDesc processorDesc = MSProcessor::requiredTableDesc() ;
2229 SetupNewTable processorTab( mstable_->processorTableName(), processorDesc, Table::New ) ;
2230 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::PROCESSOR ), Table( processorTab ) ) ;
2231
2232 TableDesc sourceDesc = MSSource::requiredTableDesc() ;
2233 MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::TRANSITION, 1 ) ;
2234 MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::REST_FREQUENCY, 1 ) ;
2235 MSSource::addColumnToDesc( sourceDesc, MSSourceEnums::SYSVEL, 1 ) ;
2236 SetupNewTable sourceTab( mstable_->sourceTableName(), sourceDesc, Table::New ) ;
2237 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SOURCE ), Table( sourceTab ) ) ;
2238
2239 TableDesc spwDesc = MSSpectralWindow::requiredTableDesc() ;
2240 SetupNewTable spwTab( mstable_->spectralWindowTableName(), spwDesc, Table::New ) ;
2241 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SPECTRAL_WINDOW ), Table( spwTab ) ) ;
2242
2243 TableDesc stateDesc = MSState::requiredTableDesc() ;
2244 SetupNewTable stateTab( mstable_->stateTableName(), stateDesc, Table::New ) ;
2245 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::STATE ), Table( stateTab ) ) ;
2246
2247 TableDesc sysCalDesc = MSSysCal::requiredTableDesc() ;
2248 if ( tcalSpec_ )
2249 MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TCAL_SPECTRUM, 2 ) ;
2250 else
2251 MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TCAL, 1 ) ;
2252 if ( tsysSpec_ )
2253 MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TSYS_SPECTRUM, 2 ) ;
2254 else
2255 MSSysCal::addColumnToDesc( sysCalDesc, MSSysCalEnums::TSYS, 1 ) ;
2256 SetupNewTable sysCalTab( mstable_->sysCalTableName(), sysCalDesc, Table::New ) ;
2257 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::SYSCAL ), Table( sysCalTab ) ) ;
2258
2259 TableDesc weatherDesc = MSWeather::requiredTableDesc() ;
2260 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::TEMPERATURE ) ;
2261 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::PRESSURE ) ;
2262 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::REL_HUMIDITY ) ;
2263 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::WIND_SPEED ) ;
2264 MSWeather::addColumnToDesc( weatherDesc, MSWeatherEnums::WIND_DIRECTION ) ;
2265 SetupNewTable weatherTab( mstable_->weatherTableName(), weatherDesc, Table::New ) ;
2266 mstable_->rwKeywordSet().defineTable( MeasurementSet::keywordName( MeasurementSet::WEATHER ), Table( weatherTab ) ) ;
2267
2268 mstable_->initRefs() ;
2269
2270// double endSec = mathutil::gettimeofday_sec() ;
2271// os_ << "end MSWriter::setupMS() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2272}
2273
2274void MSWriter::fillObservation()
2275{
2276 //double startSec = mathutil::gettimeofday_sec() ;
2277 //os_ << "start MSWriter::fillObservation() startSec=" << startSec << LogIO::POST ;
2278
2279 // only 1 row
2280 mstable_->observation().addRow( 1, True ) ;
2281 MSObservationColumns msObsCols( mstable_->observation() ) ;
2282 msObsCols.observer().put( 0, header_.observer ) ;
2283 // tentatively put antennaname (from ANTENNA subtable)
2284 String hAntennaName = header_.antennaname ;
2285 String::size_type pos = hAntennaName.find( "//" ) ;
2286 String telescopeName ;
2287 if ( pos != String::npos ) {
2288 telescopeName = hAntennaName.substr( 0, pos ) ;
2289 }
2290 else {
2291 pos = hAntennaName.find( "@" ) ;
2292 telescopeName = hAntennaName.substr( 0, pos ) ;
2293 }
2294// os_ << "telescopeName = " << telescopeName << LogIO::POST ;
2295 msObsCols.telescopeName().put( 0, telescopeName ) ;
2296 msObsCols.project().put( 0, header_.project ) ;
2297 //ScalarMeasColumn<MEpoch> timeCol( table_->table().sort("TIME"), "TIME" ) ;
2298 Table sortedtable = table_->table().sort("TIME") ;
2299 ScalarMeasColumn<MEpoch> timeCol( sortedtable, "TIME" ) ;
2300 Vector<MEpoch> trange( 2 ) ;
2301 trange[0] = timeCol( 0 ) ;
2302 trange[1] = timeCol( table_->nrow()-1 ) ;
2303 msObsCols.timeRangeMeas().put( 0, trange ) ;
2304
2305 //double endSec = mathutil::gettimeofday_sec() ;
2306 //os_ << "end MSWriter::fillObservation() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2307}
2308
2309void MSWriter::antennaProperty( String &name, String &m, String &t, Double &d )
2310{
2311 name.upcase() ;
2312
2313 m = "ALT-AZ" ;
2314 t = "GROUND-BASED" ;
2315 if ( name.matches( Regex( "DV[0-9]+$" ) )
2316 || name.matches( Regex( "DA[0-9]+$" ) )
2317 || name.matches( Regex( "PM[0-9]+$" ) ) )
2318 d = 12.0 ;
2319 else if ( name.matches( Regex( "CM[0-9]+$" ) ) )
2320 d = 7.0 ;
2321 else if ( name.contains( "GBT" ) )
2322 d = 104.9 ;
2323 else if ( name.contains( "MOPRA" ) )
2324 d = 22.0 ;
2325 else if ( name.contains( "PKS" ) || name.contains( "PARKS" ) )
2326 d = 64.0 ;
2327 else if ( name.contains( "TIDBINBILLA" ) )
2328 d = 70.0 ;
2329 else if ( name.contains( "CEDUNA" ) )
2330 d = 30.0 ;
2331 else if ( name.contains( "HOBART" ) )
2332 d = 26.0 ;
2333 else if ( name.contains( "APEX" ) )
2334 d = 12.0 ;
2335 else if ( name.contains( "ASTE" ) )
2336 d = 10.0 ;
2337 else if ( name.contains( "NRO" ) )
2338 d = 45.0 ;
2339 else
2340 d = 1.0 ;
2341}
2342
2343void MSWriter::fillAntenna()
2344{
2345 //double startSec = mathutil::gettimeofday_sec() ;
2346 //os_ << "start MSWriter::fillAntenna() startSec=" << startSec << LogIO::POST ;
2347
2348 // only 1 row
2349 Table anttab = mstable_->antenna() ;
2350 anttab.addRow( 1, True ) ;
2351
2352 Table &table = table_->table() ;
2353 const TableRecord &keys = table.keywordSet() ;
2354 String hAntName = keys.asString( "AntennaName" ) ;
2355 String::size_type pos = hAntName.find( "//" ) ;
2356 String antennaName ;
2357 String stationName ;
2358 if ( pos != String::npos ) {
2359 stationName = hAntName.substr( 0, pos ) ;
2360 hAntName = hAntName.substr( pos+2 ) ;
2361 }
2362 pos = hAntName.find( "@" ) ;
2363 if ( pos != String::npos ) {
2364 antennaName = hAntName.substr( 0, pos ) ;
2365 stationName = hAntName.substr( pos+1 ) ;
2366 }
2367 else {
2368 antennaName = hAntName ;
2369 }
2370 Vector<Double> antpos = keys.asArrayDouble( "AntennaPosition" ) ;
2371
2372 String mount, atype ;
2373 Double diameter ;
2374 antennaProperty( antennaName, mount, atype, diameter ) ;
2375
2376 TableRow tr( anttab ) ;
2377 TableRecord &r = tr.record() ;
2378 RecordFieldPtr<String> nameRF( r, "NAME" ) ;
2379 RecordFieldPtr<String> stationRF( r, "STATION" ) ;
2380 RecordFieldPtr<String> mountRF( r, "MOUNT" ) ;
2381 RecordFieldPtr<String> typeRF( r, "TYPE" ) ;
2382 RecordFieldPtr<Double> dishDiameterRF( r, "DISH_DIAMETER" ) ;
2383 RecordFieldPtr< Vector<Double> > positionRF( r, "POSITION" ) ;
2384 *nameRF = antennaName ;
2385 *mountRF = mount ;
2386 *typeRF = atype ;
2387 *dishDiameterRF = diameter ;
2388 *positionRF = antpos ;
2389 *stationRF = stationName ;
2390
2391 tr.put( 0 ) ;
2392
2393 //double endSec = mathutil::gettimeofday_sec() ;
2394 //os_ << "end MSWriter::fillAntenna() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2395}
2396
2397void MSWriter::fillProcessor()
2398{
2399// double startSec = mathutil::gettimeofday_sec() ;
2400// os_ << "start MSWriter::fillProcessor() startSec=" << startSec << LogIO::POST ;
2401
2402 // only add empty 1 row
2403 MSProcessor msProc = mstable_->processor() ;
2404 msProc.addRow( 1, True ) ;
2405
2406// double endSec = mathutil::gettimeofday_sec() ;
2407// os_ << "end MSWriter::fillProcessor() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2408}
2409
2410void MSWriter::fillSource()
2411{
2412// double startSec = mathutil::gettimeofday_sec() ;
2413// os_ << "start MSWriter::fillSource() startSec=" << startSec << LogIO::POST ;
2414
2415 // access to MS SOURCE subtable
2416 MSSource msSrc = mstable_->source() ;
2417
2418 // access to MOLECULE subtable
2419 STMolecules stm = table_->molecules() ;
2420
2421 Int srcId = 0 ;
2422 Vector<Double> restFreq ;
2423 Vector<String> molName ;
2424 Vector<String> fMolName ;
2425
2426 // row based
2427 TableRow row( msSrc ) ;
2428 TableRecord &rec = row.record() ;
2429 RecordFieldPtr<Int> srcidRF( rec, "SOURCE_ID" ) ;
2430 RecordFieldPtr<String> nameRF( rec, "NAME" ) ;
2431 RecordFieldPtr< Array<Double> > srcpmRF( rec, "PROPER_MOTION" ) ;
2432 RecordFieldPtr< Array<Double> > srcdirRF( rec, "DIRECTION" ) ;
2433 RecordFieldPtr<Int> numlineRF( rec, "NUM_LINES" ) ;
2434 RecordFieldPtr< Array<Double> > restfreqRF( rec, "REST_FREQUENCY" ) ;
2435 RecordFieldPtr< Array<Double> > sysvelRF( rec, "SYSVEL" ) ;
2436 RecordFieldPtr< Array<String> > transitionRF( rec, "TRANSITION" ) ;
2437 RecordFieldPtr<Double> timeRF( rec, "TIME" ) ;
2438 RecordFieldPtr<Double> intervalRF( rec, "INTERVAL" ) ;
2439 RecordFieldPtr<Int> spwidRF( rec, "SPECTRAL_WINDOW_ID" ) ;
2440
2441 //
2442 // ITERATION: SRCNAME
2443 //
2444 TableIterator iter0( table_->table(), "SRCNAME" ) ;
2445 while( !iter0.pastEnd() ) {
2446 //Table t0( iter0.table() ) ;
2447 Table t0 = iter0.table() ;
2448
2449 // get necessary information
2450 ROScalarColumn<String> srcNameCol( t0, "SRCNAME" ) ;
2451 String srcName = srcNameCol( 0 ) ;
2452 ROArrayColumn<Double> sharedDArrRCol( t0, "SRCPROPERMOTION" ) ;
2453 Vector<Double> srcPM = sharedDArrRCol( 0 ) ;
2454 sharedDArrRCol.attach( t0, "SRCDIRECTION" ) ;
2455 Vector<Double> srcDir = sharedDArrRCol( 0 ) ;
2456 ROScalarColumn<Double> srcVelCol( t0, "SRCVELOCITY" ) ;
2457 Double srcVel = srcVelCol( 0 ) ;
2458 srcRec_.define( srcName, srcId ) ;
2459
2460 // NAME
2461 *nameRF = srcName ;
2462
2463 // SOURCE_ID
2464 *srcidRF = srcId ;
2465
2466 // PROPER_MOTION
2467 *srcpmRF = srcPM ;
2468
2469 // DIRECTION
2470 *srcdirRF = srcDir ;
2471
2472 //
2473 // ITERATION: MOLECULE_ID
2474 //
2475 TableIterator iter1( t0, "MOLECULE_ID" ) ;
2476 while( !iter1.pastEnd() ) {
2477 //Table t1( iter1.table() ) ;
2478 Table t1 = iter1.table() ;
2479
2480 // get necessary information
2481 ROScalarColumn<uInt> molIdCol( t1, "MOLECULE_ID" ) ;
2482 uInt molId = molIdCol( 0 ) ;
2483 stm.getEntry( restFreq, molName, fMolName, molId ) ;
2484
2485 uInt numFreq = restFreq.size() ;
2486
2487 // NUM_LINES
2488 *numlineRF = numFreq ;
2489
2490 // REST_FREQUENCY
2491 *restfreqRF = restFreq ;
2492
2493 // TRANSITION
2494 //*transitionRF = fMolName ;
2495 Vector<String> transition ;
2496 if ( fMolName.size() != 0 ) {
2497 transition = fMolName ;
2498 }
2499 else if ( molName.size() != 0 ) {
2500 transition = molName ;
2501 }
2502 else {
2503 transition.resize( numFreq ) ;
2504 transition = "" ;
2505 }
2506 *transitionRF = transition ;
2507
2508 // SYSVEL
2509 Vector<Double> sysvelArr( numFreq, srcVel ) ;
2510 *sysvelRF = sysvelArr ;
2511
2512 //
2513 // ITERATION: IFNO
2514 //
2515 TableIterator iter2( t1, "IFNO" ) ;
2516 while( !iter2.pastEnd() ) {
2517 //Table t2( iter2.table() ) ;
2518 Table t2 = iter2.table() ;
2519 uInt nrow = msSrc.nrow() ;
2520
2521 // get necessary information
2522 ROScalarColumn<uInt> ifNoCol( t2, "IFNO" ) ;
2523 uInt ifno = ifNoCol( 0 ) ; // IFNO = SPECTRAL_WINDOW_ID
2524 Double midTime ;
2525 Double interval ;
2526 getValidTimeRange( midTime, interval, t2 ) ;
2527
2528 // fill SPECTRAL_WINDOW_ID
2529 *spwidRF = ifno ;
2530
2531 // fill TIME, INTERVAL
2532 *timeRF = midTime ;
2533 *intervalRF = interval ;
2534
2535 // add row
2536 msSrc.addRow( 1, True ) ;
2537 row.put( nrow ) ;
2538
2539 iter2.next() ;
2540 }
2541
2542 iter1.next() ;
2543 }
2544
2545 // increment srcId if SRCNAME changed
2546 srcId++ ;
2547
2548 iter0.next() ;
2549 }
2550
2551// double endSec = mathutil::gettimeofday_sec() ;
2552// os_ << "end MSWriter::fillSource() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2553}
2554
2555void MSWriter::fillWeather()
2556{
2557// double startSec = mathutil::gettimeofday_sec() ;
2558// os_ << "start MSWriter::fillWeather() startSec=" << startSec << LogIO::POST ;
2559
2560 // access to MS WEATHER subtable
2561 MSWeather msw = mstable_->weather() ;
2562
2563 // access to WEATHER subtable
2564 Table stw = table_->weather().table() ;
2565 uInt nrow = stw.nrow() ;
2566
2567 if ( nrow == 0 )
2568 return ;
2569
2570 msw.addRow( nrow, True ) ;
2571 MSWeatherColumns mswCols( msw ) ;
2572
2573 // ANTENNA_ID is always 0
2574 Vector<Int> antIdArr( nrow, 0 ) ;
2575 mswCols.antennaId().putColumn( antIdArr ) ;
2576
2577 // fill weather status
2578 ROScalarColumn<Float> sharedFloatCol( stw, "TEMPERATURE" ) ;
2579 mswCols.temperature().putColumn( sharedFloatCol ) ;
2580 sharedFloatCol.attach( stw, "PRESSURE" ) ;
2581 mswCols.pressure().putColumn( sharedFloatCol ) ;
2582 sharedFloatCol.attach( stw, "HUMIDITY" ) ;
2583 mswCols.relHumidity().putColumn( sharedFloatCol ) ;
2584 sharedFloatCol.attach( stw, "WINDSPEED" ) ;
2585 mswCols.windSpeed().putColumn( sharedFloatCol ) ;
2586 sharedFloatCol.attach( stw, "WINDAZ" ) ;
2587 mswCols.windDirection().putColumn( sharedFloatCol ) ;
2588
2589 // fill TIME and INTERVAL
2590 Double midTime ;
2591 Double interval ;
2592 Vector<Double> intervalArr( nrow, 0.0 ) ;
2593 TableIterator iter( table_->table(), "WEATHER_ID" ) ;
2594 while( !iter.pastEnd() ) {
2595 //Table tab( iter.table() ) ;
2596 Table tab = iter.table() ;
2597
2598 ROScalarColumn<uInt> widCol( tab, "WEATHER_ID" ) ;
2599 uInt wid = widCol( 0 ) ;
2600
2601 getValidTimeRange( midTime, interval, tab ) ;
2602 mswCols.time().put( wid, midTime ) ;
2603 intervalArr[wid] = interval ;
2604
2605 iter.next() ;
2606 }
2607 mswCols.interval().putColumn( intervalArr ) ;
2608
2609// double endSec = mathutil::gettimeofday_sec() ;
2610// os_ << "end MSWriter::fillWeather() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2611}
2612
2613void MSWriter::fillSysCal()
2614{
2615 Table mssc = mstable_->sysCal() ;
2616
2617 {
2618 static const char *cols[] = {
2619 "BEAMNO", "IFNO", "TIME", "POLNO",
2620 NULL
2621 };
2622 static const TypeManagerImpl<uInt> tmUInt;
2623 static const TypeManagerImpl<Double> tmDouble;
2624 static const TypeManager *const tms[] = {
2625 &tmUInt, &tmUInt, &tmDouble, &tmUInt, NULL
2626 };
2627 //double t0 = mathutil::gettimeofday_sec() ;
2628 MSSysCalVisitor myVisitor(table_->table(),mssc);
2629 //double t1 = mathutil::gettimeofday_sec() ;
2630 //cout << "MSWriterVisitor(): elapsed time " << t1-t0 << " sec" << endl ;
2631 traverseTable(table_->table(), cols, tms, &myVisitor);
2632 //double t3 = mathutil::gettimeofday_sec() ;
2633 //cout << "traverseTable(): elapsed time " << t3-t2 << " sec" << endl ;
2634 }
2635
2636}
2637
2638void MSWriter::getValidTimeRange( Double &me, Double &interval, Table &tab )
2639{
2640// double startSec = mathutil::gettimeofday_sec() ;
2641// os_ << "start MSWriter::getVaridTimeRange() startSec=" << startSec << LogIO::POST ;
2642
2643 // sort table
2644 //Table stab = tab.sort( "TIME" ) ;
2645
2646 ROScalarColumn<Double> timeCol( tab, "TIME" ) ;
2647 Vector<Double> timeArr = timeCol.getColumn() ;
2648 Double minTime ;
2649 Double maxTime ;
2650 minMax( minTime, maxTime, timeArr ) ;
2651 Double midTime = 0.5 * ( minTime + maxTime ) * 86400.0 ;
2652 // unit for TIME
2653 // Scantable: "d"
2654 // MS: "s"
2655 me = midTime ;
2656 interval = ( maxTime - minTime ) * 86400.0 ;
2657
2658// double endSec = mathutil::gettimeofday_sec() ;
2659// os_ << "end MSWriter::getValidTimeRange() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2660}
2661
2662void MSWriter::getValidTimeRange( Double &me, Double &interval, Vector<Double> &atime, Vector<Double> &ainterval )
2663{
2664// double startSec = mathutil::gettimeofday_sec() ;
2665// os_ << "start MSWriter::getVaridTimeRange() startSec=" << startSec << LogIO::POST ;
2666
2667 // sort table
2668 //Table stab = tab.sort( "TIME" ) ;
2669
2670 Double minTime ;
2671 Double maxTime ;
2672 minMax( minTime, maxTime, atime ) ;
2673 Double midTime = 0.5 * ( minTime + maxTime ) * 86400.0 ;
2674 // unit for TIME
2675 // Scantable: "d"
2676 // MS: "s"
2677 me = midTime ;
2678 interval = ( maxTime - minTime ) * 86400.0 + mean( ainterval ) ;
2679
2680// double endSec = mathutil::gettimeofday_sec() ;
2681// os_ << "end MSWriter::getValidTimeRange() endSec=" << endSec << " (" << endSec-startSec << "sec)" << LogIO::POST ;
2682}
2683
2684}
Note: See TracBrowser for help on using the repository browser.