- Timestamp:
- 07/29/10 19:13:46 (14 years ago)
- Location:
- branches/mergetest
- Files:
-
- 4 deleted
- 68 edited
- 49 copied
Legend:
- Unmodified
- Added
- Removed
-
branches/mergetest
- Property svn:mergeinfo changed
-
branches/mergetest/SConstruct
r1740 r1779 161 161 env = conf.Finish() 162 162 163 env["version"] = "3. x"163 env["version"] = "3.0.0" 164 164 165 165 if env['mode'] == 'release': -
branches/mergetest/apps/asap2to3.cpp
r1665 r1779 26 26 pa.setDefault(Float(0.0)); 27 27 tfocus.addColumn(pa); 28 //tfocus.rwKeywordSet().define("PARALLACTIFY", False) 29 Int verid=tab.rwKeywordSet().fieldNumber("VERSION"); 30 tab.rwKeywordSet().define(verid,uInt(3)); 28 31 cout << "WARNING: This has invalidated the parallactic angle in the data. Reprocess the data in ASAP 3 " 29 32 << "if you need to handle polarisation conversions" -
branches/mergetest/external/atnf/PKSIO/FITSreader.cc
r1720 r1779 55 55 const int getSpectra, 56 56 const int getXPol, 57 const int getFeedPos, 58 const int getPointing, 57 59 const int coordSys) 58 60 { … … 85 87 cGetSpectra = getSpectra && cHaveSpectra; 86 88 cGetXPol = getXPol && cGetXPol; 89 cGetFeedPos = getFeedPos; 87 90 cCoordSys = coordSys; 91 88 92 89 93 return maxNChan; -
branches/mergetest/external/atnf/PKSIO/FITSreader.h
r1720 r1779 41 41 42 42 #include <atnf/PKSIO/MBrecord.h> 43 #include <atnf/PKSIO/PKSmsg.h>44 43 45 44 using namespace std; 45 46 46 47 47 // <summary> … … 49 49 // </summary> 50 50 51 class FITSreader : public PKSmsg 51 //class FITSreader 52 class FITSreader 52 53 { 53 54 public: … … 106 107 const int refChan[], 107 108 const int getSpectra = 1, 108 const int getXPol = 0, 109 const int getXPol = 0, 110 const int getFeedPos = 0, 111 const int getPointing = 0, 109 112 const int coordSys = 0); 113 110 114 111 115 // Find the range in time and position of the data selected. … … 119 123 // Read the next data record. 120 124 virtual int read( 125 // PKSMBrecord &record) = 0; 121 126 MBrecord &record) = 0; 122 127 … … 125 130 126 131 protected: 127 int *cBeams, *cEndChan, c CoordSys, cGetSpectra, cGetXPol, cHaveBase,128 cHaveSpectra, *cHaveXPol, *cIFs, cNBeam, *cNChan, cNIF, *cNPol,129 *cRefChan, *cStartChan;132 int *cBeams, *cEndChan, cGetFeedPos, cCoordSys, cGetSpectra, cGetXPol, 133 cHaveBase, cHaveSpectra, *cHaveXPol, *cIFs, cNBeam, *cNChan, cNIF, 134 *cNPol, *cRefChan, *cStartChan; 130 135 131 136 // For use in constructing messages. 132 137 char cMsg[256]; 138 133 139 }; 134 140 -
branches/mergetest/external/atnf/PKSIO/MBFITSreader.cc
r1720 r1779 41 41 #include <atnf/PKSIO/MBrecord.h> 42 42 43 #include <casa/Logging/LogIO.h> 44 43 45 #include <casa/math.h> 44 46 #include <casa/iostream.h> … … 57 59 const double HALFPI = PI / 2.0; 58 60 const double R2D = 180.0 / PI; 61 62 // Class name 63 const string className = "MBFITSreader" ; 59 64 60 65 //------------------------------------------------- MBFITSreader::MBFITSreader … … 99 104 100 105 // Tell RPFITSIN not to report errors directly. 101 iostat_.errlun = -1; 102 103 // By default, messages are written to stderr. 104 initMsg(); 106 //iostat_.errlun = -1; 105 107 } 106 108 … … 131 133 int &extraSysCal) 132 134 { 133 // Clear the message stack.134 clearMsg();135 const string methodName = "open()" ; 136 LogIO os( LogOrigin( className, methodName, WHERE ) ) ; 135 137 136 138 if (cMBopen) { … … 143 145 int jstat = -3; 144 146 if (rpfitsin(jstat)) { 145 sprintf(cMsg, " ERROR: Failed to open MBFITS file\n%s", rpname);146 logMsg(cMsg);147 sprintf(cMsg, "Failed to open MBFITS file\n%s", rpname); 148 os << LogIO::SEVERE << cMsg << LogIO::POST ; 147 149 return 1; 148 150 } … … 161 163 jstat = -1; 162 164 if (rpfitsin(jstat)) { 163 sprintf(cMsg, " ERROR:Failed to read MBFITS header in file\n"164 " 165 logMsg(cMsg);165 sprintf(cMsg, "Failed to read MBFITS header in file\n" 166 "%s", rpname); 167 os << LogIO::SEVERE << cMsg << LogIO::POST ; 166 168 close(); 167 169 return 1; … … 173 175 // Non-ATNF data may not store the position in (u,v,w). 174 176 if (strncmp(names_.sta, "tid", 3) == 0) { 175 sprintf(cMsg, " WARNING:Found Tidbinbilla data");177 sprintf(cMsg, "Found Tidbinbilla data"); 176 178 cSUpos = 1; 177 179 } else if (strncmp(names_.sta, "HOB", 3) == 0) { 178 sprintf(cMsg, " WARNING:Found Hobart data");180 sprintf(cMsg, "Found Hobart data"); 179 181 cSUpos = 1; 180 182 } else if (strncmp(names_.sta, "CED", 3) == 0) { 181 sprintf(cMsg, " WARNING:Found Ceduna data");183 sprintf(cMsg, "Found Ceduna data"); 182 184 cSUpos = 1; 183 185 } else { … … 187 189 if (cSUpos) { 188 190 strcat(cMsg, ", using telescope position\n from SU table."); 189 logMsg(cMsg);191 os << LogIO::WARN << cMsg << LogIO::POST ; 190 192 cInterp = 0; 191 193 } … … 207 209 208 210 if (cNBeam <= 0) { 209 logMsg("ERROR: Couldn't determine number of beams.");211 os << LogIO::SEVERE << "Couldn't determine number of beams." << LogIO::POST ; 210 212 close(); 211 213 return 1; … … 232 234 233 235 sprintf(cMsg, 234 " WARNING:RPFITSIN returned beam number %2d for AN table\n"235 " 236 "RPFITSIN returned beam number %2d for AN table\n" 237 "entry %2d with name '%.8s'", beamNo, iBeam+1, sta); 236 238 237 239 char text[8]; … … 245 247 } 246 248 247 logMsg(cMsg);249 os << LogIO::WARN << cMsg << LogIO::POST ; 248 250 } 249 251 … … 339 341 // Read the first syscal record. 340 342 if (rpget(1, cEOS)) { 341 logMsg("ERROR: Failed to read first syscal record.");343 os << LogIO::SEVERE << "Failed to read first syscal record." << LogIO::POST ; 342 344 close(); 343 345 return 1; … … 374 376 double &bandwidth) 375 377 { 378 const string methodName = "getHeader()" ; 379 LogIO os( LogOrigin( className, methodName, WHERE ) ) ; 380 376 381 if (!cMBopen) { 377 logMsg("ERROR: An MBFITS file has not been opened.");382 os << LogIO::SEVERE << "An MBFITS file has not been opened." << LogIO::POST ; 378 383 return 1; 379 384 } … … 511 516 MBrecord &MBrec) 512 517 { 518 const string methodName = "read()" ; 519 LogIO os( LogOrigin( className, methodName, WHERE ) ) ; 520 513 521 int beamNo = -1; 514 522 int haveData, pCode = 0, status; … … 517 525 518 526 if (!cMBopen) { 519 logMsg("ERROR: An MBFITS file has not been opened.");527 os << LogIO::SEVERE << "An MBFITS file has not been opened." << LogIO::POST ; 520 528 return 1; 521 529 } … … 562 570 563 571 #ifdef PKSIO_DEBUG 564 fprintf(stderr, "\nEnd-of-file detected, flushing last cycle.\n");572 os << LogIO::DEBUGGING << "\nEnd-of-file detected, flushing last cycle.\n" << LogIO::POST ; 565 573 #endif 566 574 … … 646 654 647 655 if (cNBin > 1 && cNBeamSel > 1) { 648 logMsg("ERROR: Cannot handle binning mode for multiple beams.\n" 649 " Select a single beam for input."); 656 os << LogIO::SEVERE << "Cannot handle binning mode for multiple beams.\nSelect a single beam for input." << LogIO::POST ; 650 657 close(); 651 658 return 1; … … 717 724 // the start of the next. 718 725 #ifdef PKSIO_DEBUG 719 fprintf(stderr, "Change-of-day on cUTC: %.1f -> %.1f\n", 720 cPrevUTC, cUTC); 726 char buf[256] ; 727 sprintf(buf, "Change-of-day on cUTC: %.1f -> %.1f\n", cPrevUTC, cUTC); 728 os << LogIO::DEBUGGING << buf << LogIO::POST ; 721 729 #endif 722 730 // Can't change the recorded value of cUTC directly (without also … … 724 732 // an offset to be applied when comparing integration timestamps. 725 733 cod = 86400.0; 726 } 734 735 } 727 736 728 737 if ((cUTC+cod) < cPrevUTC - 1.0) { … … 738 747 // All other data should be fully time ordered. 739 748 sprintf(cMsg, 740 " WARNING:Cycle %d:%03d-%03d, UTC went backwards from\n"741 " 742 " 749 "Cycle %d:%03d-%03d, UTC went backwards from\n" 750 "%.1f to %.1f! Incrementing day number,\n" 751 "positions may be unreliable.", cScanNo, cCycleNo, 743 752 cCycleNo+1, cPrevUTC, cUTC); 744 logMsg(cMsg); 753 //logMsg(cMsg); 754 os << LogIO::WARN << cMsg << LogIO::POST ; 745 755 cUTC += 86400.0; 746 756 } … … 782 792 } 783 793 784 fprintf(stderr, "\n In:%4d%4d%3d%3d %.3f %c %.3f (%+.3fs) - "794 sprintf(buf, "\n In:%4d%4d%3d%3d %.3f %c %.3f (%+.3fs) - " 785 795 "%sflushing\n", cScanNo, cCycleNo, beamNo, cIFno, cUTC, rel, cW, dt, 786 796 cFlushing ? "" : "not "); 797 os << LogIO::DEBUGGING << buf << LogIO::POST ; 787 798 if (cEOS) { 788 fprintf(stderr, "Start of new scan, flushing previous scan.\n"); 799 sprintf(buf, "Start of new scan, flushing previous scan.\n"); 800 os << LogIO::DEBUGGING << buf << LogIO::POST ; 789 801 } 790 802 #endif … … 884 896 885 897 #ifdef PKSIO_DEBUG 886 fprintf(stderr, "This (%d) ra, dec, UTC: %9.4f %9.4f %10.3f %9.4f\n",898 sprintf(buf, "This (%d) ra, dec, UTC: %9.4f %9.4f %10.3f %9.4f\n", 887 899 iMBuff->cycleNo, thisRA*R2D, thisDec*R2D, thisUTC, thisPA*R2D); 900 os << LogIO::DEBUGGING << buf << LogIO::POST ; 888 901 #endif 889 902 … … 921 934 922 935 #ifdef PKSIO_DEBUG 923 fprintf(stderr, "Next (%d) ra, dec, UTC: %9.4f %9.4f %10.3f "936 sprintf(buf, "Next (%d) ra, dec, UTC: %9.4f %9.4f %10.3f " 924 937 "(0.000s)\n", cCycleNo, cU*R2D, cV*R2D, cW); 938 os << LogIO::DEBUGGING << buf << LogIO::POST ; 925 939 #endif 926 940 … … 937 951 938 952 #ifdef PKSIO_DEBUG 939 fprintf(stderr, "Next (%d) ra, dec, UTC: %9.4f %9.4f %10.3f "953 sprintf(buf, "Next (%d) ra, dec, UTC: %9.4f %9.4f %10.3f " 940 954 "(%+.3fs)\n", cCycleNo, nextRA*R2D, nextDec*R2D, nextUTC, 941 955 utcDiff(nextUTC, thisUTC)); 956 os << LogIO::DEBUGGING << buf << LogIO::POST ; 942 957 #endif 943 958 … … 1089 1104 #ifdef PKSIO_DEBUG 1090 1105 double avRate = sqrt(cAvRate[0]*cAvRate[0] + cAvRate[1]*cAvRate[1]); 1091 fprintf(stderr, "RA, Dec, Av & PA rates: %8.4f %8.4f %8.4f %8.4f "1106 sprintf(buf, "RA, Dec, Av & PA rates: %8.4f %8.4f %8.4f %8.4f " 1092 1107 "pCode %d\n", raRate*R2D, decRate*R2D, avRate*R2D, paRate*R2D, pCode); 1108 os << LogIO::DEBUGGING << buf << LogIO::POST ; 1093 1109 #endif 1094 1110 … … 1113 1129 1114 1130 #ifdef PKSIO_DEBUG 1115 fprintf(stderr, "Intp (%d) ra, dec, UTC: %9.4f %9.4f %10.3f (pCode, "1131 sprintf(buf, "Intp (%d) ra, dec, UTC: %9.4f %9.4f %10.3f (pCode, " 1116 1132 "age: %d %.1fs)\n", iMBuff->cycleNo, cBuffer[jbuff].ra*R2D, 1117 1133 cBuffer[jbuff].dec*R2D, cBuffer[jbuff].utc, iMBuff->pCode, 1118 1134 iMBuff->rateAge); 1135 os << LogIO::DEBUGGING << buf << LogIO::POST ; 1119 1136 #endif 1120 1137 } … … 1130 1147 1131 1148 #ifdef PKSIO_DEBUG 1132 fprintf(stderr, "Out:%4d%4d%3d%3d\n", MBrec.scanNo, MBrec.cycleNo,1149 sprintf(buf, "Out:%4d%4d%3d%3d\n", MBrec.scanNo, MBrec.cycleNo, 1133 1150 MBrec.beamNo, MBrec.IFno[0]); 1151 os << LogIO::DEBUGGING << buf << LogIO::POST ; 1134 1152 #endif 1135 1153 … … 1172 1190 // Sanity check on the number of IFs in the new scan. 1173 1191 if (if_.n_if != cNIF) { 1174 sprintf(cMsg, " WARNING:Scan %d has %d IFs instead of %d, "1192 sprintf(cMsg, "Scan %d has %d IFs instead of %d, " 1175 1193 "continuing.", cScanNo, if_.n_if, cNIF); 1176 logMsg(cMsg);1194 os << LogIO::WARN << cMsg << LogIO::POST ; 1177 1195 } 1178 1196 } … … 1186 1204 1187 1205 #ifdef PKSIO_DEBUG 1188 fprintf(stderr, "Buf:%4d%4d%3d%3d\n", cScanNo, cCycleNo, beamNo, cIFno); 1206 sprintf(buf, "Buf:%4d%4d%3d%3d\n", cScanNo, cCycleNo, beamNo, cIFno); 1207 os << LogIO::DEBUGGING << buf << LogIO::POST ; 1189 1208 #endif 1190 1209 … … 1265 1284 // Integration cycle written to the output file twice (the only known 1266 1285 // example is 1999-05-22_1914_000-031805_03v.hpf). 1267 sprintf(cMsg, " WARNING:Integration cycle %d:%d, beam %2d, \n"1268 " 1286 sprintf(cMsg, "Integration cycle %d:%d, beam %2d, \n" 1287 "IF %d was duplicated.", cScanNo, cCycleNo-1, 1269 1288 beamNo, cIFno); 1270 logMsg(cMsg);1289 os << LogIO::WARN << cMsg << LogIO::POST ; 1271 1290 } 1272 1291 iMBuff->nChan[iIFSel] = nChan; … … 1454 1473 int MBFITSreader::rpget(int syscalonly, int &EOS) 1455 1474 { 1475 const string methodName = "rpget()" ; 1476 LogIO os( LogOrigin( className, methodName, WHERE ) ) ; 1477 1456 1478 EOS = 0; 1457 1479 … … 1469 1491 // Read failed; retry. 1470 1492 numErr++; 1471 logMsg("WARNING: RPFITS read failed - retrying.");1493 os << LogIO::WARN << "RPFITS read failed - retrying." << LogIO::POST ; 1472 1494 jstat = 0; 1473 1495 break; … … 1525 1547 default: 1526 1548 // Shouldn't reach here. 1527 sprintf(cMsg, " WARNING:Unrecognized RPFITSIN return code: %d "1549 sprintf(cMsg, "Unrecognized RPFITSIN return code: %d " 1528 1550 "(retrying).", jstat); 1529 logMsg(cMsg);1551 os << LogIO::WARN << cMsg << LogIO::POST ; 1530 1552 jstat = 0; 1531 1553 break; … … 1533 1555 } 1534 1556 1535 logMsg("ERROR: RPFITS read failed too many times.");1557 os << LogIO::SEVERE << "RPFITS read failed too many times." << LogIO::POST ; 1536 1558 return 2; 1537 1559 } … … 1549 1571 1550 1572 // Handle messages from RPFITSIN. 1573 /** 1551 1574 if (names_.errmsg[0] != ' ') { 1552 1575 int i; … … 1559 1582 logMsg(cMsg); 1560 1583 } 1561 1584 **/ 1562 1585 return jstat; 1563 1586 } -
branches/mergetest/external/atnf/PKSIO/MBrecord.cc
r1720 r1779 322 322 refBeam = other.refBeam; 323 323 324 polNo = other.polNo ; 325 srcVelocity = other.srcVelocity ; 326 324 327 return *this; 325 328 } … … 436 439 refBeam = other.refBeam; 437 440 441 polNo = other.polNo ; 442 srcVelocity = other.srcVelocity ; 443 438 444 return 0; 439 445 } -
branches/mergetest/external/atnf/PKSIO/MBrecord.h
r1720 r1779 166 166 short refBeam; // Reference beam, in beam-switching (MX) 167 167 // mode (added 1999/03/17). 168 int polNo ; // polarization ID 169 float srcVelocity ; // source velocity w.r.t. reference frame 168 170 169 171 private: -
branches/mergetest/external/atnf/PKSIO/PKSFITSreader.cc
r1720 r1779 34 34 //#--------------------------------------------------------------------------- 35 35 36 #include <atnf/PKSIO/PKSmsg.h>37 36 #include <atnf/PKSIO/MBFITSreader.h> 38 37 #include <atnf/PKSIO/SDFITSreader.h> … … 44 43 #include <casa/BasicMath/Math.h> 45 44 #include <casa/Quanta/MVTime.h> 45 #include <casa/Logging/LogIO.h> 46 46 47 47 //----------------------------------------------- PKSFITSreader::PKSFITSreader … … 61 61 cReader = new MBFITSreader(retry, interpolate ? 1 : 0); 62 62 } 63 64 // By default, messages are written to stderr.65 initMsg();66 63 } 67 64 … … 76 73 } 77 74 78 //------------------------------------------------------ PKSFITSreader::setMsg79 80 // Set message disposition. If fd is non-zero messages will be written81 // to that file descriptor, else stored for retrieval by getMsg().82 83 Int PKSFITSreader::setMsg(FILE *fd)84 {85 PKSmsg::setMsg(fd);86 cReader->setMsg(fd);87 88 return 0;89 }90 91 75 //-------------------------------------------------------- PKSFITSreader::open 92 76 … … 95 79 Int PKSFITSreader::open( 96 80 const String fitsName, 81 const String antenna, 97 82 Vector<Bool> &beams, 98 83 Vector<Bool> &IFs, … … 103 88 Bool &haveSpectra) 104 89 { 105 clearMsg();106 107 90 int extraSysCal, haveBase_, *haveXPol_, haveSpectra_, nBeam, *nChan_, 108 91 nIF, *nPol_, status; … … 110 93 nChan_, nPol_, haveXPol_, haveBase_, haveSpectra_, 111 94 extraSysCal); 112 logMsg(cReader->getMsg());113 cReader->clearMsg();95 //logMsg(cReader->getMsg()); 96 //cReader->clearMsg(); 114 97 if (status) { 115 98 return status; … … 178 161 obsType_, bunit_, equinox_, radecsys, 179 162 dopplerFrame_, datobs, utc, refFreq, bandwidth); 180 logMsg(cReader->getMsg());181 cReader->clearMsg();163 //logMsg(cReader->getMsg()); 164 //cReader->clearMsg(); 182 165 if (status) { 183 166 return 1; … … 218 201 Int status = cReader->getFreqInfo(nIF, startfreq, endfreq); 219 202 220 logMsg(cReader->getMsg());221 cReader->clearMsg();203 //logMsg(cReader->getMsg()); 204 //cReader->clearMsg(); 222 205 if (!status) { 223 206 startFreq.takeStorage(IPosition(1,nIF), startfreq, TAKE_OVER); … … 240 223 const Bool getSpectra, 241 224 const Bool getXPol, 225 const Bool getFeedPos, 226 const Bool getPointing, 242 227 const Int coordSys) 243 228 { … … 307 292 cGetSpectra = getSpectra; 308 293 cGetXPol = getXPol; 294 cGetFeedPos = getFeedPos; 295 cGetPointing = getPointing; 309 296 cCoordSys = coordSys; 310 297 311 298 uInt maxNChan = cReader->select(start, end, ref, cGetSpectra, cGetXPol, 312 c CoordSys);313 logMsg(cReader->getMsg());314 cReader->clearMsg();299 cGetFeedPos, cGetPointing, cCoordSys); 300 //logMsg(cReader->getMsg()); 301 //cReader->clearMsg(); 315 302 316 303 delete [] end; … … 336 323 337 324 Int status = cReader->findRange(nRow, nSel, dateSpan, utcSpan, posns); 338 logMsg(cReader->getMsg());339 cReader->clearMsg();325 //logMsg(cReader->getMsg()); 326 //cReader->clearMsg(); 340 327 341 328 if (!status) { … … 361 348 { 362 349 Int status = cReader->read(cMBrec); 363 logMsg(cReader->getMsg());364 cReader->clearMsg();350 //logMsg(cReader->getMsg()); 351 //cReader->clearMsg(); 365 352 366 353 if (status) { … … 378 365 pksrec.scanNo = cMBrec.scanNo; 379 366 pksrec.cycleNo = cMBrec.cycleNo; 367 pksrec.polNo = cMBrec.polNo ; 380 368 381 369 // Extract MJD. 382 370 Int day, month, year; 383 sscanf(cMBrec.datobs, "%4d-%2d-%2d", &year, &month, &day); 384 pksrec.mjd = MVTime(year, month, Double(day)).day() + cMBrec.utc/86400.0; 371 if ( strstr( cMBrec.datobs, "T" ) == NULL ) { 372 sscanf(cMBrec.datobs, "%4d-%2d-%2d", &year, &month, &day); 373 pksrec.mjd = MVTime(year, month, Double(day)).day() + cMBrec.utc/86400.0; 374 } 375 else { 376 Double dd, hour, min, sec ; 377 sscanf( cMBrec.datobs, "%4d-%2d-%2lfT%lf:%lf:%lf", &year, &month, &dd, &hour, &min, &sec ) ; 378 dd = dd + ( hour * 3600.0 + min * 60.0 + sec ) / 86400.0 ; 379 pksrec.mjd = MVTime(year, month, dd).day() ; 380 } 385 381 386 382 pksrec.interval = cMBrec.exposure; … … 388 384 pksrec.fieldName = trim(cMBrec.srcName); 389 385 pksrec.srcName = pksrec.fieldName; 386 387 int namelen = pksrec.srcName.length() ; 388 if ( namelen > 4 ) { 389 String srcsub = pksrec.srcName.substr( namelen-4, 4 ) ; 390 if ( srcsub.find( "_psc" ) != string::npos ) { 391 pksrec.fieldName = pksrec.srcName.substr( 0, namelen-4 ) ; 392 pksrec.srcName = pksrec.fieldName + "_ps_calon" ; 393 } 394 else if ( srcsub.find( "_pso" ) != string::npos ) { 395 pksrec.fieldName = pksrec.srcName.substr( 0, namelen-4 ) ; 396 pksrec.srcName = pksrec.fieldName + "_ps" ; 397 } 398 else if ( srcsub.find( "_prc" ) != string::npos ) { 399 pksrec.fieldName = pksrec.srcName.substr( 0, namelen-4 ) ; 400 pksrec.srcName = pksrec.fieldName + "_psr_calon" ; 401 } 402 else if ( srcsub.find( "_pro" ) != string::npos ) { 403 pksrec.fieldName = pksrec.srcName.substr( 0, namelen-4 ) ; 404 pksrec.srcName = pksrec.fieldName + "_psr" ; 405 } 406 else if ( srcsub.find( "_fsc" ) != string::npos ) { 407 pksrec.fieldName = pksrec.srcName.substr( 0, namelen-4 ) ; 408 pksrec.srcName = pksrec.fieldName + "_fs_calon" ; 409 } 410 else if ( srcsub.find( "_fso" ) != string::npos ) { 411 pksrec.fieldName = pksrec.srcName.substr( 0, namelen-4 ) ; 412 pksrec.srcName = pksrec.fieldName + "_fs" ; 413 } 414 else if ( srcsub.find( "_frc" ) != string::npos ) { 415 pksrec.fieldName = pksrec.srcName.substr( 0, namelen-4 ) ; 416 pksrec.srcName = pksrec.fieldName + "_fsr_calon" ; 417 } 418 else if ( srcsub.find( "_fro" ) != string::npos ) { 419 pksrec.fieldName = pksrec.srcName.substr( 0, namelen-4 ) ; 420 pksrec.srcName = pksrec.fieldName + "_fsr" ; 421 } 422 else if ( srcsub.find( "_nsc" ) != string::npos || srcsub.find( "_nrc" ) != string::npos ) { 423 pksrec.fieldName = pksrec.srcName.substr( 0, namelen-4 ) ; 424 pksrec.srcName = pksrec.fieldName + "_nod_calon" ; 425 } 426 else if ( srcsub.find( "_nso" ) != string::npos || srcsub.find( "_nro" ) != string::npos ) { 427 pksrec.fieldName = pksrec.srcName.substr( 0, namelen-4 ) ; 428 pksrec.srcName = pksrec.fieldName + "_nod" ; 429 } 430 } 390 431 391 432 pksrec.srcDir.resize(2); … … 396 437 pksrec.srcPM(0) = 0.0; 397 438 pksrec.srcPM(1) = 0.0; 398 pksrec.srcVel = 0.0;439 pksrec.srcVel = cMBrec.srcVelocity; 399 440 pksrec.obsType = trim(cMBrec.obsType); 400 441 … … 404 445 pksrec.bandwidth = chanWidth * nChan; 405 446 pksrec.freqInc = cMBrec.fqDelt[0]; 406 pksrec.restFreq = cMBrec.restFreq; 447 pksrec.restFreq.resize(1) ; 448 pksrec.restFreq(0) = cMBrec.restFreq; 407 449 408 450 pksrec.tcal.resize(nPol); … … 498 540 { 499 541 cReader->close(); 500 logMsg(cReader->getMsg());501 cReader->clearMsg();542 //logMsg(cReader->getMsg()); 543 //cReader->clearMsg(); 502 544 } 503 545 -
branches/mergetest/external/atnf/PKSIO/PKSFITSreader.h
r1720 r1779 70 70 virtual ~PKSFITSreader(); 71 71 72 // Set message disposition.73 virtual Int setMsg(74 FILE *fd = 0x0);75 76 72 // Open the FITS file for reading. 77 73 virtual Int open( 78 74 const String fitsName, 75 const String antenna, 79 76 Vector<Bool> &beams, 80 77 Vector<Bool> &IFs, … … 114 111 const Bool getSpectra = True, 115 112 const Bool getXPol = False, 113 const Bool getFeedPos = False, 114 const Bool getPointing = False, 116 115 const Int coordSys = 0); 117 116 -
branches/mergetest/external/atnf/PKSIO/PKSMS2reader.cc
r1720 r1779 34 34 //#--------------------------------------------------------------------------- 35 35 36 #include <atnf/pks/pks_maths.h> 37 #include <atnf/PKSIO/PKSmsg.h> 38 #include <atnf/PKSIO/PKSrecord.h> 39 #include <atnf/PKSIO/PKSMS2reader.h> 40 36 // AIPS++ includes. 41 37 #include <casa/stdio.h> 42 38 #include <casa/Arrays/ArrayMath.h> … … 44 40 #include <ms/MeasurementSets/MSColumns.h> 45 41 #include <tables/Tables.h> 42 #include <casa/Quanta/MVTime.h> 43 #include <casa/Quanta/MVAngle.h> 44 #include <casa/BasicMath/Math.h> 45 #include <casa/Logging/LogIO.h> 46 #include <casa/Utilities/Sort.h> 47 #include <measures/Measures/MeasConvert.h> 48 #include <measures/Measures/MEpoch.h> 49 #include <measures/Measures/MeasRef.h> 50 51 52 // Parkes includes. 53 #include <atnf/pks/pks_maths.h> 54 #include <atnf/PKSIO/PKSrecord.h> 55 #include <atnf/PKSIO/PKSMS2reader.h> 56 46 57 47 58 //------------------------------------------------- PKSMS2reader::PKSMS2reader … … 52 63 { 53 64 cMSopen = False; 54 55 // By default, messages are written to stderr.56 initMsg();57 65 } 58 66 … … 70 78 Int PKSMS2reader::open( 71 79 const String msName, 80 const String antenna, 72 81 Vector<Bool> &beams, 73 82 Vector<Bool> &IFs, … … 88 97 89 98 cPKSMS = MeasurementSet(msName); 99 100 // data selection by antenna 101 if ( antenna.length() == 0 ) { 102 cAntId.resize( 1 ) ; 103 cAntId[0] = 0 ; 104 } 105 else { 106 setupAntennaList( antenna ) ; 107 if ( cAntId.size() > 1 ) { 108 LogIO os( LogOrigin( "PKSMS2reader", "open()", WHERE ) ) ; 109 os << LogIO::WARN << "PKSMS2reader is not ready for multiple antenna selection. Use first antenna id " << cAntId[0] << "."<< LogIO::POST ; 110 Int tmp = cAntId[0] ; 111 cAntId.resize( 1 ) ; 112 cAntId[0] = tmp ; 113 } 114 stringstream ss ; 115 ss << "SELECT FROM $1 WHERE ANTENNA1 == ANTENNA2 && ANTENNA1 IN [" ; 116 for ( uInt i = 0 ; i < cAntId.size() ; i++ ) { 117 ss << cAntId[i] ; 118 if ( i == cAntId.size()-1 ) { 119 ss << "]" ; 120 } 121 else { 122 ss << "," ; 123 } 124 } 125 string taql = ss.str() ; 126 //cerr << "taql = " << taql << endl ; 127 cPKSMS = MeasurementSet( tableCommand( taql, cPKSMS ) ) ; 128 } 129 130 // taql access to the syscal table 131 cHaveSysCal = False; 132 if (cHaveSysCal=Table::isReadable(cPKSMS.sysCalTableName())) { 133 cSysCalTab = Table(cPKSMS.sysCalTableName()); 134 } 135 136 // Lock the table for read access. 137 cPKSMS.lock(False); 138 90 139 cIdx = 0; 140 lastmjd = 0.0; 91 141 cNRow = cPKSMS.nrow(); 92 142 cMSopen = True; 93 94 // Lock the table for read access.95 cPKSMS.lock(False);96 143 97 144 // Main MS table and subtable column access. … … 107 154 ROMSSysCalColumns sysCalCols(cPKSMS.sysCal()); 108 155 ROMSWeatherColumns weatherCols(cPKSMS.weather()); 156 ROMSAntennaColumns antennaCols(cPKSMS.antenna()); 109 157 110 158 // Column accessors for required columns. … … 115 163 cFieldIdCol.reference(msCols.fieldId()); 116 164 cFieldNameCol.reference(fieldCols.name()); 165 cFieldDelayDirCol.reference(fieldCols.delayDir()); 117 166 118 167 cSrcIdCol.reference(fieldCols.sourceId()); 168 cSrcId2Col.reference(sourceCols.sourceId()); 119 169 cSrcNameCol.reference(sourceCols.name()); 120 170 cSrcDirCol.reference(sourceCols.direction()); … … 124 174 cStateIdCol.reference(msCols.stateId()); 125 175 cObsModeCol.reference(stateCols.obsMode()); 176 cCalCol.reference(stateCols.cal()); 177 cSigStateCol.reference(stateCols.sig()); 178 cRefStateCol.reference(stateCols.ref()); 126 179 127 180 cDataDescIdCol.reference(msCols.dataDescId()); 181 cSpWinIdCol.reference(dataDescCols.spectralWindowId()); 128 182 cChanFreqCol.reference(spWinCols.chanFreq()); 183 cTotBWCol.reference(spWinCols.totalBandwidth()); 129 184 130 185 cWeatherTimeCol.reference(weatherCols.time()); … … 135 190 cBeamNoCol.reference(msCols.feed1()); 136 191 cPointingCol.reference(pointingCols.direction()); 192 cPointingTimeCol.reference(pointingCols.time()); 137 193 cSigmaCol.reference(msCols.sigma()); 138 194 cNumReceptorCol.reference(feedCols.numReceptors()); 139 195 140 196 // Optional columns. 197 cHaveTsys = False; 198 cHaveTcal = False; 141 199 if ((cHaveSrcVel = cPKSMS.source().tableDesc().isColumn("SYSVEL"))) { 142 200 cSrcVelCol.attach(cPKSMS.source(), "SYSVEL"); 143 201 } 144 202 145 if ( (cHaveTsys = cPKSMS.sysCal().tableDesc().isColumn("TSYS"))) {203 if (cHaveSysCal && (cHaveTsys = cPKSMS.sysCal().tableDesc().isColumn("TSYS"))) { 146 204 cTsysCol.attach(cPKSMS.sysCal(), "TSYS"); 205 } 206 207 if (cHaveSysCal && (cHaveTcal = cPKSMS.sysCal().tableDesc().isColumn("TCAL"))) { 208 cTcalCol.attach(cPKSMS.sysCal(), "TCAL"); 147 209 } 148 210 … … 158 220 // Spectral data should always be present. 159 221 haveSpectra = True; 160 cFloatDataCol.reference(msCols.floatData()); 222 cHaveDataCol = False; 223 cHaveCorrectedDataCol = False; 224 ROMSObservationColumns observationCols(cPKSMS.observation()); 225 //String telName = observationCols.telescopeName()(0); 226 cTelName = observationCols.telescopeName()(0); 227 //cATF = cTelName.contains("ATF"); 228 //cOSF = cTelName.contains("OSF"); 229 //cALMA = cTelName.contains("ALMA"); 230 cALMA = cTelName.contains("ATF")||cTelName.contains("OSF")|| 231 cTelName.contains("ALMA"); 232 233 if (cHaveDataCol = cPKSMS.isColumn(MSMainEnums::DATA)) { 234 if (cALMA) { 235 //try to read a single baseline interferometeric data 236 //and treat it as single dish data 237 //maybe extended for ALMA commissioning later 238 cDataCol.reference(msCols.data()); 239 if (cHaveCorrectedDataCol = cPKSMS.isColumn(MSMainEnums::CORRECTED_DATA)) { 240 //cerr<<"Do have CORRECTED_DATA column"<<endl; 241 cCorrectedDataCol.reference(msCols.correctedData()); 242 } 243 } 244 } 245 else { 246 cFloatDataCol.reference(msCols.floatData()); 247 } 161 248 cFlagCol.reference(msCols.flag()); 162 163 if ((cGetXPol = cPKSMS.isColumn(MSMainEnums::DATA))) { 249 cFlagRowCol.reference(msCols.flagRow()); 250 251 if (cGetXPol = (cPKSMS.isColumn(MSMainEnums::DATA) && (!cALMA))) { 164 252 if ((cHaveXCalFctr = cPKSMS.tableDesc().isColumn("XCALFCTR"))) { 165 253 cXCalFctrCol.attach(cPKSMS, "XCALFCTR"); … … 181 269 182 270 // Number of IFs. 183 uInt nIF = dataDescCols.nrow(); 271 //uInt nIF = dataDescCols.nrow(); 272 uInt nIF =spWinCols.nrow(); 273 Vector<Int> spWinIds = cSpWinIdCol.getColumn() ; 184 274 IFs.resize(nIF); 185 275 IFs = True; 276 for ( Int ispw = 0 ; ispw < nIF ; ispw++ ) { 277 if ( allNE( ispw, spWinIds ) ) { 278 IFs(ispw) = False ; 279 } 280 } 186 281 187 282 // Number of polarizations and channels in each IF. 188 ROScalarColumn<Int> spWinIdCol(dataDescCols.spectralWindowId());189 283 ROScalarColumn<Int> numChanCol(spWinCols.numChan()); 190 284 … … 195 289 nPol.resize(nIF); 196 290 for (uInt iIF = 0; iIF < nIF; iIF++) { 197 nChan(iIF) = numChanCol(spWinIdCol(iIF)); 198 nPol(iIF) = numPolCol(polIdCol(iIF)); 291 if ( IFs(iIF) ) { 292 nChan(iIF) = numChanCol(cSpWinIdCol(iIF)) ; 293 nPol(iIF) = numPolCol(polIdCol(iIF)) ; 294 } 295 else { 296 nChan(iIF) = 0 ; 297 nPol(iIF) = 0 ; 298 } 199 299 } 200 300 … … 203 303 haveXPol = False; 204 304 205 if (cGetXPol ) {305 if (cGetXPol && !(cALMA)) { 206 306 for (Int irow = 0; irow < cNRow; irow++) { 207 307 if (cDataCol.isDefined(irow)) { … … 252 352 String &antName, 253 353 Vector<Double> &antPosition, 354 // before merge... 355 //String &obsMode, 254 356 String &obsType, 255 357 String &bunit, … … 258 360 Double &mjd, 259 361 Double &refFreq, 260 Double &bandwidth) 362 Double &bandwidth) 261 363 { 262 364 if (!cMSopen) { … … 271 373 // Antenna name and ITRF coordinates. 272 374 ROMSAntennaColumns antennaCols(cPKSMS.antenna()); 273 antName = antennaCols.name()(0); 274 antPosition = antennaCols.position()(0); 375 //antName = antennaCols.name()(0); 376 antName = antennaCols.name()(cAntId[0]); 377 if (cALMA) { 378 antName = cTelName + "-" + antName; 379 } 380 //antPosition = antennaCols.position()(0); 381 antPosition = antennaCols.position()(cAntId[0]); 275 382 276 383 // Observation type. … … 282 389 } 283 390 284 // Brightness units. 285 bunit = cPKSMS.unit(MSMainEnums::FLOAT_DATA); 286 391 bunit = ""; 392 if (cHaveDataCol) { 393 const TableRecord& keywordSet2 394 = cDataCol.columnDesc().keywordSet(); 395 if(keywordSet2.isDefined("UNIT")) { 396 bunit = keywordSet2.asString("UNIT"); 397 } 398 } else { 399 const TableRecord& keywordSet 400 = cFloatDataCol.columnDesc().keywordSet(); 401 if(keywordSet.isDefined("UNIT")) { 402 bunit = keywordSet.asString("UNIT"); 403 } 404 } 405 406 /*** 407 const TableRecord& keywordSet 408 = cFloatDataCol.columnDesc().keywordSet(); 409 if(keywordSet.isDefined("UNIT")) { 410 fluxunit = keywordSet.asString("UNIT"); 411 } 412 ***/ 287 413 // Coordinate equinox. 288 414 ROMSPointingColumns pointingCols(cPKSMS.pointing()); 289 415 String dirref = pointingCols.direction().keywordSet().asRecord("MEASINFO"). 290 416 asString("Ref"); 417 cDirRef = dirref; 418 if (dirref =="AZELGEO" || dirref == "AZEL") { 419 dirref = "J2000"; 420 } 291 421 sscanf(dirref.chars()+1, "%f", &equinox); 292 422 … … 357 487 const Bool getSpectra, 358 488 const Bool getXPol, 489 const Bool getFeedPos, 490 const Bool getPointing, 359 491 const Int coordSys) 360 492 { … … 436 568 cGetXPol = cGetXPol && getXPol; 437 569 570 // Get feed positions? (Not available.) 571 cGetFeedPos = False; 572 573 // Get Pointing data (for MS) 574 cGetPointing = getPointing; 575 438 576 // Coordinate system? (Only equatorial available.) 439 577 cCoordSys = 0; … … 490 628 // Read the next data record. 491 629 630 /** 631 Int PKSMS2reader::read( 632 Int &scanNo, 633 Int &cycleNo, 634 Double &mjd, 635 Double &interval, 636 String &fieldName, 637 String &srcName, 638 Vector<Double> &srcDir, 639 Vector<Double> &srcPM, 640 Double &srcVel, 641 String &obsMode, 642 Int &IFno, 643 Double &refFreq, 644 Double &bandwidth, 645 Double &freqInc, 646 Vector<Double> &restFreq, 647 Vector<Float> &tcal, 648 String &tcalTime, 649 Float &azimuth, 650 Float &elevation, 651 Float &parAngle, 652 Float &focusAxi, 653 Float &focusTan, 654 Float &focusRot, 655 Float &temperature, 656 Float &pressure, 657 Float &humidity, 658 Float &windSpeed, 659 Float &windAz, 660 Int &refBeam, 661 Int &beamNo, 662 Vector<Double> &direction, 663 Vector<Double> &scanRate, 664 Vector<Float> &tsys, 665 Vector<Float> &sigma, 666 Vector<Float> &calFctr, 667 Matrix<Float> &baseLin, 668 Matrix<Float> &baseSub, 669 Matrix<Float> &spectra, 670 Matrix<uChar> &flagged, 671 uInt &flagrow, 672 Complex &xCalFctr, 673 Vector<Complex> &xPol) 674 **/ 492 675 Int PKSMS2reader::read(PKSrecord &pksrec) 493 676 { 677 LogIO os( LogOrigin( "PKSMS2reader", "read()", WHERE ) ) ; 678 494 679 if (!cMSopen) { 495 680 return 1; … … 504 689 Int ibeam; 505 690 Int iIF; 691 Int iDataDesc; 692 506 693 while (True) { 507 694 ibeam = cBeamNoCol(cIdx); 508 iIF = cDataDescIdCol(cIdx); 695 iDataDesc = cDataDescIdCol(cIdx); 696 iIF =cSpWinIdCol(iDataDesc); 509 697 if (cBeams(ibeam) && cIFs(iIF)) { 510 698 break; … … 516 704 } 517 705 } 518 519 706 // Renumerate scan no. Here still is 1-based 520 pksrec.scanNo = cScanNoCol(cIdx) - cScanNoCol(0) + 1; 707 //scanNo = cScanNoCol(cIdx) - cScanNoCol(0) + 1; 708 //scanNo = cScanNoCol(cIdx); 709 pksrec.scanNo = cScanNoCol(cIdx); 521 710 522 711 if (pksrec.scanNo != cScanNo) { … … 542 731 543 732 Int srcId = cSrcIdCol(fieldId); 544 pksrec.srcName = cSrcNameCol(srcId); 733 //For source with multiple spectral window setting, this is not 734 // correct. Source name of srcId may not be at 'srcId'th row of SrcNameCol 735 //srcName = cSrcNameCol(srcId); 736 for (uInt irow = 0; irow < cSrcId2Col.nrow(); irow++) { 737 if (cSrcId2Col(irow) == srcId) { 738 //srcName = cSrcNameCol(irow); 739 pksrec.srcName = cSrcNameCol(irow); 740 } 741 } 742 545 743 pksrec.srcDir = cSrcDirCol(srcId); 546 744 pksrec.srcPM = cSrcPMCol(srcId); 547 745 548 746 // Systemic velocity. 549 if (!cHaveSrcVel ) {747 if (!cHaveSrcVel || cALMA) { 550 748 pksrec.srcVel = 0.0f; 551 749 } else { … … 553 751 } 554 752 753 ROMSAntennaColumns antennaCols(cPKSMS.antenna()); 754 //String telescope = antennaCols.name()(0); 755 String telescope = antennaCols.name()(cAntId[0]); 756 Bool cGBT = telescope.contains("GBT"); 757 //Bool cPM = telescope.contains("PM"); // ACA TP antenna 758 //Bool cDV = telescope.contains("DV"); // VERTEX 759 //Bool cCM = telescope.contains("CM"); // ACA 7m antenna 760 //Bool cALMA = cPM || cDV || cCM ; 555 761 // Observation type. 556 Int stateId = cStateIdCol(cIdx); 557 pksrec.obsType = cObsModeCol(stateId); 762 // check if State Table exist 763 //Bool cHaveStateTab=Table::isReadable(cPKSMS.stateTableName()); 764 Int stateId = 0; 765 Int StateNRow = 0; 766 StateNRow=cObsModeCol.nrow(); 767 if (Table::isReadable(cPKSMS.stateTableName())) { 768 pksrec.obsType = " "; 769 if (StateNRow > 0) { 770 stateId = cStateIdCol(cIdx); 771 if (stateId == -1) { 772 //pksrec.obsType = " "; 773 } else { 774 pksrec.obsType = cObsModeCol(stateId); 775 Bool sigState =cSigStateCol(stateId); 776 Bool refState =cRefStateCol(stateId); 777 //DEBUG 778 //cerr <<"stateid="<<stateId<<" obsmode="<<pksrec.obsType<<endl; 779 if (cGBT) { 780 // split the obsType string and append a proper label 781 // (these are GBT specific) 782 int epos = pksrec.obsType.find_first_of(':'); 783 int nextpos = pksrec.obsType.find_first_of(':',epos+1); 784 string obsMode1 = pksrec.obsType.substr(0,epos); 785 string obsMode2 = pksrec.obsType.substr(epos+1,nextpos-epos-1); 786 787 //cerr <<"obsMode2= "<<obsMode2<<endl; 788 if (!pksrec.srcName.contains("_ps") 789 &&!pksrec.srcName.contains("_psr") 790 &&!pksrec.srcName.contains("_nod") 791 &&!pksrec.srcName.contains("_fs") 792 &&!pksrec.srcName.contains("_fsr")) { 793 // if Nod mode observation , append '_nod' 794 if (obsMode1 == "Nod") { 795 //pksrec.srcName.append("_nod"); 796 pksrec.srcType = SrcType::NOD ; 797 } else if (obsMode1 == "OffOn") { 798 // for GBT position switch observations (OffOn or OnOff) 799 //if (obsMode2 == "PSWITCHON") pksrec.srcName.append("_ps"); 800 //if (obsMode2 == "PSWITCHOFF") pksrec.srcName.append("_psr"); 801 if (obsMode2 == "PSWITCHON") pksrec.srcType = SrcType::PSON ; 802 if (obsMode2 == "PSWITCHOFF") pksrec.srcType = SrcType::PSOFF ; 803 } else { 804 if (obsMode2 == "FSWITCH") { 805 // for GBT frequency switch mode 806 //if (sigState) pksrec.srcName.append("_fs"); 807 //if (refState) pksrec.srcName.append("_fsr"); 808 if (sigState) pksrec.srcType = SrcType::FSON ; 809 if (refState) pksrec.srcType = SrcType::FSOFF ; 810 } 811 } 812 } 813 } 814 else if (cALMA) { 815 // ALMA tag 816 // split the obsType string and append a proper label 817 string substr[1] ; 818 int numSubstr = split( pksrec.obsType, substr, 1, "," ); 819 String obsType = String( substr[0] ); 820 int epos = obsType.find_first_of('.'); 821 int nextpos = obsType.find_first_of('.',epos+1); 822 string obsMode1 = obsType.substr(0,epos); 823 string obsMode2 = obsType.substr(epos+1,nextpos-epos-1); 824 825 //cerr <<"obsMode2= "<<obsMode2<<endl; 826 // Current OBS_MODE format: 827 // 828 // ON: OBSERVE_TARGET.ON_SOURCE 829 // OFF: OBSERVE_TARGET.OFF_SOURCE 830 // 831 if (obsMode1 == "OBSERVE_TARGET") { 832 //if (obsMode2 == "ON_SOURCE") pksrec.srcName.append("_pson"); 833 //if (obsMode2 == "OFF_SOURCE") pksrec.srcName.append("_psoff"); 834 if (obsMode2 == "ON_SOURCE") pksrec.srcType = SrcType::PSON ; 835 if (obsMode2 == "OFF_SOURCE") pksrec.srcType = SrcType::PSOFF ; 836 } 837 } 838 } 839 } 840 } 841 // CAL state 842 // this should be apply just for GBT data? 843 Double Cal; 844 if (stateId==-1 || StateNRow==0) { 845 Cal = 0; 846 } else { 847 Cal = cCalCol(stateId); 848 } 849 if (cGBT) { 850 if (Cal > 0 && !pksrec.srcName.contains("_calon")) { 851 //pksrec.srcName.append("_calon"); 852 if ( pksrec.srcType == SrcType::NOD ) 853 pksrec.srcType = SrcType::NODCAL ; 854 else if ( pksrec.srcType == SrcType::PSON ) 855 pksrec.srcType = SrcType::PONCAL ; 856 else if ( pksrec.srcType == SrcType::PSOFF ) 857 pksrec.srcType = SrcType::POFFCAL ; 858 else if ( pksrec.srcType == SrcType::FSON ) 859 pksrec.srcType = SrcType::FONCAL ; 860 else if ( pksrec.srcType == SrcType::FSOFF ) 861 pksrec.srcType = SrcType::FOFFCAL ; 862 else 863 pksrec.srcName.append("_calon"); 864 } 865 } 558 866 559 867 pksrec.IFno = iIF + 1; 560 868 Int nChan = abs(cEndChan(iIF) - cStartChan(iIF)) + 1; 561 869 562 870 // Minimal handling on continuum data. 563 871 Vector<Double> chanFreq = cChanFreqCol(iIF); 872 pksrec.nchan = nChan; 564 873 if (nChan == 1) { 565 cout << "The input is continuum data. "<< endl;566 pksrec.freqInc = c hanFreq(0);874 //pksrec.freqInc = chanFreq(0); 875 pksrec.freqInc = cTotBWCol(iIF); 567 876 pksrec.refFreq = chanFreq(0); 568 pksrec.restFreq = 0.0f; 877 pksrec.restFreq.resize(1); 878 pksrec.restFreq[0] = 0.0f; 569 879 } else { 880 570 881 if (cStartChan(iIF) <= cEndChan(iIF)) { 571 882 pksrec.freqInc = chanFreq(1) - chanFreq(0); … … 575 886 576 887 pksrec.refFreq = chanFreq(cRefChan(iIF)-1); 577 pksrec.restFreq = cSrcRestFrqCol(srcId)(IPosition(1,0)); 578 } 579 pksrec.bandwidth = abs(pksrec.freqInc * nChan); 888 889 Bool HaveSrcRestFreq= cSrcRestFrqCol.isDefined(srcId); 890 if (HaveSrcRestFreq) { 891 //restFreq = cSrcRestFrqCol(srcId)(IPosition(1,0)); 892 //restFreq = cSrcRestFrqCol(srcId); 893 pksrec.restFreq = cSrcRestFrqCol(srcId); 894 } else { 895 pksrec.restFreq.resize(1); 896 pksrec.restFreq[0] = 0.0f; 897 } 898 } 899 //pksrec.bandwidth = abs(pksrec.freqInc * nChan); 900 pksrec.bandwidth = abs(cTotBWCol(0)); 580 901 581 902 pksrec.tcal.resize(cNPol(iIF)); 582 903 pksrec.tcal = 0.0f; 583 904 pksrec.tcalTime = ""; 584 pksrec.azimuth = 0.0f;585 pksrec.elevation = 0.0f;905 // pksrec.azimuth = 0.0f; 906 // pksrec.elevation = 0.0f; 586 907 pksrec.parAngle = 0.0f; 587 908 … … 591 912 592 913 // Find the appropriate entry in the WEATHER subtable. 593 Vector<Double> wTimes = cWeatherTimeCol.getColumn(); 594 Int weatherIdx; 595 for (weatherIdx = wTimes.nelements()-1; weatherIdx >= 0; weatherIdx--) { 596 if (cWeatherTimeCol(weatherIdx) <= time) { 597 break; 598 } 599 } 600 601 if (weatherIdx < 0) { 914 //Bool cHaveStateTab=Table::isReadable(cPKSMS.stateTableName()); 915 Bool cHaveWeatherTab = Table::isReadable(cPKSMS.weatherTableName()); 916 Int weatherIdx=-1; 917 if (cHaveWeatherTab) { 918 Vector<Double> wTimes = cWeatherTimeCol.getColumn(); 919 for (weatherIdx = wTimes.nelements()-1; weatherIdx >= 0; weatherIdx--) { 920 if (cWeatherTimeCol(weatherIdx) <= time) { 921 break; 922 } 923 } 924 } 925 926 if (weatherIdx < 0 || !cHaveWeatherTab) { 602 927 // No appropriate WEATHER entry. 603 928 pksrec.temperature = 0.0f; … … 616 941 pksrec.beamNo = ibeam + 1; 617 942 618 Matrix<Double> pointingDir = cPointingCol(fieldId); 619 pksrec.direction = pointingDir.column(0); 943 //pointing/azel 944 MVPosition mvpos(antennaCols.position()(cAntId[0])); 945 MPosition mp(mvpos); 946 Quantum<Double> qt(time,"s"); 947 MVEpoch mvt(qt); 948 MEpoch me(mvt); 949 MeasFrame frame(mp, me); 950 MDirection md; 620 951 pksrec.pCode = 0; 621 952 pksrec.rateAge = 0.0f; 622 uInt ncols = pointingDir.ncolumn();623 if (ncols == 1) {624 pksrec.scanRate = 0.0f;625 } else {626 pksrec.scanRate(0) = pointingDir.column(1)(0);627 pksrec.scanRate(1) = pointingDir.column(1)(1);628 }629 953 pksrec.paRate = 0.0f; 954 if (cGetPointing) { 955 //cerr << "get pointing data ...." << endl; 956 ROScalarColumn<Int> pAntIdCol ; 957 ROScalarColumn<Double> psTimeCol ; 958 Table ptTable = cPKSMS.pointing() ; 959 MSPointing selPtTab( ptTable( ptTable.col("ANTENNA_ID") == cAntId[0] ) ) ; 960 pAntIdCol.attach( selPtTab, "ANTENNA_ID" ) ; 961 Vector<Int> antIds = pAntIdCol.getColumn() ; 962 psTimeCol.attach( selPtTab, "TIME" ) ; 963 Vector<Double> pTimes = psTimeCol.getColumn(); 964 Bool doInterp = False ; 965 Int PtIdx=-1; 966 for (PtIdx = pTimes.nelements()-1; PtIdx >= 0; PtIdx--) { 967 if ( pTimes[PtIdx] == time ) { 968 break ; 969 } 970 else if ( pTimes[PtIdx] < time ) { 971 if ( PtIdx != pTimes.nelements()-1 ) { 972 doInterp = True ; 973 } 974 break ; 975 } 976 } 977 if ( PtIdx == -1 ) { 978 PtIdx = 0 ; 979 } 980 //cerr << "got index=" << PtIdx << endl; 981 Matrix<Double> pointingDir = cPointingCol(PtIdx); 982 ROMSPointingColumns PtCols( selPtTab ) ; 983 Vector<Double> pointingDirVec ; 984 if ( doInterp ) { 985 Double dt1 = time - pTimes[PtIdx] ; 986 Double dt2 = pTimes[PtIdx+1] - time ; 987 Vector<Double> dirVec1 = pointingDir.column(0) ; 988 Matrix<Double> pointingDir2 = cPointingCol(PtIdx+1) ; 989 Vector<Double> dirVec2 = pointingDir2.column(0) ; 990 pointingDirVec = (dt1*dirVec2+dt2*dirVec1)/(dt1+dt2) ; 991 Vector<MDirection> vmd1(1) ; 992 Vector<MDirection> vmd2(1) ; 993 PtCols.directionMeasCol().get(PtIdx,vmd1) ; 994 Vector<Double> angle1 = vmd1(0).getAngle().getValue("rad") ; 995 PtCols.directionMeasCol().get(PtIdx+1,vmd2) ; 996 Vector<Double> angle2 = vmd2(0).getAngle().getValue("rad") ; 997 Vector<Double> angle = (dt1*angle2+dt2*angle1)/(dt1+dt2) ; 998 Quantum< Vector<Double> > qangle( angle, "rad" ) ; 999 String typeStr = vmd1(0).getRefString() ; 1000 //cerr << "vmd1.getRefString()=" << typeStr << endl ; 1001 MDirection::Types mdType ; 1002 MDirection::getType( mdType, typeStr ) ; 1003 //cerr << "mdType=" << mdType << endl ; 1004 md = MDirection( qangle, mdType ) ; 1005 //cerr << "md=" << md.getAngle().getValue("rad") << endl ; 1006 } 1007 else { 1008 pointingDirVec = pointingDir.column(0) ; 1009 Vector<MDirection> vmd(1); 1010 PtCols.directionMeasCol().get(PtIdx,vmd); 1011 md = vmd[0]; 1012 } 1013 // put J2000 coordinates in "direction" 1014 if (cDirRef =="J2000") { 1015 pksrec.direction = pointingDirVec ; 1016 } 1017 else { 1018 pksrec.direction = 1019 MDirection::Convert(md, MDirection::Ref(MDirection::J2000, 1020 frame) 1021 )().getAngle("rad").getValue(); 1022 1023 } 1024 uInt ncols = pointingDir.ncolumn(); 1025 pksrec.scanRate.resize(2); 1026 if (ncols == 1) { 1027 pksrec.scanRate = 0.0f; 1028 } else { 1029 pksrec.scanRate(0) = pointingDir.column(1)(0); 1030 pksrec.scanRate(1) = pointingDir.column(1)(1); 1031 } 1032 } 1033 else { 1034 // Get direction from FIELD table 1035 // here, assume direction to be the field direction not pointing 1036 Matrix<Double> delayDir = cFieldDelayDirCol(fieldId); 1037 pksrec.direction = delayDir.column(0); 1038 uInt ncols = delayDir.ncolumn(); 1039 pksrec.scanRate.resize(2); 1040 if (ncols == 1) { 1041 pksrec.scanRate = 0.0f; 1042 } else { 1043 pksrec.scanRate(0) = delayDir.column(1)(0); 1044 pksrec.scanRate(1) = delayDir.column(1)(1); 1045 } 1046 } 1047 // caluculate azimuth and elevation 1048 // first, get the reference frame 1049 /** 1050 MVPosition mvpos(antennaCols.position()(0)); 1051 MPosition mp(mvpos); 1052 Quantum<Double> qt(time,"s"); 1053 MVEpoch mvt(qt); 1054 MEpoch me(mvt); 1055 MeasFrame frame(mp, me); 1056 **/ 1057 // 1058 ROMSFieldColumns fldCols(cPKSMS.field()); 1059 Vector<MDirection> vmd(1); 1060 //MDirection md; 1061 fldCols.delayDirMeasCol().get(fieldId,vmd); 1062 md = vmd[0]; 1063 //Vector<Double> dircheck = md.getAngle("rad").getValue(); 1064 //cerr<<"dircheck="<<dircheck<<endl; 1065 1066 Vector<Double> azel = 1067 MDirection::Convert(md, MDirection::Ref(MDirection::AZEL, 1068 frame) 1069 )().getAngle("rad").getValue(); 1070 //cerr<<"azel="<<azel<<endl; 1071 pksrec.azimuth = azel[0]; 1072 pksrec.elevation = azel[1]; 630 1073 631 1074 // Get Tsys assuming that entries in the SYSCAL table match the main table. … … 646 1089 cSigmaCol.get(cIdx, pksrec.sigma, True); 647 1090 1091 //get Tcal if available 1092 if (cHaveTcal) { 1093 Int nTcalColRow = cTcalCol.nrow(); 1094 uInt nBeam = cBeams.nelements(); 1095 uInt nIF = cIFs.nelements(); 1096 uInt nrws = nBeam * nIF; 1097 if (nTcalColRow > 0) { 1098 // find tcal match with the data with the data time stamp 1099 Double mjds = pksrec.mjd*(24*3600); 1100 Double dtcalTime; 1101 if ( pksrec.mjd > lastmjd || cIdx==0 ) { 1102 //Table tmptab = cSysCalTab(near(cSysCalTab.col("TIME"),mjds)); 1103 tmptab = cSysCalTab(near(cSysCalTab.col("TIME"),mjds), nrws); 1104 //DEBUG 1105 //if (cIdx == 0) { 1106 // cerr<<"inital table retrieved"<<endl; 1107 //} 1108 1109 } 1110 1111 if (nBeam == 1) { 1112 tmptab2 = tmptab( tmptab.col("SPECTRAL_WINDOW_ID") == iIF, 1); 1113 } else { 1114 tmptab2 = tmptab( tmptab.col("SPECTRAL_WINDOW_ID") == iIF && 1115 tmptab.col("FEED_ID") == ibeam , 1); 1116 } 1117 //cerr<<"first subtab rows="<<tmptab.nrow()<<endl; 1118 int syscalrow = tmptab2.nrow(); 1119 ROArrayColumn<Float> tcalCol(tmptab2, "TCAL"); 1120 ROScalarColumn<Double> tcalTimeCol(tmptab2, "TIME"); 1121 if (syscalrow==0) { 1122 os << LogIO::NORMAL 1123 <<"Cannot find any matching Tcal at/near the data timestamp." 1124 << " Set Tcal=0.0" << LogIO::POST ; 1125 } else { 1126 tcalCol.get(0, pksrec.tcal); 1127 tcalTimeCol.get(0,dtcalTime); 1128 pksrec.tcalTime = MVTime(dtcalTime/(24*3600)).string(MVTime::YMD); 1129 //DEBUG 1130 //cerr<<"cIdx:"<<cIdx<<" tcal="<<tcal<<" tcalTime="<<tcalTime<<endl; 1131 tmptab.markForDelete(); 1132 tmptab2.markForDelete(); 1133 } 1134 } 1135 lastmjd = pksrec.mjd; 1136 } 1137 648 1138 // Calibration factors (if available). 649 1139 pksrec.calFctr.resize(cNPol(iIF)); … … 672 1162 Matrix<Float> tmpData; 673 1163 Matrix<Bool> tmpFlag; 674 cFloatDataCol.getSlice(cIdx, cDataSel(iIF), tmpData, True); 1164 if (cHaveDataCol) { 1165 Matrix<Complex> tmpCmplxData; 1166 Matrix<Float> tmpReData; 1167 Matrix<Float> tmpImData; 1168 //cerr<<"reading spectra..."<<endl; 1169 //# TODO - should have a flag to user to select DATA or CORRECTED_DATA 1170 //# currently just automatically determined, --- read CORRECTED one 1171 //# if the column exist. 1172 if (cHaveCorrectedDataCol) { 1173 cCorrectedDataCol.getSlice(cIdx, cDataSel(iIF), tmpCmplxData, True); 1174 } else { 1175 cDataCol.getSlice(cIdx, cDataSel(iIF), tmpCmplxData, True); 1176 } 1177 tmpReData = real(tmpCmplxData); 1178 tmpImData = imag(tmpCmplxData); 1179 tmpData = sqrt(tmpReData*tmpReData + tmpImData*tmpImData); 1180 } else { 1181 cFloatDataCol.getSlice(cIdx, cDataSel(iIF), tmpData, True); 1182 } 675 1183 cFlagCol.getSlice(cIdx, cDataSel(iIF), tmpFlag, True); 676 1184 … … 698 1206 } 699 1207 } 1208 1209 // Row-based flagging info. (True:1, False:0) 1210 pksrec.flagrow = (cFlagRowCol(cIdx) ? 1 : 0); 700 1211 } 701 1212 702 1213 // Get cross-polarization data. 703 1214 if (cGetXPol) { 1215 //cerr<<"cGetXPol="<<cGetXPol<<endl; 1216 //cerr<<"cHaveXCalFctr="<<cHaveXCalFctr<<endl; 1217 704 1218 if (cHaveXCalFctr) { 705 1219 cXCalFctrCol.get(cIdx, pksrec.xCalFctr); … … 708 1222 } 709 1223 710 cDataCol.get(cIdx, pksrec.xPol, True); 711 712 if (cEndChan(iIF) < cStartChan(iIF)) { 713 Complex ctmp; 1224 if(!cALMA) { 1225 cDataCol.get(cIdx, pksrec.xPol, True); 1226 1227 if (cEndChan(iIF) < cStartChan(iIF)) { 1228 Complex ctmp; 1229 Int jchan = nChan - 1; 1230 for (Int ichan = 0; ichan < nChan/2; ichan++, jchan--) { 1231 ctmp = pksrec.xPol(ichan); 1232 pksrec.xPol(ichan) = pksrec.xPol(jchan); 1233 pksrec.xPol(jchan) = ctmp; 1234 } 1235 } 1236 } 1237 } 1238 /** 1239 cerr<<"scanNo="<<scanNo<<endl; 1240 cerr<<"cycleNo="<<cycleNo<<endl; 1241 cerr<<"mjd="<<mjd<<endl; 1242 cerr<<"interval="<<interval<<endl; 1243 cerr<<"fieldName="<<fieldName<<endl; 1244 cerr<<"srcNmae="<<srcName<<endl; 1245 cerr<<"srcDir="<<srcDir<<endl; 1246 cerr<<"srcPM="<<srcPM<<endl; 1247 cerr<<"srcVel="<<srcVel<<endl; 1248 cerr<<"obsMode="<<obsMode<<endl; 1249 cerr<<"IFno="<<IFno<<endl; 1250 cerr<<"refFreq="<<refFreq<<endl; 1251 cerr<<"tcal="<<tcal<<endl; 1252 cerr<<"direction="<<direction<<endl; 1253 cerr<<"scanRate="<<scanRate<<endl; 1254 cerr<<"tsys="<<tsys<<endl; 1255 cerr<<"sigma="<<sigma<<endl; 1256 cerr<<"calFctr="<<calFctr<<endl; 1257 cerr<<"baseLin="<<baseLin<<endl; 1258 cerr<<"baseSub="<<baseSub<<endl; 1259 cerr<<"spectra="<<spectra.shape()<<endl; 1260 cerr<<"flagged="<<flagged.shape()<<endl; 1261 cerr<<"xCalFctr="<<xCalFctr<<endl; 1262 cerr<<"xPol="<<xPol<<endl; 1263 **/ 1264 cIdx++; 1265 1266 return 0; 1267 } 1268 1269 //--------------------------------------------------------- PKSMS2reader::read 1270 1271 // Read the next data record, just the basics. 1272 1273 Int PKSMS2reader::read( 1274 Int &IFno, 1275 Vector<Float> &tsys, 1276 Vector<Float> &calFctr, 1277 Matrix<Float> &baseLin, 1278 Matrix<Float> &baseSub, 1279 Matrix<Float> &spectra, 1280 Matrix<uChar> &flagged) 1281 { 1282 if (!cMSopen) { 1283 return 1; 1284 } 1285 1286 // Check for EOF. 1287 if (cIdx >= cNRow) { 1288 return -1; 1289 } 1290 1291 // Find the next selected beam and IF. 1292 Int ibeam; 1293 Int iIF; 1294 Int iDataDesc; 1295 while (True) { 1296 ibeam = cBeamNoCol(cIdx); 1297 //iIF = cDataDescIdCol(cIdx); 1298 iDataDesc = cDataDescIdCol(cIdx); 1299 iIF = cSpWinIdCol(iDataDesc); 1300 if (cBeams(ibeam) && cIFs(iIF)) { 1301 break; 1302 } 1303 1304 // Check for EOF. 1305 if (++cIdx >= cNRow) { 1306 return -1; 1307 } 1308 } 1309 1310 IFno = iIF + 1; 1311 // Get Tsys assuming that entries in the SYSCAL table match the main table. 1312 cTsysCol.get(cIdx, tsys, True); 1313 1314 // Calibration factors (if available). 1315 if (cHaveCalFctr) { 1316 cCalFctrCol.get(cIdx, calFctr, True); 1317 } else { 1318 calFctr.resize(cNPol(iIF)); 1319 calFctr = 0.0f; 1320 } 1321 1322 // Baseline parameters (if available). 1323 if (cHaveBaseLin) { 1324 baseLin.resize(2,cNPol(iIF)); 1325 cBaseLinCol.get(cIdx, baseLin); 1326 1327 baseSub.resize(24,cNPol(iIF)); 1328 cBaseSubCol.get(cIdx, baseSub); 1329 1330 } else { 1331 baseLin.resize(0,0); 1332 baseSub.resize(0,0); 1333 } 1334 1335 if (cGetSpectra) { 1336 // Get spectral data. 1337 Matrix<Float> tmpData; 1338 Matrix<Bool> tmpFlag; 1339 if (cHaveDataCol) { 1340 Matrix<Complex> tmpCmplxData; 1341 cDataCol.getSlice(cIdx, cDataSel(iIF), tmpCmplxData, True); 1342 tmpData = real(tmpCmplxData); 1343 } else { 1344 cFloatDataCol.getSlice(cIdx, cDataSel(iIF), tmpData, True); 1345 } 1346 cFlagCol.getSlice(cIdx, cDataSel(iIF), tmpFlag, True); 1347 1348 // Transpose spectra. 1349 Int nChan = tmpData.ncolumn(); 1350 Int nPol = tmpData.nrow(); 1351 spectra.resize(nChan, nPol); 1352 flagged.resize(nChan, nPol); 1353 if (cEndChan(iIF) >= cStartChan(iIF)) { 1354 // Simple transposition. 1355 for (Int ipol = 0; ipol < nPol; ipol++) { 1356 for (Int ichan = 0; ichan < nChan; ichan++) { 1357 spectra(ichan,ipol) = tmpData(ipol,ichan); 1358 flagged(ichan,ipol) = tmpFlag(ipol,ichan); 1359 } 1360 } 1361 1362 } else { 1363 // Transpose with inversion. 714 1364 Int jchan = nChan - 1; 715 for (Int ichan = 0; ichan < nChan/2; ichan++, jchan--) { 716 ctmp = pksrec.xPol(ichan); 717 pksrec.xPol(ichan) = pksrec.xPol(jchan); 718 pksrec.xPol(jchan) = ctmp; 1365 for (Int ipol = 0; ipol < nPol; ipol++) { 1366 for (Int ichan = 0; ichan < nChan; ichan++, jchan--) { 1367 spectra(ichan,ipol) = tmpData(ipol,jchan); 1368 flagged(ichan,ipol) = tmpFlag(ipol,jchan); 1369 } 719 1370 } 720 1371 } … … 735 1386 cMSopen = False; 736 1387 } 1388 1389 //-------------------------------------------------------- PKSMS2reader::splitAntenanSelectionString 1390 1391 // split antenna selection string 1392 // delimiter is ',' 1393 1394 Vector<String> PKSMS2reader::splitAntennaSelectionString( const String s ) 1395 { 1396 Char delim = ',' ; 1397 Int n = s.freq( delim ) + 1 ; 1398 Vector<String> antlist ; 1399 string sl[n] ; 1400 Int numSubstr = split( s, sl, n, "," ); 1401 antlist.resize( numSubstr ) ; 1402 for ( Int i = 0 ; i < numSubstr ; i++ ) { 1403 antlist[i] = String( sl[i] ) ; 1404 antlist[i].trim() ; 1405 } 1406 //cerr << "antlist = " << antlist << endl ; 1407 return antlist ; 1408 } 1409 1410 //-------------------------------------------------------- PKSMS2reader::setupAntennaList 1411 1412 // Fill cAntenna and cAntId 1413 1414 void PKSMS2reader::setupAntennaList( const String s ) 1415 { 1416 LogIO os( LogOrigin( "PKSMS2reader", "setupAntennaList()", WHERE ) ) ; 1417 //cerr << "antenna specification: " << s << endl ; 1418 ROMSAntennaColumns antennaCols(cPKSMS.antenna()); 1419 ROScalarColumn<String> antNames = antennaCols.name(); 1420 Int nrow = antNames.nrow() ; 1421 Vector<String> antlist = splitAntennaSelectionString( s ) ; 1422 Int len = antlist.size() ; 1423 Vector<Int> AntId( len ) ; 1424 Regex re( "[0-9]+" ) ; 1425 for ( Int i = 0 ; i < len ; i++ ) { 1426 if ( antlist[i].matches( re ) ) { 1427 AntId[i] = atoi( antlist[i].c_str() ) ; 1428 if ( AntId[i] >= nrow ) { 1429 os << LogIO::SEVERE << "Antenna index out of range: " << AntId[i] << LogIO::EXCEPTION ; 1430 } 1431 } 1432 else { 1433 AntId[i] = -1 ; 1434 for ( uInt j = 0 ; j < antNames.nrow() ; j++ ) { 1435 if ( antlist[i] == antNames(j) ) { 1436 AntId[i] = j ; 1437 break ; 1438 } 1439 } 1440 if ( AntId[i] == -1 ) { 1441 os << LogIO::SEVERE << "Specified antenna name not found: " << antlist[i] << LogIO::EXCEPTION ; 1442 } 1443 } 1444 } 1445 //cerr << "AntId = " << AntId << endl ; 1446 vector<Int> uniqId ; 1447 uniqId.push_back( AntId(0) ) ; 1448 for ( uInt i = 1 ; i < AntId.size() ; i++ ) { 1449 if ( count(uniqId.begin(),uniqId.end(),AntId[i]) == 0 ) { 1450 uniqId.push_back( AntId[i] ) ; 1451 } 1452 } 1453 Vector<Int> newAntId( uniqId ) ; 1454 cAntId.assign( newAntId ) ; 1455 //cerr << "cAntId = " << cAntId << endl ; 1456 } -
branches/mergetest/external/atnf/PKSIO/PKSMS2reader.h
r1720 r1779 68 68 virtual Int open( 69 69 const String msName, 70 const String antenna, 70 71 Vector<Bool> &beams, 71 72 Vector<Bool> &IFs, … … 85 86 String &bunit, 86 87 Float &equinox, 88 //String &freqRef, 87 89 String &dopplerFrame, 88 90 Double &mjd, … … 105 107 const Bool getSpectra = True, 106 108 const Bool getXPol = False, 109 const Bool getFeedPos = False, 110 const Bool getPointing = False, 107 111 const Int coordSys = 0); 112 108 113 109 114 // Find the range of the data selected in time and position. … … 115 120 116 121 // Read the next data record. 122 /** 123 virtual Int read( 124 Int &scanNo, 125 Int &cycleNo, 126 Double &mjd, 127 Double &interval, 128 String &fieldName, 129 String &srcName, 130 Vector<Double> &srcDir, 131 Vector<Double> &srcPM, 132 Double &srcVel, 133 String &obsMode, 134 Int &IFno, 135 Double &refFreq, 136 Double &bandwidth, 137 Double &freqInc, 138 Vector<Double> &restFreq, 139 Vector<Float> &tcal, 140 String &tcalTime, 141 Float &azimuth, 142 Float &elevation, 143 Float &parAngle, 144 Float &focusAxi, 145 Float &focusTan, 146 Float &focusRot, 147 Float &temperature, 148 Float &pressure, 149 Float &humidity, 150 Float &windSpeed, 151 Float &windAz, 152 Int &refBeam, 153 Int &beamNo, 154 Vector<Double> &direction, 155 Vector<Double> &scanRate, 156 Vector<Float> &tsys, 157 Vector<Float> &sigma, 158 Vector<Float> &calFctr, 159 Matrix<Float> &baseLin, 160 Matrix<Float> &baseSub, 161 Matrix<Float> &spectra, 162 Matrix<uChar> &flagged, 163 Complex &xCalFctr, 164 Vector<Complex> &xPol); 165 **/ 117 166 virtual Int read(PKSrecord &pksrec); 167 168 169 // Read the next data record, just the basics. 170 virtual Int read( 171 Int &IFno, 172 Vector<Float> &tsys, 173 Vector<Float> &calFctr, 174 Matrix<Float> &baseLin, 175 Matrix<Float> &baseSub, 176 Matrix<Float> &spectra, 177 Matrix<uChar> &flagged); 118 178 119 179 // Close the MS. … … 121 181 122 182 private: 183 Vector<String> splitAntennaSelectionString( const String s ); 184 void setupAntennaList( const String s ) ; 185 123 186 Bool cHaveBaseLin, cHaveCalFctr, cHaveSrcVel, cHaveTsys, cHaveXCalFctr, 124 cMSopen ;187 cMSopen, cHaveTcal, cHaveDataCol, cALMA, cHaveSysCal, cHaveCorrectedDataCol; 125 188 Int cCycleNo, cIdx, cNRow, cScanNo; 126 Double cTime ;189 Double cTime, lastmjd; 127 190 Vector<Int> cEndChan, cRefChan, cStartChan; 128 191 Vector<Bool> cBeams, cIFs; 129 192 Vector<Slicer> cDataSel; 193 String cDirRef, cTelName; 130 194 MeasurementSet cPKSMS; 195 Table cSysCalTab, tmptab, tmptab2; 196 197 //Vector<String> cAntenna; 198 Vector<Int> cAntId; 131 199 132 200 ROScalarColumn<Int> cScanNoCol; … … 135 203 ROScalarColumn<Int> cFieldIdCol; 136 204 ROScalarColumn<String> cFieldNameCol; 205 ROArrayColumn<Double> cFieldDelayDirCol; 137 206 ROScalarColumn<Int> cSrcIdCol; 207 ROScalarColumn<Int> cSrcId2Col; 138 208 ROScalarColumn<String> cSrcNameCol; 139 209 ROArrayColumn<Double> cSrcDirCol; … … 141 211 ROArrayColumn<Double> cSrcVelCol; 142 212 ROScalarColumn<Int> cStateIdCol; 213 ROScalarColumn<Double> cCalCol; 143 214 ROScalarColumn<String> cObsModeCol; 144 215 ROArrayColumn<Double> cSrcRestFrqCol; 145 216 ROScalarColumn<Int> cDataDescIdCol; 217 ROScalarColumn<Int> cSpWinIdCol; 146 218 ROArrayColumn<Double> cChanFreqCol; 219 ROScalarColumn<Double> cTotBWCol; 147 220 ROScalarColumn<Double> cWeatherTimeCol; 148 221 ROScalarColumn<Float> cTemperatureCol; 149 222 ROScalarColumn<Float> cPressureCol; 150 223 ROScalarColumn<Float> cHumidityCol; 224 ROArrayColumn<Float> cTcalCol; 151 225 ROScalarColumn<Int> cBeamNoCol; 152 226 ROArrayColumn<Double> cPointingCol; 227 ROScalarColumn<Double> cPointingTimeCol; 153 228 ROArrayColumn<Float> cTsysCol; 154 229 ROArrayColumn<Float> cSigmaCol; … … 158 233 ROArrayColumn<Float> cFloatDataCol; 159 234 ROArrayColumn<Bool> cFlagCol; 235 ROScalarColumn<Bool> cFlagRowCol; 160 236 ROScalarColumn<Complex> cXCalFctrCol; 161 237 ROArrayColumn<Complex> cDataCol; 238 ROArrayColumn<Complex> cCorrectedDataCol; 162 239 ROScalarColumn<Int> cNumReceptorCol; 240 ROScalarColumn<Bool> cSigStateCol; 241 ROScalarColumn<Bool> cRefStateCol; 242 163 243 }; 164 244 -
branches/mergetest/external/atnf/PKSIO/PKSMS2writer.cc
r1720 r1779 42 42 #include <casa/BasicSL/Constants.h> 43 43 #include <casa/Quanta/QC.h> 44 #include <casa/Logging/LogIO.h> 44 45 #include <measures/Measures/Stokes.h> 45 46 #include <tables/Tables/ArrColDesc.h> … … 52 53 #include <tables/Tables/TiledShapeStMan.h> 53 54 55 // Class name 56 const string className = "PKSMS2writer" ; 57 54 58 //------------------------------------------------- PKSMS2writer::PKSMS2writer 55 59 … … 59 63 { 60 64 cPKSMS = 0x0; 61 62 // By default, messages are written to stderr.63 initMsg();64 65 } 65 66 … … 92 93 const Bool haveBase) 93 94 { 95 const string methodName = "create()" ; 96 LogIO os( LogOrigin( className, methodName, WHERE ) ) ; 97 94 98 if (cPKSMS) { 95 logMsg("ERROR: Output MS already open, close it first.");99 os << LogIO::SEVERE << "Output MS already open, close it first." << LogIO::POST ; 96 100 return 1; 97 101 } 98 99 // Clear the message stack.100 clearMsg();101 102 102 103 // Open a MS table. … … 108 109 109 110 Int maxNPol = max(cNPol); 110 111 111 cGBT = cAPEX = cSMT = cALMA = cATF = False; 112 113 String telName = antName; 114 // check if it is GBT data 115 if (antName.contains("GBT")) { 116 cGBT = True; 117 } 118 else if (antName.contains("APEX")) { 119 cAPEX = True; 120 } 121 else if (antName.contains("HHT") || antName.contains("SMT")) { 122 cSMT = True; 123 } 124 else if (antName.contains("ALMA")) { 125 cALMA = True; 126 } 127 else if (antName.contains("ATF")) { 128 cATF = True; 129 telName="ATF"; 130 } 131 112 132 // Add the non-standard CALFCTR column. 113 133 pksDesc.addColumn(ArrayColumnDesc<Float>("CALFCTR", "Calibration factors", … … 116 136 // Add the optional FLOAT_DATA column. 117 137 MS::addColumnToDesc(pksDesc, MS::FLOAT_DATA, 2); 138 //pksDesc.rwColumnDesc(MS::columnName(MS::FLOAT_DATA)).rwKeywordSet(). 139 // define("UNIT", String("Jy")); 118 140 pksDesc.rwColumnDesc(MS::columnName(MS::FLOAT_DATA)).rwKeywordSet(). 119 141 define("UNIT", bunit); … … 136 158 137 159 MS::addColumnToDesc(pksDesc, MS::DATA, 2); 160 //pksDesc.rwColumnDesc(MS::columnName(MS::DATA)).rwKeywordSet(). 161 // define("UNIT", "Jy"); 138 162 pksDesc.rwColumnDesc(MS::columnName(MS::DATA)).rwKeywordSet(). 139 163 define("UNIT", bunit); … … 152 176 newtab.bindAll(incrStMan, True); 153 177 154 // Use TiledShapeStMan for the FLOAT_DATA hypercube with tile size 1 6 kiB.155 TiledShapeStMan tiledStMan("TiledData", IPosition(3,1,128, 32));178 // Use TiledShapeStMan for the FLOAT_DATA hypercube with tile size 1 MB. 179 TiledShapeStMan tiledStMan("TiledData", IPosition(3,1,128,2048)); 156 180 newtab.bindColumn(MS::columnName(MS::FLOAT_DATA), tiledStMan); 157 181 … … 367 391 } else if (dopplerFrame == "SOURCE") { 368 392 MFrequency::getType(cDopplerFrame, "REST"); 393 } else if (dopplerFrame == "LSRK") { 394 MFrequency::getType(cDopplerFrame, "LSRK"); 369 395 } 370 396 … … 374 400 addDopplerEntry(); 375 401 addFeedEntry(); 376 addObservationEntry(observer, project); 402 //addObservationEntry(observer, project); 403 addObservationEntry(observer, project, telName); 377 404 addProcessorEntry(); 378 405 … … 384 411 // Write the next data record. 385 412 413 /** 414 Int PKSMS2writer::write( 415 const Int scanNo, 416 const Int cycleNo, 417 const Double mjd, 418 const Double interval, 419 const String fieldName, 420 const String srcName, 421 const Vector<Double> srcDir, 422 const Vector<Double> srcPM, 423 const Double srcVel, 424 const String obsMode, 425 const Int IFno, 426 const Double refFreq, 427 const Double bandwidth, 428 const Double freqInc, 429 //const Double restFreq, 430 const Vector<Double> restFreq, 431 const Vector<Float> tcal, 432 const String tcalTime, 433 const Float azimuth, 434 const Float elevation, 435 const Float parAngle, 436 const Float focusAxi, 437 const Float focusTan, 438 const Float focusRot, 439 const Float temperature, 440 const Float pressure, 441 const Float humidity, 442 const Float windSpeed, 443 const Float windAz, 444 const Int refBeam, 445 const Int beamNo, 446 const Vector<Double> direction, 447 const Vector<Double> scanRate, 448 const Vector<Float> tsys, 449 const Vector<Float> sigma, 450 const Vector<Float> calFctr, 451 const Matrix<Float> baseLin, 452 const Matrix<Float> baseSub, 453 const Matrix<Float> &spectra, 454 const Matrix<uChar> &flagged, 455 const uInt flagrow, 456 const Complex xCalFctr, 457 const Vector<Complex> &xPol) 458 **/ 386 459 Int PKSMS2writer::write( 387 460 const PKSrecord &pksrec) … … 415 488 pksrec.restFreq, pksrec.srcVel); 416 489 417 // Find or add the obs Type to the STATE subtable.490 // Find or add the obsMode to the STATE subtable. 418 491 Int stateId = addStateEntry(pksrec.obsType); 419 492 420 493 // FIELD subtable. 421 Vector<Double> scanRate(2);422 scanRate(0) = pksrec.scanRate(0);423 scanRate(1) = pksrec.scanRate(1);494 //Vector<Double> scanRate(2); 495 //scanRate(0) = pksrec.scanRate(0); 496 //scanRate(1) = pksrec.scanRate(1); 424 497 Int fieldId = addFieldEntry(pksrec.fieldName, time, pksrec.direction, 425 scanRate, srcId);498 pksrec.scanRate, srcId); 426 499 427 500 // POINTING subtable. 428 501 addPointingEntry(time, pksrec.interval, pksrec.fieldName, pksrec.direction, 429 scanRate);502 pksrec.scanRate); 430 503 431 504 // SYSCAL subtable. 432 505 addSysCalEntry(pksrec.beamNo, iIF, time, pksrec.interval, pksrec.tcal, 433 pksrec.tsys );506 pksrec.tsys, nPol); 434 507 435 508 // Handle weather information. … … 508 581 cMSCols->sigma().put(irow, pksrec.sigma); 509 582 510 Vector<Float> weight(1, 1.0f); 583 //Vector<Float> weight(1, 1.0f); 584 Vector<Float> weight(nPol, 1.0f); 511 585 cMSCols->weight().put(irow, weight); 586 //imaging weight 587 //Vector<Float> imagingWeight(nChan); 588 //cMSCols->imagingWeight().put(irow, imagingWeight); 512 589 513 590 // Flag information. 514 591 Cube<Bool> flags(nPol, nChan, 1, False); 515 cMSCols->flag().put(irow, flags.xyPlane(0));592 //cMSCols->flag().put(irow, flags.xyPlane(0)); 516 593 cMSCols->flagCategory().put(irow, flags); 517 cMSCols->flagRow().put(irow, False); 594 // Row-based flagging info. (True:>0, False:0) 595 cMSCols->flagRow().put(irow, (pksrec.flagrow > 0)); 596 518 597 519 598 return 0; … … 571 650 cSysCal = MSSysCal(); 572 651 cWeather = MSWeather(); 573 574 652 // Release the main table. 575 delete cPKSMS; 576 cPKSMS =0x0;653 delete cPKSMS; 654 cPKSMS=0x0; 577 655 } 578 656 … … 589 667 Int n = cAntenna.nrow() - 1; 590 668 669 // do specific things for GBT 591 670 // Data. 671 // plus some more telescopes 592 672 cAntennaCols->name().put(n, antName); 593 cAntennaCols->station().put(n, "ATNF_PARKES"); 673 //cAntennaCols->station().put(n, "ATNF_PARKES"); 674 if (cGBT) { 675 cAntennaCols->station().put(n, "GREENBANK"); 676 cAntennaCols->dishDiameter().put(n, 110.0); 677 } 678 else if (cAPEX) { 679 cAntennaCols->station().put(n, "CHAJNANTOR"); 680 cAntennaCols->dishDiameter().put(n, 12.0); 681 } 682 else if (cALMA) { 683 // this needs to be changed in future... 684 cAntennaCols->station().put(n, "CHAJNANTOR"); 685 cAntennaCols->dishDiameter().put(n, 12.0); 686 } 687 else if (cATF) { 688 //pad name for the antenna is static... 689 String stname="unknown"; 690 if (antName.contains("DV")) { 691 stname="PAD001"; 692 } 693 if (antName.contains("DA")) { 694 stname="PAD002"; 695 } 696 cAntennaCols->station().put(n, stname); 697 cAntennaCols->dishDiameter().put(n, 12.0); 698 } 699 else if (cSMT) { 700 cAntennaCols->station().put(n, "MT_GRAHAM"); 701 cAntennaCols->dishDiameter().put(n, 10.0); 702 } 703 else { 704 cAntennaCols->station().put(n, "ATNF_PARKES"); 705 cAntennaCols->dishDiameter().put(n, 64.0); 706 } 594 707 cAntennaCols->type().put(n, "GROUND-BASED"); 595 708 cAntennaCols->mount().put(n, "ALT-AZ"); … … 597 710 Vector<Double> antOffset(3, 0.0); 598 711 cAntennaCols->offset().put(n, antOffset); 599 cAntennaCols->dishDiameter().put(n, 64.0); 600 712 //cAntennaCols->dishDiameter().put(n, 64.0); 713 //if (cGBT) { 714 // cAntennaCols->dishDiameter().put(n, 110.0); 715 //} 716 //else { 717 // cAntennaCols->dishDiameter().put(n, 64.0); 718 //} 601 719 // Flags. 602 720 cAntennaCols->flagRow().put(n, False); … … 711 829 const Int srcId) 712 830 { 831 832 ROScalarColumn<String> fldn(cField, "NAME"); 833 ROScalarColumn<Int> sourceid(cField, "SOURCE_ID"); 834 Int n; 835 Int nFld = cField.nrow(); 836 for (n = 0; n < nFld; n++) { 837 if (fldn(n) == fieldName && sourceid(n) == srcId) { 838 break; 839 } 840 } 841 713 842 // Extend the FIELD subtable. 714 cField.addRow(); 715 Int n = cField.nrow() - 1; 716 717 // Data. 718 cFieldCols->name().put(n, fieldName); 719 cFieldCols->code().put(n, "DRIFT"); 720 cFieldCols->time().put(n, time); 721 722 Matrix<Double> track(2, 2); 723 track.column(0) = direction; 724 track.column(1) = scanRate; 725 cFieldCols->numPoly().put(n, 1); 726 cFieldCols->delayDir().put(n, track); 727 cFieldCols->phaseDir().put(n, track); 728 cFieldCols->referenceDir().put(n, track); 729 cFieldCols->sourceId().put(n, srcId); 730 731 // Flags. 732 cFieldCols->flagRow().put(n, False); 843 if (n == nFld) { 844 cField.addRow(); 845 //Int n = cField.nrow() - 1; 846 847 // Data. 848 cFieldCols->name().put(n, fieldName); 849 if (cGBT) { 850 cFieldCols->code().put(n, " "); 851 } 852 else { 853 cFieldCols->code().put(n, "DRIFT"); 854 } 855 cFieldCols->time().put(n, time); 856 857 //Matrix<Double> track(2, 2); 858 Matrix<Double> track(2, 1); 859 track.column(0) = direction; 860 //track.column(1) = scanRate; 861 cFieldCols->numPoly().put(n, 1); 862 cFieldCols->delayDir().put(n, track); 863 cFieldCols->phaseDir().put(n, track); 864 cFieldCols->referenceDir().put(n, track); 865 cFieldCols->sourceId().put(n, srcId); 866 867 // Flags. 868 cFieldCols->flagRow().put(n, False); 869 } 733 870 734 871 return n; … … 741 878 Int PKSMS2writer::addObservationEntry( 742 879 const String observer, 743 const String project) 880 const String project, 881 const String antName) 744 882 { 745 883 // Extend the OBSERVATION subtable. … … 748 886 749 887 // Data. 750 cObservationCols->telescopeName().put(n, "Parkes"); 888 //cObservationCols->telescopeName().put(n, "Parkes"); 889 cObservationCols->telescopeName().put(n, antName); 751 890 Vector<Double> timerange(2, 0.0); 752 891 cObservationCols->timeRange().put(n, timerange); … … 754 893 Vector<String> log(1, "none"); 755 894 cObservationCols->log().put(n, log); 756 cObservationCols->scheduleType().put(n, "ATNF"); 895 //cObservationCols->scheduleType().put(n, "ATNF"); 896 cObservationCols->scheduleType().put(n, ""); 757 897 Vector<String> schedule(1, "Not available"); 758 898 cObservationCols->schedule().put(n, schedule); … … 767 907 768 908 //--------------------------------------------- PKSMS2writer::addPointingEntry 909 910 // Modified to fill pointing data if the direction is the pointing direction. 911 // So the following comment is no longer true. 769 912 770 913 // Add an entry to the POINTING subtable. This compulsory subtable simply … … 778 921 const Vector<Double> scanRate) 779 922 { 780 // Extend the POINTING subtable. 781 cPointing.addRow(); 782 Int n = cPointing.nrow() - 1; 783 784 // Keys. 785 cPointingCols->antennaId().put(n, 0); 786 cPointingCols->time().put(n, time); 787 cPointingCols->interval().put(n, interval); 788 789 // Data. 790 cPointingCols->name().put(n, fieldName); 791 cPointingCols->numPoly().put(n, 1); 792 cPointingCols->timeOrigin().put(n, time); 793 794 Matrix<Double> track(2, 2); 795 track.column(0) = direction; 796 track.column(1) = scanRate; 797 cPointingCols->direction().put(n, track); 798 cPointingCols->target().put(n, track); 799 cPointingCols->tracking().put(n, True); 800 923 924 ROScalarColumn<Double> tms(cPointing, "TIME"); 925 Int n; 926 Int ntm = cPointing.nrow(); 927 for (n = 0; n < ntm; n++) { 928 if (tms(n) == time) { 929 break; 930 } 931 } 932 933 if (n == ntm) { 934 // Extend the POINTING subtable. 935 cPointing.addRow(); 936 //Int n = cPointing.nrow() - 1; 937 938 // Keys. 939 cPointingCols->antennaId().put(n, 0); 940 cPointingCols->time().put(n, time); 941 cPointingCols->interval().put(n, interval); 942 943 // Data. 944 cPointingCols->name().put(n, fieldName); 945 cPointingCols->numPoly().put(n, 1); 946 cPointingCols->timeOrigin().put(n, time); 947 948 //Matrix<Double> track(2, 2); 949 Matrix<Double> track(2, 1); 950 track.column(0) = direction; 951 //track.column(1) = scanRate; 952 cPointingCols->direction().put(n, track); 953 cPointingCols->target().put(n, track); 954 cPointingCols->tracking().put(n, True); 955 } 801 956 return n; 802 957 } … … 821 976 // Data. 822 977 Vector<Int> corrType(2); 978 if (nPol == 1) { 979 corrType.resize(1); 980 corrType(0) = Stokes::XX; 981 } 982 else { 983 //Vector<Int> corrType(2); 823 984 corrType(0) = Stokes::XX; 824 985 corrType(1) = Stokes::YY; 986 } 825 987 cPolarizationCols->corrType().put(n, corrType); 826 988 827 989 Matrix<Int> corrProduct(2,2,1); 990 if (nPol == 1) { 991 corrProduct.resize(2,1,1); 992 corrProduct(1,0) = 0; 993 } 828 994 if (nPol == 2) { 829 995 corrProduct(1,0) = 0; … … 869 1035 const Vector<Double> direction, 870 1036 const Vector<Double> properMotion, 871 const Double restFreq, 1037 //const Double restFreq, 1038 const Vector<Double> restFreq, 872 1039 const Double radialVelocity) 873 1040 { … … 903 1070 // cSourceCols->position().put(n, position); 904 1071 cSourceCols->properMotion().put(n, properMotion); 905 Vector<Double> restFrequency(1, restFreq); 906 cSourceCols->restFrequency().put(n, restFrequency); 1072 // Vector<Double> restFrequency(1, restFreq); 1073 // cSourceCols->restFrequency().put(n, restFrequency); 1074 cSourceCols->restFrequency().put(n, restFreq); 907 1075 Vector<Double> sysvel(1, radialVelocity); 908 1076 cSourceCols->sysvel().put(n, sysvel); … … 933 1101 934 1102 // Data. 935 cSpWindowCols->name().put(n, "L-band"); 1103 //cSpWindowCols->name().put(n, "L-band"); 1104 cSpWindowCols->name().put(n, " "); 936 1105 cSpWindowCols->refFrequency().put(n, refFreq); 937 1106 … … 1015 1184 const Double interval, 1016 1185 const Vector<Float> tcal, 1017 const Vector<Float> tsys) 1018 { 1186 const Vector<Float> tsys, 1187 const Int nPol) 1188 { 1189 LogIO os(LogOrigin("PKSMS2writer", "addSysCalEntry()", WHERE)); 1190 1019 1191 // Extend the SYSCAL subtable. 1020 1192 cSysCal.addRow(); 1021 1193 Int n = cSysCal.nrow() - 1; 1022 1194 1195 //check fo consistency with n pol 1196 //here assume size of Tcal vector = npol 1197 Vector<Float> inTcal(nPol,0); 1198 Int ndim = tcal.shape()(0); 1199 Vector<Float> tmpTcal = tcal; 1200 if (nPol != ndim) { 1201 os << LogIO::WARN 1202 << "Found "<< ndim <<" Tcal value(s) for the data with "<<nPol<<" polarization(s)" 1203 << "(expecting one Tcal per pol)."<<endl 1204 << "First "<< nPol << " Tcal value(s) will be filled." << LogIO::POST; 1205 tmpTcal.resize(nPol, True); 1206 inTcal = tmpTcal; 1207 } 1023 1208 // Keys. 1024 1209 cSysCalCols->antennaId().put(n, 0); … … 1029 1214 1030 1215 // Data. 1031 cSysCalCols->tcal().put(n, tcal); 1216 //cSysCalCols->tcal().put(n, tcal); 1217 cSysCalCols->tcal().put(n, inTcal); 1032 1218 cSysCalCols->tsys().put(n, tsys); 1033 1219 -
branches/mergetest/external/atnf/PKSIO/PKSMS2writer.h
r1720 r1779 78 78 79 79 // Write the next data record. 80 /** 81 virtual Int write( 82 const Int scanNo, 83 const Int cycleNo, 84 const Double mjd, 85 const Double interval, 86 const String fieldName, 87 const String srcName, 88 const Vector<Double> srcDir, 89 const Vector<Double> srcPM, 90 const Double srcVel, 91 const String obsMode, 92 const Int IFno, 93 const Double refFreq, 94 const Double bandwidth, 95 const Double freqInc, 96 //const Double restFreq, 97 const Vector<Double> restFreq, 98 const Vector<Float> tcal, 99 const String tcalTime, 100 const Float azimuth, 101 const Float elevation, 102 const Float parAngle, 103 const Float focusAxi, 104 const Float focusTan, 105 const Float focusRot, 106 const Float temperature, 107 const Float pressure, 108 const Float humidity, 109 const Float windSpeed, 110 const Float windAz, 111 const Int refBeam, 112 const Int beamNo, 113 const Vector<Double> direction, 114 const Vector<Double> scanRate, 115 const Vector<Float> tsys, 116 const Vector<Float> sigma, 117 const Vector<Float> calFctr, 118 const Matrix<Float> baseLin, 119 const Matrix<Float> baseSub, 120 const Matrix<Float> &spectra, 121 const Matrix<uChar> &flagged, 122 const uInt flagrow, 123 const Complex xCalFctr, 124 const Vector<Complex> &xPol); 125 **/ 80 126 virtual Int write( 81 127 const PKSrecord &pksrec); … … 131 177 ScalarColumn<Complex> *cXCalFctrCol; 132 178 179 // for handling parameters specific to GBT and other telescopes 180 Bool cGBT, cSMT, cAPEX, cALMA, cATF; 133 181 134 182 // Add an entry to the ANTENNA subtable. … … 164 212 Int addObservationEntry( 165 213 const String observer, 166 const String project); 214 const String project, 215 const String antName); 167 216 168 217 // Add an entry to the POINTING subtable. … … 187 236 const Vector<Double> direction, 188 237 const Vector<Double> properMotion, 189 const Double restFreq, 238 //const Double restFreq, 239 const Vector<Double> restFreq, 190 240 const Double radialVelocity); 191 241 … … 209 259 const Double interval, 210 260 const Vector<Float> Tcal, 211 const Vector<Float> Tsys); 261 const Vector<Float> Tsys, 262 const Int nPol); 212 263 213 264 // Add an entry to the WEATHER subtable. -
branches/mergetest/external/atnf/PKSIO/PKSSDwriter.cc
r1735 r1779 35 35 #include <atnf/PKSIO/PKSSDwriter.h> 36 36 37 #include <casa/Logging/LogIO.h> 38 37 39 #include <casa/stdio.h> 38 40 #include <casa/Quanta/MVTime.h> … … 41 43 #include <cstring> 42 44 45 // Class name 46 const string className = "PKSSDwriter" ; 47 43 48 //--------------------------------------------------- PKSSDwriter::PKSSDwriter 44 49 … … 47 52 PKSSDwriter::PKSSDwriter() 48 53 { 49 // By default, messages are written to stderr.50 initMsg();51 54 } 52 55 … … 58 61 { 59 62 close(); 60 }61 62 //-------------------------------------------------------- PKSSDwriter::setMsg63 64 // Set message disposition. If fd is non-zero messages will be written65 // to that file descriptor, else stored for retrieval by getMsg().66 67 Int PKSSDwriter::setMsg(FILE *fd)68 {69 PKSmsg::setMsg(fd);70 cSDwriter.setMsg(fd);71 72 return 0;73 63 } 74 64 … … 92 82 const Bool haveBase) 93 83 { 94 // Clear the message stack.95 clearMsg();84 const string methodName = "create()" ; 85 LogIO os( LogOrigin( className, methodName, WHERE ) ) ; 96 86 97 87 double antPos[3]; … … 102 92 cNIF = nChan.nelements(); 103 93 if (nPol.nelements() != cNIF || haveXPol.nelements() != cNIF) { 104 cerr << "PKSSDwriter::create: " 105 << "Inconsistent number of IFs for nChan, nPol, and/or haveXPol." 106 << endl; 94 os << LogIO::SEVERE << "Inconsistent number of IFs for nChan, nPol, and/or haveXPol." << LogIO::POST ; 107 95 return 1; 108 96 } … … 131 119 (int *)cNPol.getStorage(deleteIt), 132 120 (int *)cHaveXPol.getStorage(deleteIt), (int)cHaveBase, 1); 133 logMsg(cSDwriter.getMsg());134 cSDwriter.clearMsg();121 //logMsg(cSDwriter.getMsg()); 122 //cSDwriter.clearMsg(); 135 123 if (status) { 136 124 cSDwriter.deleteFile(); … … 148 136 const PKSrecord &pksrec) 149 137 { 138 const string methodName = "write()" ; 139 LogIO os( LogOrigin( className, methodName, WHERE ) ) ; 140 150 141 // Do basic checks. 151 142 Int IFno = pksrec.IFno; 152 143 uInt iIF = IFno - 1; 153 144 if (IFno < 1 || Int(cNIF) < IFno) { 154 cerr << "PKSDwriter::write: "155 156 << " (maximum " << cNIF << ")." << endl;145 os << LogIO::SEVERE 146 << "Invalid IF number " << IFno 147 << " (maximum " << cNIF << ")." << LogIO::POST ; 157 148 return 1; 158 149 } … … 160 151 uInt nChan = pksrec.spectra.nrow(); 161 152 if (nChan != cNChan(iIF)) { 162 cerr << "PKSDwriter::write: " 163 << "Wrong number of channels for IF " << IFno << "," << endl 164 << " " 153 os << LogIO::SEVERE << "Wrong number of channels for IF " << IFno << "," << endl 165 154 << "got " << nChan << " should be " << cNChan(iIF) << "." << endl; 155 os << LogIO::POST ; 166 156 return 1; 167 157 } … … 169 159 uInt nPol = pksrec.spectra.ncolumn(); 170 160 if (nPol != cNPol(iIF)) { 171 cerr << "PKSDwriter::write: " 172 << "Wrong number of polarizations for IF " << IFno << "," << endl 173 << " " 174 << "got " << nPol << " should be " << cNPol(iIF) << "." << endl; 161 os << LogIO::SEVERE << "Wrong number of polarizations for IF " << IFno << "," << endl 162 << "got " << nPol << " should be " << cNPol(iIF) << "." << endl; 163 os << LogIO::POST ; 175 164 return 1; 176 165 } 177 166 178 // Extract calendar information fr om mjd.167 // Extract calendar information frrom mjd. 179 168 MVTime time(pksrec.mjd); 180 169 Int year = time.year(); … … 196 185 mbrec.srcRA = pksrec.srcDir(0); 197 186 mbrec.srcDec = pksrec.srcDir(1); 198 199 mbrec.restFreq = pksrec.restFreq; 200 187 if (pksrec.restFreq.shape()==0) { 188 mbrec.restFreq = 0; 189 } 190 else { 191 mbrec.restFreq = pksrec.restFreq(0); 192 } 201 193 strncpy(mbrec.obsType, (char *)pksrec.obsType.chars(), 16); 202 194 … … 291 283 292 284 Int status = cSDwriter.write(mbrec); 293 logMsg(cSDwriter.getMsg());294 cSDwriter.clearMsg();285 //logMsg(cSDwriter.getMsg()); 286 //cSDwriter.clearMsg(); 295 287 if (status) { 296 288 status = 1; … … 325 317 { 326 318 cSDwriter.close(); 327 logMsg(cSDwriter.getMsg());328 cSDwriter.clearMsg();329 } 319 //logMsg(cSDwriter.getMsg()); 320 //cSDwriter.clearMsg(); 321 } -
branches/mergetest/external/atnf/PKSIO/PKSSDwriter.h
r1720 r1779 62 62 virtual ~PKSSDwriter(); 63 63 64 // Set message disposition.65 virtual Int setMsg(66 FILE *fd = 0x0);67 68 64 // Create the SDFITS file and write static data. 69 65 virtual Int create( -
branches/mergetest/external/atnf/PKSIO/PKSreader.cc
r1720 r1779 85 85 reader = new PKSFITSreader("SDFITS"); 86 86 87 } else {88 // Assume it's MBFITS.89 format = "MBFITS";90 reader = new PKSFITSreader("MBFITS", retry, interpolate);91 }87 } else { 88 // Assume it's MBFITS. 89 format = "MBFITS"; 90 reader = new PKSFITSreader("MBFITS", retry, interpolate); 91 } 92 92 } 93 93 … … 106 106 format = "UNRECOGNIZED INPUT FORMAT"; 107 107 } 108 109 108 return reader; 110 109 } … … 113 112 114 113 // Search a list of directories for a Parkes Multibeam dataset and return an 115 // appropriate PKSreader for it.116 114 117 115 PKSreader* getPKSreader( … … 145 143 PKSreader* getPKSreader( 146 144 const String name, 145 const String antenna, 147 146 const Int retry, 148 147 const Int interpolate, … … 160 159 // Try to open it. 161 160 if (reader) { 162 if (reader->open(name, beams, IFs, nChan, nPol, haveXPol, haveBase,163 have Spectra)) {161 if (reader->open(name, antenna, beams, IFs, nChan, nPol, haveXPol, 162 haveBase, haveSpectra)) { 164 163 format += " OPEN ERROR"; 165 164 delete reader; … … 173 172 //--------------------------------------------------------------- getPKSreader 174 173 175 // Search a list of directories for a Parkes Multibeam dataset and open an174 // Search a list of directories for a Parkes Multibeam dataset and return an 176 175 // appropriate PKSreader for it. 177 178 PKSreader* getPKSreader( 179 const String name,176 PKSreader* getPKSreader( 177 const String name, 178 const String antenna, 180 179 const Vector<String> directories, 181 180 const Int retry, … … 196 195 // Try to open it. 197 196 if (reader) { 198 if (reader->open(name, beams, IFs, nChan, nPol, haveXPol, haveBase,199 have Spectra)) {197 if (reader->open(name, antenna, beams, IFs, nChan, nPol, haveXPol, 198 haveBase, haveSpectra)) { 200 199 format += " OPEN ERROR"; 201 200 delete reader; -
branches/mergetest/external/atnf/PKSIO/PKSreader.h
r1720 r1779 37 37 #define ATNF_PKSREADER_H 38 38 39 #include <atnf/PKSIO/PKSmsg.h>40 39 #include <atnf/PKSIO/PKSrecord.h> 40 #include <atnf/PKSIO/SrcType.h> 41 41 42 42 #include <casa/aips.h> 43 43 #include <casa/Arrays/Matrix.h> 44 44 #include <casa/Arrays/Vector.h> 45 #include <casa/BasicSL/Complex.h> 45 46 #include <casa/BasicSL/String.h> 46 47 … … 70 71 class PKSreader* getPKSreader( 71 72 const String name, 73 const String antenna, 72 74 const Int retry, 73 75 const Int interpolate, … … 84 86 class PKSreader* getPKSreader( 85 87 const String name, 88 const String antenna, 86 89 const Vector<String> directories, 87 90 const Int retry, … … 97 100 Bool &haveSpectra); 98 101 99 class PKSreader : public PKSmsg 102 103 class PKSreader 100 104 { 101 105 public: … … 106 110 virtual Int open( 107 111 const String inName, 112 const String antenna, 108 113 Vector<Bool> &beams, 109 114 Vector<Bool> &IFs, … … 148 153 const Bool getSpectra = True, 149 154 const Bool getXPol = False, 155 const Bool getFeedPos = False, 156 const Bool getPointing = False, 150 157 const Int coordSys = 0) = 0; 158 151 159 152 160 // Find the range of the data selected in time and position. … … 157 165 Matrix<Double> &positions) = 0; 158 166 159 // Read the next data record. 167 // Read the next data record. 168 /** 169 virtual Int read( 170 Int &scanNo, 171 Int &cycleNo, 172 Double &mjd, 173 Double &interval, 174 String &fieldName, 175 String &srcName, 176 Vector<Double> &srcDir, 177 Vector<Double> &srcPM, 178 Double &srcVel, 179 String &obsType, 180 Int &IFno, 181 Double &refFreq, 182 Double &bandwidth, 183 Double &freqInc, 184 Vector<Double> &restFreq, 185 Vector<Float> &tcal, 186 String &tcalTime, 187 Float &azimuth, 188 Float &elevation, 189 Float &parAngle, 190 Float &focusAxi, 191 Float &focusTan, 192 Float &focusRot, 193 Float &temperature, 194 Float &pressure, 195 Float &humidity, 196 Float &windSpeed, 197 Float &windAz, 198 Int &refBeam, 199 Int &beamNo, 200 Vector<Double> &direction, 201 Vector<Double> &scanRate, 202 Vector<Float> &tsys, 203 Vector<Float> &sigma, 204 Vector<Float> &calFctr, 205 Matrix<Float> &baseLin, 206 Matrix<Float> &baseSub, 207 Matrix<Float> &spectra, 208 Matrix<uChar> &flagged, 209 Complex &xCalFctr, 210 Vector<Complex> &xPol) = 0; 211 **/ 212 /** 213 // Read the next data record, just the basics. 214 virtual Int read( 215 Int &IFno, 216 Vector<Float> &tsys, 217 Vector<Float> &calFctr, 218 Matrix<Float> &baseLin, 219 Matrix<Float> &baseSub, 220 Matrix<Float> &spectra, 221 Matrix<uChar> &flagged) = 0; 222 **/ 160 223 virtual Int read(PKSrecord &pksrec) = 0; 161 224 … … 164 227 165 228 protected: 166 Bool cGetSpectra, cGetXPol;229 Bool cGetFeedPos, cGetSpectra, cGetXPol, cGetPointing; 167 230 Int cCoordSys; 168 231 -
branches/mergetest/external/atnf/PKSIO/PKSrecord.h
r1720 r1779 67 67 Double bandwidth; 68 68 Double freqInc; 69 Double restFreq; 69 Int nchan; 70 Vector<Double> restFreq; 70 71 Vector<Float> tcal; 71 72 String tcalTime; … … 86 87 Int pCode; 87 88 Float rateAge; 88 Vector< Float>scanRate;89 Vector<Double> scanRate; 89 90 Float paRate; 90 91 Vector<Float> tsys; … … 95 96 Matrix<Float> spectra; 96 97 Matrix<uChar> flagged; 98 uInt flagrow; 97 99 Complex xCalFctr; 98 100 Vector<Complex> xPol; 101 Int polNo ; 102 Int srcType ; 99 103 }; 100 104 -
branches/mergetest/external/atnf/PKSIO/PKSwriter.h
r1720 r1779 35 35 #define ATNF_PKSWRITER_H 36 36 37 #include <atnf/PKSIO/PKSmsg.h>38 37 #include <atnf/PKSIO/PKSrecord.h> 39 38 … … 50 49 // </summary> 51 50 52 class PKSwriter : public PKSmsg51 class PKSwriter 53 52 { 54 53 public: -
branches/mergetest/external/atnf/PKSIO/SDFITSreader.cc
r1737 r1779 38 38 39 39 #include <atnf/pks/pks_maths.h> 40 #include <atnf/PKSIO/PKSmsg.h>41 40 #include <atnf/PKSIO/MBrecord.h> 42 41 #include <atnf/PKSIO/SDFITSreader.h> 43 42 43 #include <casa/Logging/LogIO.h> 44 #include <casa/Quanta/MVTime.h> 44 45 #include <casa/math.h> 45 46 #include <casa/stdio.h> … … 67 68 const double D2R = PI / 180.0; 68 69 70 // Class name 71 const string className = "SDFITSreader" ; 72 69 73 //---------------------------------------------------- SDFITSreader::(statics) 70 74 … … 97 101 cEndChan = 0x0; 98 102 cRefChan = 0x0; 99 100 // By default, messages are written to stderr. 101 initMsg(); 103 cPols = 0x0; 102 104 } 103 105 … … 128 130 int &extraSysCal) 129 131 { 130 // Clear the message stack. 131 clearMsg(); 132 const string methodName = "open()" ; 132 133 133 134 if (cSDptr) { … … 139 140 if (fits_open_file(&cSDptr, sdName, READONLY, &cStatus)) { 140 141 sprintf(cMsg, "ERROR: Failed to open SDFITS file\n %s", sdName); 141 log Msg(cMsg);142 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, cMsg); 142 143 return 1; 143 144 } … … 162 163 163 164 } else { 164 log Msg("ERROR:Failed to locate SDFITS binary table.");165 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "Failed to locate SDFITS binary table."); 165 166 close(); 166 167 return 1; … … 201 202 cNAxes = 5; 202 203 if (readDim(DATA, 1, &cNAxes, cNAxis)) { 203 log Msg();204 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 204 205 close(); 205 206 return 1; … … 220 221 if (cNAxes < 4) { 221 222 // Need at least four axes (for now). 222 log Msg("ERROR:DATA array contains fewer than four axes.");223 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "DATA array contains fewer than four axes."); 223 224 close(); 224 225 return 1; 225 226 } else if (cNAxes > 5) { 226 227 // We support up to five axes. 227 log Msg("ERROR:DATA array contains more than five axes.");228 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "DATA array contains more than five axes."); 228 229 close(); 229 230 return 1; … … 236 237 findData(DATAXED, "DATAXED", TSTRING); 237 238 if (cData[DATAXED].colnum < 0) { 238 log Msg("ERROR:DATA array column absent from binary table.");239 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "DATA array column absent from binary table."); 239 240 close(); 240 241 return 1; … … 266 267 267 268 if (cStatus) { 268 log Msg();269 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 269 270 close(); 270 271 return 1; … … 280 281 char *timeCRPIX = 0; 281 282 char *beamCRVAL = 0; 283 char *polCRVAL = 0; 282 284 283 285 cFreqAxis = -1; … … 297 299 } else if (strncmp(ctype[iaxis], "STOKES", 6) == 0) { 298 300 cStokesAxis = iaxis; 301 polCRVAL = CRVAL[iaxis]; 299 302 300 303 } else if (strncmp(ctype[iaxis], "RA", 2) == 0) { … … 318 321 sprintf(cMsg, "DATA array contains a TIME axis of length %ld.", 319 322 cNAxisTime); 320 logMsg(cMsg); 323 //logMsg(cMsg); 324 log(LogOrigin( className, methodName, WHERE ), LogIO::NORMAL, cMsg); 321 325 } 322 326 … … 337 341 } 338 342 343 339 344 // Check that required axes are present. 340 345 if (cFreqAxis < 0 || cStokesAxis < 0 || cRaAxis < 0 || cDecAxis < 0) { 341 log Msg("ERROR:Could not find required DATA array axes.");346 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "Could not find required DATA array axes."); 342 347 close(); 343 348 return 1; … … 403 408 findData(WINDDIRE, "WINDDIRE", TFLOAT); // Shared. 404 409 410 findData(STOKES, polCRVAL, TINT); 411 findData(SIG, "SIG", TSTRING); 412 findData(CAL, "CAL", TSTRING); 413 414 findData(RVSYS, "RVSYS", TDOUBLE); 415 findData(VFRAME, "VFRAME", TDOUBLE); 416 findData(VELDEF, "VELDEF", TSTRING); 417 405 418 if (cStatus) { 406 log Msg();419 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 407 420 close(); 408 421 return 1; … … 433 446 cCycleNo = 0; 434 447 cLastUTC = 0.0; 448 for ( int i = 0 ; i < 4 ; i++ ) { 449 cGLastUTC[i] = 0.0 ; 450 cGLastScan[i] = -1 ; 451 cGCycleNo[i] = 0 ; 452 } 435 453 436 454 // Beam number, 1-relative by default. … … 536 554 fits_get_num_rows(cSDptr, &cNRow, &cStatus); 537 555 if (!cNRow) { 538 log Msg("ERROR:Table contains no entries.");556 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "Table contains no entries."); 539 557 close(); 540 558 return 1; … … 550 568 &beamNul, beamCol, &anynul, &cStatus)) { 551 569 delete [] beamCol; 552 log Msg();570 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 553 571 close(); 554 572 return 1; … … 565 583 if (beamCol[irow] < cBeam_1rel) { 566 584 delete [] beamCol; 567 log Msg("ERROR:SDFITS file contains invalid beam number.");585 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "SDFITS file contains invalid beam number."); 568 586 close(); 569 587 return 1; … … 606 624 &IFNul, IFCol, &anynul, &cStatus)) { 607 625 delete [] IFCol; 608 log Msg();626 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 609 627 close(); 610 628 return 1; … … 621 639 if (IFCol[irow] < cIF_1rel) { 622 640 delete [] IFCol; 623 log Msg("ERROR:SDFITS file contains invalid IF number.");641 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "SDFITS file contains invalid IF number."); 624 642 close(); 625 643 return 1; … … 653 671 // Variable dimension array. 654 672 if (readDim(DATA, irow+1, &cNAxes, cNAxis)) { 655 log Msg();673 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 656 674 close(); 657 675 return 1; … … 681 699 682 700 if (readDim(XPOLDATA, irow+1, &nAxis, nAxes)) { 683 log Msg();701 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE ); 684 702 close(); 685 703 return 1; … … 719 737 cNPol[0] = cNIF; 720 738 cNIF = 1; 739 } 740 741 // For GBT data that stores spectra for each polarization in separate rows 742 if ( cData[STOKES].colnum > 0 ) { 743 int *stokesCol = new int[cNRow]; 744 int stokesNul = 1; 745 int anynul; 746 if (fits_read_col(cSDptr, TINT, cData[STOKES].colnum, 1, 1, cNRow, 747 &stokesNul, stokesCol, &anynul, &cStatus)) { 748 delete [] stokesCol; 749 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 750 close(); 751 return 1; 752 } 753 754 vector<int> pols ; 755 pols.push_back( stokesCol[0] ) ; 756 for ( int i = 0 ; i < cNRow ; i++ ) { 757 bool pmatch = false ; 758 for ( uint j = 0 ; j < pols.size() ; j++ ) { 759 if ( stokesCol[i] == pols[j] ) { 760 pmatch = true ; 761 break ; 762 } 763 } 764 if ( !pmatch ) { 765 pols.push_back( stokesCol[i] ) ; 766 } 767 } 768 769 cPols = new int[pols.size()] ; 770 for ( uint i = 0 ; i < pols.size() ; i++ ) { 771 cPols[i] = pols[i] ; 772 } 773 774 for ( int i = 0 ; i < cNIF ; i++ ) { 775 cNPol[i] = pols.size() ; 776 } 777 778 delete [] stokesCol ; 721 779 } 722 780 … … 806 864 double &bandwidth) 807 865 { 866 const string methodName = "getHeader()" ; 867 808 868 // Has the file been opened? 809 869 if (!cSDptr) { … … 879 939 880 940 // Look for VELFRAME, written by earlier versions of Livedata. 941 // 942 // Added few more codes currently (as of 2009 Oct) used in the GBT 943 // SDFITS (based io_sdfits_define.pro of GBTIDL). - TT 881 944 if (readParm("VELFRAME", TSTRING, dopplerFrame)) { // Additional. 882 945 // No, try digging it out of the CTYPE card (AIPS convention). … … 890 953 // LSR unqualified usually means LSR (kinematic). 891 954 strcpy(dopplerFrame, "LSRK"); 955 } else if (strcmp(dopplerFrame, "LSD") == 0) { 956 // LSR as a dynamical defintion 957 strcpy(dopplerFrame, "LSRD"); 892 958 } else if (strcmp(dopplerFrame, "HEL") == 0) { 893 959 // Almost certainly barycentric. 894 960 strcpy(dopplerFrame, "BARYCENT"); 961 } else if (strcmp(dopplerFrame, "BAR") == 0) { 962 // barycentric. 963 strcpy(dopplerFrame, "BARYCENT"); 964 } else if (strcmp(dopplerFrame, "OBS") == 0) { 965 // observed or topocentric. 966 strcpy(dopplerFrame, "TOPO"); 967 } else if (strcmp(dopplerFrame, "GEO") == 0) { 968 // geocentric 969 strcpy(dopplerFrame, "GEO"); 970 } else if (strcmp(dopplerFrame, "GAL") == 0) { 971 // galactic 972 strcpy(dopplerFrame, "GAL"); 973 } else if (strcmp(dopplerFrame, "LGR") == 0) { 974 // Local group 975 strcpy(dopplerFrame, "LGROUP"); 976 } else if (strcmp(dopplerFrame, "CMB") == 0) { 977 // Cosimic Microwave Backgroup 978 strcpy(dopplerFrame, "CMB"); 895 979 } 896 980 } else { … … 898 982 } 899 983 } 900 901 984 // Translate to FITS standard names. 902 985 if (strncmp(dopplerFrame, "TOP", 3) == 0) { … … 908 991 } else if (strncmp(dopplerFrame, "BARY", 4) == 0) { 909 992 strcpy(dopplerFrame, "BARYCENT"); 910 } 911 } 912 993 } else if (strncmp(dopplerFrame, "GAL", 3) == 0) { 994 strcpy(dopplerFrame, "GALACTOC"); 995 } else if (strncmp(dopplerFrame, "LGROUP", 6) == 0) { 996 strcpy(dopplerFrame, "LOCALGRP"); 997 } else if (strncmp(dopplerFrame, "CMB", 3) == 0) { 998 strcpy(dopplerFrame, "CMBDIPOL"); 999 } 1000 } 1001 913 1002 if (cStatus) { 914 log Msg();1003 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 915 1004 return 1; 916 1005 } … … 922 1011 923 1012 if (cStatus) { 924 log Msg();1013 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 925 1014 return 1; 926 1015 } … … 938 1027 double* &endFreq) 939 1028 { 1029 const string methodName = "getFreqInfo()" ; 1030 940 1031 float fqRefPix; 941 1032 double fqDelt, fqRefVal; … … 952 1043 &IFNul, IFCol, &anynul, &cStatus)) { 953 1044 delete [] IFCol; 954 log Msg();1045 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 955 1046 close(); 956 1047 return 1; … … 1015 1106 double* &positions) 1016 1107 { 1108 const string methodName = "findRange()" ; 1109 1017 1110 // Has the file been opened? 1018 1111 if (!cSDptr) { … … 1036 1129 delete [] beamCol; 1037 1130 delete [] sel; 1038 log Msg();1131 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 1039 1132 return 1; 1040 1133 } … … 1056 1149 delete [] IFCol; 1057 1150 delete [] sel; 1058 log Msg();1151 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 1059 1152 return 1; 1060 1153 } … … 1088 1181 if (cData[AZIMUTH].colnum < 0 || 1089 1182 cData[ELEVATIO].colnum < 0) { 1090 log Msg("WARNING:Azimuth/elevation information absent.");1183 log(LogOrigin( className, methodName, WHERE ), LogIO::WARN, "Azimuth/elevation information absent."); 1091 1184 cStatus = -1; 1092 1185 … … 1115 1208 cData[FOCUSROT].colnum < 0 || 1116 1209 cData[ELEVATIO].colnum < 0) { 1117 log Msg("WARNING:ZPA/elevation information absent.");1210 log(LogOrigin( className, methodName, WHERE ), LogIO::WARN, "ZPA/elevation information absent."); 1118 1211 cStatus = -1; 1119 1212 … … 1191 1284 cData[PARANGLE].colnum < 0 || 1192 1285 cData[FOCUSROT].colnum < 0) { 1193 logMsg("WARNING: Insufficient information to compute feed-plane\n" 1194 " coordinates."); 1286 log( LogOrigin( className, methodName, WHERE ), LogIO::WARN, 1287 "Insufficient information to compute feed-plane\n" 1288 " coordinates."); 1195 1289 cStatus = -1; 1196 1290 … … 1241 1335 nSel = 0; 1242 1336 delete [] positions; 1243 log Msg();1337 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 1244 1338 cStatus = 0; 1245 1339 return 1; … … 1257 1351 MBrecord &mbrec) 1258 1352 { 1353 const string methodName = "read()" ; 1354 1259 1355 // Has the file been opened? 1260 1356 if (!cSDptr) { 1261 1357 return 1; 1262 1358 } 1263 1264 1359 // Find the next selected beam and IF. 1265 1360 short iBeam = 0, iIF = 0; 1361 int iPol = -1 ; 1266 1362 while (1) { 1267 1363 if (++cTimeIdx > cNAxisTime) { … … 1321 1417 sprintf(cMsg, "ALFA cal factors for beam %d: %.3e, %.3e", 1322 1418 iBeam+1, sALFAcal[iBeam][0], sALFAcal[iBeam][1]); 1323 logMsg(cMsg); 1419 log(LogOrigin( className, methodName, WHERE ), LogIO::NORMAL, cMsg); 1420 //logMsg(cMsg); 1324 1421 } 1325 1422 } 1326 1423 } 1327 1424 1425 // for GBT SDFITS 1426 if (cData[STOKES].colnum > 0 ) { 1427 readData(STOKES, cRow, &iPol ) ; 1428 for ( int i = 0 ; i < cNPol[iIF] ; i++ ) { 1429 if ( cPols[i] == iPol ) { 1430 iPol = i ; 1431 break ; 1432 } 1433 } 1434 } 1328 1435 break; 1329 1436 } … … 1370 1477 } 1371 1478 1479 if ( iPol != -1 ) { 1480 if ( mbrec.scanNo != cGLastScan[iPol] ) { 1481 cGLastScan[iPol] = mbrec.scanNo ; 1482 cGCycleNo[iPol] = 0 ; 1483 mbrec.cycleNo = ++cGCycleNo[iPol] ; 1484 } 1485 else { 1486 mbrec.cycleNo = ++cGCycleNo[iPol] ; 1487 } 1488 } 1489 1372 1490 readData(EXPOSURE, cRow, &mbrec.exposure); 1373 1491 1374 1492 // Source identification. 1375 1493 readData(OBJECT, cRow, mbrec.srcName); 1494 1495 if ( iPol != -1 ) { 1496 char obsmode[32] ; 1497 readData( OBSMODE, cRow, obsmode ) ; 1498 char sig[1] ; 1499 char cal[1] ; 1500 readData( SIG, cRow, sig ) ; 1501 readData( CAL, cRow, cal ) ; 1502 if ( strstr( obsmode, "PSWITCH" ) != NULL ) { 1503 // position switch 1504 strcat( mbrec.srcName, "_p" ) ; 1505 if ( strstr( obsmode, "PSWITCHON" ) != NULL ) { 1506 strcat( mbrec.srcName, "s" ) ; 1507 } 1508 else if ( strstr( obsmode, "PSWITCHOFF" ) != NULL ) { 1509 strcat( mbrec.srcName, "r" ) ; 1510 } 1511 } 1512 else if ( strstr( obsmode, "Nod" ) != NULL ) { 1513 // nod 1514 strcat( mbrec.srcName, "_n" ) ; 1515 if ( sig[0] == 'T' ) { 1516 strcat( mbrec.srcName, "s" ) ; 1517 } 1518 else { 1519 strcat( mbrec.srcName, "r" ) ; 1520 } 1521 } 1522 else if ( strstr( obsmode, "FSWITCH" ) != NULL ) { 1523 // frequency switch 1524 strcat( mbrec.srcName, "_f" ) ; 1525 if ( sig[0] == 'T' ) { 1526 strcat( mbrec.srcName, "s" ) ; 1527 } 1528 else { 1529 strcat( mbrec.srcName, "r" ) ; 1530 } 1531 } 1532 if ( cal[0] == 'T' ) { 1533 strcat( mbrec.srcName, "c" ) ; 1534 } 1535 else { 1536 strcat( mbrec.srcName, "o" ) ; 1537 } 1538 } 1376 1539 1377 1540 readData(OBJ_RA, cRow, &mbrec.srcRA); … … 1421 1584 int nPol = cNPol[iIF]; 1422 1585 1586 if ( cData[STOKES].colnum > 0 ) 1587 nPol = 1 ; 1588 1423 1589 if (cGetSpectra || cGetXPol) { 1424 1590 int nxpol = cGetXPol ? 2*nChan : 0; … … 1430 1596 mbrec.nChan[0] = nChan; 1431 1597 mbrec.nPol[0] = nPol; 1598 mbrec.polNo = iPol ; 1432 1599 1433 1600 readData(FqRefPix, cRow, mbrec.fqRefPix); … … 1448 1615 1449 1616 if (cStatus) { 1450 log Msg();1617 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 1451 1618 return 1; 1452 1619 } … … 1485 1652 1486 1653 if (cStatus) { 1487 log Msg();1654 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 1488 1655 return 1; 1489 1656 } … … 1535 1702 1536 1703 if ((status = readDim(DATA, cRow, &naxes, cNAxis))) { 1537 log Msg();1704 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 1538 1705 1539 1706 } else if ((status = (naxes != cNAxes))) { 1540 log Msg("ERROR:DATA array dimensions changed.");1707 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "DATA array dimensions changed."); 1541 1708 } 1542 1709 … … 1552 1719 blc, trc, inc, 0, mbrec.spectra[0] + iPol*nChan, &anynul, 1553 1720 &cStatus)) { 1554 log Msg();1721 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 1555 1722 delete [] blc; 1556 1723 delete [] trc; … … 1613 1780 cNAxis, blc, trc, inc, 0, mbrec.flagged[0] + iPol*nChan, &anynul, 1614 1781 &cStatus)) { 1615 log Msg();1782 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 1616 1783 delete [] blc; 1617 1784 delete [] trc; … … 1664 1831 if (fits_read_subset_flt(cSDptr, cData[XPOLDATA].colnum, nAxis, nAxes, 1665 1832 blc, trc, inc, 0, mbrec.xpol[0], &anynul, &cStatus)) { 1666 log Msg();1833 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 1667 1834 delete [] blc; 1668 1835 delete [] trc; … … 1695 1862 1696 1863 if (cStatus) { 1697 log Msg();1864 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 1698 1865 return 1; 1699 1866 } … … 1729 1896 mbrec.windAz *= D2R; 1730 1897 1898 // For GBT data, source velocity can be evaluated 1899 if ( cData[RVSYS].colnum > 0 && cData[VFRAME].colnum > 0 ) { 1900 float vframe; 1901 readData(VFRAME, cRow, &vframe); 1902 float rvsys; 1903 readData(RVSYS, cRow, &rvsys); 1904 //mbrec.srcVelocity = rvsys - vframe ; 1905 mbrec.srcVelocity = rvsys ; 1906 } 1907 1731 1908 if (cStatus) { 1732 log Msg();1909 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 1733 1910 return 1; 1734 1911 } … … 1756 1933 } 1757 1934 1758 //------------------------------------------------------- SDFITSreader::log Msg1935 //------------------------------------------------------- SDFITSreader::log 1759 1936 1760 1937 // Log a message. If the current CFITSIO status value is non-zero, also log 1761 1938 // the corresponding error message and the CFITSIO message stack. 1762 1939 1763 void SDFITSreader::log Msg(const char *msg)1940 void SDFITSreader::log(LogOrigin origin, LogIO::Command cmd, const char *msg) 1764 1941 { 1765 FITSreader::logMsg(msg); 1942 LogIO os( origin ) ; 1943 1944 os << msg << endl ; 1766 1945 1767 1946 if (cStatus > 0) { 1768 1947 fits_get_errstatus(cStatus, cMsg); 1769 FITSreader::logMsg(cMsg);1948 os << cMsg << endl ; 1770 1949 1771 1950 while (fits_read_errmsg(cMsg)) { 1772 FITSreader::logMsg(cMsg); 1773 } 1774 } 1951 os << cMsg << endl ; 1952 } 1953 } 1954 os << LogIO::POST ; 1775 1955 } 1776 1956 … … 2107 2287 if (cData[TIME].colnum >= 0) { 2108 2288 readData(TIME, iRow, &utc); 2289 } else if (cGBT) { 2290 Int yy, mm ; 2291 Double dd, hour, min, sec ; 2292 sscanf( datobs, "%d-%d-%lfT%lf:%lf:%lf", &yy, &mm, &dd, &hour, &min, &sec ) ; 2293 dd = dd + ( hour * 3600.0 + min * 60.0 + sec ) / 86400.0 ; 2294 MVTime mvt( yy, mm, dd ) ; 2295 dd = mvt.day() ; 2296 utc = fmod( dd, 1.0 ) * 86400.0 ; 2109 2297 } else if (cNAxisTime > 1) { 2110 2298 double timeDelt, timeRefPix, timeRefVal; … … 2153 2341 short iPol) 2154 2342 { 2343 const string methodName = "alfaCal()" ; 2344 2155 2345 int calOn; 2156 2346 char chars[32]; … … 2205 2395 if (fits_read_subset_flt(cSDptr, cData[DATA].colnum, cNAxes, cNAxis, 2206 2396 blc, trc, inc, 0, spectrum, &anynul, &cStatus)) { 2207 log Msg();2397 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE); 2208 2398 delete [] blc; 2209 2399 delete [] trc; -
branches/mergetest/external/atnf/PKSIO/SDFITSreader.h
r1720 r1779 43 43 #include <atnf/PKSIO/MBrecord.h> 44 44 45 #include <casa/Logging/LogIO.h> 46 45 47 #include <fitsio.h> 46 48 47 49 using namespace std; 50 using namespace casa; 48 51 49 52 // <summary> … … 121 124 int cBeam_1rel, cIF_1rel; 122 125 126 // for GBT 127 int *cPols ; 128 123 129 enum {SCAN, CYCLE, DATE_OBS, TIME, EXPOSURE, OBJECT, OBJ_RA, OBJ_DEC, 124 130 RESTFRQ, OBSMODE, BEAM, IF, FqRefVal, FqDelt, FqRefPix, RA, DEC, … … 126 132 BASELIN, BASESUB, DATA, FLAGGED, DATAXED, XPOLDATA, REFBEAM, TCAL, 127 133 TCALTIME, AZIMUTH, ELEVATIO, PARANGLE, FOCUSAXI, FOCUSTAN, FOCUSROT, 128 TAMBIENT, PRESSURE, HUMIDITY, WINDSPEE, WINDDIRE, NDATA}; 134 TAMBIENT, PRESSURE, HUMIDITY, WINDSPEE, WINDDIRE, STOKES, SIG, CAL, 135 VFRAME, RVSYS, VELDEF, NDATA}; 129 136 130 137 // Message handling. 131 v irtual void logMsg(const char *msg = 0x0);138 void log(LogOrigin origin, LogIO::Command cmd, const char *msg = 0x0); 132 139 133 140 void findData(int iData, char *name, int type); … … 153 160 // These are for GBT data. 154 161 int cGBT, cFirstScanNo; 162 double cGLastUTC[4] ; 163 int cGLastScan[4] ; 164 int cGCycleNo[4] ; 155 165 }; 156 166 -
branches/mergetest/external/atnf/PKSIO/SDFITSwriter.cc
r1736 r1779 35 35 36 36 #include <atnf/PKSIO/MBrecord.h> 37 #include <atnf/PKSIO/PKSmsg.h>38 37 #include <atnf/PKSIO/SDFITSwriter.h> 38 39 #include <casa/Logging/LogIO.h> 39 40 40 41 #include <casa/iostream.h> … … 51 52 // Factor to convert radians to degrees. 52 53 const double R2D = 180.0 / PI; 54 55 // Class name 56 const string className = "SDFITSwriter" ; 53 57 54 58 //------------------------------------------------- SDFITSwriter::SDFITSwriter … … 58 62 // Default constructor. 59 63 cSDptr = 0x0; 60 61 // By default, messages are written to stderr.62 initMsg();63 64 } 64 65 … … 91 92 int extraSysCal) 92 93 { 94 const string methodName = "create()" ; 95 93 96 if (cSDptr) { 94 log Msg("ERROR:Output file already open, close it first.");97 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "Output file already open, close it first."); 95 98 return 1; 96 99 } 97 98 // Clear the message stack.99 clearMsg();100 100 101 101 // Prepend an '!' to the output name to force it to be overwritten. … … 107 107 cStatus = 0; 108 108 if (fits_create_file(&cSDptr, sdname, &cStatus)) { 109 sprintf(cMsg, " ERROR:Failed to create SDFITS file\n %s", sdName);110 log Msg(cMsg);109 sprintf(cMsg, "Failed to create SDFITS file\n %s", sdName); 110 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, cMsg); 111 111 return cStatus; 112 112 } … … 156 156 // Write required primary header keywords. 157 157 if (fits_write_imghdr(cSDptr, 8, 0, 0, &cStatus)) { 158 log Msg("ERROR:Failed to write required primary header keywords.");158 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "Failed to write required primary header keywords."); 159 159 return cStatus; 160 160 } … … 188 188 189 189 if (cStatus) { 190 log Msg("ERROR:Failed in writing primary header.");190 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "Failed in writing primary header."); 191 191 return cStatus; 192 192 } … … 198 198 if (fits_create_tbl(cSDptr, BINARY_TBL, nrow, ncol, NULL, NULL, NULL, 199 199 "SINGLE DISH", &cStatus)) { 200 log Msg("ERROR:Failed to create a binary table extension.");200 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "Failed to create a binary table extension."); 201 201 return 1; 202 202 } … … 548 548 549 549 if (cStatus) { 550 log Msg("ERROR:Failed in writing binary table header.");550 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "Failed in writing binary table header."); 551 551 } 552 552 … … 560 560 int SDFITSwriter::write(MBrecord &mbrec) 561 561 { 562 const string methodName = "write()" ; 563 LogIO os( LogOrigin( className, methodName, WHERE ) ) ; 564 562 565 char *cptr; 563 566 … … 565 568 int IFno = mbrec.IFno[0]; 566 569 if (IFno < 1 || cNIF < IFno) { 567 cerr << "SDFITSwriter::write: " 568 << "Invalid IF number " << IFno 569 << " (maximum " << cNIF << ")." << endl; 570 os << LogIO::WARN 571 << "SDFITSwriter::write: " 572 << "Invalid IF number " << IFno 573 << " (maximum " << cNIF << ")." << LogIO::POST ; 570 574 return 1; 571 575 } … … 574 578 int nChan = cNChan[iIF]; 575 579 if (mbrec.nChan[0] != nChan) { 576 cerr << "SDFITSriter::write: " 577 << "Wrong number of channels for IF " << IFno << "," << endl 578 << " " 579 << "got " << nChan << " should be " << mbrec.nChan[0] << "." << endl; 580 os << LogIO::WARN 581 << "SDFITSriter::write: " 582 << "Wrong number of channels for IF " << IFno << "," << endl 583 << " " 584 << "got " << nChan << " should be " << mbrec.nChan[0] << "." << endl; 585 os << LogIO::POST ; 580 586 return 1; 581 587 } … … 583 589 int nPol = cNPol[iIF]; 584 590 if (mbrec.nPol[0] != nPol) { 585 cerr << "SDFITSriter::write: " 586 << "Wrong number of polarizations for IF " << IFno << "," << endl 587 << " " 588 << "got " << nPol << " should be " << mbrec.nPol[0] << "." << endl; 591 os << LogIO::WARN 592 << "SDFITSriter::write: " 593 << "Wrong number of polarizations for IF " << IFno << "," << endl 594 << " " 595 << "got " << nPol << " should be " << mbrec.nPol[0] << "." << endl; 596 os << LogIO::POST ; 589 597 return 1; 590 598 } … … 768 776 769 777 if (cStatus) { 770 log Msg("ERROR:Failed in writing binary table entry.");778 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "Failed in writing binary table entry."); 771 779 } 772 780 … … 782 790 783 791 { 792 const string methodName = "history()" ; 793 784 794 if (!cSDptr) { 785 795 return 1; … … 787 797 788 798 if (fits_write_history(cSDptr, text, &cStatus)) { 789 log Msg("ERROR:Failed in writing HISTORY records.");799 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "Failed in writing HISTORY records."); 790 800 } 791 801 … … 799 809 void SDFITSwriter::close() 800 810 { 811 const string methodName = "close()" ; 812 801 813 if (cSDptr) { 802 814 cStatus = 0; 803 815 if (fits_close_file(cSDptr, &cStatus)) { 804 log Msg("ERROR:Failed to close file.");816 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "Failed to close file."); 805 817 } 806 818 … … 815 827 void SDFITSwriter::deleteFile() 816 828 { 829 const string methodName = "deleteFile()" ; 830 817 831 if (cSDptr) { 818 832 cStatus = 0; 819 833 if (fits_delete_file(cSDptr, &cStatus)) { 820 log Msg("ERROR:Failed to close and delete file.");834 log(LogOrigin( className, methodName, WHERE ), LogIO::SEVERE, "Failed to close and delete file."); 821 835 } 822 836 … … 825 839 } 826 840 827 //------------------------------------------------------- SDFITSwriter::log Msg841 //------------------------------------------------------- SDFITSwriter::log 828 842 829 843 // Log a message. If the current CFITSIO status value is non-zero, also log 830 844 // the corresponding error message and dump the CFITSIO message stack. 831 845 832 void SDFITSwriter::log Msg(const char *msg)846 void SDFITSwriter::log(LogOrigin origin, LogIO::Command cmd, const char *msg) 833 847 { 834 PKSmsg::logMsg(msg); 848 LogIO os( origin ) ; 849 850 os << cmd << msg << endl ; 835 851 836 852 if (cStatus) { 837 853 fits_get_errstatus(cStatus, cMsg); 838 PKSmsg::logMsg(cMsg);854 os << cMsg << endl ; 839 855 840 856 while (fits_read_errmsg(cMsg)) { 841 PKSmsg::logMsg(cMsg); 842 } 843 } 857 os << cMsg << endl ; 858 } 859 } 860 861 os << LogIO::POST ; 844 862 } -
branches/mergetest/external/atnf/PKSIO/SDFITSwriter.h
r1720 r1779 38 38 39 39 #include <atnf/PKSIO/MBrecord.h> 40 #include < atnf/PKSIO/PKSmsg.h>40 #include <casa/Logging/LogIO.h> 41 41 42 42 #include <fitsio.h> 43 43 44 44 using namespace std; 45 using namespace casa; 45 46 46 47 // <summary> … … 48 49 // </summary> 49 50 50 class SDFITSwriter : public PKSmsg51 class SDFITSwriter 51 52 { 52 53 public: … … 95 96 // Message handling. 96 97 char cMsg[256]; 97 v irtual void logMsg(const char *msg = 0x0);98 void log(LogOrigin origin, LogIO::Command cmd, const char *msg = 0x0); 98 99 }; 99 100 -
branches/mergetest/external/atnf/PKSIO/makefile
r1452 r1779 1 # $Id : makefile,v 19.0 2003-07-16 03:34:05 aips2adm Exp$1 # $Id$ 2 2 3 3 XLIBLIST := CFITSIO RPFITS … … 5 5 # Use the generic AIPS++ class implementation makefile. 6 6 #------------------------------------------------------ 7 include $(word 1, $( AIPSPATH))/code/install/makefile.imp7 include $(word 1, $(CASAPATH))/code/install/makefile.imp -
branches/mergetest/external/atnf/pks/makefile
r1452 r1779 1 # $Id : makefile,v 19.0 2003-07-16 03:33:47 aips2adm Exp$1 # $Id$ 2 2 3 3 # Use the generic AIPS++ class implementation makefile. 4 4 #------------------------------------------------------ 5 include $(word 1, $( AIPSPATH))/code/install/makefile.imp5 include $(word 1, $(CASAPATH))/code/install/makefile.imp -
branches/mergetest/external/atnf/pks/pks_maths.cc
r1720 r1779 321 321 322 322 // Azimuth and elevation (rad). 323 az = atan2(-cos(dec)*sin(ha), 324 sin(dec)*cos(lat) - cos(dec)*sin(lat)*cos(ha)); 323 az = atan2(cos(dec)*sin(ha), 324 cos(dec)*sin(lat)*cos(ha) - sin(dec)*cos(lat)); 325 if (az < 0.0) az += C::_2pi; 325 326 el = asin(sin(dec)*sin(lat) + cos(dec)*cos(lat)*cos(ha)); 326 327 327 if (az < 0.0) az += C::_2pi;328 328 } 329 329 -
branches/mergetest/python/__init__.py
r1739 r1779 9 9 from asap.compatibility import wraps as wraps_dec 10 10 11 # Set up AIPSPATH and first time use of asap i.e. ~/.asap/*11 # Set up CASAPATH and first time use of asap i.e. ~/.asap/* 12 12 plf = None 13 13 if sys.platform == "linux2": … … 26 26 if os.path.exists(os.environ["ASAPDATA"]): 27 27 asapdata = os.environ["ASAPDATA"] 28 # use AIPSPATH if defined and "data" dir present29 if not os.environ.has_key(" AIPSPATH") or \30 not os.path.exists(os.environ[" AIPSPATH"].split()[0]+"/data"):31 os.environ[" AIPSPATH"] = "%s %s somwhere" % ( asapdata, plf)28 # use CASAPATH if defined and "data" dir present 29 if not os.environ.has_key("CASAPATH") or \ 30 not os.path.exists(os.environ["CASAPATH"].split()[0]+"/data"): 31 os.environ["CASAPATH"] = "%s %s somwhere" % ( asapdata, plf) 32 32 # set up user space 33 33 userdir = os.environ["HOME"]+"/.asap" … … 35 35 print 'First time ASAP use. Setting up ~/.asap' 36 36 os.mkdir(userdir) 37 shutil.copyfile(asapdata+"/data/ipythonrc-asap", userdir+"/ipythonrc-asap") 38 shutil.copyfile(asapdata+"/data/ipy_user_conf.py", 39 userdir+"/ipy_user_conf.py") 37 #shutil.copyfile(asapdata+"/data/ipythonrc-asap", userdir+"/ipythonrc-asap") 38 # commented out by TT on 2009.06.23 for casapy use 39 ##shutil.copyfile(asapdata+"/data/ipy_user_conf.py", 40 ## userdir+"/ipy_user_conf.py") 40 41 f = file(userdir+"/asapuserfuncs.py", "w") 41 42 f.close() 42 43 f = file(userdir+"/ipythonrc", "w") 43 44 f.close() 44 else: 45 # commented out by TT on 2009.06.23 for casapy use 46 ##else: 45 47 # upgrade to support later ipython versions 46 if not os.path.exists(userdir+"/ipy_user_conf.py"):47 shutil.copyfile(asapdata+"/data/ipy_user_conf.py",48 userdir+"/ipy_user_conf.py")48 ##if not os.path.exists(userdir+"/ipy_user_conf.py"): 49 ## shutil.copyfile(asapdata+"/data/ipy_user_conf.py", 50 ## userdir+"/ipy_user_conf.py") 49 51 50 52 # remove from namespace … … 110 112 'plotter.histogram' : [False, _validate_bool], 111 113 'plotter.papertype' : ['A4', str], 112 'plotter.axesformatting' : ['mpl', str], 114 ## for older Matplotlib version 115 #'plotter.axesformatting' : ['mpl', str], 116 'plotter.axesformatting' : ['asap', str], 113 117 114 118 # scantable … … 218 222 tup = line.split(':',1) 219 223 if len(tup) !=2: 220 print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname)) 224 #print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname)) 225 asaplog.push('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname)) 226 print_log('WARN') 221 227 continue 222 228 … … 224 230 key = key.strip() 225 231 if not defaultParams.has_key(key): 226 print ('Bad key "%s" on line %d in %s' % (key, cnt, fname)) 232 #print ('Bad key "%s" on line %d in %s' % (key, cnt, fname)) 233 asaplog.push('Bad key "%s" on line %d in %s' % (key, cnt, fname)) 234 print_log('WARN') 227 235 continue 228 236 … … 234 242 try: cval = converter(val) # try to convert to proper type or raise 235 243 except ValueError, msg: 236 print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg)) 244 #print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg)) 245 asaplog.push('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, str(msg))) 246 print_log('WARN') 237 247 continue 238 248 else: … … 366 376 return wrap_it 367 377 368 def print_log(): 369 log = asaplog.pop().strip() 370 if len(log) and rcParams['verbose']: print log 378 def print_log(level='INFO'): 379 from taskinit import casalog 380 log = asaplog.pop() 381 #if len(log) and rcParams['verbose']: print log 382 if len(log) and rcParams['verbose']: casalog.post( log, priority=level ) 371 383 return 372 384 … … 391 403 from simplelinefinder import simplelinefinder 392 404 from linecatalog import linecatalog 405 from interactivemask import interactivemask 393 406 from opacity import skydip 394 407 from opacity import model as opacity_model … … 400 413 if gui: 401 414 import matplotlib 402 matplotlib.use("TkAgg")415 if not matplotlib.sys.modules['matplotlib.backends']: matplotlib.use("TkAgg") 403 416 from matplotlib import pylab 404 417 xyplotter = pylab … … 406 419 del gui 407 420 except ImportError: 408 print "Matplotlib not installed. No plotting available" 421 #print "Matplotlib not installed. No plotting available" 422 asaplog.post( "Matplotlib not installed. No plotting available") 423 print_log('WARN') 409 424 410 425 __date__ = '$Date$'.split()[1] 411 __version__ = '$Revision$' 426 __version__ = '3.0.0 alma' 427 # nrao casapy specific, get revision number 428 #__revision__ = ' unknown ' 429 casapath=os.environ["CASAPATH"].split() 430 #svninfo.txt path 431 if os.path.isdir(casapath[0]+'/'+casapath[1]+'/python/2.5/asap'): 432 # for casa developer environment (linux or darwin) 433 revinfo=casapath[0]+'/'+casapath[1]+'/python/2.5/asap/svninfo.txt' 434 else: 435 # for end-user environments 436 if casapath[1]=='darwin': 437 revinfo=casapath[0]+'/Resources/python/asap/svninfo.txt' 438 else: 439 revinfo=casapath[0]+'/lib/python2.5/asap/svninfo.txt' 440 if os.path.isfile(revinfo): 441 f = file(revinfo) 442 f.readline() 443 revsionno=f.readline() 444 f.close() 445 del f 446 __revision__ = revsionno.rstrip() 447 else: 448 __revision__ = ' unknown ' 412 449 413 450 def is_ipython(): 414 451 return 'IPython' in sys.modules.keys() 415 416 452 if is_ipython(): 417 453 def version(): print "ASAP %s(%s)"% (__version__, __date__) -
branches/mergetest/python/asapfitter.py
r1739 r1779 1 1 import _asap 2 2 from asap import rcParams 3 from asap import print_log _dec3 from asap import print_log, print_log_dec 4 4 from asap import _n_bools 5 5 from asap import mask_and 6 from asap import asaplog 6 7 7 8 class fitter: … … 59 60 msg = "Please give a correct scan" 60 61 if rcParams['verbose']: 61 print msg 62 #print msg 63 asaplog.push(msg) 64 print_log('ERROR') 62 65 return 63 66 else: … … 79 82 lpoly: use polynomial of the order given with linear least squares fit 80 83 gauss: fit the number of gaussian specified 84 lorentz: fit the number of lorentzian specified 81 85 Example: 82 fitter.set_function(gauss=2) # will fit two gaussians83 86 fitter.set_function(poly=3) # will fit a 3rd order polynomial via nonlinear method 84 87 fitter.set_function(lpoly=3) # will fit a 3rd order polynomial via linear method 88 fitter.set_function(gauss=2) # will fit two gaussians 89 fitter.set_function(lorentz=2) # will fit two lorentzians 85 90 """ 86 91 #default poly order 0 … … 102 107 self.components = [ 3 for i in range(n) ] 103 108 self.uselinear = False 109 elif kwargs.has_key('lorentz'): 110 n = kwargs.get('lorentz') 111 self.fitfunc = 'lorentz' 112 self.fitfuncs = [ 'lorentz' for i in range(n) ] 113 self.components = [ 3 for i in range(n) ] 114 self.uselinear = False 104 115 else: 105 116 msg = "Invalid function type." 106 117 if rcParams['verbose']: 107 print msg 118 #print msg 119 asaplog.push(msg) 120 print_log('ERROR') 108 121 return 109 122 else: … … 114 127 return 115 128 116 @print_log_dec129 #@print_log_dec 117 130 def fit(self, row=0, estimate=False): 118 131 """ … … 135 148 msg = "Fitter not yet initialised. Please set data & fit function" 136 149 if rcParams['verbose']: 137 print msg 150 #print msg 151 asaplog.push(msg) 152 print_log('ERROR') 138 153 return 139 154 else: … … 145 160 self.y = self.data._getspectrum(row) 146 161 self.mask = mask_and(self.mask, self.data._getmask(row)) 147 from asap import asaplog148 162 asaplog.push("Fitting:") 149 163 i = row … … 155 169 asaplog.push(out,False) 156 170 self.fitter.setdata(self.x, self.y, self.mask) 157 if self.fitfunc == 'gauss' :171 if self.fitfunc == 'gauss' or self.fitfunc == 'lorentz': 158 172 ps = self.fitter.getparameters() 159 173 if len(ps) == 0 or estimate: … … 171 185 except RuntimeError, msg: 172 186 if rcParams['verbose']: 173 print msg 187 #print msg 188 print_log() 189 asaplog.push(str(msg)) 190 print_log('ERROR') 174 191 else: 175 192 raise 176 193 self._fittedrow = row 177 194 self.fitted = True 195 print_log() 178 196 return 179 197 … … 204 222 self.data._addfit(fit,self._fittedrow) 205 223 206 @print_log_dec224 #@print_log_dec 207 225 def set_parameters(self,*args,**kwargs): 208 226 """ … … 228 246 msg = "Please specify a fitting function first." 229 247 if rcParams['verbose']: 230 print msg 248 #print msg 249 asaplog.push(msg) 250 print_log('ERROR') 231 251 return 232 252 else: 233 253 raise RuntimeError(msg) 234 if self.fitfunc == "gauss"and component is not None:254 if (self.fitfunc == "gauss" or self.fitfunc == 'lorentz') and component is not None: 235 255 if not self.fitted and sum(self.fitter.getparameters()) == 0: 236 256 pars = _n_bools(len(self.components)*3, False) … … 247 267 if fixed is not None: 248 268 self.fitter.setfixedparameters(fixed) 269 print_log() 249 270 return 250 271 … … 269 290 msg = "Function only operates on Gaussian components." 270 291 if rcParams['verbose']: 271 print msg 292 #print msg 293 asaplog.push(msg) 294 print_log('ERROR') 272 295 return 273 296 else: … … 280 303 msg = "Please select a valid component." 281 304 if rcParams['verbose']: 282 print msg 305 #print msg 306 asaplog.push(msg) 307 print_log('ERROR') 283 308 return 284 309 else: 285 310 raise ValueError(msg) 286 311 312 def set_lorentz_parameters(self, peak, centre, fwhm, 313 peakfixed=0, centrefixed=0, 314 fwhmfixed=0, 315 component=0): 316 """ 317 Set the Parameters of a 'Lorentzian' component, set with set_function. 318 Parameters: 319 peak, centre, fwhm: The gaussian parameters 320 peakfixed, 321 centrefixed, 322 fwhmfixed: Optional parameters to indicate if 323 the paramters should be held fixed during 324 the fitting process. The default is to keep 325 all parameters flexible. 326 component: The number of the component (Default is the 327 component 0) 328 """ 329 if self.fitfunc != "lorentz": 330 msg = "Function only operates on Lorentzian components." 331 if rcParams['verbose']: 332 #print msg 333 asaplog.push(msg) 334 print_log('ERROR') 335 return 336 else: 337 raise ValueError(msg) 338 if 0 <= component < len(self.components): 339 d = {'params':[peak, centre, fwhm], 340 'fixed':[peakfixed, centrefixed, fwhmfixed]} 341 self.set_parameters(d, component) 342 else: 343 msg = "Please select a valid component." 344 if rcParams['verbose']: 345 #print msg 346 asaplog.push(msg) 347 print_log('ERROR') 348 return 349 else: 350 raise ValueError(msg) 351 287 352 def get_area(self, component=None): 288 353 """ 289 Return the area under the fitted gaussian component.290 Parameters: 291 component: the gaussian component selection,354 Return the area under the fitted gaussian/lorentzian component. 355 Parameters: 356 component: the gaussian/lorentzian component selection, 292 357 default (None) is the sum of all components 293 358 Note: 294 This will only work for gaussian fits.359 This will only work for gaussian/lorentzian fits. 295 360 """ 296 361 if not self.fitted: return 297 if self.fitfunc == "gauss" :362 if self.fitfunc == "gauss" or self.fitfunc == "lorentz": 298 363 pars = list(self.fitter.getparameters()) 299 364 from math import log,pi,sqrt 300 fac = sqrt(pi/log(16.0)) 365 if self.fitfunc == "gauss": 366 fac = sqrt(pi/log(16.0)) 367 elif self.fitfunc == "lorentz": 368 fac = pi/2.0 301 369 areas = [] 302 370 for i in range(len(self.components)): … … 321 389 msg = "Not yet fitted." 322 390 if rcParams['verbose']: 323 print msg 391 #print msg 392 asaplog.push(msg) 393 print_log('ERROR') 324 394 return 325 395 else: … … 328 398 cerrs = errs 329 399 if component is not None: 330 if self.fitfunc == "gauss" :400 if self.fitfunc == "gauss" or self.fitfunc == "lorentz": 331 401 i = 3*component 332 402 if i < len(errs): … … 344 414 msg = "Not yet fitted." 345 415 if rcParams['verbose']: 346 print msg 416 #print msg 417 asaplog.push(msg) 418 print_log('ERROR') 347 419 return 348 420 else: … … 353 425 area = [] 354 426 if component is not None: 355 if self.fitfunc == "gauss" :427 if self.fitfunc == "gauss" or self.fitfunc == "lorentz": 356 428 i = 3*component 357 429 cpars = pars[i:i+3] … … 368 440 cfixed = fixed 369 441 cerrs = errs 370 if self.fitfunc == "gauss" :442 if self.fitfunc == "gauss" or self.fitfunc == "lorentz": 371 443 for c in range(len(self.components)): 372 444 a = self.get_area(c) … … 374 446 fpars = self._format_pars(cpars, cfixed, errors and cerrs, area) 375 447 if rcParams['verbose']: 376 print fpars 448 #print fpars 449 asaplog.push(fpars) 450 print_log() 377 451 return {'params':cpars, 'fixed':cfixed, 'formatted': fpars, 378 452 'errors':cerrs} … … 391 465 c+=1 392 466 out = out[:-1] # remove trailing ',' 393 elif self.fitfunc == 'gauss' :467 elif self.fitfunc == 'gauss' or self.fitfunc == 'lorentz': 394 468 i = 0 395 469 c = 0 … … 415 489 fixed = self.fitter.getfixedparameters() 416 490 if rcParams['verbose']: 417 print self._format_pars(pars,fixed,None) 491 #print self._format_pars(pars,fixed,None) 492 asaplog.push(self._format_pars(pars,fixed,None)) 493 print_log() 418 494 return pars 419 495 … … 425 501 msg = "Not yet fitted." 426 502 if rcParams['verbose']: 427 print msg 503 #print msg 504 asaplog.push(msg) 505 print_log('ERROR') 428 506 return 429 507 else: … … 438 516 msg = "Not yet fitted." 439 517 if rcParams['verbose']: 440 print msg 518 #print msg 519 asaplog.push(msg) 520 print_log('ERROR') 441 521 return 442 522 else: … … 444 524 ch2 = self.fitter.getchi2() 445 525 if rcParams['verbose']: 446 print 'Chi^2 = %3.3f' % (ch2) 526 #print 'Chi^2 = %3.3f' % (ch2) 527 asaplog.push( 'Chi^2 = %3.3f' % (ch2) ) 528 print_log() 447 529 return ch2 448 530 … … 454 536 msg = "Not yet fitted." 455 537 if rcParams['verbose']: 456 print msg 538 #print msg 539 asaplog.push(msg) 540 print_log('ERROR') 457 541 return 458 542 else: … … 460 544 return self.fitter.getfit() 461 545 462 @print_log_dec546 #@print_log_dec 463 547 def commit(self): 464 548 """ … … 468 552 msg = "Not yet fitted." 469 553 if rcParams['verbose']: 470 print msg 554 #print msg 555 asaplog.push(msg) 556 print_log('ERROR') 471 557 return 472 558 else: … … 476 562 msg = "Not a scantable" 477 563 if rcParams['verbose']: 478 print msg 564 #print msg 565 asaplog.push(msg) 566 print_log('ERROR') 479 567 return 480 568 else: … … 482 570 scan = self.data.copy() 483 571 scan._setspectrum(self.fitter.getresidual()) 572 print_log() 484 573 return scan 485 574 486 @print_log_dec575 #@print_log_dec 487 576 def plot(self, residual=False, components=None, plotparms=False, 488 577 filename=None): … … 525 614 526 615 colours = ["#777777","#dddddd","red","orange","purple","green","magenta", "cyan"] 616 nomask=True 617 for i in range(len(m)): 618 nomask = nomask and m[i] 619 label0='Masked Region' 620 label1='Spectrum' 621 if ( nomask ): 622 label0=label1 623 else: 624 y = ma.masked_array( self.y, mask = m ) 625 self._p.palette(1,colours) 626 self._p.set_line( label = label1 ) 627 self._p.plot( self.x, y ) 527 628 self._p.palette(0,colours) 528 self._p.set_line(label= 'Spectrum')629 self._p.set_line(label=label0) 529 630 y = ma.masked_array(self.y,mask=logical_not(m)) 530 631 self._p.plot(self.x, y) 531 632 if residual: 532 self._p.palette( 1)633 self._p.palette(7) 533 634 self._p.set_line(label='Residual') 534 635 y = ma.masked_array(self.get_residual(), … … 571 672 if (not rcParams['plotter.gui']): 572 673 self._p.save(filename) 573 574 @print_log_dec 674 print_log() 675 676 #@print_log_dec 575 677 def auto_fit(self, insitu=None, plot=False): 576 678 """ … … 583 685 msg = "Data is not a scantable" 584 686 if rcParams['verbose']: 585 print msg 687 #print msg 688 asaplog.push(msg) 689 print_log('ERROR') 586 690 return 587 691 else: … … 593 697 scan = self.data 594 698 rows = xrange(scan.nrow()) 595 from asap import asaplog 699 # Save parameters of baseline fits as a class attribute. 700 # NOTICE: This does not reflect changes in scantable! 701 if len(rows) > 0: self.blpars=[] 596 702 asaplog.push("Fitting:") 597 703 for r in rows: … … 608 714 self.fit() 609 715 x = self.get_parameters() 716 fpar = self.get_parameters() 610 717 if plot: 611 718 self.plot(residual=True) 612 719 x = raw_input("Accept fit ([y]/n): ") 613 720 if x.upper() == 'N': 721 self.blpars.append(None) 614 722 continue 615 723 scan._setspectrum(self.fitter.getresidual(), r) 724 self.blpars.append(fpar) 616 725 if plot: 617 726 self._p.unmap() 618 727 self._p = None 728 print_log() 619 729 return scan -
branches/mergetest/python/asaplot.py
r1564 r1779 6 6 7 7 from matplotlib.backends.backend_agg import FigureCanvasAgg 8 from matplotlib.backend_bases import FigureManagerBase 8 9 9 10 class asaplot(asaplotbase): … … 22 23 asaplotbase.__init__(self,**v) 23 24 self.canvas = FigureCanvasAgg(self.figure) 25 self.figmgr = FigureManagerBase(self.canvas,1) -
branches/mergetest/python/asaplotbase.py
r1739 r1779 21 21 from matplotlib.transforms import blend_xy_sep_transform as blended_transform_factory 22 22 23 from asap import asaplog 24 23 25 if int(matplotlib.__version__.split(".")[1]) < 87: 24 print "Warning: matplotlib version < 0.87. This might cause errors. Please upgrade." 26 #print "Warning: matplotlib version < 0.87. This might cause errors. Please upgrade." 27 asaplog.push( "matplotlib version < 0.87. This might cause errors. Please upgrade." ) 28 print_log( 'WARN' ) 25 29 26 30 class asaplotbase: … … 147 151 from numpy import array 148 152 from numpy.ma import MaskedArray 149 150 153 if x is None: 151 154 if y is None: return … … 168 171 ymsk = y.mask 169 172 ydat = y.data 170 171 173 for i in range(l2): 172 174 x2[i] = x[i/2] … … 280 282 281 283 282 def get_region(self):283 pos = []284 print "Please select the bottom/left point"285 pos.append(self.figure.ginput(n=1, show_clicks=False)[0])286 print "Please select the top/right point"287 pos.append(self.figure.ginput(n=1, show_clicks=False)[0])288 return pos289 290 def get_point(self):291 print "Please select the point"292 pt = self.figure.ginput(n=1, show_clicks=False)293 if pt:294 return pt[0]295 else:296 return None284 # def get_region(self): 285 # pos = [] 286 # print "Please select the bottom/left point" 287 # pos.append(self.figure.ginput(n=1, show_clicks=False)[0]) 288 # print "Please select the top/right point" 289 # pos.append(self.figure.ginput(n=1, show_clicks=False)[0]) 290 # return pos 291 292 # def get_point(self): 293 # print "Please select the point" 294 # pt = self.figure.ginput(n=1, show_clicks=False) 295 # if pt: 296 # return pt[0] 297 # else: 298 # return None 297 299 298 300 def region(self): … … 304 306 305 307 def region_start(event): 306 height = self.canvas.figure.bbox.height() 307 self.rect = {'fig': None, 'height': height, 308 'x': event.x, 'y': height - event.y, 308 self.rect = {'x': event.x, 'y': event.y, 309 309 'world': [event.xdata, event.ydata, 310 310 event.xdata, event.ydata]} … … 314 314 315 315 def region_draw(event): 316 self.canvas._tkcanvas.delete(self.rect['fig']) 317 self.rect['fig'] = self.canvas._tkcanvas.create_rectangle( 318 self.rect['x'], self.rect['y'], 319 event.x, self.rect['height'] - event.y) 320 316 self.figmgr.toolbar.draw_rubberband(event, event.x, event.y, 317 self.rect['x'], self.rect['y']) 318 321 319 def region_disable(event): 322 320 self.register('motion_notify', None) 323 321 self.register('button_release', None) 324 325 self.canvas._tkcanvas.delete(self.rect['fig'])326 322 327 323 self.rect['world'][2:4] = [event.xdata, event.ydata] … … 329 325 self.rect['world'][1], self.rect['world'][2], 330 326 self.rect['world'][3]) 327 self.figmgr.toolbar.release(event) 331 328 332 329 self.register('button_press', region_start) … … 381 378 self.events[type] = None 382 379 383 # It seems to be necessary to return events to the toolbar. 384 if type == 'motion_notify':385 self.canvas.mpl_connect(type + '_event',386 self.figmgr.toolbar.mouse_move)387 elif type == 'button_press':388 self.canvas.mpl_connect(type + '_event',389 self.figmgr.toolbar.press)390 elif type == 'button_release':391 self.canvas.mpl_connect(type + '_event',392 self.figmgr.toolbar.release)380 # It seems to be necessary to return events to the toolbar. <-- Not ture. 2010.Jul.14.kana. 381 #if type == 'motion_notify': 382 # self.canvas.mpl_connect(type + '_event', 383 # self.figmgr.toolbar.mouse_move) 384 #elif type == 'button_press': 385 # self.canvas.mpl_connect(type + '_event', 386 # self.figmgr.toolbar.press) 387 #elif type == 'button_release': 388 # self.canvas.mpl_connect(type + '_event', 389 # self.figmgr.toolbar.release) 393 390 394 391 else: … … 459 456 print 'Written file %s' % (fname) 460 457 except IOError, msg: 461 print 'Failed to save %s: Error msg was\n\n%s' % (fname, msg) 458 #print 'Failed to save %s: Error msg was\n\n%s' % (fname, err) 459 print_log() 460 asaplog.push('Failed to save %s: Error msg was\n\n%s' % (fname, str(msg))) 461 print_log( 'ERROR' ) 462 462 return 463 463 else: 464 print "Invalid image type. Valid types are:" 465 print "'ps', 'eps', 'png'" 464 #print "Invalid image type. Valid types are:" 465 #print "'ps', 'eps', 'png'" 466 asaplog.push( "Invalid image type. Valid types are:" ) 467 asaplog.push( "'ps', 'eps', 'png'" ) 468 print_log('WARN') 466 469 467 470 … … 575 578 576 579 577 def set_panels(self, rows=1, cols=0, n=-1, nplots=-1, ganged=True): 580 #def set_panels(self, rows=1, cols=0, n=-1, nplots=-1, ganged=True): 581 def set_panels(self, rows=1, cols=0, n=-1, nplots=-1, layout=None,ganged=True): 578 582 """ 579 583 Set the panel layout. … … 598 602 self.set_title() 599 603 604 if layout: 605 lef, bot, rig, top, wsp, hsp = layout 606 self.figure.subplots_adjust( 607 left=lef,bottom=bot,right=rig,top=top,wspace=wsp,hspace=hsp) 608 del lef,bot,rig,top,wsp,hsp 609 600 610 if rows < 1: rows = 1 601 611 … … 610 620 if 0 <= n < rows*cols: 611 621 i = len(self.subplots) 622 612 623 self.subplots.append({}) 613 624 … … 644 655 cols, i+1) 645 656 if asaprcParams['plotter.axesformatting'] != 'mpl': 646 657 647 658 self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter()) 648 659 else: … … 671 682 self.cols = cols 672 683 self.subplot(0) 684 del rows,cols,n,nplots,layout,ganged,i 673 685 674 686 def tidy(self): … … 725 737 sp['axes'].legend((' ')) 726 738 727 728 739 from matplotlib.artist import setp 729 740 fpx = FP(size=rcParams['xtick.labelsize']) … … 734 745 fpat = FP(size=rcParams['axes.titlesize']) 735 746 axsize = fpa.get_size_in_points() 736 tsize = fpat.get_size_in_points() 747 tsize = fpat.get_size_in_points()-(self.cols)/2 737 748 for sp in self.subplots: 738 749 ax = sp['axes'] 739 off = 0 740 if len(self.subplots) > 1: 741 off = self.cols+self.rows 742 ax.title.set_size(tsize-off) 750 ax.title.set_size(tsize) 743 751 setp(ax.get_xticklabels(), fontsize=xts) 744 752 setp(ax.get_yticklabels(), fontsize=yts) 745 753 off = 0 746 if self.cols > 1: 747 off = self.cols 754 if self.cols > 1: off = self.cols 748 755 ax.xaxis.label.set_size(axsize-off) 749 if self.rows > 1:750 756 off = 0 757 if self.rows > 1: off = self.rows 751 758 ax.yaxis.label.set_size(axsize-off) 752 759 -
branches/mergetest/python/asaplotgui.py
r1563 r1779 56 56 self.window.lift() 57 57 58 def position(self):59 """60 Use the mouse to get a position from a graph.61 """62 63 def position_disable(event):64 self.register('button_press', None)65 print '%.4f, %.4f' % (event.xdata, event.ydata)66 67 print 'Press any mouse button...'68 self.register('button_press', position_disable)69 70 71 58 def quit(self): 72 59 """ … … 74 61 """ 75 62 self.window.destroy() 76 77 78 def region(self):79 """80 Use the mouse to get a rectangular region from a plot.81 82 The return value is [x0, y0, x1, y1] in world coordinates.83 """84 85 def region_start(event):86 height = self.canvas.figure.bbox.height()87 self.rect = {'fig': None, 'height': height,88 'x': event.x, 'y': height - event.y,89 'world': [event.xdata, event.ydata,90 event.xdata, event.ydata]}91 self.register('button_press', None)92 self.register('motion_notify', region_draw)93 self.register('button_release', region_disable)94 95 def region_draw(event):96 self.canvas._tkcanvas.delete(self.rect['fig'])97 self.rect['fig'] = self.canvas._tkcanvas.create_rectangle(98 self.rect['x'], self.rect['y'],99 event.x, self.rect['height'] - event.y)100 101 def region_disable(event):102 self.register('motion_notify', None)103 self.register('button_release', None)104 105 self.canvas._tkcanvas.delete(self.rect['fig'])106 107 self.rect['world'][2:4] = [event.xdata, event.ydata]108 print '(%.2f, %.2f) (%.2f, %.2f)' % (self.rect['world'][0],109 self.rect['world'][1], self.rect['world'][2],110 self.rect['world'][3])111 112 self.register('button_press', region_start)113 114 # This has to be modified to block and return the result (currently115 # printed by region_disable) when that becomes possible in matplotlib.116 117 return [0.0, 0.0, 0.0, 0.0]118 119 120 def register(self, type=None, func=None):121 """122 Register, reregister, or deregister events of type 'button_press',123 'button_release', or 'motion_notify'.124 125 The specified callback function should have the following signature:126 127 def func(event)128 129 where event is an MplEvent instance containing the following data:130 131 name # Event name.132 canvas # FigureCanvas instance generating the event.133 x = None # x position - pixels from left of canvas.134 y = None # y position - pixels from bottom of canvas.135 button = None # Button pressed: None, 1, 2, 3.136 key = None # Key pressed: None, chr(range(255)), shift,137 win, or control138 inaxes = None # Axes instance if cursor within axes.139 xdata = None # x world coordinate.140 ydata = None # y world coordinate.141 142 For example:143 144 def mouse_move(event):145 print event.xdata, event.ydata146 147 a = asaplot()148 a.register('motion_notify', mouse_move)149 150 If func is None, the event is deregistered.151 152 Note that in TkAgg keyboard button presses don't generate an event.153 """154 155 if not self.events.has_key(type): return156 157 if func is None:158 if self.events[type] is not None:159 # It's not clear that this does anything.160 self.canvas.mpl_disconnect(self.events[type])161 self.events[type] = None162 163 # It seems to be necessary to return events to the toolbar.164 if type == 'motion_notify':165 self.canvas.mpl_connect(type + '_event',166 self.figmgr.toolbar.mouse_move)167 elif type == 'button_press':168 self.canvas.mpl_connect(type + '_event',169 self.figmgr.toolbar.press)170 elif type == 'button_release':171 self.canvas.mpl_connect(type + '_event',172 self.figmgr.toolbar.release)173 174 else:175 self.events[type] = self.canvas.mpl_connect(type + '_event', func)176 177 63 178 64 def show(self, hardrefresh=True): -
branches/mergetest/python/asaplotgui_gtk.py
r1563 r1779 57 57 #self.window.lift() 58 58 59 def position(self):60 """61 Use the mouse to get a position from a graph.62 """63 64 def position_disable(event):65 self.register('button_press', None)66 print '%.4f, %.4f' % (event.xdata, event.ydata)67 68 print 'Press any mouse button...'69 self.register('button_press', position_disable)59 # def position(self): 60 # """ 61 # Use the mouse to get a position from a graph. 62 # """ 63 64 # def position_disable(event): 65 # self.register('button_press', None) 66 # print '%.4f, %.4f' % (event.xdata, event.ydata) 67 68 # print 'Press any mouse button...' 69 # self.register('button_press', position_disable) 70 70 71 71 … … 77 77 78 78 79 def region(self):80 """81 Use the mouse to get a rectangular region from a plot.82 83 The return value is [x0, y0, x1, y1] in world coordinates.84 """85 86 def region_start(event):87 height = self.canvas.figure.bbox.height()88 self.rect = {'fig': None, 'height': height,89 'x': event.x, 'y': height - event.y,90 'world': [event.xdata, event.ydata,91 event.xdata, event.ydata]}92 self.register('button_press', None)93 self.register('motion_notify', region_draw)94 self.register('button_release', region_disable)95 96 def region_draw(event):97 self.canvas._tkcanvas.delete(self.rect['fig'])98 self.rect['fig'] = self.canvas._tkcanvas.create_rectangle(99 self.rect['x'], self.rect['y'],100 event.x, self.rect['height'] - event.y)101 102 def region_disable(event):103 self.register('motion_notify', None)104 self.register('button_release', None)105 106 self.canvas._tkcanvas.delete(self.rect['fig'])107 108 self.rect['world'][2:4] = [event.xdata, event.ydata]109 print '(%.2f, %.2f) (%.2f, %.2f)' % (self.rect['world'][0],110 self.rect['world'][1], self.rect['world'][2],111 self.rect['world'][3])112 113 self.register('button_press', region_start)114 115 # This has to be modified to block and return the result (currently116 # printed by region_disable) when that becomes possible in matplotlib.117 118 return [0.0, 0.0, 0.0, 0.0]119 120 121 def register(self, type=None, func=None):122 """123 Register, reregister, or deregister events of type 'button_press',124 'button_release', or 'motion_notify'.125 126 The specified callback function should have the following signature:127 128 def func(event)129 130 where event is an MplEvent instance containing the following data:131 132 name # Event name.133 canvas # FigureCanvas instance generating the event.134 x = None # x position - pixels from left of canvas.135 y = None # y position - pixels from bottom of canvas.136 button = None # Button pressed: None, 1, 2, 3.137 key = None # Key pressed: None, chr(range(255)), shift,138 win, or control139 inaxes = None # Axes instance if cursor within axes.140 xdata = None # x world coordinate.141 ydata = None # y world coordinate.142 143 For example:144 145 def mouse_move(event):146 print event.xdata, event.ydata147 148 a = asaplot()149 a.register('motion_notify', mouse_move)150 151 If func is None, the event is deregistered.152 153 Note that in TkAgg keyboard button presses don't generate an event.154 """155 156 if not self.events.has_key(type): return157 158 if func is None:159 if self.events[type] is not None:160 # It's not clear that this does anything.161 self.canvas.mpl_disconnect(self.events[type])162 self.events[type] = None163 164 # It seems to be necessary to return events to the toolbar.165 if type == 'motion_notify':166 self.canvas.mpl_connect(type + '_event',167 self.figmgr.toolbar.mouse_move)168 elif type == 'button_press':169 self.canvas.mpl_connect(type + '_event',170 self.figmgr.toolbar.press)171 elif type == 'button_release':172 self.canvas.mpl_connect(type + '_event',173 self.figmgr.toolbar.release)174 175 else:176 self.events[type] = self.canvas.mpl_connect(type + '_event', func)79 # def region(self): 80 # """ 81 # Use the mouse to get a rectangular region from a plot. 82 83 # The return value is [x0, y0, x1, y1] in world coordinates. 84 # """ 85 86 # def region_start(event): 87 # height = self.canvas.figure.bbox.height() 88 # self.rect = {'fig': None, 'height': height, 89 # 'x': event.x, 'y': height - event.y, 90 # 'world': [event.xdata, event.ydata, 91 # event.xdata, event.ydata]} 92 # self.register('button_press', None) 93 # self.register('motion_notify', region_draw) 94 # self.register('button_release', region_disable) 95 96 # def region_draw(event): 97 # self.canvas._tkcanvas.delete(self.rect['fig']) 98 # self.rect['fig'] = self.canvas._tkcanvas.create_rectangle( 99 # self.rect['x'], self.rect['y'], 100 # event.x, self.rect['height'] - event.y) 101 102 # def region_disable(event): 103 # self.register('motion_notify', None) 104 # self.register('button_release', None) 105 106 # self.canvas._tkcanvas.delete(self.rect['fig']) 107 108 # self.rect['world'][2:4] = [event.xdata, event.ydata] 109 # print '(%.2f, %.2f) (%.2f, %.2f)' % (self.rect['world'][0], 110 # self.rect['world'][1], self.rect['world'][2], 111 # self.rect['world'][3]) 112 113 # self.register('button_press', region_start) 114 115 # # This has to be modified to block and return the result (currently 116 # # printed by region_disable) when that becomes possible in matplotlib. 117 118 # return [0.0, 0.0, 0.0, 0.0] 119 120 121 # def register(self, type=None, func=None): 122 # """ 123 # Register, reregister, or deregister events of type 'button_press', 124 # 'button_release', or 'motion_notify'. 125 126 # The specified callback function should have the following signature: 127 128 # def func(event) 129 130 # where event is an MplEvent instance containing the following data: 131 132 # name # Event name. 133 # canvas # FigureCanvas instance generating the event. 134 # x = None # x position - pixels from left of canvas. 135 # y = None # y position - pixels from bottom of canvas. 136 # button = None # Button pressed: None, 1, 2, 3. 137 # key = None # Key pressed: None, chr(range(255)), shift, 138 # win, or control 139 # inaxes = None # Axes instance if cursor within axes. 140 # xdata = None # x world coordinate. 141 # ydata = None # y world coordinate. 142 143 # For example: 144 145 # def mouse_move(event): 146 # print event.xdata, event.ydata 147 148 # a = asaplot() 149 # a.register('motion_notify', mouse_move) 150 151 # If func is None, the event is deregistered. 152 153 # Note that in TkAgg keyboard button presses don't generate an event. 154 # """ 155 156 # if not self.events.has_key(type): return 157 158 # if func is None: 159 # if self.events[type] is not None: 160 # # It's not clear that this does anything. 161 # self.canvas.mpl_disconnect(self.events[type]) 162 # self.events[type] = None 163 164 # # It seems to be necessary to return events to the toolbar. 165 # if type == 'motion_notify': 166 # self.canvas.mpl_connect(type + '_event', 167 # self.figmgr.toolbar.mouse_move) 168 # elif type == 'button_press': 169 # self.canvas.mpl_connect(type + '_event', 170 # self.figmgr.toolbar.press) 171 # elif type == 'button_release': 172 # self.canvas.mpl_connect(type + '_event', 173 # self.figmgr.toolbar.release) 174 175 # else: 176 # self.events[type] = self.canvas.mpl_connect(type + '_event', func) 177 177 178 178 -
branches/mergetest/python/asapmath.py
r1591 r1779 1 1 from asap.scantable import scantable 2 2 from asap import rcParams 3 from asap import print_log _dec3 from asap import print_log, print_log_dec 4 4 from asap import selector 5 6 @print_log_dec 5 from asap import asaplog 6 from asap import asaplotgui 7 8 #@print_log_dec 7 9 def average_time(*args, **kwargs): 8 10 """ … … 46 48 if kwargs.has_key('align'): 47 49 align = kwargs.get('align') 50 compel = False 51 if kwargs.has_key('compel'): 52 compel = kwargs.get('compel') 48 53 varlist = vars() 49 54 if isinstance(args[0],list): … … 64 69 msg = "Please give a list of scantables" 65 70 if rcParams['verbose']: 66 print msg 71 #print msg 72 asaplog.push(msg) 73 print_log('ERROR') 67 74 return 68 75 else: … … 87 94 del merged 88 95 else: 89 s = scantable(stm._average(alignedlst, mask, weight.upper(), scanav)) 96 #s = scantable(stm._average(alignedlst, mask, weight.upper(), scanav)) 97 s = scantable(stm._new_average(alignedlst, compel, mask, weight.upper(), scanav)) 90 98 s._add_history("average_time",varlist) 99 print_log() 91 100 return s 92 101 … … 111 120 s = scantable(stm._quotient(source, reference, preserve)) 112 121 s._add_history("quotient",varlist) 122 print_log() 113 123 return s 114 124 115 @print_log_dec125 #@print_log_dec 116 126 def dototalpower(calon, caloff, tcalval=0.0): 117 127 """ … … 129 139 s = scantable(stm._dototalpower(calon, caloff, tcalval)) 130 140 s._add_history("dototalpower",varlist) 141 print_log() 131 142 return s 132 143 133 @print_log_dec144 #@print_log_dec 134 145 def dosigref(sig, ref, smooth, tsysval=0.0, tauval=0.0): 135 146 """ … … 149 160 s = scantable(stm._dosigref(sig, ref, smooth, tsysval, tauval)) 150 161 s._add_history("dosigref",varlist) 162 print_log() 151 163 return s 152 164 153 @print_log_dec154 def calps(scantab, scannos, smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0 ):165 #@print_log_dec 166 def calps(scantab, scannos, smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False): 155 167 """ 156 168 Calibrate GBT position switched data … … 176 188 varlist = vars() 177 189 # check for the appropriate data 178 s = scantab.get_scan('*_ps*') 179 if s is None: 190 ## s = scantab.get_scan('*_ps*') 191 ## if s is None: 192 ## msg = "The input data appear to contain no position-switch mode data." 193 ## if rcParams['verbose']: 194 ## #print msg 195 ## asaplog.push(msg) 196 ## print_log('ERROR') 197 ## return 198 ## else: 199 ## raise TypeError(msg) 200 s = scantab.copy() 201 from asap._asap import srctype 202 sel = selector() 203 sel.set_types( srctype.pson ) 204 try: 205 scantab.set_selection( sel ) 206 except Exception, e: 180 207 msg = "The input data appear to contain no position-switch mode data." 181 208 if rcParams['verbose']: 182 print msg 209 #print msg 210 asaplog.push(msg) 211 print_log('ERROR') 183 212 return 184 213 else: 185 214 raise TypeError(msg) 215 s.set_selection() 216 sel.reset() 186 217 ssub = s.get_scan(scannos) 187 218 if ssub is None: 188 219 msg = "No data was found with given scan numbers!" 189 220 if rcParams['verbose']: 190 print msg 221 #print msg 222 asaplog.push(msg) 223 print_log('ERROR') 191 224 return 192 225 else: 193 226 raise TypeError(msg) 194 ssubon = ssub.get_scan('*calon') 195 ssuboff = ssub.get_scan('*[^calon]') 227 #ssubon = ssub.get_scan('*calon') 228 #ssuboff = ssub.get_scan('*[^calon]') 229 sel.set_types( [srctype.poncal,srctype.poffcal] ) 230 ssub.set_selection( sel ) 231 ssubon = ssub.copy() 232 ssub.set_selection() 233 sel.reset() 234 sel.set_types( [srctype.pson,srctype.psoff] ) 235 ssub.set_selection( sel ) 236 ssuboff = ssub.copy() 237 ssub.set_selection() 238 sel.reset() 196 239 if ssubon.nrow() != ssuboff.nrow(): 197 240 msg = "mismatch in numbers of CAL on/off scans. Cannot calibrate. Check the scan numbers." 198 241 if rcParams['verbose']: 199 print msg 242 #print msg 243 asaplog.push(msg) 244 print_log('ERROR') 200 245 return 201 246 else: 202 247 raise TypeError(msg) 203 248 cals = dototalpower(ssubon, ssuboff, tcalval) 204 sig = cals.get_scan('*ps') 205 ref = cals.get_scan('*psr') 249 #sig = cals.get_scan('*ps') 250 #ref = cals.get_scan('*psr') 251 sel.set_types( srctype.pson ) 252 cals.set_selection( sel ) 253 sig = cals.copy() 254 cals.set_selection() 255 sel.reset() 256 sel.set_types( srctype.psoff ) 257 cals.set_selection( sel ) 258 ref = cals.copy() 259 cals.set_selection() 260 sel.reset() 206 261 if sig.nscan() != ref.nscan(): 207 262 msg = "mismatch in numbers of on/off scans. Cannot calibrate. Check the scan numbers." 208 263 if rcParams['verbose']: 209 print msg 264 #print msg 265 asaplog.push(msg) 266 print_log('ERROR') 210 267 return 211 268 else: … … 217 274 msg = "Need to supply a valid tau to use the supplied Tsys" 218 275 if rcParams['verbose']: 219 print msg 276 #print msg 277 asaplog.push(msg) 278 print_log('ERROR') 220 279 return 221 280 else: … … 236 295 #ress = dosigref(sig, ref, smooth, tsysval) 237 296 ress = dosigref(sig, ref, smooth, tsysval, tauval) 297 ### 298 if verify: 299 # get data 300 import numpy 301 precal={} 302 postcal=[] 303 keys=['ps','ps_calon','psr','psr_calon'] 304 types=[srctype.pson,srctype.poncal,srctype.psoff,srctype.poffcal] 305 ifnos=list(ssub.getifnos()) 306 polnos=list(ssub.getpolnos()) 307 sel=selector() 308 for i in range(2): 309 #ss=ssuboff.get_scan('*'+keys[2*i]) 310 ll=[] 311 for j in range(len(ifnos)): 312 for k in range(len(polnos)): 313 sel.set_ifs(ifnos[j]) 314 sel.set_polarizations(polnos[k]) 315 sel.set_types(types[2*i]) 316 try: 317 #ss.set_selection(sel) 318 ssuboff.set_selection(sel) 319 except: 320 continue 321 #ll.append(numpy.array(ss._getspectrum(0))) 322 ll.append(numpy.array(ssuboff._getspectrum(0))) 323 sel.reset() 324 ssuboff.set_selection() 325 precal[keys[2*i]]=ll 326 #del ss 327 #ss=ssubon.get_scan('*'+keys[2*i+1]) 328 ll=[] 329 for j in range(len(ifnos)): 330 for k in range(len(polnos)): 331 sel.set_ifs(ifnos[j]) 332 sel.set_polarizations(polnos[k]) 333 sel.set_types(types[2*i+1]) 334 try: 335 #ss.set_selection(sel) 336 ssubon.set_selection(sel) 337 except: 338 continue 339 #ll.append(numpy.array(ss._getspectrum(0))) 340 ll.append(numpy.array(ssubon._getspectrum(0))) 341 sel.reset() 342 ssubon.set_selection() 343 precal[keys[2*i+1]]=ll 344 #del ss 345 for j in range(len(ifnos)): 346 for k in range(len(polnos)): 347 sel.set_ifs(ifnos[j]) 348 sel.set_polarizations(polnos[k]) 349 try: 350 ress.set_selection(sel) 351 except: 352 continue 353 postcal.append(numpy.array(ress._getspectrum(0))) 354 sel.reset() 355 ress.set_selection() 356 del sel 357 # plot 358 print_log() 359 asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.') 360 print_log('WARN') 361 p=asaplotgui.asaplotgui() 362 #nr=min(6,len(ifnos)*len(polnos)) 363 nr=len(ifnos)*len(polnos) 364 titles=[] 365 btics=[] 366 if nr<4: 367 p.set_panels(rows=nr,cols=2,nplots=2*nr,ganged=False) 368 for i in range(2*nr): 369 b=False 370 if i >= 2*nr-2: 371 b=True 372 btics.append(b) 373 elif nr==4: 374 p.set_panels(rows=2,cols=4,nplots=8,ganged=False) 375 for i in range(2*nr): 376 b=False 377 if i >= 2*nr-4: 378 b=True 379 btics.append(b) 380 elif nr<7: 381 p.set_panels(rows=3,cols=4,nplots=2*nr,ganged=False) 382 for i in range(2*nr): 383 if i >= 2*nr-4: 384 b=True 385 btics.append(b) 386 else: 387 print_log() 388 asaplog.push('Only first 6 [if,pol] pairs are plotted.') 389 print_log('WARN') 390 nr=6 391 for i in range(2*nr): 392 b=False 393 if i >= 2*nr-4: 394 b=True 395 btics.append(b) 396 p.set_panels(rows=3,cols=4,nplots=2*nr,ganged=False) 397 for i in range(nr): 398 p.subplot(2*i) 399 p.color=0 400 title='raw data IF%s POL%s' % (ifnos[int(i/len(polnos))],polnos[i%len(polnos)]) 401 titles.append(title) 402 #p.set_axes('title',title,fontsize=40) 403 ymin=1.0e100 404 ymax=-1.0e100 405 nchan=s.nchan() 406 edge=int(nchan*0.01) 407 for j in range(4): 408 spmin=min(precal[keys[j]][i][edge:nchan-edge]) 409 spmax=max(precal[keys[j]][i][edge:nchan-edge]) 410 ymin=min(ymin,spmin) 411 ymax=max(ymax,spmax) 412 for j in range(4): 413 if i==0: 414 p.set_line(label=keys[j]) 415 else: 416 p.legend() 417 p.plot(precal[keys[j]][i]) 418 p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax)) 419 if not btics[2*i]: 420 p.axes.set_xticks([]) 421 p.subplot(2*i+1) 422 p.color=0 423 title='cal data IF%s POL%s' % (ifnos[int(i/len(polnos))],polnos[i%len(polnos)]) 424 titles.append(title) 425 #p.set_axes('title',title) 426 p.legend() 427 ymin=postcal[i][edge:nchan-edge].min() 428 ymax=postcal[i][edge:nchan-edge].max() 429 p.plot(postcal[i]) 430 p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax)) 431 if not btics[2*i+1]: 432 p.axes.set_xticks([]) 433 for i in range(2*nr): 434 p.subplot(i) 435 p.set_axes('title',titles[i],fontsize='medium') 436 x=raw_input('Accept calibration ([y]/n): ' ) 437 if x.upper() == 'N': 438 p.unmap() 439 del p 440 return scabtab 441 p.unmap() 442 del p 443 ### 238 444 ress._add_history("calps", varlist) 445 print_log() 239 446 return ress 240 447 241 @print_log_dec242 def calnod(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0 ):448 #@print_log_dec 449 def calnod(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False): 243 450 """ 244 451 Do full (but a pair of scans at time) processing of GBT Nod data … … 255 462 varlist = vars() 256 463 from asap._asap import stmath 464 from asap._asap import srctype 257 465 stm = stmath() 258 466 stm._setinsitu(False) 259 467 260 468 # check for the appropriate data 261 s = scantab.get_scan('*_nod*') 262 if s is None: 469 ## s = scantab.get_scan('*_nod*') 470 ## if s is None: 471 ## msg = "The input data appear to contain no Nod observing mode data." 472 ## if rcParams['verbose']: 473 ## #print msg 474 ## asaplog.push(msg) 475 ## print_log('ERROR') 476 ## return 477 ## else: 478 ## raise TypeError(msg) 479 s = scantab.copy() 480 sel = selector() 481 sel.set_types( srctype.nod ) 482 try: 483 s.set_selection( sel ) 484 except Exception, e: 263 485 msg = "The input data appear to contain no Nod observing mode data." 264 486 if rcParams['verbose']: 265 print msg 487 #print msg 488 asaplog.push(msg) 489 print_log('ERROR') 266 490 return 267 491 else: 268 492 raise TypeError(msg) 493 sel.reset() 494 del sel 495 del s 269 496 270 497 # need check correspondance of each beam with sig-ref ... … … 300 527 msg = "Need to supply a valid tau to use the supplied Tsys" 301 528 if rcParams['verbose']: 302 print msg 529 #print msg 530 asaplog.push(msg) 531 print_log('ERROR') 303 532 return 304 533 else: … … 307 536 scantab.recalc_azel() 308 537 resspec = scantable(stm._donod(scantab, pairScans, smooth, tsysval,tauval,tcalval)) 538 ### 539 if verify: 540 # get data 541 import numpy 542 precal={} 543 postcal=[] 544 keys=['','_calon'] 545 types=[srctype.nod,srctype.nodcal] 546 ifnos=list(scantab.getifnos()) 547 polnos=list(scantab.getpolnos()) 548 sel=selector() 549 ss = scantab.copy() 550 for i in range(2): 551 #ss=scantab.get_scan('*'+keys[i]) 552 ll=[] 553 ll2=[] 554 for j in range(len(ifnos)): 555 for k in range(len(polnos)): 556 sel.set_ifs(ifnos[j]) 557 sel.set_polarizations(polnos[k]) 558 sel.set_scans(pairScans[0]) 559 sel.set_types(types[i]) 560 try: 561 ss.set_selection(sel) 562 except: 563 continue 564 ll.append(numpy.array(ss._getspectrum(0))) 565 sel.reset() 566 ss.set_selection() 567 sel.set_ifs(ifnos[j]) 568 sel.set_polarizations(polnos[k]) 569 sel.set_scans(pairScans[1]) 570 sel.set_types(types[i]) 571 try: 572 ss.set_selection(sel) 573 except: 574 ll.pop() 575 continue 576 ll2.append(numpy.array(ss._getspectrum(0))) 577 sel.reset() 578 ss.set_selection() 579 key='%s%s' %(pairScans[0],keys[i]) 580 precal[key]=ll 581 key='%s%s' %(pairScans[1],keys[i]) 582 precal[key]=ll2 583 #del ss 584 keys=precal.keys() 585 for j in range(len(ifnos)): 586 for k in range(len(polnos)): 587 sel.set_ifs(ifnos[j]) 588 sel.set_polarizations(polnos[k]) 589 sel.set_scans(pairScans[0]) 590 try: 591 resspec.set_selection(sel) 592 except: 593 continue 594 postcal.append(numpy.array(resspec._getspectrum(0))) 595 sel.reset() 596 resspec.set_selection() 597 del sel 598 # plot 599 print_log() 600 asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.') 601 print_log('WARN') 602 p=asaplotgui.asaplotgui() 603 #nr=min(6,len(ifnos)*len(polnos)) 604 nr=len(ifnos)*len(polnos) 605 titles=[] 606 btics=[] 607 if nr<4: 608 p.set_panels(rows=nr,cols=2,nplots=2*nr,ganged=False) 609 for i in range(2*nr): 610 b=False 611 if i >= 2*nr-2: 612 b=True 613 btics.append(b) 614 elif nr==4: 615 p.set_panels(rows=2,cols=4,nplots=8,ganged=False) 616 for i in range(2*nr): 617 b=False 618 if i >= 2*nr-4: 619 b=True 620 btics.append(b) 621 elif nr<7: 622 p.set_panels(rows=3,cols=4,nplots=2*nr,ganged=False) 623 for i in range(2*nr): 624 if i >= 2*nr-4: 625 b=True 626 btics.append(b) 627 else: 628 print_log() 629 asaplog.push('Only first 6 [if,pol] pairs are plotted.') 630 print_log('WARN') 631 nr=6 632 for i in range(2*nr): 633 b=False 634 if i >= 2*nr-4: 635 b=True 636 btics.append(b) 637 p.set_panels(rows=3,cols=4,nplots=2*nr,ganged=False) 638 for i in range(nr): 639 p.subplot(2*i) 640 p.color=0 641 title='raw data IF%s POL%s' % (ifnos[int(i/len(polnos))],polnos[i%len(polnos)]) 642 titles.append(title) 643 #p.set_axes('title',title,fontsize=40) 644 ymin=1.0e100 645 ymax=-1.0e100 646 nchan=scantab.nchan() 647 edge=int(nchan*0.01) 648 for j in range(4): 649 spmin=min(precal[keys[j]][i][edge:nchan-edge]) 650 spmax=max(precal[keys[j]][i][edge:nchan-edge]) 651 ymin=min(ymin,spmin) 652 ymax=max(ymax,spmax) 653 for j in range(4): 654 if i==0: 655 p.set_line(label=keys[j]) 656 else: 657 p.legend() 658 p.plot(precal[keys[j]][i]) 659 p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax)) 660 if not btics[2*i]: 661 p.axes.set_xticks([]) 662 p.subplot(2*i+1) 663 p.color=0 664 title='cal data IF%s POL%s' % (ifnos[int(i/len(polnos))],polnos[i%len(polnos)]) 665 titles.append(title) 666 #p.set_axes('title',title) 667 p.legend() 668 ymin=postcal[i][edge:nchan-edge].min() 669 ymax=postcal[i][edge:nchan-edge].max() 670 p.plot(postcal[i]) 671 p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax)) 672 if not btics[2*i+1]: 673 p.axes.set_xticks([]) 674 for i in range(2*nr): 675 p.subplot(i) 676 p.set_axes('title',titles[i],fontsize='medium') 677 x=raw_input('Accept calibration ([y]/n): ' ) 678 if x.upper() == 'N': 679 p.unmap() 680 del p 681 return scabtab 682 p.unmap() 683 del p 684 ### 309 685 resspec._add_history("calnod",varlist) 686 print_log() 310 687 return resspec 311 688 312 @print_log_dec313 def calfs(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0 ):689 #@print_log_dec 690 def calfs(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False): 314 691 """ 315 692 Calibrate GBT frequency switched data. … … 333 710 varlist = vars() 334 711 from asap._asap import stmath 712 from asap._asap import srctype 335 713 stm = stmath() 336 714 stm._setinsitu(False) … … 348 726 349 727 resspec = scantable(stm._dofs(s, scannos, smooth, tsysval,tauval,tcalval)) 728 ### 729 if verify: 730 # get data 731 ssub = s.get_scan(scannos) 732 #ssubon = ssub.get_scan('*calon') 733 #ssuboff = ssub.get_scan('*[^calon]') 734 sel = selector() 735 sel.set_types( [srctype.foncal,srctype.foffcal] ) 736 ssub.set_selection( sel ) 737 ssubon = ssub.copy() 738 ssub.set_selection() 739 sel.reset() 740 sel.set_types( [srctype.fson,srctype.fsoff] ) 741 ssub.set_selection( sel ) 742 ssuboff = ssub.copy() 743 ssub.set_selection() 744 sel.reset() 745 import numpy 746 precal={} 747 postcal=[] 748 keys=['fs','fs_calon','fsr','fsr_calon'] 749 types=[srctype.fson,srctype.foncal,srctype.fsoff,srctype.foffcal] 750 ifnos=list(ssub.getifnos()) 751 polnos=list(ssub.getpolnos()) 752 for i in range(2): 753 #ss=ssuboff.get_scan('*'+keys[2*i]) 754 ll=[] 755 for j in range(len(ifnos)): 756 for k in range(len(polnos)): 757 sel.set_ifs(ifnos[j]) 758 sel.set_polarizations(polnos[k]) 759 sel.set_types(types[2*i]) 760 try: 761 #ss.set_selection(sel) 762 ssuboff.set_selection(sel) 763 except: 764 continue 765 ll.append(numpy.array(ss._getspectrum(0))) 766 sel.reset() 767 #ss.set_selection() 768 ssuboff.set_selection() 769 precal[keys[2*i]]=ll 770 #del ss 771 #ss=ssubon.get_scan('*'+keys[2*i+1]) 772 ll=[] 773 for j in range(len(ifnos)): 774 for k in range(len(polnos)): 775 sel.set_ifs(ifnos[j]) 776 sel.set_polarizations(polnos[k]) 777 sel.set_types(types[2*i+1]) 778 try: 779 #ss.set_selection(sel) 780 ssubon.set_selection(sel) 781 except: 782 continue 783 ll.append(numpy.array(ss._getspectrum(0))) 784 sel.reset() 785 #ss.set_selection() 786 ssubon.set_selection() 787 precal[keys[2*i+1]]=ll 788 #del ss 789 #sig=resspec.get_scan('*_fs') 790 #ref=resspec.get_scan('*_fsr') 791 sel.set_types( srctype.fson ) 792 resspec.set_selection( sel ) 793 sig=resspec.copy() 794 resspec.set_selection() 795 sel.reset() 796 sel.set_type( srctype.fsoff ) 797 resspec.set_selection( sel ) 798 ref=resspec.copy() 799 resspec.set_selection() 800 sel.reset() 801 for k in range(len(polnos)): 802 for j in range(len(ifnos)): 803 sel.set_ifs(ifnos[j]) 804 sel.set_polarizations(polnos[k]) 805 try: 806 sig.set_selection(sel) 807 postcal.append(numpy.array(sig._getspectrum(0))) 808 except: 809 ref.set_selection(sel) 810 postcal.append(numpy.array(ref._getspectrum(0))) 811 sel.reset() 812 resspec.set_selection() 813 del sel 814 # plot 815 print_log() 816 asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.') 817 print_log('WARN') 818 p=asaplotgui.asaplotgui() 819 #nr=min(6,len(ifnos)*len(polnos)) 820 nr=len(ifnos)/2*len(polnos) 821 titles=[] 822 btics=[] 823 if nr>3: 824 print_log() 825 asaplog.push('Only first 3 [if,pol] pairs are plotted.') 826 print_log('WARN') 827 nr=3 828 p.set_panels(rows=nr,cols=3,nplots=3*nr,ganged=False) 829 for i in range(3*nr): 830 b=False 831 if i >= 3*nr-3: 832 b=True 833 btics.append(b) 834 for i in range(nr): 835 p.subplot(3*i) 836 p.color=0 837 title='raw data IF%s,%s POL%s' % (ifnos[2*int(i/len(polnos))],ifnos[2*int(i/len(polnos))+1],polnos[i%len(polnos)]) 838 titles.append(title) 839 #p.set_axes('title',title,fontsize=40) 840 ymin=1.0e100 841 ymax=-1.0e100 842 nchan=s.nchan() 843 edge=int(nchan*0.01) 844 for j in range(4): 845 spmin=min(precal[keys[j]][i][edge:nchan-edge]) 846 spmax=max(precal[keys[j]][i][edge:nchan-edge]) 847 ymin=min(ymin,spmin) 848 ymax=max(ymax,spmax) 849 for j in range(4): 850 if i==0: 851 p.set_line(label=keys[j]) 852 else: 853 p.legend() 854 p.plot(precal[keys[j]][i]) 855 p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax)) 856 if not btics[3*i]: 857 p.axes.set_xticks([]) 858 p.subplot(3*i+1) 859 p.color=0 860 title='sig data IF%s POL%s' % (ifnos[2*int(i/len(polnos))],polnos[i%len(polnos)]) 861 titles.append(title) 862 #p.set_axes('title',title) 863 p.legend() 864 ymin=postcal[2*i][edge:nchan-edge].min() 865 ymax=postcal[2*i][edge:nchan-edge].max() 866 p.plot(postcal[2*i]) 867 p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax)) 868 if not btics[3*i+1]: 869 p.axes.set_xticks([]) 870 p.subplot(3*i+2) 871 p.color=0 872 title='ref data IF%s POL%s' % (ifnos[2*int(i/len(polnos))+1],polnos[i%len(polnos)]) 873 titles.append(title) 874 #p.set_axes('title',title) 875 p.legend() 876 ymin=postcal[2*i+1][edge:nchan-edge].min() 877 ymax=postcal[2*i+1][edge:nchan-edge].max() 878 p.plot(postcal[2*i+1]) 879 p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax)) 880 if not btics[3*i+2]: 881 p.axes.set_xticks([]) 882 for i in range(3*nr): 883 p.subplot(i) 884 p.set_axes('title',titles[i],fontsize='medium') 885 x=raw_input('Accept calibration ([y]/n): ' ) 886 if x.upper() == 'N': 887 p.unmap() 888 del p 889 return scabtab 890 p.unmap() 891 del p 892 ### 350 893 resspec._add_history("calfs",varlist) 894 print_log() 351 895 return resspec 352 896 353 354 @print_log_dec 897 #@print_log_dec 355 898 def merge(*args): 356 899 """ … … 380 923 msg = "Please give a list of scantables" 381 924 if rcParams['verbose']: 382 print msg 925 #print msg 926 asaplog.push(msg) 927 print_log('ERROR') 383 928 return 384 929 else: … … 386 931 s = scantable(stm._merge(lst)) 387 932 s._add_history("merge", varlist) 933 print_log() 388 934 return s 935 936 def calibrate( scantab, scannos=[], calmode='none', verify=None ): 937 """ 938 Calibrate data. 939 940 Parameters: 941 scantab: scantable 942 scannos: list of scan number 943 calmode: calibration mode 944 verify: verify calibration 945 """ 946 antname = scantab.get_antennaname() 947 if ( calmode == 'nod' ): 948 asaplog.push( 'Calibrating nod data.' ) 949 print_log() 950 scal = calnod( scantab, scannos=scannos, verify=verify ) 951 elif ( calmode == 'quotient' ): 952 asaplog.push( 'Calibrating using quotient.' ) 953 print_log() 954 scal = scantab.auto_quotient( verify=verify ) 955 elif ( calmode == 'ps' ): 956 asaplog.push( 'Calibrating %s position-switched data.' % antname ) 957 print_log() 958 if ( antname.find( 'APEX' ) != -1 ): 959 scal = apexcal( scantab, scannos, calmode, verify ) 960 elif ( antname.find( 'ALMA' ) != -1 or antname.find( 'OSF' ) != -1 ): 961 scal = almacal( scantab, scannos, calmode, verify ) 962 else: 963 scal = calps( scantab, scannos=scannos, verify=verify ) 964 elif ( calmode == 'fs' or calmode == 'fsotf' ): 965 asaplog.push( 'Calibrating %s frequency-switched data.' % antname ) 966 print_log() 967 if ( antname.find( 'APEX' ) != -1 ): 968 scal = apexcal( scantab, scannos, calmode, verify ) 969 elif ( antname.find( 'ALMA' ) != -1 or antname.find( 'OSF' ) != -1 ): 970 scal = almacal( scantab, scannos, calmode, verify ) 971 else: 972 scal = calfs( scantab, scannos=scannos, verify=verify ) 973 elif ( calmode == 'otf' ): 974 asaplog.push( 'Calibrating %s On-The-Fly data.' % antname ) 975 print_log() 976 scal = almacal( scantab, scannos, calmode, verify ) 977 else: 978 asaplog.push( 'No calibration.' ) 979 scal = scantab.copy() 980 981 return scal 982 983 def apexcal( scantab, scannos=[], calmode='none', verify=False ): 984 """ 985 Calibrate APEX data 986 987 Parameters: 988 scantab: scantable 989 scannos: list of scan number 990 calmode: calibration mode 991 992 verify: verify calibration 993 """ 994 from asap._asap import stmath 995 stm = stmath() 996 antname = scantab.get_antennaname() 997 ssub = scantab.get_scan( scannos ) 998 scal = scantable( stm.cwcal( ssub, calmode, antname ) ) 999 return scal 1000 1001 def almacal( scantab, scannos=[], calmode='none', verify=False ): 1002 """ 1003 Calibrate ALMA data 1004 1005 Parameters: 1006 scantab: scantable 1007 scannos: list of scan number 1008 calmode: calibration mode 1009 1010 verify: verify calibration 1011 """ 1012 from asap._asap import stmath 1013 stm = stmath() 1014 ssub = scantab.get_scan( scannos ) 1015 scal = scantable( stm.almacal( ssub, calmode ) ) 1016 return scal 1017 1018 def splitant(filename, outprefix='',overwrite=False): 1019 """ 1020 Split Measurement set by antenna name, save data as a scantables, 1021 and return a list of filename. 1022 Notice this method can only be available from CASA. 1023 Prameter 1024 filename: the name of Measurement set to be read. 1025 outprefix: the prefix of output scantable name. 1026 the names of output scantable will be 1027 outprefix.antenna1, outprefix.antenna2, .... 1028 If not specified, outprefix = filename is assumed. 1029 overwrite If the file should be overwritten if it exists. 1030 The default False is to return with warning 1031 without writing the output. USE WITH CARE. 1032 1033 """ 1034 # Import the table toolkit from CASA 1035 try: 1036 import casac 1037 except ImportError: 1038 if rcParams['verbose']: 1039 #print "failed to load casa" 1040 print_log() 1041 asaplog.push("failed to load casa") 1042 print_log('ERROR') 1043 else: raise 1044 return False 1045 try: 1046 tbtool = casac.homefinder.find_home_by_name('tableHome') 1047 tb = tbtool.create() 1048 tb2 = tbtool.create() 1049 except: 1050 if rcParams['verbose']: 1051 #print "failed to load a table tool:\n", e 1052 print_log() 1053 asaplog.push("failed to load table tool") 1054 print_log('ERROR') 1055 else: raise 1056 return False 1057 # Check the input filename 1058 if isinstance(filename, str): 1059 import os.path 1060 filename = os.path.expandvars(filename) 1061 filename = os.path.expanduser(filename) 1062 if not os.path.exists(filename): 1063 s = "File '%s' not found." % (filename) 1064 if rcParams['verbose']: 1065 print_log() 1066 asaplog.push(s) 1067 print_log('ERROR') 1068 return 1069 raise IOError(s) 1070 # check if input file is MS 1071 if not os.path.isdir(filename) \ 1072 or not os.path.exists(filename+'/ANTENNA') \ 1073 or not os.path.exists(filename+'/table.f1'): 1074 s = "File '%s' is not a Measurement set." % (filename) 1075 if rcParams['verbose']: 1076 print_log() 1077 asaplog.push(s) 1078 print_log('ERROR') 1079 return 1080 raise IOError(s) 1081 else: 1082 s = "The filename should be string. " 1083 if rcParams['verbose']: 1084 print_log() 1085 asaplog.push(s) 1086 print_log('ERROR') 1087 return 1088 raise TypeError(s) 1089 # Check out put file name 1090 outname='' 1091 if len(outprefix) > 0: prefix=outprefix+'.' 1092 else: 1093 prefix=filename.rstrip('/') 1094 # Now do the actual splitting. 1095 outfiles=[] 1096 tb.open(tablename=filename+'/ANTENNA',nomodify=True) 1097 nant=tb.nrows() 1098 antnames=tb.getcol('NAME',0,nant,1) 1099 antpos=tb.getcol('POSITION',0,nant,1).transpose() 1100 tb.close() 1101 tb.open(tablename=filename,nomodify=True) 1102 ant1=tb.getcol('ANTENNA1',0,-1,1) 1103 tb.close() 1104 for antid in set(ant1): 1105 scan=scantable(filename,average=False,getpt=True,antenna=int(antid)) 1106 outname=prefix+antnames[antid]+'.asap' 1107 scan.save(outname,format='ASAP',overwrite=overwrite) 1108 del scan 1109 outfiles.append(outname) 1110 del tb, tb2 1111 return outfiles 1112 1113 def _array2dOp( scan, value, mode="ADD", tsys=False ): 1114 """ 1115 This function is workaround on the basic operation of scantable 1116 with 2 dimensional float list. 1117 1118 scan: scantable operand 1119 value: float list operand 1120 mode: operation mode (ADD, SUB, MUL, DIV) 1121 tsys: if True, operate tsys as well 1122 """ 1123 nrow = scan.nrow() 1124 s = None 1125 if len( value ) == 1: 1126 from asap._asap import stmath 1127 stm = stmath() 1128 s = scantable( stm._arrayop( scan.copy(), value[0], mode, tsys ) ) 1129 del stm 1130 elif len( value ) != nrow: 1131 asaplog.push( 'len(value) must be 1 or conform to scan.nrow()' ) 1132 print_log( 'ERROR' ) 1133 else: 1134 from asap._asap import stmath 1135 stm = stmath() 1136 # insitu must be True 1137 stm._setinsitu( True ) 1138 s = scan.copy() 1139 sel = selector() 1140 for irow in range( nrow ): 1141 sel.set_rows( irow ) 1142 s.set_selection( sel ) 1143 if len( value[irow] ) == 1: 1144 stm._unaryop( s, value[irow][0], mode, tsys ) 1145 else: 1146 stm._arrayop( s, value[irow], mode, tsys, 'channel' ) 1147 s.set_selection() 1148 sel.reset() 1149 del sel 1150 del stm 1151 return s 1152 1153 1154 -
branches/mergetest/python/asapplotter.py
r1739 r1779 1 1 from asap import rcParams, print_log, print_log_dec 2 2 from asap import selector, scantable 3 from asap import asaplog 3 4 import matplotlib.axes 4 5 from matplotlib.font_manager import FontProperties … … 21 22 self._visible = visible 22 23 self._plotter = self._newplotter(**kwargs) 24 # additional tool bar 25 self._plotter.figmgr.casabar=self._newcasabar() 23 26 24 27 self._panelling = None … … 43 46 self._hist = rcParams['plotter.histogram'] 44 47 self._fp = FontProperties() 48 self._panellayout = self.set_panellayout(refresh=False) 45 49 46 50 def _translate(self, instr): … … 53 57 54 58 def _newplotter(self, **kwargs): 55 if self._visible: 59 backend=matplotlib.get_backend() 60 if not self._visible: 61 from asap.asaplot import asaplot 62 elif backend == 'TkAgg': 56 63 from asap.asaplotgui import asaplotgui as asaplot 64 elif backend == 'Qt4Agg': 65 from asap.asaplotgui_qt4 import asaplotgui as asaplot 66 elif backend == 'GTkAgg': 67 from asap.asaplotgui_gtk import asaplotgui as asaplot 57 68 else: 58 69 from asap.asaplot import asaplot 59 70 return asaplot(**kwargs) 60 71 61 @print_log_dec 72 def _newcasabar(self): 73 backend=matplotlib.get_backend() 74 if self._visible and backend == "TkAgg": 75 from asap.casatoolbar import CustomToolbarTkAgg 76 return CustomToolbarTkAgg(self) 77 else: return None 78 79 #@print_log_dec 62 80 def plot(self, scan=None): 63 81 """ … … 72 90 """ 73 91 if self._plotter.is_dead: 92 if hasattr(self._plotter.figmgr,'casabar'): 93 del self._plotter.figmgr.casabar 74 94 self._plotter = self._newplotter() 95 self._plotter.figmgr.casabar=self._newcasabar() 75 96 self._plotter.hold() 76 97 self._plotter.clear() 77 from asap import scantable78 98 if not self._data and not scan: 79 99 msg = "Input is not a scantable" 80 100 if rcParams['verbose']: 81 print msg 101 #print msg 102 asaplog.push( msg ) 103 print_log( 'ERROR' ) 82 104 return 83 105 raise TypeError(msg) 84 if isinstance(scan, scantable): 85 if self._data is not None: 86 if scan != self._data: 87 self._data = scan 88 # reset 89 self._reset() 90 else: 91 self._data = scan 92 self._reset() 93 # ranges become invalid when unit changes 94 if self._abcunit and self._abcunit != self._data.get_unit(): 95 self._minmaxx = None 96 self._minmaxy = None 97 self._abcunit = self._data.get_unit() 98 self._datamask = None 106 if scan: self.set_data(scan,refresh=False) 99 107 self._plot(self._data) 100 108 if self._minmaxy is not None: 101 109 self._plotter.set_limits(ylim=self._minmaxy) 110 if self._plotter.figmgr.casabar: self._plotter.figmgr.casabar.enable_button() 102 111 self._plotter.release() 103 112 self._plotter.tidy() 104 113 self._plotter.show(hardrefresh=False) 114 print_log() 105 115 return 106 116 … … 170 180 def text(self, *args, **kwargs): 171 181 if kwargs.has_key("interactive"): 172 if kwargs.pop("interactive"): 173 pos = self._plotter.get_point() 174 args = tuple(pos)+args 182 #if kwargs.pop("interactive"): 183 # pos = self._plotter.get_point() 184 # args = tuple(pos)+args 185 kwargs.pop("interactive") 175 186 self._axes_callback("text", *args, **kwargs) 176 187 … … 179 190 def arrow(self, *args, **kwargs): 180 191 if kwargs.has_key("interactive"): 181 if kwargs.pop("interactive"): 182 pos = self._plotter.get_region() 183 dpos = (pos[0][0], pos[0][1], 184 pos[1][0]-pos[0][0], 185 pos[1][1] - pos[0][1]) 186 args = dpos + args 192 #if kwargs.pop("interactive"): 193 # pos = self._plotter.get_region() 194 # dpos = (pos[0][0], pos[0][1], 195 # pos[1][0]-pos[0][0], 196 # pos[1][1] - pos[0][1]) 197 # args = dpos + args 198 kwargs.pop("interactive") 187 199 self._axes_callback("arrow", *args, **kwargs) 188 200 … … 191 203 def annotate(self, text, xy=None, xytext=None, **kwargs): 192 204 if kwargs.has_key("interactive"): 193 if kwargs.pop("interactive"): 194 xy = self._plotter.get_point() 195 xytext = self._plotter.get_point() 205 #if kwargs.pop("interactive"): 206 # xy = self._plotter.get_point() 207 # xytext = self._plotter.get_point() 208 kwargs.pop("interactive") 196 209 if not kwargs.has_key("arrowprops"): 197 210 kwargs["arrowprops"] = dict(arrowstyle="->") … … 202 215 def axvline(self, *args, **kwargs): 203 216 if kwargs.has_key("interactive"): 204 if kwargs.pop("interactive"): 205 pos = self._plotter.get_point() 206 args = (pos[0],)+args 217 #if kwargs.pop("interactive"): 218 # pos = self._plotter.get_point() 219 # args = (pos[0],)+args 220 kwargs.pop("interactive") 207 221 self._axes_callback("axvline", *args, **kwargs) 208 222 … … 211 225 def axhline(self, *args, **kwargs): 212 226 if kwargs.has_key("interactive"): 213 if kwargs.pop("interactive"): 214 pos = self._plotter.get_point() 215 args = (pos[1],)+args 227 #if kwargs.pop("interactive"): 228 # pos = self._plotter.get_point() 229 # args = (pos[1],)+args 230 kwargs.pop("interactive") 216 231 self._axes_callback("axhline", *args, **kwargs) 217 232 … … 220 235 def axvspan(self, *args, **kwargs): 221 236 if kwargs.has_key("interactive"): 222 if kwargs.pop("interactive"): 223 pos = self._plotter.get_region() 224 dpos = (pos[0][0], pos[1][0]) 225 args = dpos + args 237 #if kwargs.pop("interactive"): 238 # pos = self._plotter.get_region() 239 # dpos = (pos[0][0], pos[1][0]) 240 # args = dpos + args 241 kwargs.pop("interactive") 226 242 self._axes_callback("axvspan", *args, **kwargs) 227 243 # hack to preventy mpl from redrawing the patch … … 234 250 def axhspan(self, *args, **kwargs): 235 251 if kwargs.has_key("interactive"): 236 if kwargs.pop("interactive"):237 pos = self._plotter.get_region()238 dpos = (pos[0][1], pos[1][1])239 args = dpos + args240 252 #if kwargs.pop("interactive"): 253 # pos = self._plotter.get_region() 254 # dpos = (pos[0][1], pos[1][1]) 255 # args = dpos + args 256 kwargs.pop("interactive") 241 257 self._axes_callback("axhspan", *args, **kwargs) 242 258 # hack to preventy mpl from redrawing the patch … … 265 281 # end matplotlib.axes fowarding functions 266 282 267 268 def set_mode(self, stacking=None, panelling=None): 283 def set_data(self, scan, refresh=True): 284 """ 285 Set a scantable to plot. 286 Parameters: 287 scan: a scantable 288 refresh: True (default) or False. If True, the plot is 289 replotted based on the new parameter setting(s). 290 Otherwise,the parameter(s) are set without replotting. 291 Note: 292 The user specified masks and data selections will be reset 293 if a new scantable is set. This method should be called before 294 setting data selections (set_selection) and/or masks (set_mask). 295 """ 296 from asap import scantable 297 if isinstance(scan, scantable): 298 if self._data is not None: 299 if scan != self._data: 300 self._data = scan 301 # reset 302 self._reset() 303 msg = "A new scantable is set to the plotter. The masks and data selections are reset." 304 asaplog.push( msg ) 305 print_log( 'INFO' ) 306 else: 307 self._data = scan 308 self._reset() 309 else: 310 msg = "Input is not a scantable" 311 if rcParams['verbose']: 312 #print msg 313 asaplog.push( msg ) 314 print_log( 'ERROR' ) 315 return 316 raise TypeError(msg) 317 318 # ranges become invalid when unit changes 319 if self._abcunit and self._abcunit != self._data.get_unit(): 320 self._minmaxx = None 321 self._minmaxy = None 322 self._abcunit = self._data.get_unit() 323 self._datamask = None 324 if refresh: self.plot() 325 326 327 def set_mode(self, stacking=None, panelling=None, refresh=True): 269 328 """ 270 329 Set the plots look and feel, i.e. what you want to see on the plot. … … 274 333 panelling: tell the plotter which variable to plot 275 334 across multiple panels (default 'scan' 335 refresh: True (default) or False. If True, the plot is 336 replotted based on the new parameter setting(s). 337 Otherwise,the parameter(s) are set without replotting. 276 338 Note: 277 339 Valid modes are: … … 286 348 not self.set_stacking(stacking): 287 349 if rcParams['verbose']: 288 print msg 350 #print msg 351 asaplog.push( msg ) 352 print_log( 'ERROR' ) 289 353 return 290 354 else: 291 355 raise TypeError(msg) 292 if self._data: self.plot(self._data)356 if refresh and self._data: self.plot(self._data) 293 357 return 294 358 … … 304 368 return False 305 369 306 def set_layout(self,rows=None,cols=None ):370 def set_layout(self,rows=None,cols=None,refresh=True): 307 371 """ 308 372 Set the multi-panel layout, i.e. how many rows and columns plots … … 311 375 rows: The number of rows of plots 312 376 cols: The number of columns of plots 377 refresh: True (default) or False. If True, the plot is 378 replotted based on the new parameter setting(s). 379 Otherwise,the parameter(s) are set without replotting. 313 380 Note: 314 381 If no argument is given, the potter reverts to its auto-plot … … 317 384 self._rows = rows 318 385 self._cols = cols 319 if self._data: self.plot(self._data)386 if refresh and self._data: self.plot(self._data) 320 387 return 321 388 … … 331 398 return False 332 399 333 def set_range(self,xstart=None,xend=None,ystart=None,yend=None ):400 def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True): 334 401 """ 335 402 Set the range of interest on the abcissa of the plot 336 403 Parameters: 337 404 [x,y]start,[x,y]end: The start and end points of the 'zoom' window 405 refresh: True (default) or False. If True, the plot is 406 replotted based on the new parameter setting(s). 407 Otherwise,the parameter(s) are set without replotting. 338 408 Note: 339 409 These become non-sensical when the unit changes. … … 349 419 else: 350 420 self._minmaxy = [ystart,yend] 351 if self._data: self.plot(self._data)421 if refresh and self._data: self.plot(self._data) 352 422 return 353 423 354 def set_legend(self, mp=None, fontsize = None, mode = 0 ):424 def set_legend(self, mp=None, fontsize = None, mode = 0, refresh=True): 355 425 """ 356 426 Specify a mapping for the legend instead of using the default … … 376 446 9: upper center 377 447 10: center 448 refresh: True (default) or False. If True, the plot is 449 replotted based on the new parameter setting(s). 450 Otherwise,the parameter(s) are set without replotting. 378 451 379 452 Example: … … 390 463 from matplotlib import rc as rcp 391 464 rcp('legend', fontsize=fontsize) 392 if self._data: 393 self.plot(self._data) 465 if refresh and self._data: self.plot(self._data) 394 466 return 395 467 396 def set_title(self, title=None, fontsize=None ):468 def set_title(self, title=None, fontsize=None, refresh=True): 397 469 """ 398 470 Set the title of the plot. If multiple panels are plotted, 399 471 multiple titles have to be specified. 472 Parameters: 473 refresh: True (default) or False. If True, the plot is 474 replotted based on the new parameter setting(s). 475 Otherwise,the parameter(s) are set without replotting. 400 476 Example: 401 477 # two panels are visible on the plotter … … 406 482 from matplotlib import rc as rcp 407 483 rcp('axes', titlesize=fontsize) 408 if self._data: self.plot(self._data)484 if refresh and self._data: self.plot(self._data) 409 485 return 410 486 411 def set_ordinate(self, ordinate=None, fontsize=None ):487 def set_ordinate(self, ordinate=None, fontsize=None, refresh=True): 412 488 """ 413 489 Set the y-axis label of the plot. If multiple panels are plotted, … … 416 492 ordinate: a list of ordinate labels. None (default) let 417 493 data determine the labels 494 refresh: True (default) or False. If True, the plot is 495 replotted based on the new parameter setting(s). 496 Otherwise,the parameter(s) are set without replotting. 418 497 Example: 419 498 # two panels are visible on the plotter … … 425 504 rcp('axes', labelsize=fontsize) 426 505 rcp('ytick', labelsize=fontsize) 427 if self._data: self.plot(self._data)506 if refresh and self._data: self.plot(self._data) 428 507 return 429 508 430 def set_abcissa(self, abcissa=None, fontsize=None ):509 def set_abcissa(self, abcissa=None, fontsize=None, refresh=True): 431 510 """ 432 511 Set the x-axis label of the plot. If multiple panels are plotted, … … 435 514 abcissa: a list of abcissa labels. None (default) let 436 515 data determine the labels 516 refresh: True (default) or False. If True, the plot is 517 replotted based on the new parameter setting(s). 518 Otherwise,the parameter(s) are set without replotting. 437 519 Example: 438 520 # two panels are visible on the plotter … … 444 526 rcp('axes', labelsize=fontsize) 445 527 rcp('xtick', labelsize=fontsize) 446 if self._data: self.plot(self._data)528 if refresh and self._data: self.plot(self._data) 447 529 return 448 530 449 def set_colors(self, colmap ):531 def set_colors(self, colmap, refresh=True): 450 532 """ 451 533 Set the colours to be used. The plotter will cycle through … … 453 535 Parameters: 454 536 colmap: a list of colour names 537 refresh: True (default) or False. If True, the plot is 538 replotted based on the new parameter setting(s). 539 Otherwise,the parameter(s) are set without replotting. 455 540 Example: 456 541 plotter.set_colors("red green blue") … … 462 547 colmap = colmap.split() 463 548 self._plotter.palette(0, colormap=colmap) 464 if self._data: self.plot(self._data)549 if refresh and self._data: self.plot(self._data) 465 550 466 551 # alias for english speakers 467 552 set_colours = set_colors 468 553 469 def set_histogram(self, hist=True, linewidth=None ):554 def set_histogram(self, hist=True, linewidth=None, refresh=True): 470 555 """ 471 556 Enable/Disable histogram-like plotting. … … 474 559 is taken from the .asaprc setting 475 560 plotter.histogram 561 refresh: True (default) or False. If True, the plot is 562 replotted based on the new parameter setting(s). 563 Otherwise,the parameter(s) are set without replotting. 476 564 """ 477 565 self._hist = hist … … 479 567 from matplotlib import rc as rcp 480 568 rcp('lines', linewidth=linewidth) 481 if self._data: self.plot(self._data)482 483 def set_linestyles(self, linestyles=None, linewidth=None ):569 if refresh and self._data: self.plot(self._data) 570 571 def set_linestyles(self, linestyles=None, linewidth=None, refresh=True): 484 572 """ 485 573 Set the linestyles to be used. The plotter will cycle through … … 491 579 'dashdotdot' and 'dashdashdot' are 492 580 possible 493 581 refresh: True (default) or False. If True, the plot is 582 replotted based on the new parameter setting(s). 583 Otherwise,the parameter(s) are set without replotting. 494 584 Example: 495 585 plotter.set_colors("black") … … 505 595 from matplotlib import rc as rcp 506 596 rcp('lines', linewidth=linewidth) 507 if self._data: self.plot(self._data)508 509 def set_font(self, **kwargs):597 if refresh and self._data: self.plot(self._data) 598 599 def set_font(self, refresh=True,**kwargs): 510 600 """ 511 601 Set font properties. … … 516 606 size: the 'general' font size, individual elements can be adjusted 517 607 seperately 608 refresh: True (default) or False. If True, the plot is 609 replotted based on the new parameter setting(s). 610 Otherwise,the parameter(s) are set without replotting. 518 611 """ 519 612 from matplotlib import rc as rcp … … 523 616 fdict[k] = v 524 617 self._fp = FontProperties(**fdict) 525 if self._data: 526 self.plot() 618 if refresh and self._data: self.plot(self._data) 619 620 def set_panellayout(self,layout=[],refresh=True): 621 """ 622 Set the layout of subplots. 623 Parameters: 624 layout: a list of subplots layout in figure coordinate (0-1), 625 i.e., fraction of the figure width or height. 626 The order of elements should be: 627 [left, bottom, right, top, horizontal space btw panels, 628 vertical space btw panels]. 629 refresh: True (default) or False. If True, the plot is 630 replotted based on the new parameter setting(s). 631 Otherwise,the parameter(s) are set without replotting. 632 Note 633 * When layout is not specified, the values are reset to the defaults 634 of matplotlib. 635 * If any element is set to be None, the current value is adopted. 636 """ 637 if layout == []: self._panellayout=self._reset_panellayout() 638 else: 639 self._panellayout=[None]*6 640 self._panellayout[0:len(layout)]=layout 641 #print "panel layout set to ",self._panellayout 642 if refresh and self._data: self.plot(self._data) 643 644 def _reset_panellayout(self): 645 ks=map(lambda x: 'figure.subplot.'+x, 646 ['left','bottom','right','top','hspace','wspace']) 647 return map(matplotlib.rcParams.get,ks) 527 648 528 649 def plot_lines(self, linecat=None, doppler=0.0, deltachan=10, rotate=90.0, … … 622 743 623 744 624 def set_mask(self, mask=None, selection=None ):745 def set_mask(self, mask=None, selection=None, refresh=True): 625 746 """ 626 747 Set a plotting mask for a specific polarization. … … 629 750 mask: a mask from scantable.create_mask 630 751 selection: the spectra to apply the mask to. 752 refresh: True (default) or False. If True, the plot is 753 replotted based on the new parameter setting(s). 754 Otherwise,the parameter(s) are set without replotting. 631 755 Example: 632 756 select = selector() … … 637 761 msg = "Can only set mask after a first call to plot()" 638 762 if rcParams['verbose']: 639 print msg 763 #print msg 764 asaplog.push( msg ) 765 print_log( 'ERROR' ) 640 766 return 641 767 else: … … 657 783 else: 658 784 self._maskselection = None 659 self.plot(self._data)785 if refresh: self.plot(self._data) 660 786 661 787 def _slice_indeces(self, data): … … 671 797 inc = -1 672 798 # find min index 673 while start > 0 and data[start] < mn: 674 start+= inc 799 #while start > 0 and data[start] < mn: 800 # start+= inc 801 minind=start 802 for ind in xrange(start,end+inc,inc): 803 if data[ind] > mn: break 804 minind=ind 675 805 # find max index 676 while end > 0 and data[end] > mx: 677 end-=inc 678 if end > 0: end +=1 806 #while end > 0 and data[end] > mx: 807 # end-=inc 808 #if end > 0: end +=1 809 maxind=end 810 for ind in xrange(end,start-inc,-inc): 811 if data[ind] < mx: break 812 maxind=ind 813 start=minind 814 end=maxind 679 815 if start > end: 680 return end,start 681 return start,end 816 return end,start+1 817 elif start < end: 818 return start,end+1 819 else: 820 return start,end 682 821 683 822 def _reset(self): … … 708 847 maxpanel, maxstack = 16,16 709 848 if n > maxpanel or nstack > maxstack: 710 from asap import asaplog711 849 maxn = 0 712 850 if nstack > maxstack: maxn = maxstack … … 715 853 "Selecting first %d selections..." % (maxn, maxn) 716 854 asaplog.push(msg) 717 print_log( )855 print_log('WARN') 718 856 n = min(n,maxpanel) 719 857 nstack = min(nstack,maxstack) 720 858 if n > 1: 721 859 ganged = rcParams['plotter.ganged'] 860 if self._panelling == 'i': 861 ganged = False 722 862 if self._rows and self._cols: 723 863 n = min(n,self._rows*self._cols) 724 864 self._plotter.set_panels(rows=self._rows,cols=self._cols, 725 nplots=n,ganged=ganged) 865 # nplots=n,ganged=ganged) 866 nplots=n,layout=self._panellayout,ganged=ganged) 726 867 else: 727 self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged) 868 # self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged) 869 self._plotter.set_panels(rows=n,cols=0,nplots=n,layout=self._panellayout,ganged=ganged) 728 870 else: 729 self._plotter.set_panels() 871 # self._plotter.set_panels() 872 self._plotter.set_panels(layout=self._panellayout) 730 873 r=0 731 874 nr = scan.nrow() … … 799 942 ylim= self._minmaxy or [ma.minimum(y),ma.maximum(y)] 800 943 allylim += ylim 944 else: 945 xlim = self._minmaxx or [] 946 allxlim += xlim 947 ylim= self._minmaxy or [] 948 allylim += ylim 801 949 stackcount += 1 802 950 # last in colour stack -> autoscale x 803 if stackcount == nstack :951 if stackcount == nstack and len(allxlim) > 0: 804 952 allxlim.sort() 805 self._plotter. axes.set_xlim([allxlim[0],allxlim[-1]])953 self._plotter.subplots[panelcount-1]['axes'].set_xlim([allxlim[0],allxlim[-1]]) 806 954 # clear 807 955 allxlim =[] … … 813 961 if (panelcount == n) and (stackcount == nstack): 814 962 # last panel -> autoscale y if ganged 815 if rcParams['plotter.ganged'] :963 if rcParams['plotter.ganged'] and len(allylim) > 0: 816 964 allylim.sort() 817 965 self._plotter.set_limits(ylim=[allylim[0],allylim[-1]]) … … 820 968 #reset the selector to the scantable's original 821 969 scan.set_selection(savesel) 822 if self._fp is not None: 970 971 #temporary switch-off for older matplotlib 972 #if self._fp is not None: 973 if self._fp is not None and getattr(self._plotter.figure,'findobj',False): 823 974 for o in self._plotter.figure.findobj(Text): 824 975 o.set_fontproperties(self._fp) 825 976 826 827 977 def set_selection(self, selection=None, refresh=True, **kw): 978 """ 979 Parameters: 980 selection: a selector object (default unset the selection) 981 refresh: True (default) or False. If True, the plot is 982 replotted based on the new parameter setting(s). 983 Otherwise,the parameter(s) are set without replotting. 984 """ 828 985 if selection is None: 829 986 # reset … … 845 1002 order = [d0[self._panelling],d0[self._stacking]] 846 1003 self._selection.set_order(order) 847 if self._data and refresh: self.plot(self._data)1004 if refresh and self._data: self.plot(self._data) 848 1005 849 1006 def _get_selected_n(self, scan): … … 868 1025 poleval = scan._getpollabel(scan.getpol(row),scan.poltype()) 869 1026 d = {'b': "Beam "+str(scan.getbeam(row)), 870 's': scan._getsourcename(row), 1027 #'s': scan._getsourcename(row), 1028 's': "Scan "+str(scan.getscan(row))+\ 1029 " ("+str(scan._getsourcename(row))+")", 871 1030 'i': "IF"+str(scan.getif(row)), 872 1031 'p': poleval, … … 874 1033 return userlabel or d[mode] 875 1034 876 def plotazel(self): 1035 def plotazel(self, scan=None, outfile=None): 1036 #def plotazel(self): 877 1037 """ 878 1038 plot azimuth and elevation versus time of a scantable … … 883 1043 from matplotlib.ticker import MultipleLocator 884 1044 from numpy import array, pi 1045 self._data = scan 1046 self._outfile = outfile 885 1047 dates = self._data.get_time(asdatetime=True) 886 1048 t = PL.date2num(dates) … … 889 1051 PL.ioff() 890 1052 PL.clf() 1053 # Adjust subplot layouts 1054 if len(self._panellayout) !=6: self.set_panellayout(refresh=False) 1055 lef, bot, rig, top, wsp, hsp = self._panellayout 1056 PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top, 1057 wspace=wsp,hspace=hsp) 1058 891 1059 tdel = max(t) - min(t) 892 1060 ax = PL.subplot(2,1,1) … … 910 1078 911 1079 PL.title(dstr) 912 PL.plot_date(t,el,'b,', tz=tz) 1080 if tdel == 0.0: 1081 th = (t - PL.floor(t))*24.0 1082 PL.plot(th,el,'o',markersize=2, markerfacecolor='b', markeredgecolor='b') 1083 else: 1084 PL.plot_date(t,el,'o', markersize=2, markerfacecolor='b', markeredgecolor='b',tz=tz) 1085 #ax.grid(True) 1086 ax.xaxis.set_major_formatter(timefmt) 1087 ax.xaxis.set_major_locator(majloc) 1088 ax.xaxis.set_minor_locator(minloc) 913 1089 ax.yaxis.grid(True) 914 1090 yloc = MultipleLocator(30) 1091 ax.set_ylim(0,90) 1092 ax.yaxis.set_major_locator(yloc) 915 1093 if tdel > 1.0: 916 1094 labels = ax.get_xticklabels() 917 1095 # PL.setp(labels, fontsize=10, rotation=45) 918 1096 PL.setp(labels, fontsize=10) 1097 919 1098 # Az plot 920 1099 az = array(self._data.get_azimuth())*180./pi … … 923 1102 if az[irow] < 0: az[irow] += 360.0 924 1103 925 ax2 = ax.figure.add_subplot(2,1,2, sharex=ax) 926 ax2.set_xlabel('Time (UT)') 927 ax2.set_ylabel('Az [deg.]') 928 ax2.plot_date(t,az,'b,', tz=tz) 1104 ax2 = PL.subplot(2,1,2) 1105 #PL.xlabel('Time (UT [hour])') 1106 PL.ylabel('Az [deg.]') 1107 if tdel == 0.0: 1108 PL.plot(th,az,'o',markersize=2, markeredgecolor='b',markerfacecolor='b') 1109 else: 1110 PL.plot_date(t,az,'o', markersize=2,markeredgecolor='b',markerfacecolor='b',tz=tz) 1111 ax2.xaxis.set_major_formatter(timefmt) 1112 ax2.xaxis.set_major_locator(majloc) 1113 ax2.xaxis.set_minor_locator(minloc) 1114 #ax2.grid(True) 1115 ax2.set_ylim(0,360) 929 1116 ax2.yaxis.grid(True) 930 # set this last as x axis is shared 931 ax.xaxis.set_major_formatter(timefmt) 932 ax.xaxis.set_major_locator(majloc) 933 ax.xaxis.set_minor_locator(minloc) 1117 #hfmt = DateFormatter('%H') 1118 #hloc = HourLocator() 1119 yloc = MultipleLocator(60) 1120 ax2.yaxis.set_major_locator(yloc) 1121 if tdel > 1.0: 1122 labels = ax2.get_xticklabels() 1123 PL.setp(labels, fontsize=10) 1124 PL.xlabel('Time (UT [day])') 1125 else: 1126 PL.xlabel('Time (UT [hour])') 1127 934 1128 PL.ion() 935 1129 PL.draw() 936 937 def plotpointing(self): 1130 if (self._outfile is not None): 1131 PL.savefig(self._outfile) 1132 1133 def plotpointing(self, scan=None, outfile=None): 1134 #def plotpointing(self): 938 1135 """ 939 1136 plot telescope pointings 940 1137 """ 941 1138 from matplotlib import pylab as PL 942 from numpy import array 1139 from numpy import array, pi 1140 self._data = scan 1141 self._outfile = outfile 943 1142 dir = array(self._data.get_directionval()).transpose() 944 1143 ra = dir[0]*180./pi 945 1144 dec = dir[1]*180./pi 946 1145 PL.cla() 947 PL.ioff()1146 #PL.ioff() 948 1147 PL.clf() 949 ax = PL.axes([0.1,0.1,0.8,0.8]) 950 ax = PL.axes([0.1,0.1,0.8,0.8]) 1148 # Adjust subplot layouts 1149 if len(self._panellayout) !=6: self.set_panellayout(refresh=False) 1150 lef, bot, rig, top, wsp, hsp = self._panellayout 1151 PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top, 1152 wspace=wsp,hspace=hsp) 1153 ax = PL.gca() 1154 #ax = PL.axes([0.1,0.1,0.8,0.8]) 1155 #ax = PL.axes([0.1,0.1,0.8,0.8]) 951 1156 ax.set_aspect('equal') 952 1157 PL.plot(ra, dec, 'b,') … … 956 1161 [xmin,xmax,ymin,ymax] = PL.axis() 957 1162 PL.axis([xmax,xmin,ymin,ymax]) 958 PL.ion()1163 #PL.ion() 959 1164 PL.draw() 1165 if (self._outfile is not None): 1166 PL.savefig(self._outfile) 1167 1168 # plot total power data 1169 # plotting in time is not yet implemented.. 1170 def plottp(self, scan=None, outfile=None): 1171 if self._plotter.is_dead: 1172 if hasattr(self._plotter.figmgr,'casabar'): 1173 del self._plotter.figmgr.casabar 1174 self._plotter = self._newplotter() 1175 self._plotter.figmgr.casabar=self._newcasabar() 1176 self._plotter.hold() 1177 self._plotter.clear() 1178 from asap import scantable 1179 if not self._data and not scan: 1180 msg = "Input is not a scantable" 1181 if rcParams['verbose']: 1182 #print msg 1183 asaplog.push( msg ) 1184 print_log( 'ERROR' ) 1185 return 1186 raise TypeError(msg) 1187 if isinstance(scan, scantable): 1188 if self._data is not None: 1189 if scan != self._data: 1190 self._data = scan 1191 # reset 1192 self._reset() 1193 else: 1194 self._data = scan 1195 self._reset() 1196 # ranges become invalid when abcissa changes? 1197 #if self._abcunit and self._abcunit != self._data.get_unit(): 1198 # self._minmaxx = None 1199 # self._minmaxy = None 1200 # self._abcunit = self._data.get_unit() 1201 # self._datamask = None 1202 1203 # Adjust subplot layouts 1204 if len(self._panellayout) !=6: self.set_panellayout(refresh=False) 1205 lef, bot, rig, top, wsp, hsp = self._panellayout 1206 self._plotter.figure.subplots_adjust( 1207 left=lef,bottom=bot,right=rig,top=top,wspace=wsp,hspace=hsp) 1208 if self._plotter.figmgr.casabar: self._plotter.figmgr.casabar.disable_button() 1209 self._plottp(self._data) 1210 if self._minmaxy is not None: 1211 self._plotter.set_limits(ylim=self._minmaxy) 1212 self._plotter.release() 1213 self._plotter.tidy() 1214 self._plotter.show(hardrefresh=False) 1215 print_log() 1216 return 1217 1218 def _plottp(self,scan): 1219 """ 1220 private method for plotting total power data 1221 """ 1222 from matplotlib.numerix import ma, array, arange, logical_not 1223 r=0 1224 nr = scan.nrow() 1225 a0,b0 = -1,-1 1226 allxlim = [] 1227 allylim = [] 1228 y=[] 1229 self._plotter.set_panels() 1230 self._plotter.palette(0) 1231 #title 1232 #xlab = self._abcissa and self._abcissa[panelcount] \ 1233 # or scan._getabcissalabel() 1234 #ylab = self._ordinate and self._ordinate[panelcount] \ 1235 # or scan._get_ordinate_label() 1236 xlab = self._abcissa or 'row number' #or Time 1237 ylab = self._ordinate or scan._get_ordinate_label() 1238 self._plotter.set_axes('xlabel',xlab) 1239 self._plotter.set_axes('ylabel',ylab) 1240 lbl = self._get_label(scan, r, 's', self._title) 1241 if isinstance(lbl, list) or isinstance(lbl, tuple): 1242 # if 0 <= panelcount < len(lbl): 1243 # lbl = lbl[panelcount] 1244 # else: 1245 # get default label 1246 lbl = self._get_label(scan, r, self._panelling, None) 1247 self._plotter.set_axes('title',lbl) 1248 y=array(scan._get_column(scan._getspectrum,-1)) 1249 m = array(scan._get_column(scan._getmask,-1)) 1250 y = ma.masked_array(y,mask=logical_not(array(m,copy=False))) 1251 x = arange(len(y)) 1252 # try to handle spectral data somewhat... 1253 l,m = y.shape 1254 if m > 1: 1255 y=y.mean(axis=1) 1256 plotit = self._plotter.plot 1257 llbl = self._get_label(scan, r, self._stacking, None) 1258 self._plotter.set_line(label=llbl) 1259 if len(x) > 0: 1260 plotit(x,y) 1261 1262 1263 # forwards to matplotlib.Figure.text 1264 def figtext(self, *args, **kwargs): 1265 """ 1266 Add text to figure at location x,y (relative 0-1 coords). 1267 This method forwards *args and **kwargs to a Matplotlib method, 1268 matplotlib.Figure.text. 1269 See the method help for detailed information. 1270 """ 1271 self._plotter.text(*args, **kwargs) 1272 # end matplotlib.Figure.text forwarding function 1273 1274 1275 # printing header information 1276 def print_header(self, plot=True, fontsize=9, logger=False, selstr='', extrastr=''): 1277 """ 1278 print data (scantable) header on the plot and/or logger. 1279 Parameters: 1280 plot: whether or not print header info on the plot. 1281 fontsize: header font size (valid only plot=True) 1282 autoscale: whether or not autoscale the plot (valid only plot=True) 1283 logger: whether or not print header info on the logger. 1284 selstr: additional selection string (not verified) 1285 extrastr: additional string to print (not verified) 1286 """ 1287 if not plot and not logger: return 1288 if not self._data: raise RuntimeError("No scantable has been set yet.") 1289 # Now header will be printed on plot and/or logger. 1290 # Get header information and format it. 1291 ssum=self._data.__str__() 1292 # Print Observation header to the upper-left corner of plot 1293 if plot: 1294 headstr=[ssum[ssum.find('Observer:'):ssum.find('Flux Unit:')]] 1295 headstr.append(ssum[ssum.find('Beams:'):ssum.find('Observer:')] 1296 +ssum[ssum.find('Rest Freqs:'):ssum.find('Abcissa:')]) 1297 if extrastr != '': headstr[0]=extrastr+'\n'+headstr[0] 1298 #headstr[1]='Data File: '+(filestr or 'unknown')+'\n'+headstr[1] 1299 ssel='***Selections***\n'+(selstr+self._data.get_selection().__str__() or 'none') 1300 headstr.append(ssel) 1301 nstcol=len(headstr) 1302 1303 self._plotter.hold() 1304 for i in range(nstcol): 1305 self._plotter.figure.text(0.03+float(i)/nstcol,0.98, 1306 headstr[i], 1307 horizontalalignment='left', 1308 verticalalignment='top', 1309 fontsize=fontsize) 1310 import time 1311 self._plotter.figure.text(0.99,0.0, 1312 time.strftime("%a %d %b %Y %H:%M:%S %Z"), 1313 horizontalalignment='right', 1314 verticalalignment='bottom',fontsize=8) 1315 self._plotter.release() 1316 del headstr, ssel 1317 if logger: 1318 asaplog.push("----------------\n Plot Summary\n----------------") 1319 asaplog.push(extrastr) 1320 asaplog.push(ssum[ssum.find('Beams:'):]) 1321 print_log() 1322 del ssum 1323 1324 -
branches/mergetest/python/asapreader.py
r1695 r1779 1 1 from asap._asap import stfiller 2 from asap import print_log _dec2 from asap import print_log, print_log_dec 3 3 4 4 class reader(stfiller): … … 25 25 rpfits ONLY. 26 26 """ 27 @print_log_dec27 #@print_log_dec 28 28 def __init__(self, filename, unit=None, theif=None, thebeam=None): 29 29 self.unit = unit … … 46 46 filename = expandvars(filename) 47 47 stfiller.__init__(self, filename, theif, thebeam) 48 print_log() 48 49 49 @print_log_dec50 #@print_log_dec 50 51 def read(self): 51 52 """ … … 59 60 if self.unit is not None: 60 61 tbl.set_fluxunit(self.unit) 62 print_log() 61 63 return scantable(tbl) 62 64 -
branches/mergetest/python/linecatalog.py
r1534 r1779 8 8 from asap._asap import linecatalog as lcbase 9 9 from asap import rcParams 10 from asap import asaplog 10 11 import os 11 12 … … 30 31 msg = "File '%s' not found" % fpath 31 32 if rcParams['verbose']: 32 print msg 33 #print msg 34 asaplog.push( msg ) 35 print_log( 'ERROR' ) 33 36 return 34 37 else: … … 97 100 msg = "File %s exists." % name 98 101 if rcParams['verbose']: 99 print msg 102 #print msg 103 asaplog.push( msg ) 104 print_log( 'ERROR' ) 100 105 return 101 106 else: -
branches/mergetest/python/scantable.py
r1731 r1779 35 35 The ASAP container for scans 36 36 """ 37 @print_log_dec 38 def __init__(self, filename, average=None, unit=None, parallactify=None): 37 38 #@print_log_dec 39 def __init__(self, filename, average=None, unit=None, getpt=None, antenna=None, parallactify=None): 39 40 """ 40 41 Create a scantable from a saved one or make a reference … … 54 55 (input rpfits/sdfits/ms) or replaces the value 55 56 in existing scantables 57 getpt: for MeasurementSet input data only: 58 If True, all pointing data are filled. 59 The deafult is False, which makes time to load 60 the MS data faster in some cases. 61 antenna: Antenna selection. integer (id) or string (name 62 or id). 56 63 parallactify: Indcicate that the data had been parallatified. 57 64 Default is taken form rc file. … … 59 66 if average is None: 60 67 average = rcParams['scantable.autoaverage'] 68 if getpt is None: 69 getpt = True 70 if antenna is None: 71 antenna = '' 72 elif type(antenna) == int: 73 antenna = '%s'%antenna 74 elif type(antenna) == list: 75 tmpstr = '' 76 for i in range( len(antenna) ): 77 if type(antenna[i]) == int: 78 tmpstr = tmpstr + ('%s,'%(antenna[i])) 79 elif type(antenna[i]) == str: 80 tmpstr=tmpstr+antenna[i]+',' 81 else: 82 asaplog.push('Bad antenna selection.') 83 print_log('ERROR') 84 return 85 antenna = tmpstr.rstrip(',') 61 86 parallactify = parallactify or rcParams['scantable.parallactify'] 62 87 varlist = vars() 63 88 from asap._asap import stmath 64 self._math = stmath( )89 self._math = stmath( rcParams['insitu'] ) 65 90 if isinstance(filename, Scantable): 66 91 Scantable.__init__(self, filename) … … 73 98 if rcParams['verbose']: 74 99 asaplog.push(s) 100 print_log('ERROR') 75 101 return 76 102 raise IOError(s) … … 80 106 if unit is not None: 81 107 self.set_fluxunit(unit) 82 self.set_freqframe(rcParams['scantable.freqframe']) 108 # do not reset to the default freqframe 109 #self.set_freqframe(rcParams['scantable.freqframe']) 110 elif os.path.isdir(filename) \ 111 and not os.path.exists(filename+'/table.f1'): 112 msg = "The given file '%s'is not a valid " \ 113 "asap table." % (filename) 114 if rcParams['verbose']: 115 #print msg 116 asaplog.push( msg ) 117 print_log( 'ERROR' ) 118 return 119 else: 120 raise IOError(msg) 83 121 else: 84 self._fill([filename], unit, average )122 self._fill([filename], unit, average, getpt, antenna) 85 123 elif (isinstance(filename, list) or isinstance(filename, tuple)) \ 86 124 and isinstance(filename[-1], str): 87 self._fill(filename, unit, average )125 self._fill(filename, unit, average, getpt, antenna) 88 126 self.parallactify(parallactify) 89 127 self._add_history("scantable", varlist) 90 91 @print_log_dec 128 print_log() 129 130 #@print_log_dec 92 131 def save(self, name=None, format=None, overwrite=False): 93 132 """ … … 126 165 msg = "File %s exists." % name 127 166 if rcParams['verbose']: 128 print msg 167 #print msg 168 asaplog.push( msg ) 169 print_log( 'ERROR' ) 129 170 return 130 171 else: … … 137 178 writer = stw(format2) 138 179 writer.write(self, name) 180 print_log() 139 181 return 140 182 … … 164 206 if not _is_valid(scanid): 165 207 if rcParams['verbose']: 166 print "Please specify a scanno to drop from the scantable" 208 #print "Please specify a scanno to drop from the scantable" 209 asaplog.push( 'Please specify a scanno to drop from the scantable' ) 210 print_log( 'ERROR' ) 167 211 return 168 212 else: … … 176 220 except ValueError: 177 221 if rcParams['verbose']: 178 print "Couldn't find any match." 222 #print "Couldn't find any match." 223 print_log() 224 asaplog.push( "Couldn't find any match." ) 225 print_log( 'ERROR' ) 179 226 return 180 227 else: raise … … 184 231 except RuntimeError: 185 232 if rcParams['verbose']: 186 print "Couldn't find any match." 233 #print "Couldn't find any match." 234 print_log() 235 asaplog.push( "Couldn't find any match." ) 236 print_log( 'ERROR' ) 187 237 else: 188 238 raise … … 215 265 if scanid is None: 216 266 if rcParams['verbose']: 217 print "Please specify a scan no or name to " \ 218 "retrieve from the scantable" 267 #print "Please specify a scan no or name to " \ 268 # "retrieve from the scantable" 269 asaplog.push( 'Please specify a scan no or name to retrieve from the scantable' ) 270 print_log( 'ERROR' ) 219 271 return 220 272 else: … … 236 288 msg = "Illegal scanid type, use 'int' or 'list' if ints." 237 289 if rcParams['verbose']: 238 print msg 290 #print msg 291 asaplog.push( msg ) 292 print_log( 'ERROR' ) 239 293 else: 240 294 raise TypeError(msg) 241 295 except RuntimeError: 242 if rcParams['verbose']: print "Couldn't find any match." 296 if rcParams['verbose']: 297 #print "Couldn't find any match." 298 print_log() 299 asaplog.push( "Couldn't find any match." ) 300 print_log( 'ERROR' ) 243 301 else: raise 244 302 … … 266 324 msg = "Illegal file name '%s'." % (filename) 267 325 if rcParams['verbose']: 268 print msg 326 #print msg 327 asaplog.push( msg ) 328 print_log( 'ERROR' ) 269 329 else: 270 330 raise IOError(msg) … … 367 427 self._setselection(selection) 368 428 369 def stats(self, stat='stddev', mask=None): 429 def get_row(self, row=0, insitu=None): 430 """ 431 Select a row in the scantable. 432 Return a scantable with single row. 433 Parameters: 434 row: row no of integration, default is 0. 435 insitu: if False a new scantable is returned. 436 Otherwise, the scaling is done in-situ 437 The default is taken from .asaprc (False) 438 """ 439 if insitu is None: insitu = rcParams['insitu'] 440 if not insitu: 441 workscan = self.copy() 442 else: 443 workscan = self 444 # Select a row 445 sel=selector() 446 sel.set_scans([workscan.getscan(row)]) 447 sel.set_cycles([workscan.getcycle(row)]) 448 sel.set_beams([workscan.getbeam(row)]) 449 sel.set_ifs([workscan.getif(row)]) 450 sel.set_polarisations([workscan.getpol(row)]) 451 sel.set_name(workscan._getsourcename(row)) 452 workscan.set_selection(sel) 453 if not workscan.nrow() == 1: 454 msg = "Cloud not identify single row. %d rows selected."%(workscan.nrow()) 455 raise RuntimeError(msg) 456 del sel 457 if insitu: 458 self._assign(workscan) 459 else: 460 return workscan 461 462 #def stats(self, stat='stddev', mask=None): 463 def stats(self, stat='stddev', mask=None, form='3.3f'): 370 464 """ 371 465 Determine the specified statistic of the current beam/if/pol … … 373 467 channels should be excluded. 374 468 Parameters: 375 stat: 'min', 'max', ' sumsq', 'sum', 'mean'376 ' var', 'stddev', 'avdev', 'rms', 'median'469 stat: 'min', 'max', 'min_abc', 'max_abc', 'sumsq', 'sum', 470 'mean', 'var', 'stddev', 'avdev', 'rms', 'median' 377 471 mask: an optional mask specifying where the statistic 378 472 should be determined. 473 form: format string to print statistic values 379 474 Example: 380 475 scan.set_unit('channel') … … 387 482 "number of channels. Please use setselection() " 388 483 "to select individual IFs") 389 390 statvals = self._math._stats(self, mask, stat) 391 def cb(i): 392 return statvals[i] 393 394 return self._row_callback(cb, stat) 484 rtnabc = False 485 if stat.lower().endswith('_abc'): rtnabc = True 486 getchan = False 487 if stat.lower().startswith('min') or stat.lower().startswith('max'): 488 chan = self._math._minmaxchan(self, mask, stat) 489 getchan = True 490 statvals = [] 491 if not rtnabc: statvals = self._math._stats(self, mask, stat) 492 493 #def cb(i): 494 # return statvals[i] 495 496 #return self._row_callback(cb, stat) 497 498 label=stat 499 #callback=cb 500 out = "" 501 #outvec = [] 502 sep = '-'*50 503 for i in range(self.nrow()): 504 refstr = '' 505 statunit= '' 506 if getchan: 507 qx, qy = self.chan2data(rowno=i, chan=chan[i]) 508 if rtnabc: 509 statvals.append(qx['value']) 510 refstr = ('(value: %'+form) % (qy['value'])+' ['+qy['unit']+'])' 511 statunit= '['+qx['unit']+']' 512 else: 513 refstr = ('(@ %'+form) % (qx['value'])+' ['+qx['unit']+'])' 514 515 tm = self._gettime(i) 516 src = self._getsourcename(i) 517 out += 'Scan[%d] (%s) ' % (self.getscan(i), src) 518 out += 'Time[%s]:\n' % (tm) 519 if self.nbeam(-1) > 1: 520 out += ' Beam[%d] ' % (self.getbeam(i)) 521 if self.nif(-1) > 1: out += ' IF[%d] ' % (self.getif(i)) 522 if self.npol(-1) > 1: out += ' Pol[%d] ' % (self.getpol(i)) 523 #outvec.append(callback(i)) 524 #out += ('= %'+form) % (outvec[i]) +' '+refstr+'\n' 525 out += ('= %'+form) % (statvals[i]) +' '+refstr+'\n' 526 out += sep+"\n" 527 528 if rcParams['verbose']: 529 import os 530 if os.environ.has_key( 'USER' ): 531 usr=os.environ['USER'] 532 else: 533 import commands 534 usr=commands.getoutput( 'whoami' ) 535 tmpfile='/tmp/tmp_'+usr+'_casapy_asap_scantable_stats' 536 f=open(tmpfile,'w') 537 print >> f, sep 538 print >> f, ' %s %s' % (label, statunit) 539 print >> f, sep 540 print >> f, out 541 f.close() 542 f=open(tmpfile,'r') 543 x=f.readlines() 544 f.close() 545 blanc='' 546 asaplog.push(blanc.join(x), False) 547 #for xx in x: 548 # asaplog.push( xx, False ) 549 print_log() 550 return statvals 551 552 def chan2data(self, rowno=0, chan=0): 553 """ 554 Returns channel/frequency/velocity and spectral value 555 at an arbitrary row and channel in the scantable. 556 Parameters: 557 rowno: a row number in the scantable. Default is the 558 first row, i.e. rowno=0 559 chan: a channel in the scantable. Default is the first 560 channel, i.e. pos=0 561 """ 562 if isinstance(rowno, int) and isinstance(chan, int): 563 qx = {'unit': self.get_unit(), 564 'value': self._getabcissa(rowno)[chan]} 565 qy = {'unit': self.get_fluxunit(), 566 'value': self._getspectrum(rowno)[chan]} 567 return qx, qy 395 568 396 569 def stddev(self, mask=None): … … 462 635 out += sep+'\n' 463 636 if rcParams['verbose']: 464 print sep 465 print " %s" % (label) 466 print sep 467 print out 637 asaplog.push(sep) 638 asaplog.push(" %s" % (label)) 639 asaplog.push(sep) 640 asaplog.push(out) 641 print_log() 468 642 return outvec 469 643 … … 474 648 return [callback(i) for i in range(self.nrow())] 475 649 else: 476 if 0 <= row < self.nrow():650 if 0 <= row < self.nrow(): 477 651 return callback(row) 478 652 … … 578 752 return self._get_column(self._getdirectionvec, row) 579 753 580 @print_log_dec754 #@print_log_dec 581 755 def set_unit(self, unit='channel'): 582 756 """ … … 594 768 self._add_history("set_unit", varlist) 595 769 596 @print_log_dec770 #@print_log_dec 597 771 def set_instrument(self, instr): 598 772 """ … … 604 778 self._setInstrument(instr) 605 779 self._add_history("set_instument", vars()) 606 607 @print_log_dec 780 print_log() 781 782 #@print_log_dec 608 783 def set_feedtype(self, feedtype): 609 784 """ … … 614 789 self._setfeedtype(feedtype) 615 790 self._add_history("set_feedtype", vars()) 616 617 @print_log_dec 791 print_log() 792 793 #@print_log_dec 618 794 def set_doppler(self, doppler='RADIO'): 619 795 """ … … 627 803 self._setcoordinfo(inf) 628 804 self._add_history("set_doppler", vars()) 629 630 @print_log_dec 805 print_log() 806 807 #@print_log_dec 631 808 def set_freqframe(self, frame=None): 632 809 """ … … 634 811 Parameters: 635 812 frame: an optional frame type, default 'LSRK'. Valid frames are: 636 ' REST', 'TOPO', 'LSRD', 'LSRK', 'BARY',813 'TOPO', 'LSRD', 'LSRK', 'BARY', 637 814 'GEO', 'GALACTO', 'LGROUP', 'CMB' 638 815 Examples: … … 641 818 frame = frame or rcParams['scantable.freqframe'] 642 819 varlist = vars() 643 valid = ['REST', 'TOPO', 'LSRD', 'LSRK', 'BARY', \ 820 # "REST" is not implemented in casacore 821 #valid = ['REST', 'TOPO', 'LSRD', 'LSRK', 'BARY', \ 822 # 'GEO', 'GALACTO', 'LGROUP', 'CMB'] 823 valid = ['TOPO', 'LSRD', 'LSRK', 'BARY', \ 644 824 'GEO', 'GALACTO', 'LGROUP', 'CMB'] 645 825 … … 652 832 msg = "Please specify a valid freq type. Valid types are:\n", valid 653 833 if rcParams['verbose']: 654 print msg 834 #print msg 835 asaplog.push( msg ) 836 print_log( 'ERROR' ) 655 837 else: 656 838 raise TypeError(msg) 839 print_log() 657 840 658 841 def set_dirframe(self, frame=""): … … 670 853 except RuntimeError, msg: 671 854 if rcParams['verbose']: 672 print msg 855 #print msg 856 print_log() 857 asaplog.push( str(msg) ) 858 print_log( 'ERROR' ) 673 859 else: 674 860 raise … … 698 884 abc = self._getabcissa(rowno) 699 885 lbl = self._getabcissalabel(rowno) 886 print_log() 700 887 return abc, lbl 701 888 702 def flag(self, mask=None ):889 def flag(self, mask=None, unflag=False): 703 890 """ 704 891 Flag the selected data using an optional channel mask. … … 706 893 mask: an optional channel mask, created with create_mask. Default 707 894 (no mask) is all channels. 895 unflag: if True, unflag the data 708 896 """ 709 897 varlist = vars() 710 898 mask = mask or [] 711 899 try: 712 self._flag(mask )900 self._flag(mask, unflag) 713 901 except RuntimeError, msg: 714 902 if rcParams['verbose']: 715 print msg 903 #print msg 904 print_log() 905 asaplog.push( str(msg) ) 906 print_log( 'ERROR' ) 716 907 return 717 908 else: raise 718 909 self._add_history("flag", varlist) 719 910 720 @print_log_dec 911 def flag_row(self, rows=[], unflag=False): 912 """ 913 Flag the selected data in row-based manner. 914 Parameters: 915 rows: list of row numbers to be flagged. Default is no row (must be explicitly specified to execute row-based flagging). 916 unflag: if True, unflag the data. 917 """ 918 varlist = vars() 919 try: 920 self._flag_row(rows, unflag) 921 except RuntimeError, msg: 922 if rcParams['verbose']: 923 print_log() 924 asaplog.push( str(msg) ) 925 print_log('ERROR') 926 return 927 else: raise 928 self._add_history("flag_row", varlist) 929 930 def clip(self, uthres=None, dthres=None, clipoutside=True, unflag=False): 931 """ 932 Flag the selected data outside a specified range (in channel-base) 933 Parameters: 934 uthres: upper threshold. 935 dthres: lower threshold 936 clipoutside: True for flagging data outside the range [dthres:uthres]. 937 False for glagging data inside the range. 938 unflag : if True, unflag the data. 939 """ 940 varlist = vars() 941 try: 942 self._clip(uthres, dthres, clipoutside, unflag) 943 except RuntimeError, msg: 944 if rcParams['verbose']: 945 print_log() 946 asaplog.push(str(msg)) 947 print_log('ERROR') 948 return 949 else: raise 950 self._add_history("clip", varlist) 951 952 #@print_log_dec 721 953 def lag_flag(self, start, end, unit="MHz", insitu=None): 954 #def lag_flag(self, frequency, width=0.0, unit="GHz", insitu=None): 722 955 """ 723 956 Flag the data in 'lag' space by providing a frequency to remove. … … 748 981 except RuntimeError, msg: 749 982 if rcParams['verbose']: 750 print msg 983 #print msg 984 print_log() 985 asaplog.push( str(msg) ) 986 print_log( 'ERROR' ) 751 987 return 752 988 else: raise 753 989 s._add_history("lag_flag", varlist) 990 print_log() 754 991 if insitu: 755 992 self._assign(s) … … 757 994 return s 758 995 759 @print_log_dec996 #@print_log_dec 760 997 def create_mask(self, *args, **kwargs): 761 998 """ … … 819 1056 if kwargs.get('invert'): 820 1057 msk = mask_not(msk) 1058 print_log() 821 1059 return msk 822 1060 823 def get_restfreqs(self): 1061 def get_masklist(self, mask=None, row=0): 1062 """ 1063 Compute and return a list of mask windows, [min, max]. 1064 Parameters: 1065 mask: channel mask, created with create_mask. 1066 row: calcutate the masklist using the specified row 1067 for unit conversions, default is row=0 1068 only necessary if frequency varies over rows. 1069 Returns: 1070 [min, max], [min2, max2], ... 1071 Pairs of start/end points (inclusive)specifying 1072 the masked regions 1073 """ 1074 if not (isinstance(mask,list) or isinstance(mask, tuple)): 1075 raise TypeError("The mask should be list or tuple.") 1076 if len(mask) < 2: 1077 raise TypeError("The mask elements should be > 1") 1078 if self.nchan() != len(mask): 1079 msg = "Number of channels in scantable != number of mask elements" 1080 raise TypeError(msg) 1081 data = self._getabcissa(row) 1082 u = self._getcoordinfo()[0] 1083 if rcParams['verbose']: 1084 if u == "": u = "channel" 1085 msg = "The current mask window unit is %s" % u 1086 i = self._check_ifs() 1087 if not i: 1088 msg += "\nThis mask is only valid for IF=%d" % (self.getif(i)) 1089 asaplog.push(msg) 1090 masklist=[] 1091 ist, ien = None, None 1092 ist, ien=self.get_mask_indices(mask) 1093 if ist is not None and ien is not None: 1094 for i in xrange(len(ist)): 1095 range=[data[ist[i]],data[ien[i]]] 1096 range.sort() 1097 masklist.append([range[0],range[1]]) 1098 return masklist 1099 1100 def get_mask_indices(self, mask=None): 1101 """ 1102 Compute and Return lists of mask start indices and mask end indices. 1103 Parameters: 1104 mask: channel mask, created with create_mask. 1105 Returns: 1106 List of mask start indices and that of mask end indices, 1107 i.e., [istart1,istart2,....], [iend1,iend2,....]. 1108 """ 1109 if not (isinstance(mask,list) or isinstance(mask, tuple)): 1110 raise TypeError("The mask should be list or tuple.") 1111 if len(mask) < 2: 1112 raise TypeError("The mask elements should be > 1") 1113 istart=[] 1114 iend=[] 1115 if mask[0]: istart.append(0) 1116 for i in range(len(mask)-1): 1117 if not mask[i] and mask[i+1]: 1118 istart.append(i+1) 1119 elif mask[i] and not mask[i+1]: 1120 iend.append(i) 1121 if mask[len(mask)-1]: iend.append(len(mask)-1) 1122 if len(istart) != len(iend): 1123 raise RuntimeError("Numbers of mask start != mask end.") 1124 for i in range(len(istart)): 1125 if istart[i] > iend[i]: 1126 raise RuntimeError("Mask start index > mask end index") 1127 break 1128 return istart,iend 1129 1130 # def get_restfreqs(self): 1131 # """ 1132 # Get the restfrequency(s) stored in this scantable. 1133 # The return value(s) are always of unit 'Hz' 1134 # Parameters: 1135 # none 1136 # Returns: 1137 # a list of doubles 1138 # """ 1139 # return list(self._getrestfreqs()) 1140 1141 def get_restfreqs(self, ids=None): 824 1142 """ 825 1143 Get the restfrequency(s) stored in this scantable. 826 1144 The return value(s) are always of unit 'Hz' 827 1145 Parameters: 828 none 1146 ids: (optional) a list of MOLECULE_ID for that restfrequency(s) to 1147 be retrieved 829 1148 Returns: 830 a list of doubles 831 """ 832 return list(self._getrestfreqs()) 833 1149 dictionary containing ids and a list of doubles for each id 1150 """ 1151 if ids is None: 1152 rfreqs={} 1153 idlist = self.getmolnos() 1154 for i in idlist: 1155 rfreqs[i]=list(self._getrestfreqs(i)) 1156 return rfreqs 1157 else: 1158 if type(ids)==list or type(ids)==tuple: 1159 rfreqs={} 1160 for i in ids: 1161 rfreqs[i]=list(self._getrestfreqs(i)) 1162 return rfreqs 1163 else: 1164 return list(self._getrestfreqs(ids)) 1165 #return list(self._getrestfreqs(ids)) 834 1166 835 1167 def set_restfreqs(self, freqs=None, unit='Hz'): 836 1168 """ 1169 ********NEED TO BE UPDATED begin************ 837 1170 Set or replace the restfrequency specified and 838 1171 If the 'freqs' argument holds a scalar, … … 846 1179 E.g. 'freqs=[1e9, 2e9]' would mean IF 0 gets restfreq 1e9 and 847 1180 IF 1 gets restfreq 2e9. 1181 ********NEED TO BE UPDATED end************ 848 1182 You can also specify the frequencies via a linecatalog. 849 1183 … … 853 1187 854 1188 Example: 855 # set the given restfrequency for the whole table1189 # set the given restfrequency for the all currently selected IFs 856 1190 scan.set_restfreqs(freqs=1.4e9) 857 # If thee number of IFs in the data is >= 2 IF0 gets the first 858 # value IF1 the second... 859 scan.set_restfreqs(freqs=[1.4e9, 1.67e9]) 1191 # set multiple restfrequencies to all the selected data 1192 scan.set_restfreqs(freqs=[1.4e9, 1.41e9, 1.42e9]) 1193 # If the number of IFs in the data is >= 2 the IF0 gets the first 1194 # value IF1 the second... NOTE that freqs needs to be 1195 # specified in list of list (e.g. [[],[],...] ). 1196 scan.set_restfreqs(freqs=[[1.4e9],[1.67e9]]) 860 1197 #set the given restfrequency for the whole table (by name) 861 1198 scan.set_restfreqs(freqs="OH1667") … … 877 1214 # simple value 878 1215 if isinstance(freqs, int) or isinstance(freqs, float): 879 self._setrestfreqs(freqs, "",unit) 1216 # TT mod 1217 #self._setrestfreqs(freqs, "",unit) 1218 self._setrestfreqs([freqs], [""],unit) 880 1219 # list of values 881 1220 elif isinstance(freqs, list) or isinstance(freqs, tuple): 882 1221 # list values are scalars 883 1222 if isinstance(freqs[-1], int) or isinstance(freqs[-1], float): 1223 self._setrestfreqs(freqs, [""],unit) 1224 # list values are tuples, (value, name) 1225 elif isinstance(freqs[-1], dict): 1226 #sel = selector() 1227 #savesel = self._getselection() 1228 #iflist = self.getifnos() 1229 #for i in xrange(len(freqs)): 1230 # sel.set_ifs(iflist[i]) 1231 # self._setselection(sel) 1232 # self._setrestfreqs(freqs[i], "",unit) 1233 #self._setselection(savesel) 1234 self._setrestfreqs(freqs["value"], 1235 freqs["name"], "MHz") 1236 elif isinstance(freqs[-1], list) or isinstance(freqs[-1], tuple): 884 1237 sel = selector() 885 1238 savesel = self._getselection() 886 1239 iflist = self.getifnos() 887 for i in xrange(len(freqs)): 888 sel.set_ifs(iflist[i]) 889 self._setselection(sel) 890 self._setrestfreqs(freqs[i], "",unit) 891 self._setselection(savesel) 892 # list values are tuples, (value, name) 893 elif isinstance(freqs[-1], dict): 894 sel = selector() 895 savesel = self._getselection() 896 iflist = self.getifnos() 1240 if len(freqs)>len(iflist): 1241 raise ValueError("number of elements in list of list exeeds the current IF selections") 897 1242 for i in xrange(len(freqs)): 898 1243 sel.set_ifs(iflist[i]) … … 905 1250 sel = selector() 906 1251 savesel = self._getselection() 907 iflist = self.getifnos()908 1252 for i in xrange(freqs.nrow()): 909 1253 sel.set_ifs(iflist[i]) … … 963 1307 msg = "Illegal file name '%s'." % (filename) 964 1308 if rcParams['verbose']: 965 print msg 1309 #print msg 1310 asaplog.push( msg ) 1311 print_log( 'ERROR' ) 966 1312 else: 967 1313 raise IOError(msg) … … 978 1324 # Maths business 979 1325 # 980 @print_log_dec1326 #@print_log_dec 981 1327 def average_time(self, mask=None, scanav=False, weight='tint', align=False): 982 1328 """ … … 1020 1366 except RuntimeError, msg: 1021 1367 if rcParams['verbose']: 1022 print msg 1368 #print msg 1369 print_log() 1370 asaplog.push( str(msg) ) 1371 print_log( 'ERROR' ) 1023 1372 return 1024 1373 else: raise 1025 1374 s._add_history("average_time", varlist) 1375 print_log() 1026 1376 return s 1027 1377 1028 @print_log_dec1378 #@print_log_dec 1029 1379 def convert_flux(self, jyperk=None, eta=None, d=None, insitu=None): 1030 1380 """ … … 1051 1401 s = scantable(self._math._convertflux(self, d, eta, jyperk)) 1052 1402 s._add_history("convert_flux", varlist) 1403 print_log() 1053 1404 if insitu: self._assign(s) 1054 1405 else: return s 1055 1406 1056 @print_log_dec1407 #@print_log_dec 1057 1408 def gain_el(self, poly=None, filename="", method="linear", insitu=None): 1058 1409 """ … … 1103 1454 s = scantable(self._math._gainel(self, poly, filename, method)) 1104 1455 s._add_history("gain_el", varlist) 1456 print_log() 1105 1457 if insitu: 1106 1458 self._assign(s) … … 1108 1460 return s 1109 1461 1110 @print_log_dec1462 #@print_log_dec 1111 1463 def freq_align(self, reftime=None, method='cubic', insitu=None): 1112 1464 """ … … 1130 1482 s = scantable(self._math._freq_align(self, reftime, method)) 1131 1483 s._add_history("freq_align", varlist) 1484 print_log() 1132 1485 if insitu: self._assign(s) 1133 1486 else: return s 1134 1487 1135 @print_log_dec1488 #@print_log_dec 1136 1489 def opacity(self, tau=None, insitu=None): 1137 1490 """ … … 1158 1511 s = scantable(self._math._opacity(self, tau)) 1159 1512 s._add_history("opacity", varlist) 1513 print_log() 1160 1514 if insitu: self._assign(s) 1161 1515 else: return s 1162 1516 1163 @print_log_dec1517 #@print_log_dec 1164 1518 def bin(self, width=5, insitu=None): 1165 1519 """ … … 1176 1530 s = scantable(self._math._bin(self, width)) 1177 1531 s._add_history("bin", varlist) 1532 print_log() 1178 1533 if insitu: 1179 1534 self._assign(s) … … 1181 1536 return s 1182 1537 1183 @print_log_dec1538 #@print_log_dec 1184 1539 def resample(self, width=5, method='cubic', insitu=None): 1185 1540 """ 1186 1541 Return a scan where all spectra have been binned up. 1187 1542 1188 1543 Parameters: 1189 1544 width: The bin width (default=5) in pixels … … 1200 1555 s = scantable(self._math._resample(self, method, width)) 1201 1556 s._add_history("resample", varlist) 1557 print_log() 1202 1558 if insitu: self._assign(s) 1203 1559 else: return s 1204 1560 1205 @print_log_dec1561 #@print_log_dec 1206 1562 def average_pol(self, mask=None, weight='none'): 1207 1563 """ … … 1218 1574 s = scantable(self._math._averagepol(self, mask, weight.upper())) 1219 1575 s._add_history("average_pol", varlist) 1576 print_log() 1220 1577 return s 1221 1578 1222 @print_log_dec1579 #@print_log_dec 1223 1580 def average_beam(self, mask=None, weight='none'): 1224 1581 """ … … 1235 1592 s = scantable(self._math._averagebeams(self, mask, weight.upper())) 1236 1593 s._add_history("average_beam", varlist) 1594 print_log() 1237 1595 return s 1238 1596 … … 1249 1607 self._add_history("parallactify", varlist) 1250 1608 1251 @print_log_dec1609 #@print_log_dec 1252 1610 def convert_pol(self, poltype=None): 1253 1611 """ … … 1263 1621 except RuntimeError, msg: 1264 1622 if rcParams['verbose']: 1265 print msg 1623 #print msg 1624 print_log() 1625 asaplog.push( str(msg) ) 1626 print_log( 'ERROR' ) 1266 1627 return 1267 1628 else: 1268 1629 raise 1269 1630 s._add_history("convert_pol", varlist) 1631 print_log() 1270 1632 return s 1271 1633 1272 @print_log_dec1273 def smooth(self, kernel="hanning", width=5.0, order=2, insitu=None):1634 #@print_log_dec 1635 def smooth(self, kernel="hanning", width=5.0, order=2, plot=False, insitu=None): 1274 1636 """ 1275 1637 Smooth the spectrum by the specified kernel (conserving flux). … … 1286 1648 specify the order of the polnomial. Ignored by all other 1287 1649 kernels. 1650 plot: plot the original and the smoothed spectra. 1651 In this each indivual fit has to be approved, by 1652 typing 'y' or 'n' 1288 1653 insitu: if False a new scantable is returned. 1289 1654 Otherwise, the scaling is done in-situ … … 1295 1660 self._math._setinsitu(insitu) 1296 1661 varlist = vars() 1662 1663 if plot: orgscan = self.copy() 1664 1297 1665 s = scantable(self._math._smooth(self, kernel.lower(), width, order)) 1298 1666 s._add_history("smooth", varlist) 1667 1668 if plot: 1669 if rcParams['plotter.gui']: 1670 from asap.asaplotgui import asaplotgui as asaplot 1671 else: 1672 from asap.asaplot import asaplot 1673 self._p=asaplot() 1674 self._p.set_panels() 1675 ylab=s._get_ordinate_label() 1676 #self._p.palette(0,["#777777","red"]) 1677 for r in xrange(s.nrow()): 1678 xsm=s._getabcissa(r) 1679 ysm=s._getspectrum(r) 1680 xorg=orgscan._getabcissa(r) 1681 yorg=orgscan._getspectrum(r) 1682 self._p.clear() 1683 self._p.hold() 1684 self._p.set_axes('ylabel',ylab) 1685 self._p.set_axes('xlabel',s._getabcissalabel(r)) 1686 self._p.set_axes('title',s._getsourcename(r)) 1687 self._p.set_line(label='Original',color="#777777") 1688 self._p.plot(xorg,yorg) 1689 self._p.set_line(label='Smoothed',color="red") 1690 self._p.plot(xsm,ysm) 1691 ### Ugly part for legend 1692 for i in [0,1]: 1693 self._p.subplots[0]['lines'].append([self._p.subplots[0]['axes'].lines[i]]) 1694 self._p.release() 1695 ### Ugly part for legend 1696 self._p.subplots[0]['lines']=[] 1697 res = raw_input("Accept smoothing ([y]/n): ") 1698 if res.upper() == 'N': 1699 s._setspectrum(yorg, r) 1700 self._p.unmap() 1701 self._p = None 1702 del orgscan 1703 1704 print_log() 1299 1705 if insitu: self._assign(s) 1300 1706 else: return s 1301 1707 1302 @print_log_dec1708 #@print_log_dec 1303 1709 def poly_baseline(self, mask=None, order=0, plot=False, uselin=False, 1304 1710 insitu=None): … … 1321 1727 """ 1322 1728 if insitu is None: insitu = rcParams['insitu'] 1729 if not insitu: 1730 workscan = self.copy() 1731 else: 1732 workscan = self 1323 1733 varlist = vars() 1324 1734 if mask is None: 1325 1735 mask = [True for i in xrange(self.nchan(-1))] 1736 1326 1737 from asap.asapfitter import fitter 1327 1738 try: 1328 1739 f = fitter() 1329 f.set_scan(self, mask)1330 #f.set_function(poly=order)1331 1740 if uselin: 1332 1741 f.set_function(lpoly=order) 1333 1742 else: 1334 1743 f.set_function(poly=order) 1335 s = f.auto_fit(insitu, plot=plot) 1336 s._add_history("poly_baseline", varlist) 1337 if insitu: self._assign(s) 1338 else: return s 1744 1745 rows = range(workscan.nrow()) 1746 if len(rows) > 0: 1747 self.blpars = [] 1748 1749 for r in rows: 1750 # take into account flagtra info (CAS-1434) 1751 flagtra = workscan._getmask(r) 1752 actualmask = mask[:] 1753 if len(actualmask) == 0: 1754 actualmask = list(flagtra[:]) 1755 else: 1756 if len(actualmask) != len(flagtra): 1757 raise RuntimeError, "Mask and flagtra have different length" 1758 else: 1759 for i in range(0, len(actualmask)): 1760 actualmask[i] = actualmask[i] and flagtra[i] 1761 f.set_scan(workscan, actualmask) 1762 f.x = workscan._getabcissa(r) 1763 f.y = workscan._getspectrum(r) 1764 f.data = None 1765 f.fit() 1766 if plot: 1767 f.plot(residual=True) 1768 x = raw_input("Accept fit ( [y]/n ): ") 1769 if x.upper() == 'N': 1770 self.blpars.append(None) 1771 continue 1772 workscan._setspectrum(f.fitter.getresidual(), r) 1773 self.blpars.append(f.get_parameters()) 1774 1775 if plot: 1776 f._p.unmap() 1777 f._p = None 1778 workscan._add_history("poly_baseline", varlist) 1779 print_log() 1780 if insitu: self._assign(workscan) 1781 else: return workscan 1339 1782 except RuntimeError: 1340 1783 msg = "The fit failed, possibly because it didn't converge." 1341 1784 if rcParams['verbose']: 1342 print msg 1785 #print msg 1786 print_log() 1787 asaplog.push( str(msg) ) 1788 print_log( 'ERROR' ) 1343 1789 return 1344 1790 else: 1345 1791 raise RuntimeError(msg) 1792 1346 1793 1347 1794 def auto_poly_baseline(self, mask=[], edge=(0, 0), order=0, … … 1427 1874 1428 1875 rows = range(workscan.nrow()) 1876 # Save parameters of baseline fits & masklists as a class attribute. 1877 # NOTICE: It does not reflect changes in scantable! 1878 if len(rows) > 0: 1879 self.blpars=[] 1880 self.masklists=[] 1429 1881 asaplog.push("Processing:") 1430 1882 for r in rows: … … 1441 1893 curedge = edge[workscan.getif(r)] 1442 1894 1895 # take into account flagtra info (CAS-1434) 1896 flagtra = workscan._getmask(r) 1897 actualmask = mask[:] 1898 if len(actualmask) == 0: 1899 actualmask = list(flagtra[:]) 1900 else: 1901 if len(actualmask) != len(flagtra): 1902 raise RuntimeError, "Mask and flagtra have different length" 1903 else: 1904 for i in range(0, len(actualmask)): 1905 actualmask[i] = actualmask[i] and flagtra[i] 1906 1443 1907 # setup line finder 1444 fl.find_lines(r, mask, curedge) 1445 f.set_data(workscan._getabcissa(r), workscan._getspectrum(r), 1446 mask_and(workscan._getmask(r), fl.get_mask())) 1908 fl.find_lines(r, actualmask, curedge) 1909 outmask=fl.get_mask() 1910 f.set_scan(workscan, fl.get_mask()) 1911 f.x = workscan._getabcissa(r) 1912 f.y = workscan._getspectrum(r) 1913 f.data = None 1447 1914 f.fit() 1448 x = f.get_parameters() 1915 1916 # Show mask list 1917 masklist=workscan.get_masklist(fl.get_mask(),row=r) 1918 msg = "mask range: "+str(masklist) 1919 asaplog.push(msg, False) 1920 1449 1921 if plot: 1450 1922 f.plot(residual=True) 1451 1923 x = raw_input("Accept fit ( [y]/n ): ") 1452 1924 if x.upper() == 'N': 1925 self.blpars.append(None) 1926 self.masklists.append(None) 1453 1927 continue 1928 1454 1929 workscan._setspectrum(f.fitter.getresidual(), r) 1930 self.blpars.append(f.get_parameters()) 1931 self.masklists.append(masklist) 1455 1932 if plot: 1456 1933 f._p.unmap() … … 1462 1939 return workscan 1463 1940 1464 @print_log_dec1941 #@print_log_dec 1465 1942 def rotate_linpolphase(self, angle): 1466 1943 """ … … 1476 1953 self._math._rotate_linpolphase(self, angle) 1477 1954 self._add_history("rotate_linpolphase", varlist) 1955 print_log() 1478 1956 return 1479 1957 1480 @print_log_dec1958 #@print_log_dec 1481 1959 def rotate_xyphase(self, angle): 1482 1960 """ … … 1492 1970 self._math._rotate_xyphase(self, angle) 1493 1971 self._add_history("rotate_xyphase", varlist) 1972 print_log() 1494 1973 return 1495 1974 1496 @print_log_dec1975 #@print_log_dec 1497 1976 def swap_linears(self): 1498 1977 """ … … 1503 1982 self._math._swap_linears(self) 1504 1983 self._add_history("swap_linears", varlist) 1984 print_log() 1505 1985 return 1506 1986 1507 @print_log_dec1987 #@print_log_dec 1508 1988 def invert_phase(self): 1509 1989 """ … … 1513 1993 self._math._invert_phase(self) 1514 1994 self._add_history("invert_phase", varlist) 1995 print_log() 1515 1996 return 1516 1997 1517 @print_log_dec1998 #@print_log_dec 1518 1999 def add(self, offset, insitu=None): 1519 2000 """ … … 1530 2011 s = scantable(self._math._unaryop(self, offset, "ADD", False)) 1531 2012 s._add_history("add", varlist) 2013 print_log() 1532 2014 if insitu: 1533 2015 self._assign(s) … … 1535 2017 return s 1536 2018 1537 @print_log_dec2019 #@print_log_dec 1538 2020 def scale(self, factor, tsys=True, insitu=None): 1539 2021 """ 1540 2022 Return a scan where all spectra are scaled by the give 'factor' 1541 2023 Parameters: 1542 factor: the scaling factor 2024 factor: the scaling factor (float or 1D float list) 1543 2025 insitu: if False a new scantable is returned. 1544 2026 Otherwise, the scaling is done in-situ … … 1550 2032 self._math._setinsitu(insitu) 1551 2033 varlist = vars() 1552 s = scantable(self._math._unaryop(self, factor, "MUL", tsys)) 2034 s = None 2035 import numpy 2036 if isinstance(factor, list) or isinstance(factor, numpy.ndarray): 2037 if isinstance(factor[0], list) or isinstance(factor[0], numpy.ndarray): 2038 from asapmath import _array2dOp 2039 s = _array2dOp( self.copy(), factor, "MUL", tsys ) 2040 else: 2041 s = scantable( self._math._arrayop( self.copy(), factor, "MUL", tsys ) ) 2042 else: 2043 s = scantable(self._math._unaryop(self.copy(), factor, "MUL", tsys)) 1553 2044 s._add_history("scale", varlist) 2045 print_log() 1554 2046 if insitu: 1555 2047 self._assign(s) … … 1593 2085 self._add_history("set_sourcetype", varlist) 1594 2086 1595 @print_log_dec1596 def auto_quotient(self, preserve=True, mode='paired' ):2087 #@print_log_dec 2088 def auto_quotient(self, preserve=True, mode='paired', verify=False): 1597 2089 """ 1598 2090 This function allows to build quotients automatically. 1599 It assumes the observation to have the same num er of2091 It assumes the observation to have the same number of 1600 2092 "ons" and "offs" 1601 2093 Parameters: … … 1634 2126 s = scantable(self._math._auto_quotient(self, mode, preserve)) 1635 2127 s._add_history("auto_quotient", varlist) 2128 print_log() 1636 2129 return s 1637 2130 1638 @print_log_dec2131 #@print_log_dec 1639 2132 def mx_quotient(self, mask = None, weight='median', preserve=True): 1640 2133 """ … … 1656 2149 q = quotient(on, off, preserve) 1657 2150 q._add_history("mx_quotient", varlist) 2151 print_log() 1658 2152 return q 1659 2153 1660 @print_log_dec2154 #@print_log_dec 1661 2155 def freq_switch(self, insitu=None): 1662 2156 """ … … 1674 2168 s = scantable(self._math._freqswitch(self)) 1675 2169 s._add_history("freq_switch", varlist) 2170 print_log() 1676 2171 if insitu: self._assign(s) 1677 2172 else: return s 1678 2173 1679 @print_log_dec2174 #@print_log_dec 1680 2175 def recalc_azel(self): 1681 2176 """ … … 1688 2183 self._recalcazel() 1689 2184 self._add_history("recalc_azel", varlist) 2185 print_log() 1690 2186 return 1691 2187 1692 @print_log_dec2188 #@print_log_dec 1693 2189 def __add__(self, other): 1694 varlist = vars() 1695 s = None 1696 if isinstance(other, scantable): 1697 s = scantable(self._math._binaryop(self, other, "ADD")) 1698 elif isinstance(other, float): 1699 s = scantable(self._math._unaryop(self, other, "ADD", False)) 1700 else: 1701 raise TypeError("Other input is not a scantable or float value") 1702 s._add_history("operator +", varlist) 1703 return s 1704 1705 @print_log_dec 2190 """ 2191 implicit on all axes and on Tsys 2192 """ 2193 return self._operation( other, "ADD" ) 2194 2195 #@print_log_dec 1706 2196 def __sub__(self, other): 1707 2197 """ 1708 2198 implicit on all axes and on Tsys 1709 2199 """ 1710 varlist = vars() 1711 s = None 1712 if isinstance(other, scantable): 1713 s = scantable(self._math._binaryop(self, other, "SUB")) 1714 elif isinstance(other, float): 1715 s = scantable(self._math._unaryop(self, other, "SUB", False)) 1716 else: 1717 raise TypeError("Other input is not a scantable or float value") 1718 s._add_history("operator -", varlist) 1719 return s 1720 1721 @print_log_dec 2200 return self._operation( other, 'SUB' ) 2201 2202 #@print_log_dec 1722 2203 def __mul__(self, other): 1723 2204 """ 1724 2205 implicit on all axes and on Tsys 1725 2206 """ 1726 varlist = vars() 1727 s = None 1728 if isinstance(other, scantable): 1729 s = scantable(self._math._binaryop(self, other, "MUL")) 1730 elif isinstance(other, float): 1731 s = scantable(self._math._unaryop(self, other, "MUL", False)) 1732 else: 1733 raise TypeError("Other input is not a scantable or float value") 1734 s._add_history("operator *", varlist) 1735 return s 1736 1737 1738 @print_log_dec 2207 return self._operation( other, 'MUL' ) 2208 2209 #@print_log_dec 1739 2210 def __div__(self, other): 1740 2211 """ 1741 2212 implicit on all axes and on Tsys 1742 2213 """ 1743 varlist = vars() 1744 s = None 1745 if isinstance(other, scantable): 1746 s = scantable(self._math._binaryop(self, other, "DIV")) 1747 elif isinstance(other, float): 1748 if other == 0.0: 1749 raise ZeroDivisionError("Dividing by zero is not recommended") 1750 s = scantable(self._math._unaryop(self, other, "DIV", False)) 1751 else: 1752 raise TypeError("Other input is not a scantable or float value") 1753 s._add_history("operator /", varlist) 1754 return s 2214 return self._operation( other, 'DIV' ) 1755 2215 1756 2216 def get_fit(self, row=0): … … 1765 2225 fit = asapfit(self._getfit(row)) 1766 2226 if rcParams['verbose']: 1767 print fit 2227 #print fit 2228 asaplog.push( '%s' %(fit) ) 2229 print_log() 1768 2230 return 1769 2231 else: … … 1862 2324 return (sum(nchans)/len(nchans) == nchans[0]) 1863 2325 1864 def _fill(self, names, unit, average ):2326 def _fill(self, names, unit, average, getpt, antenna): 1865 2327 import os 1866 2328 from asap._asap import stfiller … … 1874 2336 if rcParams['verbose']: 1875 2337 asaplog.push(msg) 1876 print asaplog.pop().strip() 2338 #print asaplog.pop().strip() 2339 print_log( 'ERROR' ) 1877 2340 return 1878 2341 raise IOError(msg) … … 1889 2352 asaplog.push(msg, False) 1890 2353 print_log() 1891 r._open(name, -1, -1)2354 r._open(name, antenna, -1, -1, getpt) 1892 2355 r._read() 1893 2356 if average: … … 1901 2364 if unit is not None: 1902 2365 self.set_fluxunit(unit) 1903 self.set_freqframe(rcParams['scantable.freqframe'])2366 #self.set_freqframe(rcParams['scantable.freqframe']) 1904 2367 1905 2368 def __getitem__(self, key): … … 1926 2389 for i in range(len(self)): 1927 2390 yield self[i] 2391 2392 def _operation(self, other, opmode): 2393 varlist = vars() 2394 s = None 2395 import numpy 2396 if isinstance(other, scantable): 2397 s = scantable(self._math._binaryop(self.copy(), other, opmode)) 2398 elif isinstance(other, float) or isinstance(other, int): 2399 if opmode == 'DIV' and float(other) == 0.0: 2400 raise ZeroDivisionError("Dividing by zero is not recommended") 2401 s = scantable(self._math._unaryop(self.copy(), other, opmode, False)) 2402 elif isinstance(other, list) or isinstance(other, numpy.ndarray): 2403 if isinstance(other[0], list) or isinstance(other[0], numpy.ndarray): 2404 from asapmath import _array2dOp 2405 s = _array2dOp( self.copy(), other, opmode, False ) 2406 else: 2407 s = scantable(self._math._arrayop(self.copy(), other, opmode, False)) 2408 else: 2409 raise TypeError("Other input is not a scantable or float value or float list") 2410 opdic = {} 2411 opdic['ADD'] = '+' 2412 opdic['SUB'] = '-' 2413 opdic['MUL'] = '*' 2414 opdic['DIV'] = '/' 2415 s._add_history("operator %s" % opdic[opmode], varlist) 2416 print_log() 2417 return s 2418 2419 -
branches/mergetest/python/selector.py
r1596 r1779 160 160 """ 161 161 self._setorder(order) 162 163 def set_rows(self, rows=[]): 164 """ 165 Set a sequence of row numbers (0-based). Power users Only! 166 NOTICE row numbers can be changed easily by sorting, 167 prior selection, etc. 168 Parameters: 169 rows: a list of integers. Default [] is to unset the selection. 170 """ 171 vec = _to_list(rows, int) 172 if isinstance(vec,list): 173 self._setrows(vec) 174 else: 175 raise TypeError('Unknown row number type. Use lists of integers.') 176 177 def set_types(self, types=[]): 178 """ 179 Set a sequence of source types. 180 Parameters: 181 types: a list of integers. Default [] is to unset the selection. 182 """ 183 vec = _to_list(types, int) 184 if isinstance(vec,list): 185 self._settypes(vec) 186 else: 187 raise TypeError('Unknown row number type. Use lists of integers.') 162 188 163 189 def get_scans(self): … … 175 201 def get_order(self): 176 202 return list(self._getorder()) 203 def get_types(self): 204 return list(self._gettypes()) 177 205 def get_query(self): 178 206 prefix = "SELECT FROM $1 WHERE " -
branches/mergetest/src/MathUtils.cpp
r1570 r1779 38 38 #include <casa/BasicSL/String.h> 39 39 #include <scimath/Mathematics/MedianSlider.h> 40 #include <casa/Exceptions/Error.h> 40 41 41 42 #include <scimath/Fitting/LinearFit.h> … … 53 54 String str(which); 54 55 str.upcase(); 55 if (str. contains(String("MIN"))) {56 if (str.matches(String("MIN"))) { 56 57 return min(data); 57 } else if (str. contains(String("MAX"))) {58 } else if (str.matches(String("MAX"))) { 58 59 return max(data); 59 } else if (str. contains(String("SUMSQ"))) {60 } else if (str.matches(String("SUMSQ"))) { 60 61 return sumsquares(data); 61 } else if (str. contains(String("SUM"))) {62 } else if (str.matches(String("SUM"))) { 62 63 return sum(data); 63 } else if (str. contains(String("MEAN"))) {64 } else if (str.matches(String("MEAN"))) { 64 65 return mean(data); 65 } else if (str. contains(String("VAR"))) {66 } else if (str.matches(String("VAR"))) { 66 67 return variance(data); 67 } else if (str.contains(String("STDDEV"))) {68 } else if (str.matches(String("STDDEV"))) { 68 69 return stddev(data); 69 } else if (str. contains(String("AVDEV"))) {70 } else if (str.matches(String("AVDEV"))) { 70 71 return avdev(data); 71 } else if (str. contains(String("RMS"))) {72 } else if (str.matches(String("RMS"))) { 72 73 uInt n = data.nelementsValid(); 73 74 return sqrt(sumsquares(data)/n); 74 } else if (str. contains(String("MED"))) {75 } else if (str.matches(String("MEDIAN"))) { 75 76 return median(data); 76 } 77 } else { 78 String msg = str + " is not a valid type of statistics"; 79 throw(AipsError(msg)); 80 } 77 81 return 0.0; 78 82 } 79 83 84 IPosition mathutil::minMaxPos(const String& which, 85 const MaskedArray<Float>& data) 86 { 87 Float minVal, maxVal; 88 IPosition minPos(data.ndim(), 0), maxPos(data.ndim(), 0); 89 minMax(minVal, maxVal, minPos, maxPos, data); 90 String str(which); 91 str.upcase(); 92 if (str.contains(String("MIN"))) { 93 return minPos; 94 } else if (str.contains(String("MAX"))) { 95 return maxPos; 96 } else { 97 String msg = str + " is not a valid type of statistics"; 98 throw(AipsError(msg)); 99 } 100 //return 0.0; 101 } 80 102 81 103 void mathutil::replaceMaskByZero(Vector<Float>& data, const Vector<Bool>& mask) -
branches/mergetest/src/MathUtils.h
r1570 r1779 37 37 #include <casa/Arrays/Vector.h> 38 38 #include <casa/BasicSL/String.h> 39 #include <casa/Arrays/IPosition.h> 39 40 40 41 namespace mathutil { … … 79 80 float hwidth, int order); 80 81 81 82 82 // Generate specified statistic 83 83 float statistics(const casa::String& which, 84 const casa::MaskedArray<casa::Float>& data); 85 86 // Return a position of min or max value 87 casa::IPosition minMaxPos(const casa::String& which, 84 88 const casa::MaskedArray<casa::Float>& data); 85 89 -
branches/mergetest/src/RowAccumulator.cpp
r1569 r1779 152 152 userMask_ = m; 153 153 } 154 155 // Added by TT check the state of RowAccumulator 156 casa::Bool RowAccumulator::state() const 157 { 158 return initialized_; 159 } 160 -
branches/mergetest/src/RowAccumulator.h
r1569 r1779 85 85 */ 86 86 void reset(); 87 /** 88 * check the initialization state 89 */ 90 casa::Bool state() const; 87 91 88 92 private: -
branches/mergetest/src/SConscript
r1429 r1779 3 3 # import root environment 4 4 Import( "env") 5 myenv = env.C lone()5 myenv = env.Copy() 6 6 7 7 # gather cpp files -
branches/mergetest/src/STAsciiWriter.cpp
r1552 r1779 1 1 2 //#--------------------------------------------------------------------------- 2 3 //# STAsciiWriter.cc: ASAP class to write out single dish spectra as FITS images … … 88 89 89 90 String rootName(fileName); 90 91 91 92 Block<String> cols(4); 92 93 cols[0] = String("SCANNO"); … … 132 133 String wcs = stable.frequencies().print(rec.asuInt("FREQ_ID"), True); 133 134 addLine(of, "WCS", wcs); 134 addLine(of, "Rest Freq.", 135 stable.molecules().getRestFrequency(rec.asuInt("MOLECULE_ID") )); 135 std::vector<double> restfreqs= stable.molecules().getRestFrequency(rec.asuInt("MOLECULE_ID")); 136 int nf = restfreqs.size(); 137 //addLine(of, "Rest Freq.", 138 // stable.molecules().getRestFrequency(rec.asuInt("MOLECULE_ID") )); 139 addLine(of, "Rest Freq.", restfreqs[0]); 140 for ( unsigned int i=1; i<nf; ++i) { 141 addLine(of, " ", restfreqs[i]); 142 } 143 ostringstream osflagrow; 144 for ( unsigned int i=0; i<t.nrow(); ++i) { 145 osflagrow << "Pol" << i << ":" << ((row.get(i).asuInt("FLAGROW") > 0) ? "True" : "False") << " "; 146 } 147 addLine(of, "Row_Flagged", String(osflagrow)); 136 148 of << setfill('#') << setw(70) << "" << setfill(' ') << endl; 137 149 -
branches/mergetest/src/STFiller.cpp
r1777 r1779 25 25 #include <tables/Tables/TableRow.h> 26 26 27 #include <measures/Measures/MDirection.h> 28 #include <measures/Measures/MeasConvert.h> 29 27 30 #include <atnf/PKSIO/PKSrecord.h> 28 31 #include <atnf/PKSIO/PKSreader.h> … … 30 33 #include <casa/System/ProgressMeter.h> 31 34 #endif 35 #include <casa/System/ProgressMeter.h> 36 #include <atnf/PKSIO/NROReader.h> 37 #include <casa/Logging/LogIO.h> 38 39 #include <time.h> 40 32 41 33 42 #include "STDefs.h" … … 45 54 header_(0), 46 55 table_(0), 47 refRx_(".*(e|w|_R)$") 56 refRx_(".*(e|w|_R)$"), 57 nreader_(0) 48 58 { 49 59 } … … 53 63 header_(0), 54 64 table_(stbl), 55 refRx_(".*(e|w|_R)$") 65 refRx_(".*(e|w|_R)$"), 66 nreader_(0) 56 67 { 57 68 } … … 61 72 header_(0), 62 73 table_(0), 63 refRx_(".*(e|w|_R)$") 74 refRx_(".*(e|w|_R)$"), 75 nreader_(0) 64 76 { 65 open(filename, whichIF, whichBeam);77 open(filename, "", whichIF, whichBeam); 66 78 } 67 79 … … 70 82 close(); 71 83 } 72 73 void STFiller::open( const std::string& filename, int whichIF, int whichBeam)84 85 void STFiller::open( const std::string& filename, const std::string& antenna, int whichIF, int whichBeam, casa::Bool getPt ) 74 86 { 75 87 if (table_.null()) { … … 93 105 Vector<Bool> beams, ifs; 94 106 Vector<uInt> nchans,npols; 95 if ( (reader_ = getPKSreader(inName, 0, 0, format, beams, ifs, 107 108 // 109 // if isNRO_ is true, try NROReader 110 // 111 // 2008/11/11 Takeshi Nakazato 112 isNRO_ = fileCheck() ; 113 if ( isNRO_ ) { 114 if ( (nreader_ = getNROReader( inName, format )) == 0 ) { 115 throw(AipsError("Creation of NROReader failed")) ; 116 } 117 else { 118 openNRO( whichIF, whichBeam ) ; 119 return ; 120 } 121 } 122 // 123 124 if ( (reader_ = getPKSreader(inName, antenna, 0, 0, format, beams, ifs, 96 125 nchans, npols, haveXPol_,haveBase, haveSpectra 97 126 )) == 0 ) { … … 197 226 Vector<Int> start(nIF_, 1); 198 227 Vector<Int> end(nIF_, 0); 199 reader_->select(beams, ifs, start, end, ref, True, haveXPol_[0] );228 reader_->select(beams, ifs, start, end, ref, True, haveXPol_[0], False, getPt); 200 229 table_->setHeader(*header_); 201 230 //For MS, add the location of POINTING of the input MS so one get 202 231 //pointing data from there, if necessary. 203 //Also find nrow in MS 232 //Also find nrow in MS 204 233 nInDataRow = 0; 205 234 if (format == "MS2") { 206 Path datapath(inName); 235 Path datapath(inName); 207 236 String ptTabPath = datapath.absoluteName(); 208 237 Table inMS(ptTabPath); … … 216 245 } 217 246 } 247 String freqFrame = header_->freqref; 248 //translate frequency reference frame back to 249 //MS style (as PKSMS2reader converts the original frame 250 //in FITS standard style) 251 if (freqFrame == "TOPOCENT") { 252 freqFrame = "TOPO"; 253 } else if (freqFrame == "GEOCENER") { 254 freqFrame = "GEO"; 255 } else if (freqFrame == "BARYCENT") { 256 freqFrame = "BARY"; 257 } else if (freqFrame == "GALACTOC") { 258 freqFrame = "GALACTO"; 259 } else if (freqFrame == "LOCALGRP") { 260 freqFrame = "LGROUP"; 261 } else if (freqFrame == "CMBDIPOL") { 262 freqFrame = "CMB"; 263 } else if (freqFrame == "SOURCE") { 264 freqFrame = "REST"; 265 } 266 // set both "FRAME" and "BASEFRAME" 267 table_->frequencies().setFrame(freqFrame, false); 268 table_->frequencies().setFrame(freqFrame,true); 218 269 //table_->focus().setParallactify(true); 219 270 } … … 222 273 { 223 274 delete reader_;reader_=0; 275 delete nreader_;nreader_=0; 224 276 delete header_;header_=0; 225 277 table_ = 0; … … 229 281 { 230 282 int status = 0; 283 284 // 285 // for NRO data 286 // 287 // 2008/11/12 Takeshi Nakazato 288 if ( isNRO_ ) { 289 status = readNRO() ; 290 return status ; 291 } 292 // 293 294 /** 295 Int beamNo, IFno, refBeam, scanNo, cycleNo; 296 Float azimuth, elevation, focusAxi, focusRot, focusTan, 297 humidity, parAngle, pressure, temperature, windAz, windSpeed; 298 Double bandwidth, freqInc, interval, mjd, refFreq, srcVel; 299 String fieldName, srcName, tcalTime, obsType; 300 Vector<Float> calFctr, sigma, tcal, tsys; 301 Matrix<Float> baseLin, baseSub; 302 Vector<Double> direction(2), scanRate(2), srcDir(2), srcPM(2), restFreq(1); 303 Matrix<Float> spectra; 304 Matrix<uChar> flagtra; 305 Complex xCalFctr; 306 Vector<Complex> xPol; 307 **/ 231 308 232 309 Double min = 0.0; … … 236 313 #endif 237 314 PKSrecord pksrec; 315 pksrec.srcType=-1; 238 316 int n = 0; 317 bool isGBTFITS = false ; 318 if ((header_->antennaname.find( "GBT" ) != String::npos) && File(filename_).isRegular()) { 319 FILE *fp = fopen( filename_.c_str(), "r" ) ; 320 fseek( fp, 640, SEEK_SET ) ; 321 char buf[81] ; 322 fread( buf, 80, 1, fp ) ; 323 buf[80] = '\0' ; 324 if ( strstr( buf, "NRAO_GBT" ) != NULL ) { 325 isGBTFITS = true ; 326 } 327 fclose( fp ) ; 328 } 239 329 while ( status == 0 ) { 240 330 status = reader_->read(pksrec); … … 288 378 //*srcnCol = pksrec.srcName;//.before(rx2); 289 379 *srctCol = match; 380 if ( pksrec.srcType != -1 ) { 381 *srctCol = pksrec.srcType ; 382 } 290 383 RecordFieldPtr<uInt> beamCol(rec, "BEAMNO"); 291 384 *beamCol = pksrec.beamNo-beamOffset_-1; … … 298 391 uInt id; 299 392 /// @todo this has to change when nchan isn't global anymore 300 id = table_->frequencies().addEntry(Double(header_->nchan/2), 301 pksrec.refFreq, pksrec.freqInc); 393 //id = table_->frequencies().addEntry(Double(header_->nchan/2), 394 // pksrec.refFreq, pksrec.freqInc); 395 if ( pksrec.nchan == 1 ) { 396 id = table_->frequencies().addEntry(Double(0), 397 pksrec.refFreq, pksrec.freqInc); 398 } 399 else { 400 id = table_->frequencies().addEntry(Double(pksrec.nchan/2), 401 pksrec.refFreq, pksrec.freqInc); 402 } 302 403 RecordFieldPtr<uInt> mfreqidCol(rec, "FREQ_ID"); 303 404 *mfreqidCol = id; 405 //*ifCol = id; 304 406 305 407 id = table_->molecules().addEntry(pksrec.restFreq); … … 317 419 318 420 RecordFieldPtr<uInt> mfocusidCol(rec, "FOCUS_ID"); 319 id = table_->focus().addEntry(pksrec.parAngle, pksrec.focusAxi, 421 id = table_->focus().addEntry(pksrec.parAngle, pksrec.focusAxi, 320 422 pksrec.focusTan, pksrec.focusRot); 321 423 *mfocusidCol = id; … … 335 437 // into 2-4 rows in the scantable 336 438 Vector<Float> tsysvec(1); 337 // Why is pksrec.spectra.ncolumn() == 3 for haveXPol_ == True439 // Why is spectra.ncolumn() == 3 for haveXPol_ == True 338 440 uInt npol = (pksrec.spectra.ncolumn()==1 ? 1: 2); 339 441 for ( uInt i=0; i< npol; ++i ) { 340 442 tsysvec = pksrec.tsys(i); 341 443 *tsysCol = tsysvec; 342 *polnoCol = i; 444 if (isGBTFITS) 445 *polnoCol = pksrec.polNo ; 446 else 447 *polnoCol = i; 343 448 344 449 *specCol = pksrec.spectra.column(i); … … 347 452 row.put(table_->table().nrow()-1, rec); 348 453 } 454 455 RecordFieldPtr< uInt > flagrowCol(rec, "FLAGROW"); 456 *flagrowCol = pksrec.flagrow; 457 349 458 if ( haveXPol_[0] ) { 350 459 // no tsys given for xpol, so emulate it … … 381 490 } 382 491 492 /** 493 * For NRO data 494 * 495 * 2008/11/11 Takeshi Nakazato 496 **/ 497 void STFiller::openNRO( int whichIF, int whichBeam ) 498 { 499 // open file 500 // DEBUG 501 time_t t0 ; 502 time( &t0 ) ; 503 tm *ttm = localtime( &t0 ) ; 504 LogIO os( LogOrigin( "STFiller", "openNRO()", WHERE ) ) ; 505 // cout << "STFiller::openNRO() Start time = " << t0 506 // << " (" 507 // << ttm->tm_year + 1900 << "/" << ttm->tm_mon + 1 << "/" << ttm->tm_mday 508 // << " " 509 // << ttm->tm_hour << ":" << ttm->tm_min << ":" << ttm->tm_sec 510 // << ")" << endl ; 511 os << "Start time = " << t0 512 << " (" 513 << ttm->tm_year + 1900 << "/" << ttm->tm_mon + 1 << "/" << ttm->tm_mday 514 << " " 515 << ttm->tm_hour << ":" << ttm->tm_min << ":" << ttm->tm_sec 516 << ")" << LogIO::POST ; 517 518 // fill STHeader 519 header_ = new STHeader() ; 520 521 if ( nreader_->getHeaderInfo( header_->nchan, 522 header_->npol, 523 nIF_, 524 nBeam_, 525 header_->observer, 526 header_->project, 527 header_->obstype, 528 header_->antennaname, 529 header_->antennaposition, 530 header_->equinox, 531 header_->freqref, 532 header_->reffreq, 533 header_->bandwidth, 534 header_->utc, 535 header_->fluxunit, 536 header_->epoch, 537 header_->poltype ) ) { 538 // cout << "STFiller::openNRO() Failed to get header information." << endl ; 539 // return ; 540 throw( AipsError("Failed to get header information.") ) ; 541 } 542 543 // set FRAME and BASEFRAME keyword of FREQUENCIES table 544 if ( header_->freqref != "TOPO" ) { 545 table_->frequencies().setFrame( header_->freqref, false ) ; 546 table_->frequencies().setFrame( header_->freqref, true ) ; 547 } 548 549 ifOffset_ = 0; 550 vector<Bool> ifs = nreader_->getIFs() ; 551 if ( whichIF >= 0 ) { 552 if ( whichIF >= 0 && whichIF < nIF_ ) { 553 for ( int i = 0 ; i < nIF_ ; i++ ) 554 ifs[i] = False ; 555 ifs[whichIF] = True ; 556 header_->nif = 1; 557 nIF_ = 1; 558 ifOffset_ = whichIF; 559 } else { 560 delete reader_; 561 reader_ = 0; 562 delete header_; 563 header_ = 0; 564 throw(AipsError("Illegal IF selection")); 565 } 566 } 567 568 beamOffset_ = 0; 569 vector<Bool> beams = nreader_->getBeams() ; 570 if (whichBeam>=0) { 571 if (whichBeam>=0 && whichBeam<nBeam_) { 572 for ( int i = 0 ; i < nBeam_ ; i++ ) 573 beams[i] = False ; 574 beams[whichBeam] = True; 575 header_->nbeam = 1; 576 nBeam_ = 1; 577 beamOffset_ = whichBeam; 578 } else { 579 delete reader_; 580 reader_ = 0; 581 delete header_; 582 header_ = 0; 583 throw(AipsError("Illegal Beam selection")); 584 } 585 } 586 587 header_->nbeam = nBeam_ ; 588 header_->nif = nIF_ ; 589 590 // set header 591 table_->setHeader( *header_ ) ; 592 593 // DEBUG 594 time_t t1 ; 595 time( &t1 ) ; 596 ttm = localtime( &t1 ) ; 597 // cout << "STFiller::openNRO() End time = " << t1 598 // << " (" 599 // << ttm->tm_year + 1900 << "/" << ttm->tm_mon + 1 << "/" << ttm->tm_mday 600 // << " " 601 // << ttm->tm_hour << ":" << ttm->tm_min << ":" << ttm->tm_sec 602 // << ")" << endl ; 603 // cout << "STFiller::openNRO() Elapsed time = " << t1 - t0 << " sec" << endl ; 604 os << "End time = " << t1 605 << " (" 606 << ttm->tm_year + 1900 << "/" << ttm->tm_mon + 1 << "/" << ttm->tm_mday 607 << " " 608 << ttm->tm_hour << ":" << ttm->tm_min << ":" << ttm->tm_sec 609 << ")" << endl ; 610 os << "Elapsed time = " << t1 - t0 << " sec" << endl ; 611 os.post() ; 612 // 613 614 return ; 615 } 616 617 int STFiller::readNRO() 618 { 619 // DEBUG 620 time_t t0 ; 621 time( &t0 ) ; 622 tm *ttm = localtime( &t0 ) ; 623 LogIO os( LogOrigin( "STFiller", "readNRO()", WHERE ) ) ; 624 // cout << "STFiller::readNRO() Start time = " << t0 625 // << " (" 626 // << ttm->tm_year + 1900 << "/" << ttm->tm_mon + 1 << "/" << ttm->tm_mday 627 // << " " 628 // << ttm->tm_hour << ":" << ttm->tm_min << ":" << ttm->tm_sec 629 // << ")" << endl ; 630 os << "Start time = " << t0 631 << " (" 632 << ttm->tm_year + 1900 << "/" << ttm->tm_mon + 1 << "/" << ttm->tm_mday 633 << " " 634 << ttm->tm_hour << ":" << ttm->tm_min << ":" << ttm->tm_sec 635 << ")" << LogIO::POST ; 636 // 637 638 // fill row 639 uInt id ; 640 uInt imax = nreader_->getRowNum() ; 641 vector< vector<double > > freqs ; 642 uInt i = 0 ; 643 int count = 0 ; 644 uInt scanno ; 645 uInt cycleno ; 646 uInt beamno ; 647 uInt polno ; 648 vector<double> fqs ; 649 Vector<Double> restfreq ; 650 uInt refbeamno ; 651 Double scantime ; 652 Double interval ; 653 String srcname ; 654 String fieldname ; 655 Array<Float> spectra ; 656 Array<uChar> flagtra ; 657 Array<Float> tsys ; 658 Array<Double> direction ; 659 Float azimuth ; 660 Float elevation ; 661 Float parangle ; 662 Float opacity ; 663 uInt tcalid ; 664 Int fitid ; 665 uInt focusid ; 666 Float temperature ; 667 Float pressure ; 668 Float humidity ; 669 Float windvel ; 670 Float winddir ; 671 Double srcvel ; 672 Array<Double> propermotion ; 673 Vector<Double> srcdir ; 674 Array<Double> scanrate ; 675 for ( i = 0 ; i < imax ; i++ ) { 676 string scanType = nreader_->getScanType( i ) ; 677 Int srcType = -1 ; 678 if ( scanType.compare( 0, 2, "ON") == 0 ) { 679 // os << "ON srcType: " << i << LogIO::POST ; 680 srcType = 0 ; 681 } 682 else if ( scanType.compare( 0, 3, "OFF" ) == 0 ) { 683 //os << "OFF srcType: " << i << LogIO::POST ; 684 srcType = 1 ; 685 } 686 else if ( scanType.compare( 0, 4, "ZERO" ) == 0 ) { 687 //os << "ZERO srcType: " << i << LogIO::POST ; 688 srcType = 2 ; 689 } 690 else { 691 //os << "Undefined srcType: " << i << LogIO::POST ; 692 srcType = 3 ; 693 } 694 695 // if srcType is 2 (ZERO scan), ignore scan 696 if ( srcType != 2 && srcType != -1 && srcType != 3 ) { 697 TableRow row( table_->table() ) ; 698 TableRecord& rec = row.record(); 699 700 if ( nreader_->getScanInfo( i, 701 scanno, 702 cycleno, 703 beamno, 704 polno, 705 fqs, 706 restfreq, 707 refbeamno, 708 scantime, 709 interval, 710 srcname, 711 fieldname, 712 spectra, 713 flagtra, 714 tsys, 715 direction, 716 azimuth, 717 elevation, 718 parangle, 719 opacity, 720 tcalid, 721 fitid, 722 focusid, 723 temperature, 724 pressure, 725 humidity, 726 windvel, 727 winddir, 728 srcvel, 729 propermotion, 730 srcdir, 731 scanrate ) ) { 732 // cerr << "STFiller::readNRO() Failed to get scan information." << endl ; 733 // return 1 ; 734 throw( AipsError("Failed to get scan information.") ) ; 735 } 736 737 RecordFieldPtr<uInt> scannoCol( rec, "SCANNO" ) ; 738 *scannoCol = scanno ; 739 RecordFieldPtr<uInt> cyclenoCol(rec, "CYCLENO") ; 740 *cyclenoCol = cycleno ; 741 RecordFieldPtr<uInt> beamCol(rec, "BEAMNO") ; 742 *beamCol = beamno ; 743 RecordFieldPtr<uInt> ifCol(rec, "IFNO") ; 744 RecordFieldPtr< uInt > polnoCol(rec, "POLNO") ; 745 *polnoCol = polno ; 746 RecordFieldPtr<uInt> mfreqidCol(rec, "FREQ_ID") ; 747 if ( freqs.size() == 0 ) { 748 id = table_->frequencies().addEntry( Double( fqs[0] ), 749 Double( fqs[1] ), 750 Double( fqs[2] ) ) ; 751 *mfreqidCol = id ; 752 *ifCol = id ; 753 freqs.push_back( fqs ) ; 754 } 755 else { 756 int iadd = -1 ; 757 for ( uInt iif = 0 ; iif < freqs.size() ; iif++ ) { 758 //os << "freqs[" << iif << "][1] = " << freqs[iif][1] << LogIO::POST ; 759 double fdiff = abs( freqs[iif][1] - fqs[1] ) / freqs[iif][1] ; 760 //os << "fdiff = " << fdiff << LogIO::POST ; 761 if ( fdiff < 1.0e-8 ) { 762 iadd = iif ; 763 break ; 764 } 765 } 766 if ( iadd == -1 ) { 767 id = table_->frequencies().addEntry( Double( fqs[0] ), 768 Double( fqs[1] ), 769 Double( fqs[2] ) ) ; 770 *mfreqidCol = id ; 771 *ifCol = id ; 772 freqs.push_back( fqs ) ; 773 } 774 else { 775 *mfreqidCol = iadd ; 776 *ifCol = iadd ; 777 } 778 } 779 RecordFieldPtr<uInt> molidCol(rec, "MOLECULE_ID") ; 780 id = table_->molecules().addEntry( restfreq ) ; 781 *molidCol = id ; 782 RecordFieldPtr<Int> rbCol(rec, "REFBEAMNO") ; 783 *rbCol = refbeamno ; 784 RecordFieldPtr<Double> mjdCol( rec, "TIME" ) ; 785 *mjdCol = scantime ; 786 RecordFieldPtr<Double> intervalCol( rec, "INTERVAL" ) ; 787 *intervalCol = interval ; 788 RecordFieldPtr<String> srcnCol(rec, "SRCNAME") ; 789 *srcnCol = srcname ; 790 RecordFieldPtr<Int> srctCol(rec, "SRCTYPE") ; 791 *srctCol = srcType ; 792 RecordFieldPtr<String> fieldnCol(rec, "FIELDNAME"); 793 *fieldnCol = fieldname ; 794 RecordFieldPtr< Array<Float> > specCol(rec, "SPECTRA") ; 795 *specCol = spectra ; 796 RecordFieldPtr< Array<uChar> > flagCol(rec, "FLAGTRA") ; 797 *flagCol = flagtra ; 798 RecordFieldPtr< Array<Float> > tsysCol(rec, "TSYS") ; 799 *tsysCol = tsys ; 800 RecordFieldPtr< Array<Double> > dirCol(rec, "DIRECTION") ; 801 *dirCol = direction ; 802 RecordFieldPtr<Float> azCol(rec, "AZIMUTH") ; 803 *azCol = azimuth ; 804 RecordFieldPtr<Float> elCol(rec, "ELEVATION") ; 805 *elCol = elevation ; 806 RecordFieldPtr<Float> parCol(rec, "PARANGLE") ; 807 *parCol = parangle ; 808 RecordFieldPtr<Float> tauCol(rec, "OPACITY") ; 809 *tauCol = opacity ; 810 RecordFieldPtr<uInt> mcalidCol(rec, "TCAL_ID") ; 811 *mcalidCol = tcalid ; 812 RecordFieldPtr<Int> fitCol(rec, "FIT_ID") ; 813 *fitCol = fitid ; 814 RecordFieldPtr<uInt> mfocusidCol(rec, "FOCUS_ID") ; 815 *mfocusidCol = focusid ; 816 RecordFieldPtr<uInt> mweatheridCol(rec, "WEATHER_ID") ; 817 id = table_->weather().addEntry( temperature, 818 pressure, 819 humidity, 820 windvel, 821 winddir ) ; 822 *mweatheridCol = id ; 823 RecordFieldPtr<Double> svelCol(rec, "SRCVELOCITY") ; 824 *svelCol = srcvel ; 825 RecordFieldPtr<Array<Double> > spmCol(rec, "SRCPROPERMOTION") ; 826 *spmCol = propermotion ; 827 RecordFieldPtr<Array<Double> > sdirCol(rec, "SRCDIRECTION") ; 828 *sdirCol = srcdir ; 829 RecordFieldPtr<Array<Double> > srateCol(rec, "SCANRATE"); 830 *srateCol = scanrate ; 831 832 table_->table().addRow() ; 833 row.put(table_->table().nrow()-1, rec) ; 834 } 835 else { 836 count++ ; 837 } 838 // DEBUG 839 //int rownum = nreader_->getRowNum() ; 840 //os << "Finished row " << i << "/" << rownum << LogIO::POST ; 841 // 842 } 843 844 // DEBUG 845 time_t t1 ; 846 time( &t1 ) ; 847 ttm = localtime( &t1 ) ; 848 // cout << "STFiller::readNRO() Processed " << i << " rows" << endl ; 849 // cout << "STFiller::readNRO() Added " << i - count << " rows (ignored " 850 // << count << " \"ZERO\" scans)" << endl ; 851 // cout << "STFiller::readNRO() End time = " << t1 852 // << " (" 853 // << ttm->tm_year + 1900 << "/" << ttm->tm_mon + 1 << "/" << ttm->tm_mday 854 // << " " 855 // << ttm->tm_hour << ":" << ttm->tm_min << ":" << ttm->tm_sec 856 // << ")" << endl ; 857 // cout << "STFiller::readNRO() Elapsed time = " << t1 - t0 << " sec" << endl ; 858 os << "Processed " << i << " rows" << endl ; 859 os << "Added " << i - count << " rows (ignored " 860 << count << " \"ZERO\" scans)" << endl ; 861 os.post() ; 862 os << "End time = " << t1 863 << " (" 864 << ttm->tm_year + 1900 << "/" << ttm->tm_mon + 1 << "/" << ttm->tm_mday 865 << " " 866 << ttm->tm_hour << ":" << ttm->tm_min << ":" << ttm->tm_sec 867 << ")" << endl ; 868 os << "Elapsed time = " << t1 - t0 << " sec" << endl ; 869 os.post() ; 870 // 871 872 return 0 ; 873 } 874 875 Bool STFiller::fileCheck() 876 { 877 bool bval = false ; 878 879 // if filename_ is directory, return false 880 File inFile( filename_ ) ; 881 if ( inFile.isDirectory() ) 882 return bval ; 883 884 // if beginning of header data is "RW", return true 885 // otherwise, return false ; 886 FILE *fp = fopen( filename_.c_str(), "r" ) ; 887 char buf[9] ; 888 char buf2[80] ; 889 fread( buf, 4, 1, fp ) ; 890 buf[4] = '\0' ; 891 fseek( fp, 640, SEEK_SET ) ; 892 fread( buf2, 80, 1, fp ) ; 893 if ( ( strncmp( buf, "RW", 2 ) == 0 ) || ( strstr( buf2, "NRO45M" ) != NULL ) ) { 894 bval = true ; 895 } 896 fclose( fp ) ; 897 return bval ; 898 } 899 383 900 }//namespace asap -
branches/mergetest/src/STFiller.h
r1504 r1779 27 27 28 28 class PKSreader; 29 class NROReader; 29 30 30 31 namespace asap { … … 61 62 */ 62 63 explicit STFiller( const std::string& filename, int whichIF=-1, 63 int whichBeam=-1 );64 int whichBeam=-1 ); 64 65 65 66 /** … … 75 76 * @exception AipsError Creation of PKSreader failed 76 77 */ 77 void open( const std::string& filename, int whichIF=-1, int whichBeam=-1);78 void open( const std::string& filename, const std::string& antenna, int whichIF=-1, int whichBeam=-1, casa::Bool getPt=casa::False ); 78 79 79 80 /** … … 93 94 casa::CountedPtr<Scantable> getTable() const { return table_;} 94 95 96 /** 97 * For NRO data 98 * 99 * 2008/11/11 Takeshi Nakazato 100 * 101 * openNRO : NRO version of open(), which performs to open file and 102 * read header data. 103 * 104 * readNRO : NRO version of read(), which performs to read scan 105 * records. 106 * 107 * fileCheck: Identify a type (NRO data or not) of filename_. 108 **/ 109 void openNRO( int whichIF=-1, int whichBeam=-1 ) ; 110 int readNRO() ; 111 casa::Bool fileCheck() ; 112 95 113 void setReferenceExpr(const std::string& rx) { refRx_ = rx; } 96 114 … … 105 123 casa::Vector<casa::Bool> haveXPol_; 106 124 casa::String refRx_; 125 NROReader *nreader_ ; 126 casa::Bool isNRO_ ; 107 127 }; 108 128 -
branches/mergetest/src/STFitter.cpp
r1391 r1779 32 32 #include <casa/Arrays/ArrayMath.h> 33 33 #include <casa/Arrays/ArrayLogical.h> 34 #include <casa/Logging/LogIO.h> 34 35 #include <scimath/Fitting.h> 35 36 #include <scimath/Fitting/LinearFit.h> … … 37 38 #include <scimath/Functionals/CompoundFunction.h> 38 39 #include <scimath/Functionals/Gaussian1D.h> 40 #include "Lorentzian1D.h" 39 41 #include <scimath/Functionals/Polynomial.h> 40 42 #include <scimath/Mathematics/AutoDiff.h> … … 146 148 funcs_.resize(1); 147 149 funcs_[0] = new Polynomial<Float>(ncomp); 150 } else if (expr == "lorentz") { 151 if (ncomp < 1) throw (AipsError("Need at least one lorentzian to fit.")); 152 funcs_.resize(ncomp); 153 for (Int k=0; k<ncomp; ++k) { 154 funcs_[k] = new Lorentzian1D<Float>(); 155 } 148 156 } else { 149 cerr << " compiled functions not yet implemented" << endl; 157 //cerr << " compiled functions not yet implemented" << endl; 158 LogIO os( LogOrigin( "Fitter", "setExpression()", WHERE ) ) ; 159 os << LogIO::WARN << " compiled functions not yet implemented" << LogIO::POST; 150 160 //funcs_.resize(1); 151 161 //funcs_[0] = new CompiledFunction<Float>(); … … 227 237 (funcs_[0]->parameters())[i] = tmppar[i]; 228 238 } 239 } else if (dynamic_cast<Lorentzian1D<Float>* >(funcs_[0]) != 0) { 240 uInt count = 0; 241 for (uInt j=0; j < funcs_.nelements(); ++j) { 242 for (uInt i=0; i < funcs_[j]->nparameters(); ++i) { 243 (funcs_[j]->parameters())[i] = tmppar[count]; 244 parameters_[count] = tmppar[count]; 245 ++count; 246 } 247 } 229 248 } 230 249 // reset … … 260 279 funcs_[0]->mask(i) = !fixed[i]; 261 280 } 281 } else if (dynamic_cast<Lorentzian1D<Float>* >(funcs_[0]) != 0) { 282 uInt count = 0; 283 for (uInt j=0; j < funcs_.nelements(); ++j) { 284 for (uInt i=0; i < funcs_[j]->nparameters(); ++i) { 285 funcs_[j]->mask(i) = !fixed[count]; 286 fixedpar_[count] = fixed[count]; 287 ++count; 288 } 289 } 262 290 } 263 291 return true; -
branches/mergetest/src/STFrequencies.cpp
r1694 r1779 128 128 } 129 129 130 void STFrequencies::setEntry( Double refpix, Double refval, Double inc, uInt id ) 131 { 132 Table t = table_(table_.col("ID") == Int(id) ); 133 if (t.nrow() == 0 ) { 134 throw(AipsError("STFrequencies::getEntry - freqID out of range")); 135 } 136 for ( uInt i = 0 ; i < table_.nrow() ; i++ ) { 137 uInt fid ; 138 idCol_.get( i, fid ) ; 139 if ( fid == id ) { 140 refpixCol_.put( i, refpix ) ; 141 refvalCol_.put( i, refval ) ; 142 incrCol_.put( i, inc ) ; 143 } 144 } 145 } 146 130 147 SpectralCoordinate STFrequencies::getSpectralCoordinate( uInt id ) const 131 148 { … … 145 162 } 146 163 164 /** 147 165 SpectralCoordinate 148 166 STFrequencies::getSpectralCoordinate( const MDirection& md, … … 150 168 const MEpoch& me, 151 169 Double restfreq, uInt id ) const 170 **/ 171 SpectralCoordinate 172 STFrequencies::getSpectralCoordinate( const MDirection& md, 173 const MPosition& mp, 174 const MEpoch& me, 175 Vector<Double> restfreq, uInt id ) const 152 176 { 153 177 SpectralCoordinate spc = getSpectralCoordinate(id); 154 spc.setRestFrequency(restfreq, True); 178 //spc.setRestFrequency(restfreq, True); 179 // for now just use the first rest frequency 180 if (restfreq.nelements()==0 ) { 181 restfreq.resize(1); 182 restfreq[0] = 0; 183 } 184 spc.setRestFrequency(restfreq[0], True); 155 185 if ( !spc.setReferenceConversion(getFrame(), me, mp, md) ) { 156 186 throw(AipsError("Couldn't convert frequency frame.")); -
branches/mergetest/src/STFrequencies.h
r1375 r1779 59 59 casa::Double& inc, casa::uInt id ); 60 60 61 /*** 62 * Set the frequency values for a specific id via references 63 * @param refpix the reference pixel 64 * @param refval the reference value 65 * @param inc the increment 66 * @param id the identifier 67 * 68 * 17/09/2008 Takeshi Nakazato 69 ***/ 70 void setEntry( casa::Double refpix, casa::Double refval, 71 casa::Double inc, casa::uInt id ) ; 72 61 73 62 74 bool conformant(const STFrequencies& other) const; … … 69 81 casa::SpectralCoordinate getSpectralCoordinate( casa::uInt freqID ) const; 70 82 83 /** 71 84 casa::SpectralCoordinate getSpectralCoordinate( const casa::MDirection& md, 72 85 const casa::MPosition& mp, … … 75 88 casa::uInt freqID 76 89 ) const; 90 **/ 91 casa::SpectralCoordinate getSpectralCoordinate( const casa::MDirection& md, 92 const casa::MPosition& mp, 93 const casa::MEpoch& me, 94 casa::Vector<casa::Double> restfreq, 95 casa::uInt freqID 96 ) const; 77 97 78 98 /** -
branches/mergetest/src/STHeader.cpp
r1439 r1779 37 37 #include <casa/Arrays/IPosition.h> 38 38 #include <casa/Quanta/MVTime.h> 39 #include <casa/Logging/LogIO.h> 39 40 40 41 #include <sstream> 41 42 42 43 #include "STDefs.h" … … 79 80 MVTime mvt(this->utc); 80 81 mvt.setFormat(MVTime::YMD); 81 cout << "Observer: " << this->observer << endl 82 << "Project: " << this->project << endl 83 << "Obstype: " << this->obstype << endl 84 << "Antenna: " << this->antennaname << endl 85 << "Ant. Position: " << this->antennaposition << endl 86 << "Equinox: " << this->equinox << endl 87 << "Freq. ref.: " << this->freqref << endl 88 << "Ref. frequency: " << this->reffreq << endl 89 << "Bandwidth: " << this->bandwidth << endl 90 << "Time (utc): " 91 << mvt 92 << endl; 82 // cout << "Observer: " << this->observer << endl 83 // << "Project: " << this->project << endl 84 // << "Obstype: " << this->obstype << endl 85 // << "Antenna: " << this->antennaname << endl 86 // << "Ant. Position: " << this->antennaposition << endl 87 // << "Equinox: " << this->equinox << endl 88 // << "Freq. ref.: " << this->freqref << endl 89 // << "Ref. frequency: " << this->reffreq << endl 90 // << "Bandwidth: " << this->bandwidth << endl 91 // << "Time (utc): " 92 // << mvt 93 // << endl; 94 LogIO os( LogOrigin( "STHeader", "print()", WHERE ) ) ; 95 os << "Observer: " << this->observer << endl 96 << "Project: " << this->project << endl 97 << "Obstype: " << this->obstype << endl 98 << "Antenna: " << this->antennaname << endl 99 << "Ant. Position: " << this->antennaposition << endl 100 << "Equinox: " << this->equinox << endl 101 << "Freq. ref.: " << this->freqref << endl 102 << "Ref. frequency: " << this->reffreq << endl 103 << "Bandwidth: " << this->bandwidth << endl 104 << "Time (utc): " 105 << mvt 106 << LogIO::POST ; 93 107 //setprecision(10) << this->utc << endl; 94 108 } … … 129 143 { 130 144 if (n_>0) { 131 cerr << "Source ID" << endl; 132 for (uInt i=0; i<n_; i++) { 133 cout << setw(11) << source_(i) << ID_(i) << endl; 134 } 145 // cerr << "Source ID" << endl; 146 // for (uInt i=0; i<n_; i++) { 147 // cout << setw(11) << source_(i) << ID_(i) << endl; 148 LogIO os( LogOrigin( "SDDataDesc", "summary()", WHERE ) ) ; 149 ostringstream oss ; 150 oss << "Source ID" << endl; 151 for (uInt i=0; i<n_; i++) { 152 oss << setw(11) << source_(i) << ID_(i) << endl; 153 } 154 os << oss.str() << LogIO::POST ; 135 155 } 136 156 } -
branches/mergetest/src/STMath.cpp
r1777 r1779 44 44 #include <scimath/Functionals/Polynomial.h> 45 45 46 #include <atnf/PKSIO/SrcType.h> 47 46 48 #include <casa/Logging/LogIO.h> 49 #include <sstream> 47 50 48 51 #include "MathUtils.h" … … 55 58 56 59 using namespace asap; 60 61 // tolerance for direction comparison (rad) 62 #define TOL_OTF 1.0e-15 63 #define TOL_POINT 2.9088821e-4 // 1 arcmin 57 64 58 65 STMath::STMath(bool insitu) : … … 72 79 const std::string& avmode) 73 80 { 81 LogIO os( LogOrigin( "STMath", "average()", WHERE ) ) ; 74 82 if ( avmode == "SCAN" && in.size() != 1 ) 75 83 throw(AipsError("Can't perform 'SCAN' averaging on multiple tables.\n" 76 84 "Use merge first.")); 77 85 WeightType wtype = stringToWeight(weight); 78 LogIO os( LogOrigin( "STMath", "average()", WHERE ) ) ; 79 os << "test" << LogIO::POST ; 86 87 // check if OTF observation 88 String obstype = in[0]->getHeader().obstype ; 89 Double tol = 0.0 ; 90 if ( (obstype.find( "OTF" ) != String::npos) || (obstype.find( "OBSERVE_TARGET" ) != String::npos) ) { 91 tol = TOL_OTF ; 92 } 93 else { 94 tol = TOL_POINT ; 95 } 80 96 81 97 // output … … 117 133 } 118 134 if ( avmode == "SCAN" && in.size() == 1) { 119 cols.resize(4); 120 cols[3] = String("SCANNO"); 135 //cols.resize(4); 136 //cols[3] = String("SCANNO"); 137 cols.resize(5); 138 cols[3] = String("SRCNAME"); 139 cols[4] = String("SCANNO"); 121 140 } 122 141 uInt outrowCount = 0; 123 142 TableIterator iter(baset, cols); 143 // int count = 0 ; 124 144 while (!iter.pastEnd()) { 125 145 Table subt = iter.table(); 126 // copy the first row of this selection into the new table 127 tout.addRow(); 128 TableCopy::copyRows(tout, subt, outrowCount, 0, 1); 129 // re-index to 0 130 if ( avmode != "SCAN" && avmode != "SOURCE" ) { 131 scanColOut.put(outrowCount, uInt(0)); 132 } 133 ++outrowCount; 146 // // copy the first row of this selection into the new table 147 // tout.addRow(); 148 // TableCopy::copyRows(tout, subt, outrowCount, 0, 1); 149 // // re-index to 0 150 // if ( avmode != "SCAN" && avmode != "SOURCE" ) { 151 // scanColOut.put(outrowCount, uInt(0)); 152 // } 153 // ++outrowCount; 154 MDirection::ScalarColumn dircol ; 155 dircol.attach( subt, "DIRECTION" ) ; 156 Int length = subt.nrow() ; 157 vector< Vector<Double> > dirs ; 158 vector<int> indexes ; 159 for ( Int i = 0 ; i < length ; i++ ) { 160 Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ; 161 //os << << count++ << ": " ; 162 //os << "[" << t[0] << "," << t[1] << "]" << LogIO::POST ; 163 bool adddir = true ; 164 for ( uInt j = 0 ; j < dirs.size() ; j++ ) { 165 //if ( allTrue( t == dirs[j] ) ) { 166 Double dx = t[0] - dirs[j][0] ; 167 Double dy = t[1] - dirs[j][1] ; 168 Double dd = sqrt( dx * dx + dy * dy ) ; 169 //if ( allNearAbs( t, dirs[j], tol ) ) { 170 if ( dd <= tol ) { 171 adddir = false ; 172 break ; 173 } 174 } 175 if ( adddir ) { 176 dirs.push_back( t ) ; 177 indexes.push_back( i ) ; 178 } 179 } 180 uInt rowNum = dirs.size() ; 181 tout.addRow( rowNum ) ; 182 for ( uInt i = 0 ; i < rowNum ; i++ ) { 183 TableCopy::copyRows( tout, subt, outrowCount+i, indexes[i], 1 ) ; 184 // re-index to 0 185 if ( avmode != "SCAN" && avmode != "SOURCE" ) { 186 scanColOut.put(outrowCount+i, uInt(0)); 187 } 188 } 189 outrowCount += rowNum ; 134 190 ++iter; 135 191 } 136 137 192 RowAccumulator acc(wtype); 138 193 Vector<Bool> cmask(mask); … … 159 214 subt = basesubt( basesubt.col("SRCNAME") == rec.asString("SRCNAME") ); 160 215 } else if (avmode == "SCAN") { 161 subt = basesubt( basesubt.col("SCANNO") == Int(rec.asuInt("SCANNO")) ); 216 //subt = basesubt( basesubt.col("SCANNO") == Int(rec.asuInt("SCANNO")) ); 217 subt = basesubt( basesubt.col("SCANNO") == Int(rec.asuInt("SCANNO")) 218 && basesubt.col("SRCNAME") == rec.asString("SRCNAME") ); 162 219 } else { 163 220 subt = basesubt; 164 221 } 222 223 vector<uInt> removeRows ; 224 uInt nrsubt = subt.nrow() ; 225 for ( uInt irow = 0 ; irow < nrsubt ; irow++ ) { 226 //if ( !allTrue((subt.col("DIRECTION").getArrayDouble(TableExprId(irow)))==rec.asArrayDouble("DIRECTION")) ) { 227 Vector<Double> x0 = (subt.col("DIRECTION").getArrayDouble(TableExprId(irow))) ; 228 Vector<Double> x1 = rec.asArrayDouble("DIRECTION") ; 229 double dx = x0[0] - x1[0] ; 230 double dy = x0[0] - x1[0] ; 231 Double dd = sqrt( dx * dx + dy * dy ) ; 232 //if ( !allNearAbs((subt.col("DIRECTION").getArrayDouble(TableExprId(irow))), rec.asArrayDouble("DIRECTION"), tol ) ) { 233 if ( dd > tol ) { 234 removeRows.push_back( irow ) ; 235 } 236 } 237 if ( removeRows.size() != 0 ) { 238 subt.removeRow( removeRows ) ; 239 } 240 241 if ( nrsubt == removeRows.size() ) 242 throw(AipsError("Averaging data is empty.")) ; 243 165 244 specCol.attach(subt,"SPECTRA"); 166 245 flagCol.attach(subt,"FLAGTRA"); … … 196 275 } 197 276 //write out 198 Vector<uChar> flg(msk.shape()); 199 convertArray(flg, !msk); 200 flagColOut.put(i, flg); 201 specColOut.put(i, acc.getSpectrum()); 202 tsysColOut.put(i, acc.getTsys()); 203 intColOut.put(i, acc.getInterval()); 204 mjdColOut.put(i, acc.getTime()); 205 // we should only have one cycle now -> reset it to be 0 206 // frequency switched data has different CYCLENO for different IFNO 207 // which requires resetting this value 208 cycColOut.put(i, uInt(0)); 277 if (acc.state()) { 278 Vector<uChar> flg(msk.shape()); 279 convertArray(flg, !msk); 280 flagColOut.put(i, flg); 281 specColOut.put(i, acc.getSpectrum()); 282 tsysColOut.put(i, acc.getTsys()); 283 intColOut.put(i, acc.getInterval()); 284 mjdColOut.put(i, acc.getTime()); 285 // we should only have one cycle now -> reset it to be 0 286 // frequency switched data has different CYCLENO for different IFNO 287 // which requires resetting this value 288 cycColOut.put(i, uInt(0)); 289 } else { 290 ostringstream oss; 291 oss << "For output row="<<i<<", all input rows of data are flagged. no averaging" << endl; 292 pushLog(String(oss)); 293 } 209 294 acc.reset(); 210 295 } 211 296 if (rowstodelete.nelements() > 0) { 297 //cout << rowstodelete << endl; 298 os << rowstodelete << LogIO::POST ; 212 299 tout.removeRow(rowstodelete); 213 300 if (tout.nrow() == 0) { … … 223 310 const std::string& avmode ) 224 311 { 312 // check if OTF observation 313 String obstype = in->getHeader().obstype ; 314 Double tol = 0.0 ; 315 if ( obstype.find( "OTF" ) != String::npos ) { 316 tol = TOL_OTF ; 317 } 318 else { 319 tol = TOL_POINT ; 320 } 321 225 322 // clone as this is non insitu 226 323 bool insitu = insitu_; … … 254 351 flagCol.attach(subt,"FLAGTRA"); 255 352 tsysCol.attach(subt,"TSYS"); 256 tout.addRow(); 257 TableCopy::copyRows(tout, subt, outrowCount, 0, 1); 258 if ( avmode != "SCAN") { 259 scanColOut.put(outrowCount, uInt(0)); 260 } 261 Vector<Float> tmp; 262 specCol.get(0, tmp); 263 uInt nchan = tmp.nelements(); 264 // have to do channel by channel here as MaskedArrMath 265 // doesn't have partialMedians 266 Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0))); 267 Vector<Float> outspec(nchan); 268 Vector<uChar> outflag(nchan,0); 269 Vector<Float> outtsys(1);/// @fixme when tsys is channel based 270 for (uInt i=0; i<nchan; ++i) { 271 Vector<Float> specs = specCol.getColumn(Slicer(Slice(i))); 272 MaskedArray<Float> ma = maskedArray(specs,flags); 273 outspec[i] = median(ma); 274 if ( allEQ(ma.getMask(), False) ) 275 outflag[i] = userflag;// flag data 276 } 277 outtsys[0] = median(tsysCol.getColumn()); 278 specColOut.put(outrowCount, outspec); 279 flagColOut.put(outrowCount, outflag); 280 tsysColOut.put(outrowCount, outtsys); 281 Double intsum = sum(intCol.getColumn()); 282 intColOut.put(outrowCount, intsum); 283 ++outrowCount; 353 // tout.addRow(); 354 // TableCopy::copyRows(tout, subt, outrowCount, 0, 1); 355 // if ( avmode != "SCAN") { 356 // scanColOut.put(outrowCount, uInt(0)); 357 // } 358 // Vector<Float> tmp; 359 // specCol.get(0, tmp); 360 // uInt nchan = tmp.nelements(); 361 // // have to do channel by channel here as MaskedArrMath 362 // // doesn't have partialMedians 363 // Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0))); 364 // Vector<Float> outspec(nchan); 365 // Vector<uChar> outflag(nchan,0); 366 // Vector<Float> outtsys(1);/// @fixme when tsys is channel based 367 // for (uInt i=0; i<nchan; ++i) { 368 // Vector<Float> specs = specCol.getColumn(Slicer(Slice(i))); 369 // MaskedArray<Float> ma = maskedArray(specs,flags); 370 // outspec[i] = median(ma); 371 // if ( allEQ(ma.getMask(), False) ) 372 // outflag[i] = userflag;// flag data 373 // } 374 // outtsys[0] = median(tsysCol.getColumn()); 375 // specColOut.put(outrowCount, outspec); 376 // flagColOut.put(outrowCount, outflag); 377 // tsysColOut.put(outrowCount, outtsys); 378 // Double intsum = sum(intCol.getColumn()); 379 // intColOut.put(outrowCount, intsum); 380 // ++outrowCount; 381 // ++iter; 382 MDirection::ScalarColumn dircol ; 383 dircol.attach( subt, "DIRECTION" ) ; 384 Int length = subt.nrow() ; 385 vector< Vector<Double> > dirs ; 386 vector<int> indexes ; 387 for ( Int i = 0 ; i < length ; i++ ) { 388 Vector<Double> t = dircol(i).getAngle(Unit(String("rad"))).getValue() ; 389 bool adddir = true ; 390 for ( uInt j = 0 ; j < dirs.size() ; j++ ) { 391 //if ( allTrue( t == dirs[j] ) ) { 392 Double dx = t[0] - dirs[j][0] ; 393 Double dy = t[1] - dirs[j][1] ; 394 Double dd = sqrt( dx * dx + dy * dy ) ; 395 //if ( allNearAbs( t, dirs[j], tol ) ) { 396 if ( dd <= tol ) { 397 adddir = false ; 398 break ; 399 } 400 } 401 if ( adddir ) { 402 dirs.push_back( t ) ; 403 indexes.push_back( i ) ; 404 } 405 } 406 uInt rowNum = dirs.size() ; 407 tout.addRow( rowNum ); 408 for ( uInt i = 0 ; i < rowNum ; i++ ) { 409 TableCopy::copyRows(tout, subt, outrowCount+i, indexes[i], 1) ; 410 if ( avmode != "SCAN") { 411 //scanColOut.put(outrowCount+i, uInt(0)); 412 } 413 } 414 MDirection::ScalarColumn dircolOut ; 415 dircolOut.attach( tout, "DIRECTION" ) ; 416 for ( uInt irow = 0 ; irow < rowNum ; irow++ ) { 417 Vector<Double> t = dircolOut(outrowCount+irow).getAngle(Unit(String("rad"))).getValue() ; 418 Vector<Float> tmp; 419 specCol.get(0, tmp); 420 uInt nchan = tmp.nelements(); 421 // have to do channel by channel here as MaskedArrMath 422 // doesn't have partialMedians 423 Vector<uChar> flags = flagCol.getColumn(Slicer(Slice(0))); 424 // mask spectra for different DIRECTION 425 for ( uInt jrow = 0 ; jrow < subt.nrow() ; jrow++ ) { 426 Vector<Double> direction = dircol(jrow).getAngle(Unit(String("rad"))).getValue() ; 427 //if ( t[0] != direction[0] || t[1] != direction[1] ) { 428 Double dx = t[0] - direction[0] ; 429 Double dy = t[1] - direction[1] ; 430 Double dd = sqrt( dx * dx + dy * dy ) ; 431 //if ( !allNearAbs( t, direction, tol ) ) { 432 if ( dd > tol ) { 433 flags[jrow] = userflag ; 434 } 435 } 436 Vector<Float> outspec(nchan); 437 Vector<uChar> outflag(nchan,0); 438 Vector<Float> outtsys(1);/// @fixme when tsys is channel based 439 for (uInt i=0; i<nchan; ++i) { 440 Vector<Float> specs = specCol.getColumn(Slicer(Slice(i))); 441 MaskedArray<Float> ma = maskedArray(specs,flags); 442 outspec[i] = median(ma); 443 if ( allEQ(ma.getMask(), False) ) 444 outflag[i] = userflag;// flag data 445 } 446 outtsys[0] = median(tsysCol.getColumn()); 447 specColOut.put(outrowCount+irow, outspec); 448 flagColOut.put(outrowCount+irow, outflag); 449 tsysColOut.put(outrowCount+irow, outtsys); 450 Vector<Double> integ = intCol.getColumn() ; 451 MaskedArray<Double> mi = maskedArray( integ, flags ) ; 452 Double intsum = sum(mi); 453 intColOut.put(outrowCount+irow, intsum); 454 } 455 outrowCount += rowNum ; 284 456 ++iter; 285 457 } … … 327 499 if ( tsys ) { 328 500 ts += val; 501 tsysCol.put(i, ts); 502 } 503 } 504 } 505 return out; 506 } 507 508 CountedPtr< Scantable > STMath::arrayOperate( const CountedPtr< Scantable >& in, 509 const std::vector<float> val, 510 const std::string& mode, 511 const std::string& opmode, 512 bool tsys ) 513 { 514 CountedPtr< Scantable > out ; 515 if ( opmode == "channel" ) { 516 out = arrayOperateChannel( in, val, mode, tsys ) ; 517 } 518 else if ( opmode == "row" ) { 519 out = arrayOperateRow( in, val, mode, tsys ) ; 520 } 521 else { 522 throw( AipsError( "Unknown array operation mode." ) ) ; 523 } 524 return out ; 525 } 526 527 CountedPtr< Scantable > STMath::arrayOperateChannel( const CountedPtr< Scantable >& in, 528 const std::vector<float> val, 529 const std::string& mode, 530 bool tsys ) 531 { 532 if ( val.size() == 1 ){ 533 return unaryOperate( in, val[0], mode, tsys ) ; 534 } 535 536 // conformity of SPECTRA and TSYS 537 if ( tsys ) { 538 TableIterator titer(in->table(), "IFNO"); 539 while ( !titer.pastEnd() ) { 540 ArrayColumn<Float> specCol( in->table(), "SPECTRA" ) ; 541 ArrayColumn<Float> tsysCol( in->table(), "TSYS" ) ; 542 Array<Float> spec = specCol.getColumn() ; 543 Array<Float> ts = tsysCol.getColumn() ; 544 if ( !spec.conform( ts ) ) { 545 throw( AipsError( "SPECTRA and TSYS must conform in shape if you want to apply operation on Tsys." ) ) ; 546 } 547 titer.next() ; 548 } 549 } 550 551 // check if all spectra in the scantable have the same number of channel 552 vector<uInt> nchans; 553 vector<uInt> ifnos = in->getIFNos() ; 554 for ( uInt i = 0 ; i < ifnos.size() ; i++ ) { 555 nchans.push_back( in->nchan( ifnos[i] ) ) ; 556 } 557 Vector<uInt> mchans( nchans ) ; 558 if ( anyNE( mchans, mchans[0] ) ) { 559 throw( AipsError("All spectra in the input scantable must have the same number of channel for vector operation." ) ) ; 560 } 561 562 // check if vector size is equal to nchan 563 Vector<Float> fact( val ) ; 564 if ( fact.nelements() != mchans[0] ) { 565 throw( AipsError("Vector size must be 1 or be same as number of channel.") ) ; 566 } 567 568 // check divided by zero 569 if ( ( mode == "DIV" ) && anyEQ( fact, (float)0.0 ) ) { 570 throw( AipsError("Divided by zero is not recommended." ) ) ; 571 } 572 573 CountedPtr< Scantable > out = getScantable(in, false); 574 Table& tab = out->table(); 575 ArrayColumn<Float> specCol(tab,"SPECTRA"); 576 ArrayColumn<Float> tsysCol(tab,"TSYS"); 577 for (uInt i=0; i<tab.nrow(); ++i) { 578 Vector<Float> spec; 579 Vector<Float> ts; 580 specCol.get(i, spec); 581 tsysCol.get(i, ts); 582 if (mode == "MUL" || mode == "DIV") { 583 if (mode == "DIV") fact = (float)1.0 / fact; 584 spec *= fact; 585 specCol.put(i, spec); 586 if ( tsys ) { 587 ts *= fact; 588 tsysCol.put(i, ts); 589 } 590 } else if ( mode == "ADD" || mode == "SUB") { 591 if (mode == "SUB") fact *= (float)-1.0 ; 592 spec += fact; 593 specCol.put(i, spec); 594 if ( tsys ) { 595 ts += fact; 596 tsysCol.put(i, ts); 597 } 598 } 599 } 600 return out; 601 } 602 603 CountedPtr< Scantable > STMath::arrayOperateRow( const CountedPtr< Scantable >& in, 604 const std::vector<float> val, 605 const std::string& mode, 606 bool tsys ) 607 { 608 if ( val.size() == 1 ) { 609 return unaryOperate( in, val[0], mode, tsys ) ; 610 } 611 612 // conformity of SPECTRA and TSYS 613 if ( tsys ) { 614 TableIterator titer(in->table(), "IFNO"); 615 while ( !titer.pastEnd() ) { 616 ArrayColumn<Float> specCol( in->table(), "SPECTRA" ) ; 617 ArrayColumn<Float> tsysCol( in->table(), "TSYS" ) ; 618 Array<Float> spec = specCol.getColumn() ; 619 Array<Float> ts = tsysCol.getColumn() ; 620 if ( !spec.conform( ts ) ) { 621 throw( AipsError( "SPECTRA and TSYS must conform in shape if you want to apply operation on Tsys." ) ) ; 622 } 623 titer.next() ; 624 } 625 } 626 627 // check if vector size is equal to nrow 628 Vector<Float> fact( val ) ; 629 if ( fact.nelements() != in->nrow() ) { 630 throw( AipsError("Vector size must be 1 or be same as number of row.") ) ; 631 } 632 633 // check divided by zero 634 if ( ( mode == "DIV" ) && anyEQ( fact, (float)0.0 ) ) { 635 throw( AipsError("Divided by zero is not recommended." ) ) ; 636 } 637 638 CountedPtr< Scantable > out = getScantable(in, false); 639 Table& tab = out->table(); 640 ArrayColumn<Float> specCol(tab,"SPECTRA"); 641 ArrayColumn<Float> tsysCol(tab,"TSYS"); 642 if (mode == "DIV") fact = (float)1.0 / fact; 643 if (mode == "SUB") fact *= (float)-1.0 ; 644 for (uInt i=0; i<tab.nrow(); ++i) { 645 Vector<Float> spec; 646 Vector<Float> ts; 647 specCol.get(i, spec); 648 tsysCol.get(i, ts); 649 if (mode == "MUL" || mode == "DIV") { 650 spec *= fact[i]; 651 specCol.put(i, spec); 652 if ( tsys ) { 653 ts *= fact[i]; 654 tsysCol.put(i, ts); 655 } 656 } else if ( mode == "ADD" || mode == "SUB") { 657 spec += fact[i]; 658 specCol.put(i, spec); 659 if ( tsys ) { 660 ts += fact[i]; 661 tsysCol.put(i, ts); 662 } 663 } 664 } 665 return out; 666 } 667 668 CountedPtr< Scantable > STMath::array2dOperate( const CountedPtr< Scantable >& in, 669 const std::vector< std::vector<float> > val, 670 const std::string& mode, 671 bool tsys ) 672 { 673 // conformity of SPECTRA and TSYS 674 if ( tsys ) { 675 TableIterator titer(in->table(), "IFNO"); 676 while ( !titer.pastEnd() ) { 677 ArrayColumn<Float> specCol( in->table(), "SPECTRA" ) ; 678 ArrayColumn<Float> tsysCol( in->table(), "TSYS" ) ; 679 Array<Float> spec = specCol.getColumn() ; 680 Array<Float> ts = tsysCol.getColumn() ; 681 if ( !spec.conform( ts ) ) { 682 throw( AipsError( "SPECTRA and TSYS must conform in shape if you want to apply operation on Tsys." ) ) ; 683 } 684 titer.next() ; 685 } 686 } 687 688 // some checks 689 vector<uInt> nchans; 690 for ( uInt i = 0 ; i < in->nrow() ; i++ ) { 691 nchans.push_back( (in->getSpectrum( i )).size() ) ; 692 } 693 //Vector<uInt> mchans( nchans ) ; 694 vector< Vector<Float> > facts ; 695 for ( uInt i = 0 ; i < nchans.size() ; i++ ) { 696 Vector<Float> tmp( val[i] ) ; 697 // check divided by zero 698 if ( ( mode == "DIV" ) && anyEQ( tmp, (float)0.0 ) ) { 699 throw( AipsError("Divided by zero is not recommended." ) ) ; 700 } 701 // conformity check 702 if ( tmp.nelements() != nchans[i] ) { 703 stringstream ss ; 704 ss << "Row " << i << ": Vector size must be same as number of channel." ; 705 throw( AipsError( ss.str() ) ) ; 706 } 707 facts.push_back( tmp ) ; 708 } 709 710 711 CountedPtr< Scantable > out = getScantable(in, false); 712 Table& tab = out->table(); 713 ArrayColumn<Float> specCol(tab,"SPECTRA"); 714 ArrayColumn<Float> tsysCol(tab,"TSYS"); 715 for (uInt i=0; i<tab.nrow(); ++i) { 716 Vector<Float> fact = facts[i] ; 717 Vector<Float> spec; 718 Vector<Float> ts; 719 specCol.get(i, spec); 720 tsysCol.get(i, ts); 721 if (mode == "MUL" || mode == "DIV") { 722 if (mode == "DIV") fact = (float)1.0 / fact; 723 spec *= fact; 724 specCol.put(i, spec); 725 if ( tsys ) { 726 ts *= fact; 727 tsysCol.put(i, ts); 728 } 729 } else if ( mode == "ADD" || mode == "SUB") { 730 if (mode == "SUB") fact *= (float)-1.0 ; 731 spec += fact; 732 specCol.put(i, spec); 733 if ( tsys ) { 734 ts += fact; 329 735 tsysCol.put(i, ts); 330 736 } … … 390 796 } 391 797 798 MaskedArray<Double> STMath::maskedArray( const Vector<Double>& s, 799 const Vector<uChar>& f) 800 { 801 Vector<Bool> mask; 802 mask.resize(f.shape()); 803 convertArray(mask, f); 804 return MaskedArray<Double>(s,!mask); 805 } 806 392 807 Vector<uChar> STMath::flagsFromMA(const MaskedArray<Float>& ma) 393 808 { … … 406 821 // make this operation non insitu 407 822 const Table& tin = in->table(); 408 Table ons = tin(tin.col("SRCTYPE") == Int( 0));409 Table offs = tin(tin.col("SRCTYPE") == Int( 1));823 Table ons = tin(tin.col("SRCTYPE") == Int(SrcType::PSON)); 824 Table offs = tin(tin.col("SRCTYPE") == Int(SrcType::PSOFF)); 410 825 if ( offs.nrow() == 0 ) 411 826 throw(AipsError("No 'off' scans present.")); … … 645 1060 //Debug 646 1061 //if(noff!=ndiff) cerr<<"noff and ndiff is not equal"<<endl; 1062 //LogIO os( LogOrigin( "STMath", "dototalpower()", WHERE ) ) ; 1063 //if(noff!=ndiff) os<<"noff and ndiff is not equal"<<LogIO::POST; 647 1064 meanoff = sum(spoff)/noff; 648 1065 meandiff = sum(spdiff)/ndiff; … … 764 1181 //Debug 765 1182 //cerr<<"Tsys used="<<tsysrefscalar<<endl; 1183 //LogIO os( LogOrigin( "STMath", "dosigref", WHERE ) ) ; 1184 //os<<"Tsys used="<<tsysrefscalar<<LogIO::POST; 766 1185 // fill the result, replay signal tsys by reference tsys 767 1186 outintCol.put(i, resint); … … 786 1205 setInsitu(false); 787 1206 STSelector sel; 788 std::vector<int> scan1, scan2, beams ;1207 std::vector<int> scan1, scan2, beams, types; 789 1208 std::vector< vector<int> > scanpair; 790 std::vector<string> calstate; 1209 //std::vector<string> calstate; 1210 std::vector<int> calstate; 791 1211 String msg; 792 1212 … … 835 1255 scanpair.push_back(scan1); 836 1256 scanpair.push_back(scan2); 837 calstate.push_back("*calon"); 838 calstate.push_back("*[^calon]"); 1257 //calstate.push_back("*calon"); 1258 //calstate.push_back("*[^calon]"); 1259 calstate.push_back(SrcType::NODCAL); 1260 calstate.push_back(SrcType::NOD); 839 1261 CountedPtr< Scantable > ws = getScantable(s, false); 840 1262 uInt l=0; … … 845 1267 sel.reset(); 846 1268 sel.setScans(scanpair[i]); 847 sel.setName(calstate[k]); 1269 //sel.setName(calstate[k]); 1270 types.clear(); 1271 types.push_back(calstate[k]); 1272 sel.setTypes(types); 848 1273 beams.clear(); 849 1274 beams.push_back(j); … … 930 1355 //Array<Float> avtsys = Float(0.5) * (tsys1 + tsys2); 931 1356 // cerr<< "Tsys1="<<tsys1<<" Tsys2="<<tsys2<<endl; 1357 // LogIO os( LogOrigin( "STMath", "donod", WHERE ) ) ; 1358 // os<< "Tsys1="<<tsys1<<" Tsys2="<<tsys2<<LogIO::POST; 932 1359 tsys1[0] = sqrt(tsyssq1 + tsyssq2); 933 1360 Array<Float> avtsys = tsys1; … … 956 1383 CountedPtr< Scantable > ws = getScantable(s, false); 957 1384 CountedPtr< Scantable > sig, sigwcal, ref, refwcal; 958 CountedPtr< Scantable > calsig, calref, out; 1385 CountedPtr< Scantable > calsig, calref, out, out1, out2; 1386 Bool nofold=False; 1387 vector<int> types ; 959 1388 960 1389 //split the data 961 sel.setName("*_fs"); 1390 //sel.setName("*_fs"); 1391 types.push_back( SrcType::FSON ) ; 1392 sel.setTypes( types ) ; 962 1393 ws->setSelection(sel); 963 1394 sig = getScantable(ws,false); 964 1395 sel.reset(); 965 sel.setName("*_fs_calon"); 1396 types.clear() ; 1397 //sel.setName("*_fs_calon"); 1398 types.push_back( SrcType::FONCAL ) ; 1399 sel.setTypes( types ) ; 966 1400 ws->setSelection(sel); 967 1401 sigwcal = getScantable(ws,false); 968 1402 sel.reset(); 969 sel.setName("*_fsr"); 1403 types.clear() ; 1404 //sel.setName("*_fsr"); 1405 types.push_back( SrcType::FSOFF ) ; 1406 sel.setTypes( types ) ; 970 1407 ws->setSelection(sel); 971 1408 ref = getScantable(ws,false); 972 1409 sel.reset(); 973 sel.setName("*_fsr_calon"); 1410 types.clear() ; 1411 //sel.setName("*_fsr_calon"); 1412 types.push_back( SrcType::FOFFCAL ) ; 1413 sel.setTypes( types ) ; 974 1414 ws->setSelection(sel); 975 1415 refwcal = getScantable(ws,false); 1416 sel.reset() ; 1417 types.clear() ; 976 1418 977 1419 calsig = dototalpower(sigwcal, sig, tcal=tcal); 978 1420 calref = dototalpower(refwcal, ref, tcal=tcal); 979 1421 980 out=dosigref(calsig,calref,smoothref,tsysv,tau); 981 1422 out1=dosigref(calsig,calref,smoothref,tsysv,tau); 1423 out2=dosigref(calref,calsig,smoothref,tsysv,tau); 1424 1425 Table& tabout1=out1->table(); 1426 Table& tabout2=out2->table(); 1427 ROScalarColumn<uInt> freqidCol1(tabout1, "FREQ_ID"); 1428 ScalarColumn<uInt> freqidCol2(tabout2, "FREQ_ID"); 1429 ROArrayColumn<Float> specCol(tabout2, "SPECTRA"); 1430 Vector<Float> spec; specCol.get(0, spec); 1431 uInt nchan = spec.nelements(); 1432 uInt freqid1; freqidCol1.get(0,freqid1); 1433 uInt freqid2; freqidCol2.get(0,freqid2); 1434 Double rp1, rp2, rv1, rv2, inc1, inc2; 1435 out1->frequencies().getEntry(rp1, rv1, inc1, freqid1); 1436 out2->frequencies().getEntry(rp2, rv2, inc2, freqid2); 1437 //cerr << out1->frequencies().table().nrow() << " " << out2->frequencies().table().nrow() << endl ; 1438 //LogIO os( LogOrigin( "STMath", "dofs()", WHERE ) ) ; 1439 //os << out1->frequencies().table().nrow() << " " << out2->frequencies().table().nrow() << LogIO::POST ; 1440 if (rp1==rp2) { 1441 Double foffset = rv1 - rv2; 1442 uInt choffset = static_cast<uInt>(foffset/abs(inc2)); 1443 if (choffset >= nchan) { 1444 //cerr<<"out-band frequency switching, no folding"<<endl; 1445 LogIO os( LogOrigin( "STMath", "dofs()", WHERE ) ) ; 1446 os<<"out-band frequency switching, no folding"<<LogIO::POST; 1447 nofold = True; 1448 } 1449 } 1450 1451 if (nofold) { 1452 std::vector< CountedPtr< Scantable > > tabs; 1453 tabs.push_back(out1); 1454 tabs.push_back(out2); 1455 out = merge(tabs); 1456 } 1457 else { 1458 //out = out1; 1459 Double choffset = ( rv1 - rv2 ) / inc2 ; 1460 out = dofold( out1, out2, choffset ) ; 1461 } 1462 982 1463 return out; 1464 } 1465 1466 CountedPtr<Scantable> STMath::dofold( const CountedPtr<Scantable> &sig, 1467 const CountedPtr<Scantable> &ref, 1468 Double choffset, 1469 Double choffset2 ) 1470 { 1471 LogIO os( LogOrigin( "STMath", "dofold", WHERE ) ) ; 1472 os << "choffset=" << choffset << " choffset2=" << choffset2 << LogIO::POST ; 1473 1474 // output scantable 1475 CountedPtr<Scantable> out = getScantable( sig, false ) ; 1476 1477 // separate choffset to integer part and decimal part 1478 Int ioffset = (Int)choffset ; 1479 Double doffset = choffset - ioffset ; 1480 Int ioffset2 = (Int)choffset2 ; 1481 Double doffset2 = choffset2 - ioffset2 ; 1482 os << "ioffset=" << ioffset << " doffset=" << doffset << LogIO::POST ; 1483 os << "ioffset2=" << ioffset2 << " doffset2=" << doffset2 << LogIO::POST ; 1484 1485 // get column 1486 ROArrayColumn<Float> specCol1( sig->table(), "SPECTRA" ) ; 1487 ROArrayColumn<Float> specCol2( ref->table(), "SPECTRA" ) ; 1488 ROArrayColumn<Float> tsysCol1( sig->table(), "TSYS" ) ; 1489 ROArrayColumn<Float> tsysCol2( ref->table(), "TSYS" ) ; 1490 ROArrayColumn<uChar> flagCol1( sig->table(), "FLAGTRA" ) ; 1491 ROArrayColumn<uChar> flagCol2( ref->table(), "FLAGTRA" ) ; 1492 ROScalarColumn<Double> mjdCol1( sig->table(), "TIME" ) ; 1493 ROScalarColumn<Double> mjdCol2( ref->table(), "TIME" ) ; 1494 ROScalarColumn<Double> intervalCol1( sig->table(), "INTERVAL" ) ; 1495 ROScalarColumn<Double> intervalCol2( ref->table(), "INTERVAL" ) ; 1496 1497 // check 1498 if ( ioffset == 0 ) { 1499 LogIO os( LogOrigin( "STMath", "dofold()", WHERE ) ) ; 1500 os << "channel offset is zero, no folding" << LogIO::POST ; 1501 return out ; 1502 } 1503 int nchan = ref->nchan() ; 1504 if ( abs(ioffset) >= nchan ) { 1505 LogIO os( LogOrigin( "STMath", "dofold()", WHERE ) ) ; 1506 os << "out-band frequency switching, no folding" << LogIO::POST ; 1507 return out ; 1508 } 1509 1510 // attach column for output scantable 1511 ArrayColumn<Float> specColOut( out->table(), "SPECTRA" ) ; 1512 ArrayColumn<uChar> flagColOut( out->table(), "FLAGTRA" ) ; 1513 ArrayColumn<Float> tsysColOut( out->table(), "TSYS" ) ; 1514 ScalarColumn<Double> mjdColOut( out->table(), "TIME" ) ; 1515 ScalarColumn<Double> intervalColOut( out->table(), "INTERVAL" ) ; 1516 ScalarColumn<uInt> fidColOut( out->table(), "FREQ_ID" ) ; 1517 1518 // for each row 1519 // assume that the data order are same between sig and ref 1520 RowAccumulator acc( asap::W_TINTSYS ) ; 1521 for ( int i = 0 ; i < sig->nrow() ; i++ ) { 1522 // get values 1523 Vector<Float> spsig ; 1524 specCol1.get( i, spsig ) ; 1525 Vector<Float> spref ; 1526 specCol2.get( i, spref ) ; 1527 Vector<Float> tsyssig ; 1528 tsysCol1.get( i, tsyssig ) ; 1529 Vector<Float> tsysref ; 1530 tsysCol2.get( i, tsysref ) ; 1531 Vector<uChar> flagsig ; 1532 flagCol1.get( i, flagsig ) ; 1533 Vector<uChar> flagref ; 1534 flagCol2.get( i, flagref ) ; 1535 Double timesig ; 1536 mjdCol1.get( i, timesig ) ; 1537 Double timeref ; 1538 mjdCol2.get( i, timeref ) ; 1539 Double intsig ; 1540 intervalCol1.get( i, intsig ) ; 1541 Double intref ; 1542 intervalCol2.get( i, intref ) ; 1543 1544 // shift reference spectra 1545 int refchan = spref.nelements() ; 1546 Vector<Float> sspref( spref.nelements() ) ; 1547 Vector<Float> stsysref( tsysref.nelements() ) ; 1548 Vector<uChar> sflagref( flagref.nelements() ) ; 1549 if ( ioffset > 0 ) { 1550 // SPECTRA and FLAGTRA 1551 for ( int j = 0 ; j < refchan-ioffset ; j++ ) { 1552 sspref[j] = spref[j+ioffset] ; 1553 sflagref[j] = flagref[j+ioffset] ; 1554 } 1555 for ( int j = refchan-ioffset ; j < refchan ; j++ ) { 1556 sspref[j] = spref[j-refchan+ioffset] ; 1557 sflagref[j] = flagref[j-refchan+ioffset] ; 1558 } 1559 spref = sspref.copy() ; 1560 flagref = sflagref.copy() ; 1561 for ( int j = 0 ; j < refchan - 1 ; j++ ) { 1562 sspref[j] = doffset * spref[j+1] + ( 1.0 - doffset ) * spref[j] ; 1563 sflagref[j] = flagref[j+1] + flagref[j] ; 1564 } 1565 sspref[refchan-1] = doffset * spref[0] + ( 1.0 - doffset ) * spref[refchan-1] ; 1566 sflagref[refchan-1] = flagref[0] + flagref[refchan-1] ; 1567 1568 // TSYS 1569 if ( spref.nelements() == tsysref.nelements() ) { 1570 for ( int j = 0 ; j < refchan-ioffset ; j++ ) { 1571 stsysref[j] = tsysref[j+ioffset] ; 1572 } 1573 for ( int j = refchan-ioffset ; j < refchan ; j++ ) { 1574 stsysref[j] = tsysref[j-refchan+ioffset] ; 1575 } 1576 tsysref = stsysref.copy() ; 1577 for ( int j = 0 ; j < refchan - 1 ; j++ ) { 1578 stsysref[j] = doffset * tsysref[j+1] + ( 1.0 - doffset ) * tsysref[j] ; 1579 } 1580 stsysref[refchan-1] = doffset * tsysref[0] + ( 1.0 - doffset ) * tsysref[refchan-1] ; 1581 } 1582 } 1583 else { 1584 // SPECTRA and FLAGTRA 1585 for ( int j = 0 ; j < abs(ioffset) ; j++ ) { 1586 sspref[j] = spref[refchan+ioffset+j] ; 1587 sflagref[j] = flagref[refchan+ioffset+j] ; 1588 } 1589 for ( int j = abs(ioffset) ; j < refchan ; j++ ) { 1590 sspref[j] = spref[j+ioffset] ; 1591 sflagref[j] = flagref[j+ioffset] ; 1592 } 1593 spref = sspref.copy() ; 1594 flagref = sflagref.copy() ; 1595 sspref[0] = doffset * spref[refchan-1] + ( 1.0 - doffset ) * spref[0] ; 1596 sflagref[0] = flagref[0] + flagref[refchan-1] ; 1597 for ( int j = 1 ; j < refchan ; j++ ) { 1598 sspref[j] = doffset * spref[j-1] + ( 1.0 - doffset ) * spref[j] ; 1599 sflagref[j] = flagref[j-1] + flagref[j] ; 1600 } 1601 // TSYS 1602 if ( spref.nelements() == tsysref.nelements() ) { 1603 for ( int j = 0 ; j < abs(ioffset) ; j++ ) { 1604 stsysref[j] = tsysref[refchan+ioffset+j] ; 1605 } 1606 for ( int j = abs(ioffset) ; j < refchan ; j++ ) { 1607 stsysref[j] = tsysref[j+ioffset] ; 1608 } 1609 tsysref = stsysref.copy() ; 1610 stsysref[0] = doffset * tsysref[refchan-1] + ( 1.0 - doffset ) * tsysref[0] ; 1611 for ( int j = 1 ; j < refchan ; j++ ) { 1612 stsysref[j] = doffset * tsysref[j-1] + ( 1.0 - doffset ) * tsysref[j] ; 1613 } 1614 } 1615 } 1616 1617 // shift signal spectra if necessary (only for APEX?) 1618 if ( choffset2 != 0.0 ) { 1619 int sigchan = spsig.nelements() ; 1620 Vector<Float> sspsig( spsig.nelements() ) ; 1621 Vector<Float> stsyssig( tsyssig.nelements() ) ; 1622 Vector<uChar> sflagsig( flagsig.nelements() ) ; 1623 if ( ioffset2 > 0 ) { 1624 // SPECTRA and FLAGTRA 1625 for ( int j = 0 ; j < sigchan-ioffset2 ; j++ ) { 1626 sspsig[j] = spsig[j+ioffset2] ; 1627 sflagsig[j] = flagsig[j+ioffset2] ; 1628 } 1629 for ( int j = sigchan-ioffset2 ; j < sigchan ; j++ ) { 1630 sspsig[j] = spsig[j-sigchan+ioffset2] ; 1631 sflagsig[j] = flagsig[j-sigchan+ioffset2] ; 1632 } 1633 spsig = sspsig.copy() ; 1634 flagsig = sflagsig.copy() ; 1635 for ( int j = 0 ; j < sigchan - 1 ; j++ ) { 1636 sspsig[j] = doffset2 * spsig[j+1] + ( 1.0 - doffset2 ) * spsig[j] ; 1637 sflagsig[j] = flagsig[j+1] || flagsig[j] ; 1638 } 1639 sspsig[sigchan-1] = doffset2 * spsig[0] + ( 1.0 - doffset2 ) * spsig[sigchan-1] ; 1640 sflagsig[sigchan-1] = flagsig[0] || flagsig[sigchan-1] ; 1641 // TSTS 1642 if ( spsig.nelements() == tsyssig.nelements() ) { 1643 for ( int j = 0 ; j < sigchan-ioffset2 ; j++ ) { 1644 stsyssig[j] = tsyssig[j+ioffset2] ; 1645 } 1646 for ( int j = sigchan-ioffset2 ; j < sigchan ; j++ ) { 1647 stsyssig[j] = tsyssig[j-sigchan+ioffset2] ; 1648 } 1649 tsyssig = stsyssig.copy() ; 1650 for ( int j = 0 ; j < sigchan - 1 ; j++ ) { 1651 stsyssig[j] = doffset2 * tsyssig[j+1] + ( 1.0 - doffset2 ) * tsyssig[j] ; 1652 } 1653 stsyssig[sigchan-1] = doffset2 * tsyssig[0] + ( 1.0 - doffset2 ) * tsyssig[sigchan-1] ; 1654 } 1655 } 1656 else { 1657 // SPECTRA and FLAGTRA 1658 for ( int j = 0 ; j < abs(ioffset2) ; j++ ) { 1659 sspsig[j] = spsig[sigchan+ioffset2+j] ; 1660 sflagsig[j] = flagsig[sigchan+ioffset2+j] ; 1661 } 1662 for ( int j = abs(ioffset2) ; j < sigchan ; j++ ) { 1663 sspsig[j] = spsig[j+ioffset2] ; 1664 sflagsig[j] = flagsig[j+ioffset2] ; 1665 } 1666 spsig = sspsig.copy() ; 1667 flagsig = sflagsig.copy() ; 1668 sspsig[0] = doffset2 * spsig[sigchan-1] + ( 1.0 - doffset2 ) * spsig[0] ; 1669 sflagsig[0] = flagsig[0] + flagsig[sigchan-1] ; 1670 for ( int j = 1 ; j < sigchan ; j++ ) { 1671 sspsig[j] = doffset2 * spsig[j-1] + ( 1.0 - doffset2 ) * spsig[j] ; 1672 sflagsig[j] = flagsig[j-1] + flagsig[j] ; 1673 } 1674 // TSYS 1675 if ( spsig.nelements() == tsyssig.nelements() ) { 1676 for ( int j = 0 ; j < abs(ioffset2) ; j++ ) { 1677 stsyssig[j] = tsyssig[sigchan+ioffset2+j] ; 1678 } 1679 for ( int j = abs(ioffset2) ; j < sigchan ; j++ ) { 1680 stsyssig[j] = tsyssig[j+ioffset2] ; 1681 } 1682 tsyssig = stsyssig.copy() ; 1683 stsyssig[0] = doffset2 * tsyssig[sigchan-1] + ( 1.0 - doffset2 ) * tsyssig[0] ; 1684 for ( int j = 1 ; j < sigchan ; j++ ) { 1685 stsyssig[j] = doffset2 * tsyssig[j-1] + ( 1.0 - doffset2 ) * tsyssig[j] ; 1686 } 1687 } 1688 } 1689 } 1690 1691 // folding 1692 acc.add( spsig, !flagsig, tsyssig, intsig, timesig ) ; 1693 acc.add( sspref, !sflagref, stsysref, intref, timeref ) ; 1694 1695 // put result 1696 specColOut.put( i, acc.getSpectrum() ) ; 1697 const Vector<Bool> &msk = acc.getMask() ; 1698 Vector<uChar> flg( msk.shape() ) ; 1699 convertArray( flg, !msk ) ; 1700 flagColOut.put( i, flg ) ; 1701 tsysColOut.put( i, acc.getTsys() ) ; 1702 intervalColOut.put( i, acc.getInterval() ) ; 1703 mjdColOut.put( i, acc.getTime() ) ; 1704 // change FREQ_ID to unshifted IF setting (only for APEX?) 1705 if ( choffset2 != 0.0 ) { 1706 uInt freqid = fidColOut( 0 ) ; // assume single-IF data 1707 double refpix, refval, increment ; 1708 out->frequencies().getEntry( refpix, refval, increment, freqid ) ; 1709 refval -= choffset * increment ; 1710 uInt newfreqid = out->frequencies().addEntry( refpix, refval, increment ) ; 1711 Vector<uInt> freqids = fidColOut.getColumn() ; 1712 for ( uInt j = 0 ; j < freqids.nelements() ; j++ ) { 1713 if ( freqids[j] == freqid ) 1714 freqids[j] = newfreqid ; 1715 } 1716 fidColOut.putColumn( freqids ) ; 1717 } 1718 1719 acc.reset() ; 1720 } 1721 1722 return out ; 983 1723 } 984 1724 … … 1055 1795 } 1056 1796 out.push_back(outstat); 1797 } 1798 return out; 1799 } 1800 1801 std::vector< int > STMath::minMaxChan( const CountedPtr< Scantable > & in, 1802 const std::vector< bool > & mask, 1803 const std::string& which ) 1804 { 1805 1806 Vector<Bool> m(mask); 1807 const Table& tab = in->table(); 1808 ROArrayColumn<Float> specCol(tab, "SPECTRA"); 1809 ROArrayColumn<uChar> flagCol(tab, "FLAGTRA"); 1810 std::vector<int> out; 1811 for (uInt i=0; i < tab.nrow(); ++i ) { 1812 Vector<Float> spec; specCol.get(i, spec); 1813 Vector<uChar> flag; flagCol.get(i, flag); 1814 MaskedArray<Float> ma = maskedArray(spec, flag); 1815 if (ma.ndim() != 1) { 1816 throw (ArrayError( 1817 "std::vector<int> STMath::minMaxChan(" 1818 "ContedPtr<Scantable> &in, std::vector<bool> &mask, " 1819 " std::string &which)" 1820 " - MaskedArray is not 1D")); 1821 } 1822 IPosition outpos(1,0); 1823 if ( spec.nelements() == m.nelements() ) { 1824 outpos = mathutil::minMaxPos(which, ma(m)); 1825 } else { 1826 outpos = mathutil::minMaxPos(which, ma); 1827 } 1828 out.push_back(outpos[0]); 1057 1829 } 1058 1830 return out; … … 1575 2347 if ( ! (*it)->conformant(*out) ) { 1576 2348 // non conformant. 1577 pushLog(String("Warning: Can't merge scantables as header info differs.")); 2349 //pushLog(String("Warning: Can't merge scantables as header info differs.")); 2350 LogIO os( LogOrigin( "STMath", "merge()", WHERE ) ) ; 2351 os << LogIO::SEVERE << "Can't merge scantables as header informations (any one of AntennaName, Equinox, and FluxUnit) differ." << LogIO::EXCEPTION ; 1578 2352 } 1579 2353 out->appendToHistoryTable((*it)->history()); … … 1597 2371 id = out->frequencies().addEntry(rp, rv, inc); 1598 2372 freqidcol.put(k,id); 1599 String name,fname;Double rf; 2373 //String name,fname;Double rf; 2374 Vector<String> name,fname;Vector<Double> rf; 1600 2375 (*it)->molecules().getEntry(rf, name, fname, rec.asuInt("MOLECULE_ID")); 1601 2376 id = out->molecules().addEntry(rf, name, fname); … … 2001 2776 int fstart = -1; 2002 2777 int fend = -1; 2003 for ( int k=0; k < flag.nelements(); ++k ) {2778 for (unsigned int k=0; k < flag.nelements(); ++k ) { 2004 2779 if (flag[k] > 0) { 2005 2780 fstart = k; … … 2055 2830 return out; 2056 2831 } 2832 2833 // Averaging spectra with different channel/resolution 2834 CountedPtr<Scantable> 2835 STMath::new_average( const std::vector<CountedPtr<Scantable> >& in, 2836 const bool& compel, 2837 const std::vector<bool>& mask, 2838 const std::string& weight, 2839 const std::string& avmode ) 2840 throw ( casa::AipsError ) 2841 { 2842 LogIO os( LogOrigin( "STMath", "new_average()", WHERE ) ) ; 2843 if ( avmode == "SCAN" && in.size() != 1 ) 2844 throw(AipsError("Can't perform 'SCAN' averaging on multiple tables.\n" 2845 "Use merge first.")); 2846 2847 // check if OTF observation 2848 String obstype = in[0]->getHeader().obstype ; 2849 Double tol = 0.0 ; 2850 if ( obstype.find( "OTF" ) != String::npos ) { 2851 tol = TOL_OTF ; 2852 } 2853 else { 2854 tol = TOL_POINT ; 2855 } 2856 2857 CountedPtr<Scantable> out ; // processed result 2858 if ( compel ) { 2859 std::vector< CountedPtr<Scantable> > newin ; // input for average process 2860 uInt insize = in.size() ; // number of input scantables 2861 2862 // TEST: do normal average in each table before IF grouping 2863 os << "Do preliminary averaging" << LogIO::POST ; 2864 vector< CountedPtr<Scantable> > tmpin( insize ) ; 2865 for ( uInt itable = 0 ; itable < insize ; itable++ ) { 2866 vector< CountedPtr<Scantable> > v( 1, in[itable] ) ; 2867 tmpin[itable] = average( v, mask, weight, avmode ) ; 2868 } 2869 2870 // warning 2871 os << "Average spectra with different spectral resolution" << LogIO::POST ; 2872 2873 // temporarily set coordinfo 2874 vector<string> oldinfo( insize ) ; 2875 for ( uInt itable = 0 ; itable < insize ; itable++ ) { 2876 vector<string> coordinfo = in[itable]->getCoordInfo() ; 2877 oldinfo[itable] = coordinfo[0] ; 2878 coordinfo[0] = "Hz" ; 2879 tmpin[itable]->setCoordInfo( coordinfo ) ; 2880 } 2881 2882 // columns 2883 ScalarColumn<uInt> freqIDCol ; 2884 ScalarColumn<uInt> ifnoCol ; 2885 ScalarColumn<uInt> scannoCol ; 2886 2887 2888 // check IF frequency coverage 2889 // freqid: list of FREQ_ID, which is used, in each table 2890 // iffreq: list of minimum and maximum frequency for each FREQ_ID in 2891 // each table 2892 // freqid[insize][numIF] 2893 // freqid: [[id00, id01, ...], 2894 // [id10, id11, ...], 2895 // ... 2896 // [idn0, idn1, ...]] 2897 // iffreq[insize][numIF*2] 2898 // iffreq: [[min_id00, max_id00, min_id01, max_id01, ...], 2899 // [min_id10, max_id10, min_id11, max_id11, ...], 2900 // ... 2901 // [min_idn0, max_idn0, min_idn1, max_idn1, ...]] 2902 //os << "Check IF settings in each table" << LogIO::POST ; 2903 vector< vector<uInt> > freqid( insize ); 2904 vector< vector<double> > iffreq( insize ) ; 2905 for ( uInt itable = 0 ; itable < insize ; itable++ ) { 2906 uInt rows = tmpin[itable]->nrow() ; 2907 uInt freqnrows = tmpin[itable]->frequencies().table().nrow() ; 2908 for ( uInt irow = 0 ; irow < rows ; irow++ ) { 2909 if ( freqid[itable].size() == freqnrows ) { 2910 break ; 2911 } 2912 else { 2913 freqIDCol.attach( tmpin[itable]->table(), "FREQ_ID" ) ; 2914 ifnoCol.attach( tmpin[itable]->table(), "IFNO" ) ; 2915 uInt id = freqIDCol( irow ) ; 2916 if ( freqid[itable].size() == 0 || count( freqid[itable].begin(), freqid[itable].end(), id ) == 0 ) { 2917 //os << "itable = " << itable << ": IF " << id << " is included in the list" << LogIO::POST ; 2918 vector<double> abcissa = tmpin[itable]->getAbcissa( irow ) ; 2919 freqid[itable].push_back( id ) ; 2920 iffreq[itable].push_back( abcissa[0] - 0.5 * ( abcissa[1] - abcissa[0] ) ) ; 2921 iffreq[itable].push_back( abcissa[abcissa.size()-1] + 0.5 * ( abcissa[1] - abcissa[0] ) ) ; 2922 } 2923 } 2924 } 2925 } 2926 2927 // debug 2928 //os << "IF settings summary:" << endl ; 2929 //for ( uInt i = 0 ; i < freqid.size() ; i++ ) { 2930 //os << " Table" << i << endl ; 2931 //for ( uInt j = 0 ; j < freqid[i].size() ; j++ ) { 2932 //os << " id = " << freqid[i][j] << " (min,max) = (" << iffreq[i][2*j] << "," << iffreq[i][2*j+1] << ")" << endl ; 2933 //} 2934 //} 2935 //os << endl ; 2936 //os.post() ; 2937 2938 // IF grouping based on their frequency coverage 2939 // ifgrp: list of table index and FREQ_ID for all members in each IF group 2940 // ifgfreq: list of minimum and maximum frequency in each IF group 2941 // ifgrp[numgrp][nummember*2] 2942 // ifgrp: [[table00, freqrow00, table01, freqrow01, ...], 2943 // [table10, freqrow10, table11, freqrow11, ...], 2944 // ... 2945 // [tablen0, freqrown0, tablen1, freqrown1, ...]] 2946 // ifgfreq[numgrp*2] 2947 // ifgfreq: [min0_grp0, max0_grp0, min1_grp1, max1_grp1, ...] 2948 //os << "IF grouping based on their frequency coverage" << LogIO::POST ; 2949 vector< vector<uInt> > ifgrp ; 2950 vector<double> ifgfreq ; 2951 2952 // parameter for IF grouping 2953 // groupmode = OR retrieve all region 2954 // AND only retrieve overlaped region 2955 //string groupmode = "AND" ; 2956 string groupmode = "OR" ; 2957 uInt sizecr = 0 ; 2958 if ( groupmode == "AND" ) 2959 sizecr = 2 ; 2960 else if ( groupmode == "OR" ) 2961 sizecr = 0 ; 2962 2963 vector<double> sortedfreq ; 2964 for ( uInt i = 0 ; i < iffreq.size() ; i++ ) { 2965 for ( uInt j = 0 ; j < iffreq[i].size() ; j++ ) { 2966 if ( count( sortedfreq.begin(), sortedfreq.end(), iffreq[i][j] ) == 0 ) 2967 sortedfreq.push_back( iffreq[i][j] ) ; 2968 } 2969 } 2970 sort( sortedfreq.begin(), sortedfreq.end() ) ; 2971 for ( vector<double>::iterator i = sortedfreq.begin() ; i != sortedfreq.end()-1 ; i++ ) { 2972 ifgfreq.push_back( *i ) ; 2973 ifgfreq.push_back( *(i+1) ) ; 2974 } 2975 ifgrp.resize( ifgfreq.size()/2 ) ; 2976 for ( uInt itable = 0 ; itable < insize ; itable++ ) { 2977 for ( uInt iif = 0 ; iif < freqid[itable].size() ; iif++ ) { 2978 double range0 = iffreq[itable][2*iif] ; 2979 double range1 = iffreq[itable][2*iif+1] ; 2980 for ( uInt j = 0 ; j < ifgrp.size() ; j++ ) { 2981 double fmin = max( range0, ifgfreq[2*j] ) ; 2982 double fmax = min( range1, ifgfreq[2*j+1] ) ; 2983 if ( fmin < fmax ) { 2984 ifgrp[j].push_back( itable ) ; 2985 ifgrp[j].push_back( freqid[itable][iif] ) ; 2986 } 2987 } 2988 } 2989 } 2990 vector< vector<uInt> >::iterator fiter = ifgrp.begin() ; 2991 vector<double>::iterator giter = ifgfreq.begin() ; 2992 while( fiter != ifgrp.end() ) { 2993 if ( fiter->size() <= sizecr ) { 2994 fiter = ifgrp.erase( fiter ) ; 2995 giter = ifgfreq.erase( giter ) ; 2996 giter = ifgfreq.erase( giter ) ; 2997 } 2998 else { 2999 fiter++ ; 3000 advance( giter, 2 ) ; 3001 } 3002 } 3003 3004 // Grouping continuous IF groups (without frequency gap) 3005 // freqgrp: list of IF group indexes in each frequency group 3006 // freqrange: list of minimum and maximum frequency in each frequency group 3007 // freqgrp[numgrp][nummember] 3008 // freqgrp: [[ifgrp00, ifgrp01, ifgrp02, ...], 3009 // [ifgrp10, ifgrp11, ifgrp12, ...], 3010 // ... 3011 // [ifgrpn0, ifgrpn1, ifgrpn2, ...]] 3012 // freqrange[numgrp*2] 3013 // freqrange: [min_grp0, max_grp0, min_grp1, max_grp1, ...] 3014 vector< vector<uInt> > freqgrp ; 3015 double freqrange = 0.0 ; 3016 uInt grpnum = 0 ; 3017 for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) { 3018 // Assumed that ifgfreq was sorted 3019 if ( grpnum != 0 && freqrange == ifgfreq[2*i] ) { 3020 freqgrp[grpnum-1].push_back( i ) ; 3021 } 3022 else { 3023 vector<uInt> grp0( 1, i ) ; 3024 freqgrp.push_back( grp0 ) ; 3025 grpnum++ ; 3026 } 3027 freqrange = ifgfreq[2*i+1] ; 3028 } 3029 3030 3031 // print IF groups 3032 ostringstream oss ; 3033 oss << "IF Group summary: " << endl ; 3034 oss << " GROUP_ID [FREQ_MIN, FREQ_MAX]: (TABLE_ID, FREQ_ID)" << endl ; 3035 for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) { 3036 oss << " GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*i] << "," << ifgfreq[2*i+1] << "]: " ; 3037 for ( uInt j = 0 ; j < ifgrp[i].size()/2 ; j++ ) { 3038 oss << "(" << ifgrp[i][2*j] << "," << ifgrp[i][2*j+1] << ") " ; 3039 } 3040 oss << endl ; 3041 } 3042 oss << endl ; 3043 os << oss.str() << LogIO::POST ; 3044 3045 // print frequency group 3046 oss.str("") ; 3047 oss << "Frequency Group summary: " << endl ; 3048 oss << " GROUP_ID [FREQ_MIN, FREQ_MAX]: IF_GROUP_ID" << endl ; 3049 for ( uInt i = 0 ; i < freqgrp.size() ; i++ ) { 3050 oss << " GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*freqgrp[i][0]] << "," << ifgfreq[2*freqgrp[i][freqgrp[i].size()-1]+1] << "]: " ; 3051 for ( uInt j = 0 ; j < freqgrp[i].size() ; j++ ) { 3052 oss << freqgrp[i][j] << " " ; 3053 } 3054 oss << endl ; 3055 } 3056 oss << endl ; 3057 os << oss.str() << LogIO::POST ; 3058 3059 // membership check 3060 // groups: list of IF group indexes whose frequency range overlaps with 3061 // that of each table and IF 3062 // groups[numtable][numIF][nummembership] 3063 // groups: [[[grp, grp,...], [grp, grp,...],...], 3064 // [[grp, grp,...], [grp, grp,...],...], 3065 // ... 3066 // [[grp, grp,...], [grp, grp,...],...]] 3067 vector< vector< vector<uInt> > > groups( insize ) ; 3068 for ( uInt i = 0 ; i < insize ; i++ ) { 3069 groups[i].resize( freqid[i].size() ) ; 3070 } 3071 for ( uInt igrp = 0 ; igrp < ifgrp.size() ; igrp++ ) { 3072 for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) { 3073 uInt tableid = ifgrp[igrp][2*imem] ; 3074 vector<uInt>::iterator iter = find( freqid[tableid].begin(), freqid[tableid].end(), ifgrp[igrp][2*imem+1] ) ; 3075 if ( iter != freqid[tableid].end() ) { 3076 uInt rowid = distance( freqid[tableid].begin(), iter ) ; 3077 groups[tableid][rowid].push_back( igrp ) ; 3078 } 3079 } 3080 } 3081 3082 // print membership 3083 //oss.str("") ; 3084 //for ( uInt i = 0 ; i < insize ; i++ ) { 3085 //oss << "Table " << i << endl ; 3086 //for ( uInt j = 0 ; j < groups[i].size() ; j++ ) { 3087 //oss << " FREQ_ID " << setw( 2 ) << freqid[i][j] << ": " ; 3088 //for ( uInt k = 0 ; k < groups[i][j].size() ; k++ ) { 3089 //oss << setw( 2 ) << groups[i][j][k] << " " ; 3090 //} 3091 //oss << endl ; 3092 //} 3093 //} 3094 //os << oss.str() << LogIO::POST ; 3095 3096 // set back coordinfo 3097 for ( uInt itable = 0 ; itable < insize ; itable++ ) { 3098 vector<string> coordinfo = tmpin[itable]->getCoordInfo() ; 3099 coordinfo[0] = oldinfo[itable] ; 3100 tmpin[itable]->setCoordInfo( coordinfo ) ; 3101 } 3102 3103 // Create additional table if needed 3104 bool oldInsitu = insitu_ ; 3105 setInsitu( false ) ; 3106 vector< vector<uInt> > addrow( insize ) ; 3107 vector<uInt> addtable( insize, 0 ) ; 3108 vector<uInt> newtableids( insize ) ; 3109 vector<uInt> newifids( insize, 0 ) ; 3110 for ( uInt itable = 0 ; itable < insize ; itable++ ) { 3111 //os << "Table " << itable << ": " ; 3112 for ( uInt ifrow = 0 ; ifrow < groups[itable].size() ; ifrow++ ) { 3113 addrow[itable].push_back( groups[itable][ifrow].size()-1 ) ; 3114 //os << addrow[itable][ifrow] << " " ; 3115 } 3116 addtable[itable] = *max_element( addrow[itable].begin(), addrow[itable].end() ) ; 3117 //os << "(" << addtable[itable] << ")" << LogIO::POST ; 3118 } 3119 newin.resize( insize ) ; 3120 copy( tmpin.begin(), tmpin.end(), newin.begin() ) ; 3121 for ( uInt i = 0 ; i < insize ; i++ ) { 3122 newtableids[i] = i ; 3123 } 3124 for ( uInt itable = 0 ; itable < insize ; itable++ ) { 3125 for ( uInt iadd = 0 ; iadd < addtable[itable] ; iadd++ ) { 3126 CountedPtr<Scantable> add = getScantable( newin[itable], false ) ; 3127 vector<int> freqidlist ; 3128 for ( uInt i = 0 ; i < groups[itable].size() ; i++ ) { 3129 if ( groups[itable][i].size() > iadd + 1 ) { 3130 freqidlist.push_back( freqid[itable][i] ) ; 3131 } 3132 } 3133 stringstream taqlstream ; 3134 taqlstream << "SELECT FROM $1 WHERE FREQ_ID IN [" ; 3135 for ( uInt i = 0 ; i < freqidlist.size() ; i++ ) { 3136 taqlstream << i ; 3137 if ( i < freqidlist.size() - 1 ) 3138 taqlstream << "," ; 3139 else 3140 taqlstream << "]" ; 3141 } 3142 string taql = taqlstream.str() ; 3143 //os << "taql = " << taql << LogIO::POST ; 3144 STSelector selector = STSelector() ; 3145 selector.setTaQL( taql ) ; 3146 add->setSelection( selector ) ; 3147 newin.push_back( add ) ; 3148 newtableids.push_back( itable ) ; 3149 newifids.push_back( iadd + 1 ) ; 3150 } 3151 } 3152 3153 // udpate ifgrp 3154 for ( uInt itable = 0 ; itable < insize ; itable++ ) { 3155 for ( uInt iadd = 0 ; iadd < addtable[itable] ; iadd++ ) { 3156 for ( uInt ifrow = 0 ; ifrow < groups[itable].size() ; ifrow++ ) { 3157 if ( groups[itable][ifrow].size() > iadd + 1 ) { 3158 uInt igrp = groups[itable][ifrow][iadd+1] ; 3159 for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) { 3160 if ( ifgrp[igrp][2*imem] == newtableids[iadd+insize] && ifgrp[igrp][2*imem+1] == freqid[newtableids[iadd+insize]][ifrow] ) { 3161 ifgrp[igrp][2*imem] = insize + iadd ; 3162 } 3163 } 3164 } 3165 } 3166 } 3167 } 3168 3169 // print IF groups again for debug 3170 //oss.str( "" ) ; 3171 //oss << "IF Group summary: " << endl ; 3172 //oss << " GROUP_ID [FREQ_MIN, FREQ_MAX]: (TABLE_ID, FREQ_ID)" << endl ; 3173 //for ( uInt i = 0 ; i < ifgrp.size() ; i++ ) { 3174 //oss << " GROUP " << setw( 2 ) << i << " [" << ifgfreq[2*i] << "," << ifgfreq[2*i+1] << "]: " ; 3175 //for ( uInt j = 0 ; j < ifgrp[i].size()/2 ; j++ ) { 3176 //oss << "(" << ifgrp[i][2*j] << "," << ifgrp[i][2*j+1] << ") " ; 3177 //} 3178 //oss << endl ; 3179 //} 3180 //oss << endl ; 3181 //os << oss.str() << LogIO::POST ; 3182 3183 // reset SCANNO and IFNO/FREQ_ID: IF is reset by the result of sortation 3184 os << "All scan number is set to 0" << LogIO::POST ; 3185 //os << "All IF number is set to IF group index" << LogIO::POST ; 3186 insize = newin.size() ; 3187 for ( uInt itable = 0 ; itable < insize ; itable++ ) { 3188 uInt rows = newin[itable]->nrow() ; 3189 Table &tmpt = newin[itable]->table() ; 3190 freqIDCol.attach( tmpt, "FREQ_ID" ) ; 3191 scannoCol.attach( tmpt, "SCANNO" ) ; 3192 ifnoCol.attach( tmpt, "IFNO" ) ; 3193 for ( uInt irow=0 ; irow < rows ; irow++ ) { 3194 scannoCol.put( irow, 0 ) ; 3195 uInt freqID = freqIDCol( irow ) ; 3196 vector<uInt>::iterator iter = find( freqid[newtableids[itable]].begin(), freqid[newtableids[itable]].end(), freqID ) ; 3197 if ( iter != freqid[newtableids[itable]].end() ) { 3198 uInt index = distance( freqid[newtableids[itable]].begin(), iter ) ; 3199 ifnoCol.put( irow, groups[newtableids[itable]][index][newifids[itable]] ) ; 3200 } 3201 else { 3202 throw(AipsError("IF grouping was wrong in additional tables.")) ; 3203 } 3204 } 3205 } 3206 oldinfo.resize( insize ) ; 3207 setInsitu( oldInsitu ) ; 3208 3209 // temporarily set coordinfo 3210 for ( uInt itable = 0 ; itable < insize ; itable++ ) { 3211 vector<string> coordinfo = newin[itable]->getCoordInfo() ; 3212 oldinfo[itable] = coordinfo[0] ; 3213 coordinfo[0] = "Hz" ; 3214 newin[itable]->setCoordInfo( coordinfo ) ; 3215 } 3216 3217 // save column values in the vector 3218 vector< vector<uInt> > freqTableIdVec( insize ) ; 3219 vector< vector<uInt> > freqIdVec( insize ) ; 3220 vector< vector<uInt> > ifNoVec( insize ) ; 3221 for ( uInt itable = 0 ; itable < insize ; itable++ ) { 3222 ScalarColumn<uInt> freqIDs ; 3223 freqIDs.attach( newin[itable]->frequencies().table(), "ID" ) ; 3224 ifnoCol.attach( newin[itable]->table(), "IFNO" ) ; 3225 freqIDCol.attach( newin[itable]->table(), "FREQ_ID" ) ; 3226 for ( uInt irow = 0 ; irow < newin[itable]->frequencies().table().nrow() ; irow++ ) { 3227 freqTableIdVec[itable].push_back( freqIDs( irow ) ) ; 3228 } 3229 for ( uInt irow = 0 ; irow < newin[itable]->table().nrow() ; irow++ ) { 3230 freqIdVec[itable].push_back( freqIDCol( irow ) ) ; 3231 ifNoVec[itable].push_back( ifnoCol( irow ) ) ; 3232 } 3233 } 3234 3235 // reset spectra and flagtra: pick up common part of frequency coverage 3236 //os << "Pick common frequency range and align resolution" << LogIO::POST ; 3237 for ( uInt itable = 0 ; itable < insize ; itable++ ) { 3238 uInt rows = newin[itable]->nrow() ; 3239 int nminchan = -1 ; 3240 int nmaxchan = -1 ; 3241 vector<uInt> freqIdUpdate ; 3242 for ( uInt irow = 0 ; irow < rows ; irow++ ) { 3243 uInt ifno = ifNoVec[itable][irow] ; // IFNO is reset by group index 3244 double minfreq = ifgfreq[2*ifno] ; 3245 double maxfreq = ifgfreq[2*ifno+1] ; 3246 //os << "frequency range: [" << minfreq << "," << maxfreq << "]" << LogIO::POST ; 3247 vector<double> abcissa = newin[itable]->getAbcissa( irow ) ; 3248 int nchan = abcissa.size() ; 3249 double resol = abcissa[1] - abcissa[0] ; 3250 //os << "abcissa range : [" << abcissa[0] << "," << abcissa[nchan-1] << "]" << LogIO::POST ; 3251 if ( minfreq <= abcissa[0] ) 3252 nminchan = 0 ; 3253 else { 3254 //double cfreq = ( minfreq - abcissa[0] ) / resol ; 3255 double cfreq = ( minfreq - abcissa[0] + 0.5 * resol ) / resol ; 3256 nminchan = int(cfreq) + ( ( cfreq - int(cfreq) <= 0.5 ) ? 0 : 1 ) ; 3257 } 3258 if ( maxfreq >= abcissa[abcissa.size()-1] ) 3259 nmaxchan = abcissa.size() - 1 ; 3260 else { 3261 //double cfreq = ( abcissa[abcissa.size()-1] - maxfreq ) / resol ; 3262 double cfreq = ( abcissa[abcissa.size()-1] - maxfreq + 0.5 * resol ) / resol ; 3263 nmaxchan = abcissa.size() - 1 - int(cfreq) - ( ( cfreq - int(cfreq) >= 0.5 ) ? 1 : 0 ) ; 3264 } 3265 //os << "channel range (" << irow << "): [" << nminchan << "," << nmaxchan << "]" << LogIO::POST ; 3266 if ( nmaxchan > nminchan ) { 3267 newin[itable]->reshapeSpectrum( nminchan, nmaxchan, irow ) ; 3268 int newchan = nmaxchan - nminchan + 1 ; 3269 if ( count( freqIdUpdate.begin(), freqIdUpdate.end(), freqIdVec[itable][irow] ) == 0 && newchan < nchan ) 3270 freqIdUpdate.push_back( freqIdVec[itable][irow] ) ; 3271 } 3272 else { 3273 throw(AipsError("Failed to pick up common part of frequency range.")) ; 3274 } 3275 } 3276 for ( uInt i = 0 ; i < freqIdUpdate.size() ; i++ ) { 3277 uInt freqId = freqIdUpdate[i] ; 3278 Double refpix ; 3279 Double refval ; 3280 Double increment ; 3281 3282 // update row 3283 newin[itable]->frequencies().getEntry( refpix, refval, increment, freqId ) ; 3284 refval = refval - ( refpix - nminchan ) * increment ; 3285 refpix = 0 ; 3286 newin[itable]->frequencies().setEntry( refpix, refval, increment, freqId ) ; 3287 } 3288 } 3289 3290 3291 // reset spectra and flagtra: align spectral resolution 3292 //os << "Align spectral resolution" << LogIO::POST ; 3293 // gmaxdnu: the coarsest frequency resolution in the frequency group 3294 // gmemid: member index that have a resolution equal to gmaxdnu 3295 // gmaxdnu[numfreqgrp] 3296 // gmaxdnu: [dnu0, dnu1, ...] 3297 // gmemid[numfreqgrp] 3298 // gmemid: [id0, id1, ...] 3299 vector<double> gmaxdnu( freqgrp.size(), 0.0 ) ; 3300 vector<uInt> gmemid( freqgrp.size(), 0 ) ; 3301 for ( uInt igrp = 0 ; igrp < ifgrp.size() ; igrp++ ) { 3302 double maxdnu = 0.0 ; // maximum (coarsest) frequency resolution 3303 int minchan = INT_MAX ; // minimum channel number 3304 Double refpixref = -1 ; // reference of 'reference pixel' 3305 Double refvalref = -1 ; // reference of 'reference frequency' 3306 Double refinc = -1 ; // reference frequency resolution 3307 uInt refreqid ; 3308 uInt reftable = INT_MAX; 3309 // process only if group member > 1 3310 if ( ifgrp[igrp].size() > 2 ) { 3311 // find minchan and maxdnu in each group 3312 for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) { 3313 uInt tableid = ifgrp[igrp][2*imem] ; 3314 uInt rowid = ifgrp[igrp][2*imem+1] ; 3315 vector<uInt>::iterator iter = find( freqIdVec[tableid].begin(), freqIdVec[tableid].end(), rowid ) ; 3316 if ( iter != freqIdVec[tableid].end() ) { 3317 uInt index = distance( freqIdVec[tableid].begin(), iter ) ; 3318 vector<double> abcissa = newin[tableid]->getAbcissa( index ) ; 3319 int nchan = abcissa.size() ; 3320 double dnu = abcissa[1] - abcissa[0] ; 3321 //os << "GROUP " << igrp << " (" << tableid << "," << rowid << "): nchan = " << nchan << " (minchan = " << minchan << ")" << LogIO::POST ; 3322 if ( nchan < minchan ) { 3323 minchan = nchan ; 3324 maxdnu = dnu ; 3325 newin[tableid]->frequencies().getEntry( refpixref, refvalref, refinc, rowid ) ; 3326 refreqid = rowid ; 3327 reftable = tableid ; 3328 } 3329 } 3330 } 3331 // regrid spectra in each group 3332 os << "GROUP " << igrp << endl ; 3333 os << " Channel number is adjusted to " << minchan << endl ; 3334 os << " Corresponding frequency resolution is " << maxdnu << "Hz" << LogIO::POST ; 3335 for ( uInt imem = 0 ; imem < ifgrp[igrp].size()/2 ; imem++ ) { 3336 uInt tableid = ifgrp[igrp][2*imem] ; 3337 uInt rowid = ifgrp[igrp][2*imem+1] ; 3338 freqIDCol.attach( newin[tableid]->table(), "FREQ_ID" ) ; 3339 //os << "tableid = " << tableid << " rowid = " << rowid << ": " << LogIO::POST ; 3340 //os << " regridChannel applied to " ; 3341 if ( tableid != reftable ) 3342 refreqid = newin[tableid]->frequencies().addEntry( refpixref, refvalref, refinc ) ; 3343 for ( uInt irow = 0 ; irow < newin[tableid]->table().nrow() ; irow++ ) { 3344 uInt tfreqid = freqIdVec[tableid][irow] ; 3345 if ( tfreqid == rowid ) { 3346 //os << irow << " " ; 3347 newin[tableid]->regridChannel( minchan, maxdnu, irow ) ; 3348 freqIDCol.put( irow, refreqid ) ; 3349 freqIdVec[tableid][irow] = refreqid ; 3350 } 3351 } 3352 //os << LogIO::POST ; 3353 } 3354 } 3355 else { 3356 uInt tableid = ifgrp[igrp][0] ; 3357 uInt rowid = ifgrp[igrp][1] ; 3358 vector<uInt>::iterator iter = find( freqIdVec[tableid].begin(), freqIdVec[tableid].end(), rowid ) ; 3359 if ( iter != freqIdVec[tableid].end() ) { 3360 uInt index = distance( freqIdVec[tableid].begin(), iter ) ; 3361 vector<double> abcissa = newin[tableid]->getAbcissa( index ) ; 3362 minchan = abcissa.size() ; 3363 maxdnu = abcissa[1] - abcissa[0] ; 3364 } 3365 } 3366 for ( uInt i = 0 ; i < freqgrp.size() ; i++ ) { 3367 if ( count( freqgrp[i].begin(), freqgrp[i].end(), igrp ) > 0 ) { 3368 if ( maxdnu > gmaxdnu[i] ) { 3369 gmaxdnu[i] = maxdnu ; 3370 gmemid[i] = igrp ; 3371 } 3372 break ; 3373 } 3374 } 3375 } 3376 3377 // set back coordinfo 3378 for ( uInt itable = 0 ; itable < insize ; itable++ ) { 3379 vector<string> coordinfo = newin[itable]->getCoordInfo() ; 3380 coordinfo[0] = oldinfo[itable] ; 3381 newin[itable]->setCoordInfo( coordinfo ) ; 3382 } 3383 3384 // accumulate all rows into the first table 3385 // NOTE: assumed in.size() = 1 3386 vector< CountedPtr<Scantable> > tmp( 1 ) ; 3387 if ( newin.size() == 1 ) 3388 tmp[0] = newin[0] ; 3389 else 3390 tmp[0] = merge( newin ) ; 3391 3392 //return tmp[0] ; 3393 3394 // average 3395 CountedPtr<Scantable> tmpout = average( tmp, mask, weight, avmode ) ; 3396 3397 //return tmpout ; 3398 3399 // combine frequency group 3400 os << "Combine spectra based on frequency grouping" << LogIO::POST ; 3401 os << "IFNO is renumbered as frequency group ID (see above)" << LogIO::POST ; 3402 vector<string> coordinfo = tmpout->getCoordInfo() ; 3403 oldinfo[0] = coordinfo[0] ; 3404 coordinfo[0] = "Hz" ; 3405 tmpout->setCoordInfo( coordinfo ) ; 3406 // create proformas of output table 3407 stringstream taqlstream ; 3408 taqlstream << "SELECT FROM $1 WHERE IFNO IN [" ; 3409 for ( uInt i = 0 ; i < gmemid.size() ; i++ ) { 3410 taqlstream << gmemid[i] ; 3411 if ( i < gmemid.size() - 1 ) 3412 taqlstream << "," ; 3413 else 3414 taqlstream << "]" ; 3415 } 3416 string taql = taqlstream.str() ; 3417 //os << "taql = " << taql << LogIO::POST ; 3418 STSelector selector = STSelector() ; 3419 selector.setTaQL( taql ) ; 3420 oldInsitu = insitu_ ; 3421 setInsitu( false ) ; 3422 out = getScantable( tmpout, false ) ; 3423 setInsitu( oldInsitu ) ; 3424 out->setSelection( selector ) ; 3425 // regrid rows 3426 ifnoCol.attach( tmpout->table(), "IFNO" ) ; 3427 for ( uInt irow = 0 ; irow < tmpout->table().nrow() ; irow++ ) { 3428 uInt ifno = ifnoCol( irow ) ; 3429 for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) { 3430 if ( count( freqgrp[igrp].begin(), freqgrp[igrp].end(), ifno ) > 0 ) { 3431 vector<double> abcissa = tmpout->getAbcissa( irow ) ; 3432 double bw = ( abcissa[1] - abcissa[0] ) * abcissa.size() ; 3433 int nchan = (int)( bw / gmaxdnu[igrp] ) ; 3434 tmpout->regridChannel( nchan, gmaxdnu[igrp], irow ) ; 3435 break ; 3436 } 3437 } 3438 } 3439 // combine spectra 3440 ArrayColumn<Float> specColOut ; 3441 specColOut.attach( out->table(), "SPECTRA" ) ; 3442 ArrayColumn<uChar> flagColOut ; 3443 flagColOut.attach( out->table(), "FLAGTRA" ) ; 3444 ScalarColumn<uInt> ifnoColOut ; 3445 ifnoColOut.attach( out->table(), "IFNO" ) ; 3446 ScalarColumn<uInt> polnoColOut ; 3447 polnoColOut.attach( out->table(), "POLNO" ) ; 3448 ScalarColumn<uInt> freqidColOut ; 3449 freqidColOut.attach( out->table(), "FREQ_ID" ) ; 3450 MDirection::ScalarColumn dirColOut ; 3451 dirColOut.attach( out->table(), "DIRECTION" ) ; 3452 Table &tab = tmpout->table() ; 3453 Block<String> cols(1); 3454 cols[0] = String("POLNO") ; 3455 TableIterator iter( tab, cols ) ; 3456 bool done = false ; 3457 vector< vector<uInt> > sizes( freqgrp.size() ) ; 3458 while( !iter.pastEnd() ) { 3459 vector< vector<Float> > specout( freqgrp.size() ) ; 3460 vector< vector<uChar> > flagout( freqgrp.size() ) ; 3461 ArrayColumn<Float> specCols ; 3462 specCols.attach( iter.table(), "SPECTRA" ) ; 3463 ArrayColumn<uChar> flagCols ; 3464 flagCols.attach( iter.table(), "FLAGTRA" ) ; 3465 ifnoCol.attach( iter.table(), "IFNO" ) ; 3466 ScalarColumn<uInt> polnos ; 3467 polnos.attach( iter.table(), "POLNO" ) ; 3468 MDirection::ScalarColumn dircol ; 3469 dircol.attach( iter.table(), "DIRECTION" ) ; 3470 uInt polno = polnos( 0 ) ; 3471 //os << "POLNO iteration: " << polno << LogIO::POST ; 3472 // for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) { 3473 // sizes[igrp].resize( freqgrp[igrp].size() ) ; 3474 // for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) { 3475 // for ( uInt irow = 0 ; irow < iter.table().nrow() ; irow++ ) { 3476 // uInt ifno = ifnoCol( irow ) ; 3477 // if ( ifno == freqgrp[igrp][imem] ) { 3478 // Vector<Float> spec = specCols( irow ) ; 3479 // Vector<uChar> flag = flagCols( irow ) ; 3480 // vector<Float> svec ; 3481 // spec.tovector( svec ) ; 3482 // vector<uChar> fvec ; 3483 // flag.tovector( fvec ) ; 3484 // //os << "spec.size() = " << svec.size() << " fvec.size() = " << fvec.size() << LogIO::POST ; 3485 // specout[igrp].insert( specout[igrp].end(), svec.begin(), svec.end() ) ; 3486 // flagout[igrp].insert( flagout[igrp].end(), fvec.begin(), fvec.end() ) ; 3487 // //os << "specout[" << igrp << "].size() = " << specout[igrp].size() << LogIO::POST ; 3488 // sizes[igrp][imem] = spec.nelements() ; 3489 // } 3490 // } 3491 // } 3492 // for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) { 3493 // uInt ifout = ifnoColOut( irow ) ; 3494 // uInt polout = polnoColOut( irow ) ; 3495 // if ( ifout == gmemid[igrp] && polout == polno ) { 3496 // // set SPECTRA and FRAGTRA 3497 // Vector<Float> newspec( specout[igrp] ) ; 3498 // Vector<uChar> newflag( flagout[igrp] ) ; 3499 // specColOut.put( irow, newspec ) ; 3500 // flagColOut.put( irow, newflag ) ; 3501 // // IFNO renumbering 3502 // ifnoColOut.put( irow, igrp ) ; 3503 // } 3504 // } 3505 // } 3506 // get a list of number of channels for each frequency group member 3507 if ( !done ) { 3508 for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) { 3509 sizes[igrp].resize( freqgrp[igrp].size() ) ; 3510 for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) { 3511 for ( uInt irow = 0 ; irow < iter.table().nrow() ; irow++ ) { 3512 uInt ifno = ifnoCol( irow ) ; 3513 if ( ifno == freqgrp[igrp][imem] ) { 3514 Vector<Float> spec = specCols( irow ) ; 3515 sizes[igrp][imem] = spec.nelements() ; 3516 break ; 3517 } 3518 } 3519 } 3520 } 3521 done = true ; 3522 } 3523 // combine spectra 3524 for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) { 3525 uInt polout = polnoColOut( irow ) ; 3526 if ( polout == polno ) { 3527 uInt ifout = ifnoColOut( irow ) ; 3528 Vector<Double> direction = dirColOut(irow).getAngle(Unit(String("rad"))).getValue() ; 3529 uInt igrp ; 3530 for ( uInt jgrp = 0 ; jgrp < freqgrp.size() ; jgrp++ ) { 3531 if ( ifout == gmemid[jgrp] ) { 3532 igrp = jgrp ; 3533 break ; 3534 } 3535 } 3536 for ( uInt imem = 0 ; imem < freqgrp[igrp].size() ; imem++ ) { 3537 for ( uInt jrow = 0 ; jrow < iter.table().nrow() ; jrow++ ) { 3538 uInt ifno = ifnoCol( jrow ) ; 3539 Vector<Double> tdir = dircol(jrow).getAngle(Unit(String("rad"))).getValue() ; 3540 //if ( ifno == freqgrp[igrp][imem] && allTrue( tdir == direction ) ) { 3541 Double dx = tdir[0] - direction[0] ; 3542 Double dy = tdir[1] - direction[1] ; 3543 Double dd = sqrt( dx * dx + dy * dy ) ; 3544 //if ( ifno == freqgrp[igrp][imem] && allNearAbs( tdir, direction, tol ) ) { 3545 if ( ifno == freqgrp[igrp][imem] && dd <= tol ) { 3546 Vector<Float> spec = specCols( jrow ) ; 3547 Vector<uChar> flag = flagCols( jrow ) ; 3548 vector<Float> svec ; 3549 spec.tovector( svec ) ; 3550 vector<uChar> fvec ; 3551 flag.tovector( fvec ) ; 3552 //os << "spec.size() = " << svec.size() << " fvec.size() = " << fvec.size() << LogIO::POST ; 3553 specout[igrp].insert( specout[igrp].end(), svec.begin(), svec.end() ) ; 3554 flagout[igrp].insert( flagout[igrp].end(), fvec.begin(), fvec.end() ) ; 3555 //os << "specout[" << igrp << "].size() = " << specout[igrp].size() << LogIO::POST ; 3556 } 3557 } 3558 } 3559 // set SPECTRA and FRAGTRA 3560 Vector<Float> newspec( specout[igrp] ) ; 3561 Vector<uChar> newflag( flagout[igrp] ) ; 3562 specColOut.put( irow, newspec ) ; 3563 flagColOut.put( irow, newflag ) ; 3564 // IFNO renumbering 3565 ifnoColOut.put( irow, igrp ) ; 3566 } 3567 } 3568 iter++ ; 3569 } 3570 // update FREQUENCIES subtable 3571 vector<bool> updated( freqgrp.size(), false ) ; 3572 for ( uInt igrp = 0 ; igrp < freqgrp.size() ; igrp++ ) { 3573 uInt index = 0 ; 3574 uInt pixShift = 0 ; 3575 while ( freqgrp[igrp][index] != gmemid[igrp] ) { 3576 pixShift += sizes[igrp][index++] ; 3577 } 3578 for ( uInt irow = 0 ; irow < out->table().nrow() ; irow++ ) { 3579 if ( ifnoColOut( irow ) == gmemid[igrp] && !updated[igrp] ) { 3580 uInt freqidOut = freqidColOut( irow ) ; 3581 //os << "freqgrp " << igrp << " freqidOut = " << freqidOut << LogIO::POST ; 3582 double refpix ; 3583 double refval ; 3584 double increm ; 3585 out->frequencies().getEntry( refpix, refval, increm, freqidOut ) ; 3586 refpix += pixShift ; 3587 out->frequencies().setEntry( refpix, refval, increm, freqidOut ) ; 3588 updated[igrp] = true ; 3589 } 3590 } 3591 } 3592 3593 //out = tmpout ; 3594 3595 coordinfo = tmpout->getCoordInfo() ; 3596 coordinfo[0] = oldinfo[0] ; 3597 tmpout->setCoordInfo( coordinfo ) ; 3598 } 3599 else { 3600 // simple average 3601 out = average( in, mask, weight, avmode ) ; 3602 } 3603 3604 return out ; 3605 } 3606 3607 CountedPtr<Scantable> STMath::cwcal( const CountedPtr<Scantable>& s, 3608 const String calmode, 3609 const String antname ) 3610 { 3611 // frequency switch 3612 if ( calmode == "fs" ) { 3613 return cwcalfs( s, antname ) ; 3614 } 3615 else { 3616 vector<bool> masks = s->getMask( 0 ) ; 3617 vector<int> types ; 3618 3619 // sky scan 3620 STSelector sel = STSelector() ; 3621 types.push_back( SrcType::SKY ) ; 3622 sel.setTypes( types ) ; 3623 s->setSelection( sel ) ; 3624 vector< CountedPtr<Scantable> > tmp( 1, getScantable( s, false ) ) ; 3625 CountedPtr<Scantable> asky = average( tmp, masks, "TINT", "SCAN" ) ; 3626 s->unsetSelection() ; 3627 sel.reset() ; 3628 types.clear() ; 3629 3630 // hot scan 3631 types.push_back( SrcType::HOT ) ; 3632 sel.setTypes( types ) ; 3633 s->setSelection( sel ) ; 3634 tmp.clear() ; 3635 tmp.push_back( getScantable( s, false ) ) ; 3636 CountedPtr<Scantable> ahot = average( tmp, masks, "TINT", "SCAN" ) ; 3637 s->unsetSelection() ; 3638 sel.reset() ; 3639 types.clear() ; 3640 3641 // cold scan 3642 CountedPtr<Scantable> acold ; 3643 // types.push_back( SrcType::COLD ) ; 3644 // sel.setTypes( types ) ; 3645 // s->setSelection( sel ) ; 3646 // tmp.clear() ; 3647 // tmp.push_back( getScantable( s, false ) ) ; 3648 // CountedPtr<Scantable> acold = average( tmp, masks, "TINT", "SCNAN" ) ; 3649 // s->unsetSelection() ; 3650 // sel.reset() ; 3651 // types.clear() ; 3652 3653 // off scan 3654 types.push_back( SrcType::PSOFF ) ; 3655 sel.setTypes( types ) ; 3656 s->setSelection( sel ) ; 3657 tmp.clear() ; 3658 tmp.push_back( getScantable( s, false ) ) ; 3659 CountedPtr<Scantable> aoff = average( tmp, masks, "TINT", "SCAN" ) ; 3660 s->unsetSelection() ; 3661 sel.reset() ; 3662 types.clear() ; 3663 3664 // on scan 3665 bool insitu = insitu_ ; 3666 insitu_ = false ; 3667 CountedPtr<Scantable> out = getScantable( s, true ) ; 3668 insitu_ = insitu ; 3669 types.push_back( SrcType::PSON ) ; 3670 sel.setTypes( types ) ; 3671 s->setSelection( sel ) ; 3672 TableCopy::copyRows( out->table(), s->table() ) ; 3673 s->unsetSelection() ; 3674 sel.reset() ; 3675 types.clear() ; 3676 3677 // process each on scan 3678 ArrayColumn<Float> tsysCol ; 3679 tsysCol.attach( out->table(), "TSYS" ) ; 3680 for ( int i = 0 ; i < out->nrow() ; i++ ) { 3681 vector<float> sp = getCalibratedSpectra( out, aoff, asky, ahot, acold, i, antname ) ; 3682 out->setSpectrum( sp, i ) ; 3683 string reftime = out->getTime( i ) ; 3684 vector<int> ii( 1, out->getIF( i ) ) ; 3685 vector<int> ib( 1, out->getBeam( i ) ) ; 3686 vector<int> ip( 1, out->getPol( i ) ) ; 3687 sel.setIFs( ii ) ; 3688 sel.setBeams( ib ) ; 3689 sel.setPolarizations( ip ) ; 3690 asky->setSelection( sel ) ; 3691 vector<float> sptsys = getTsysFromTime( reftime, asky, "linear" ) ; 3692 const Vector<Float> Vtsys( sptsys ) ; 3693 tsysCol.put( i, Vtsys ) ; 3694 asky->unsetSelection() ; 3695 sel.reset() ; 3696 } 3697 3698 // flux unit 3699 out->setFluxUnit( "K" ) ; 3700 3701 return out ; 3702 } 3703 } 3704 3705 CountedPtr<Scantable> STMath::almacal( const CountedPtr<Scantable>& s, 3706 const String calmode ) 3707 { 3708 // frequency switch 3709 if ( calmode == "fs" ) { 3710 return almacalfs( s ) ; 3711 } 3712 else { 3713 vector<bool> masks = s->getMask( 0 ) ; 3714 3715 // off scan 3716 STSelector sel = STSelector() ; 3717 vector<int> types ; 3718 types.push_back( SrcType::PSOFF ) ; 3719 sel.setTypes( types ) ; 3720 s->setSelection( sel ) ; 3721 // TODO 2010/01/08 TN 3722 // Grouping by time should be needed before averaging. 3723 // Each group must have own unique SCANNO (should be renumbered). 3724 // See PIPELINE/SDCalibration.py 3725 CountedPtr<Scantable> soff = getScantable( s, false ) ; 3726 Table ttab = soff->table() ; 3727 ROScalarColumn<Double> timeCol( ttab, "TIME" ) ; 3728 uInt nrow = timeCol.nrow() ; 3729 Vector<Double> timeSep( nrow - 1 ) ; 3730 for ( uInt i = 0 ; i < nrow - 1 ; i++ ) { 3731 timeSep[i] = timeCol(i+1) - timeCol(i) ; 3732 } 3733 ScalarColumn<Double> intervalCol( ttab, "INTERVAL" ) ; 3734 Vector<Double> interval = intervalCol.getColumn() ; 3735 interval /= 86400.0 ; 3736 ScalarColumn<uInt> scanCol( ttab, "SCANNO" ) ; 3737 vector<uInt> glist ; 3738 for ( uInt i = 0 ; i < nrow - 1 ; i++ ) { 3739 double gap = 2.0 * timeSep[i] / ( interval[i] + interval[i+1] ) ; 3740 //cout << "gap[" << i << "]=" << setw(5) << gap << endl ; 3741 if ( gap > 1.1 ) { 3742 glist.push_back( i ) ; 3743 } 3744 } 3745 Vector<uInt> gaplist( glist ) ; 3746 //cout << "gaplist = " << gaplist << endl ; 3747 uInt newid = 0 ; 3748 for ( uInt i = 0 ; i < nrow ; i++ ) { 3749 scanCol.put( i, newid ) ; 3750 if ( i == gaplist[newid] ) { 3751 newid++ ; 3752 } 3753 } 3754 //cout << "new scancol = " << scanCol.getColumn() << endl ; 3755 vector< CountedPtr<Scantable> > tmp( 1, soff ) ; 3756 CountedPtr<Scantable> aoff = average( tmp, masks, "TINT", "SCAN" ) ; 3757 //cout << "aoff.nrow = " << aoff->nrow() << endl ; 3758 s->unsetSelection() ; 3759 sel.reset() ; 3760 types.clear() ; 3761 3762 // on scan 3763 bool insitu = insitu_ ; 3764 insitu_ = false ; 3765 CountedPtr<Scantable> out = getScantable( s, true ) ; 3766 insitu_ = insitu ; 3767 types.push_back( SrcType::PSON ) ; 3768 sel.setTypes( types ) ; 3769 s->setSelection( sel ) ; 3770 TableCopy::copyRows( out->table(), s->table() ) ; 3771 s->unsetSelection() ; 3772 sel.reset() ; 3773 types.clear() ; 3774 3775 // process each on scan 3776 ArrayColumn<Float> tsysCol ; 3777 tsysCol.attach( out->table(), "TSYS" ) ; 3778 for ( int i = 0 ; i < out->nrow() ; i++ ) { 3779 vector<float> sp = getCalibratedSpectra( out, aoff, i ) ; 3780 out->setSpectrum( sp, i ) ; 3781 } 3782 3783 // flux unit 3784 out->setFluxUnit( "K" ) ; 3785 3786 return out ; 3787 } 3788 } 3789 3790 CountedPtr<Scantable> STMath::cwcalfs( const CountedPtr<Scantable>& s, 3791 const String antname ) 3792 { 3793 vector<int> types ; 3794 3795 // APEX calibration mode 3796 int apexcalmode = 1 ; 3797 3798 if ( antname.find( "APEX" ) != string::npos ) { 3799 // check if off scan exists or not 3800 STSelector sel = STSelector() ; 3801 //sel.setName( offstr1 ) ; 3802 types.push_back( SrcType::FLOOFF ) ; 3803 sel.setTypes( types ) ; 3804 try { 3805 s->setSelection( sel ) ; 3806 } 3807 catch ( AipsError &e ) { 3808 apexcalmode = 0 ; 3809 } 3810 sel.reset() ; 3811 } 3812 s->unsetSelection() ; 3813 types.clear() ; 3814 3815 vector<bool> masks = s->getMask( 0 ) ; 3816 CountedPtr<Scantable> ssig, sref ; 3817 CountedPtr<Scantable> out ; 3818 3819 if ( antname.find( "APEX" ) != string::npos ) { 3820 // APEX calibration 3821 // sky scan 3822 STSelector sel = STSelector() ; 3823 types.push_back( SrcType::FLOSKY ) ; 3824 sel.setTypes( types ) ; 3825 s->setSelection( sel ) ; 3826 vector< CountedPtr<Scantable> > tmp( 1, getScantable( s, false ) ) ; 3827 CountedPtr<Scantable> askylo = average( tmp, masks, "TINT", "SCAN" ) ; 3828 s->unsetSelection() ; 3829 sel.reset() ; 3830 types.clear() ; 3831 types.push_back( SrcType::FHISKY ) ; 3832 sel.setTypes( types ) ; 3833 s->setSelection( sel ) ; 3834 tmp.clear() ; 3835 tmp.push_back( getScantable( s, false ) ) ; 3836 CountedPtr<Scantable> askyhi = average( tmp, masks, "TINT", "SCAN" ) ; 3837 s->unsetSelection() ; 3838 sel.reset() ; 3839 types.clear() ; 3840 3841 // hot scan 3842 types.push_back( SrcType::FLOHOT ) ; 3843 sel.setTypes( types ) ; 3844 s->setSelection( sel ) ; 3845 tmp.clear() ; 3846 tmp.push_back( getScantable( s, false ) ) ; 3847 CountedPtr<Scantable> ahotlo = average( tmp, masks, "TINT", "SCAN" ) ; 3848 s->unsetSelection() ; 3849 sel.reset() ; 3850 types.clear() ; 3851 types.push_back( SrcType::FHIHOT ) ; 3852 sel.setTypes( types ) ; 3853 s->setSelection( sel ) ; 3854 tmp.clear() ; 3855 tmp.push_back( getScantable( s, false ) ) ; 3856 CountedPtr<Scantable> ahothi = average( tmp, masks, "TINT", "SCAN" ) ; 3857 s->unsetSelection() ; 3858 sel.reset() ; 3859 types.clear() ; 3860 3861 // cold scan 3862 CountedPtr<Scantable> acoldlo, acoldhi ; 3863 // types.push_back( SrcType::FLOCOLD ) ; 3864 // sel.setTypes( types ) ; 3865 // s->setSelection( sel ) ; 3866 // tmp.clear() ; 3867 // tmp.push_back( getScantable( s, false ) ) ; 3868 // CountedPtr<Scantable> acoldlo = average( tmp, masks, "TINT", "SCAN" ) ; 3869 // s->unsetSelection() ; 3870 // sel.reset() ; 3871 // types.clear() ; 3872 // types.push_back( SrcType::FHICOLD ) ; 3873 // sel.setTypes( types ) ; 3874 // s->setSelection( sel ) ; 3875 // tmp.clear() ; 3876 // tmp.push_back( getScantable( s, false ) ) ; 3877 // CountedPtr<Scantable> acoldhi = average( tmp, masks, "TINT", "SCAN" ) ; 3878 // s->unsetSelection() ; 3879 // sel.reset() ; 3880 // types.clear() ; 3881 3882 // ref scan 3883 bool insitu = insitu_ ; 3884 insitu_ = false ; 3885 sref = getScantable( s, true ) ; 3886 insitu_ = insitu ; 3887 types.push_back( SrcType::FSLO ) ; 3888 sel.setTypes( types ) ; 3889 s->setSelection( sel ) ; 3890 TableCopy::copyRows( sref->table(), s->table() ) ; 3891 s->unsetSelection() ; 3892 sel.reset() ; 3893 types.clear() ; 3894 3895 // sig scan 3896 insitu_ = false ; 3897 ssig = getScantable( s, true ) ; 3898 insitu_ = insitu ; 3899 types.push_back( SrcType::FSHI ) ; 3900 sel.setTypes( types ) ; 3901 s->setSelection( sel ) ; 3902 TableCopy::copyRows( ssig->table(), s->table() ) ; 3903 s->unsetSelection() ; 3904 sel.reset() ; 3905 types.clear() ; 3906 3907 if ( apexcalmode == 0 ) { 3908 // APEX fs data without off scan 3909 // process each sig and ref scan 3910 ArrayColumn<Float> tsysCollo ; 3911 tsysCollo.attach( ssig->table(), "TSYS" ) ; 3912 ArrayColumn<Float> tsysColhi ; 3913 tsysColhi.attach( sref->table(), "TSYS" ) ; 3914 for ( int i = 0 ; i < ssig->nrow() ; i++ ) { 3915 vector< CountedPtr<Scantable> > sky( 2 ) ; 3916 sky[0] = askylo ; 3917 sky[1] = askyhi ; 3918 vector< CountedPtr<Scantable> > hot( 2 ) ; 3919 hot[0] = ahotlo ; 3920 hot[1] = ahothi ; 3921 vector< CountedPtr<Scantable> > cold( 2 ) ; 3922 //cold[0] = acoldlo ; 3923 //cold[1] = acoldhi ; 3924 vector<float> sp = getFSCalibratedSpectra( ssig, sref, sky, hot, cold, i ) ; 3925 ssig->setSpectrum( sp, i ) ; 3926 string reftime = ssig->getTime( i ) ; 3927 vector<int> ii( 1, ssig->getIF( i ) ) ; 3928 vector<int> ib( 1, ssig->getBeam( i ) ) ; 3929 vector<int> ip( 1, ssig->getPol( i ) ) ; 3930 sel.setIFs( ii ) ; 3931 sel.setBeams( ib ) ; 3932 sel.setPolarizations( ip ) ; 3933 askylo->setSelection( sel ) ; 3934 vector<float> sptsys = getTsysFromTime( reftime, askylo, "linear" ) ; 3935 const Vector<Float> Vtsyslo( sptsys ) ; 3936 tsysCollo.put( i, Vtsyslo ) ; 3937 askylo->unsetSelection() ; 3938 sel.reset() ; 3939 sky[0] = askyhi ; 3940 sky[1] = askylo ; 3941 hot[0] = ahothi ; 3942 hot[1] = ahotlo ; 3943 cold[0] = acoldhi ; 3944 cold[1] = acoldlo ; 3945 sp = getFSCalibratedSpectra( sref, ssig, sky, hot, cold, i ) ; 3946 sref->setSpectrum( sp, i ) ; 3947 reftime = sref->getTime( i ) ; 3948 ii[0] = sref->getIF( i ) ; 3949 ib[0] = sref->getBeam( i ) ; 3950 ip[0] = sref->getPol( i ) ; 3951 sel.setIFs( ii ) ; 3952 sel.setBeams( ib ) ; 3953 sel.setPolarizations( ip ) ; 3954 askyhi->setSelection( sel ) ; 3955 sptsys = getTsysFromTime( reftime, askyhi, "linear" ) ; 3956 const Vector<Float> Vtsyshi( sptsys ) ; 3957 tsysColhi.put( i, Vtsyshi ) ; 3958 askyhi->unsetSelection() ; 3959 sel.reset() ; 3960 } 3961 } 3962 else if ( apexcalmode == 1 ) { 3963 // APEX fs data with off scan 3964 // off scan 3965 types.push_back( SrcType::FLOOFF ) ; 3966 sel.setTypes( types ) ; 3967 s->setSelection( sel ) ; 3968 tmp.clear() ; 3969 tmp.push_back( getScantable( s, false ) ) ; 3970 CountedPtr<Scantable> aofflo = average( tmp, masks, "TINT", "SCAN" ) ; 3971 s->unsetSelection() ; 3972 sel.reset() ; 3973 types.clear() ; 3974 types.push_back( SrcType::FHIOFF ) ; 3975 sel.setTypes( types ) ; 3976 s->setSelection( sel ) ; 3977 tmp.clear() ; 3978 tmp.push_back( getScantable( s, false ) ) ; 3979 CountedPtr<Scantable> aoffhi = average( tmp, masks, "TINT", "SCAN" ) ; 3980 s->unsetSelection() ; 3981 sel.reset() ; 3982 types.clear() ; 3983 3984 // process each sig and ref scan 3985 ArrayColumn<Float> tsysCollo ; 3986 tsysCollo.attach( ssig->table(), "TSYS" ) ; 3987 ArrayColumn<Float> tsysColhi ; 3988 tsysColhi.attach( sref->table(), "TSYS" ) ; 3989 for ( int i = 0 ; i < ssig->nrow() ; i++ ) { 3990 vector<float> sp = getCalibratedSpectra( ssig, aofflo, askylo, ahotlo, acoldlo, i, antname ) ; 3991 ssig->setSpectrum( sp, i ) ; 3992 sp = getCalibratedSpectra( sref, aoffhi, askyhi, ahothi, acoldhi, i, antname ) ; 3993 string reftime = ssig->getTime( i ) ; 3994 vector<int> ii( 1, ssig->getIF( i ) ) ; 3995 vector<int> ib( 1, ssig->getBeam( i ) ) ; 3996 vector<int> ip( 1, ssig->getPol( i ) ) ; 3997 sel.setIFs( ii ) ; 3998 sel.setBeams( ib ) ; 3999 sel.setPolarizations( ip ) ; 4000 askylo->setSelection( sel ) ; 4001 vector<float> sptsys = getTsysFromTime( reftime, askylo, "linear" ) ; 4002 const Vector<Float> Vtsyslo( sptsys ) ; 4003 tsysCollo.put( i, Vtsyslo ) ; 4004 askylo->unsetSelection() ; 4005 sel.reset() ; 4006 sref->setSpectrum( sp, i ) ; 4007 reftime = sref->getTime( i ) ; 4008 ii[0] = sref->getIF( i ) ; 4009 ib[0] = sref->getBeam( i ) ; 4010 ip[0] = sref->getPol( i ) ; 4011 sel.setIFs( ii ) ; 4012 sel.setBeams( ib ) ; 4013 sel.setPolarizations( ip ) ; 4014 askyhi->setSelection( sel ) ; 4015 sptsys = getTsysFromTime( reftime, askyhi, "linear" ) ; 4016 const Vector<Float> Vtsyshi( sptsys ) ; 4017 tsysColhi.put( i, Vtsyshi ) ; 4018 askyhi->unsetSelection() ; 4019 sel.reset() ; 4020 } 4021 } 4022 } 4023 else { 4024 // non-APEX fs data 4025 // sky scan 4026 STSelector sel = STSelector() ; 4027 types.push_back( SrcType::SKY ) ; 4028 sel.setTypes( types ) ; 4029 s->setSelection( sel ) ; 4030 vector< CountedPtr<Scantable> > tmp( 1, getScantable( s, false ) ) ; 4031 CountedPtr<Scantable> asky = average( tmp, masks, "TINT", "SCAN" ) ; 4032 s->unsetSelection() ; 4033 sel.reset() ; 4034 types.clear() ; 4035 4036 // hot scan 4037 types.push_back( SrcType::HOT ) ; 4038 sel.setTypes( types ) ; 4039 s->setSelection( sel ) ; 4040 tmp.clear() ; 4041 tmp.push_back( getScantable( s, false ) ) ; 4042 CountedPtr<Scantable> ahot = average( tmp, masks, "TINT", "SCAN" ) ; 4043 s->unsetSelection() ; 4044 sel.reset() ; 4045 types.clear() ; 4046 4047 // cold scan 4048 CountedPtr<Scantable> acold ; 4049 // types.push_back( SrcType::COLD ) ; 4050 // sel.setTypes( types ) ; 4051 // s->setSelection( sel ) ; 4052 // tmp.clear() ; 4053 // tmp.push_back( getScantable( s, false ) ) ; 4054 // CountedPtr<Scantable> acold = average( tmp, masks, "TINT", "SCAN" ) ; 4055 // s->unsetSelection() ; 4056 // sel.reset() ; 4057 // types.clear() ; 4058 4059 // ref scan 4060 bool insitu = insitu_ ; 4061 insitu_ = false ; 4062 sref = getScantable( s, true ) ; 4063 insitu_ = insitu ; 4064 types.push_back( SrcType::FSOFF ) ; 4065 sel.setTypes( types ) ; 4066 s->setSelection( sel ) ; 4067 TableCopy::copyRows( sref->table(), s->table() ) ; 4068 s->unsetSelection() ; 4069 sel.reset() ; 4070 types.clear() ; 4071 4072 // sig scan 4073 insitu_ = false ; 4074 ssig = getScantable( s, true ) ; 4075 insitu_ = insitu ; 4076 types.push_back( SrcType::FSON ) ; 4077 sel.setTypes( types ) ; 4078 s->setSelection( sel ) ; 4079 TableCopy::copyRows( ssig->table(), s->table() ) ; 4080 s->unsetSelection() ; 4081 sel.reset() ; 4082 types.clear() ; 4083 4084 // process each sig and ref scan 4085 ArrayColumn<Float> tsysColsig ; 4086 tsysColsig.attach( ssig->table(), "TSYS" ) ; 4087 ArrayColumn<Float> tsysColref ; 4088 tsysColref.attach( ssig->table(), "TSYS" ) ; 4089 for ( int i = 0 ; i < ssig->nrow() ; i++ ) { 4090 vector<float> sp = getFSCalibratedSpectra( ssig, sref, asky, ahot, acold, i ) ; 4091 ssig->setSpectrum( sp, i ) ; 4092 string reftime = ssig->getTime( i ) ; 4093 vector<int> ii( 1, ssig->getIF( i ) ) ; 4094 vector<int> ib( 1, ssig->getBeam( i ) ) ; 4095 vector<int> ip( 1, ssig->getPol( i ) ) ; 4096 sel.setIFs( ii ) ; 4097 sel.setBeams( ib ) ; 4098 sel.setPolarizations( ip ) ; 4099 asky->setSelection( sel ) ; 4100 vector<float> sptsys = getTsysFromTime( reftime, asky, "linear" ) ; 4101 const Vector<Float> Vtsys( sptsys ) ; 4102 tsysColsig.put( i, Vtsys ) ; 4103 asky->unsetSelection() ; 4104 sel.reset() ; 4105 sp = getFSCalibratedSpectra( sref, ssig, asky, ahot, acold, i ) ; 4106 sref->setSpectrum( sp, i ) ; 4107 tsysColref.put( i, Vtsys ) ; 4108 } 4109 } 4110 4111 // do folding if necessary 4112 Table sigtab = ssig->table() ; 4113 Table reftab = sref->table() ; 4114 ScalarColumn<uInt> sigifnoCol ; 4115 ScalarColumn<uInt> refifnoCol ; 4116 ScalarColumn<uInt> sigfidCol ; 4117 ScalarColumn<uInt> reffidCol ; 4118 Int nchan = (Int)ssig->nchan() ; 4119 sigifnoCol.attach( sigtab, "IFNO" ) ; 4120 refifnoCol.attach( reftab, "IFNO" ) ; 4121 sigfidCol.attach( sigtab, "FREQ_ID" ) ; 4122 reffidCol.attach( reftab, "FREQ_ID" ) ; 4123 Vector<uInt> sfids( sigfidCol.getColumn() ) ; 4124 Vector<uInt> rfids( reffidCol.getColumn() ) ; 4125 vector<uInt> sfids_unique ; 4126 vector<uInt> rfids_unique ; 4127 vector<uInt> sifno_unique ; 4128 vector<uInt> rifno_unique ; 4129 for ( uInt i = 0 ; i < sfids.nelements() ; i++ ) { 4130 if ( count( sfids_unique.begin(), sfids_unique.end(), sfids[i] ) == 0 ) { 4131 sfids_unique.push_back( sfids[i] ) ; 4132 sifno_unique.push_back( ssig->getIF( i ) ) ; 4133 } 4134 if ( count( rfids_unique.begin(), rfids_unique.end(), rfids[i] ) == 0 ) { 4135 rfids_unique.push_back( rfids[i] ) ; 4136 rifno_unique.push_back( sref->getIF( i ) ) ; 4137 } 4138 } 4139 double refpix_sig, refval_sig, increment_sig ; 4140 double refpix_ref, refval_ref, increment_ref ; 4141 vector< CountedPtr<Scantable> > tmp( sfids_unique.size() ) ; 4142 for ( uInt i = 0 ; i < sfids_unique.size() ; i++ ) { 4143 ssig->frequencies().getEntry( refpix_sig, refval_sig, increment_sig, sfids_unique[i] ) ; 4144 sref->frequencies().getEntry( refpix_ref, refval_ref, increment_ref, rfids_unique[i] ) ; 4145 if ( refpix_sig == refpix_ref ) { 4146 double foffset = refval_ref - refval_sig ; 4147 int choffset = static_cast<int>(foffset/increment_sig) ; 4148 double doffset = foffset / increment_sig ; 4149 if ( abs(choffset) >= nchan ) { 4150 LogIO os( LogOrigin( "STMath", "cwcalfs", WHERE ) ) ; 4151 os << "FREQ_ID=[" << sfids_unique[i] << "," << rfids_unique[i] << "]: out-band frequency switching, no folding" << LogIO::POST ; 4152 os << "Just return signal data" << LogIO::POST ; 4153 //std::vector< CountedPtr<Scantable> > tabs ; 4154 //tabs.push_back( ssig ) ; 4155 //tabs.push_back( sref ) ; 4156 //out = merge( tabs ) ; 4157 tmp[i] = ssig ; 4158 } 4159 else { 4160 STSelector sel = STSelector() ; 4161 vector<int> v( 1, sifno_unique[i] ) ; 4162 sel.setIFs( v ) ; 4163 ssig->setSelection( sel ) ; 4164 sel.reset() ; 4165 v[0] = rifno_unique[i] ; 4166 sel.setIFs( v ) ; 4167 sref->setSelection( sel ) ; 4168 sel.reset() ; 4169 if ( antname.find( "APEX" ) != string::npos ) { 4170 tmp[i] = dofold( ssig, sref, 0.5*doffset, -0.5*doffset ) ; 4171 //tmp[i] = dofold( ssig, sref, doffset ) ; 4172 } 4173 else { 4174 tmp[i] = dofold( ssig, sref, doffset ) ; 4175 } 4176 ssig->unsetSelection() ; 4177 sref->unsetSelection() ; 4178 } 4179 } 4180 } 4181 4182 if ( tmp.size() > 1 ) { 4183 out = merge( tmp ) ; 4184 } 4185 else { 4186 out = tmp[0] ; 4187 } 4188 4189 // flux unit 4190 out->setFluxUnit( "K" ) ; 4191 4192 return out ; 4193 } 4194 4195 CountedPtr<Scantable> STMath::almacalfs( const CountedPtr<Scantable>& s ) 4196 { 4197 CountedPtr<Scantable> out ; 4198 4199 return out ; 4200 } 4201 4202 vector<float> STMath::getSpectrumFromTime( string reftime, 4203 CountedPtr<Scantable>& s, 4204 string mode ) 4205 { 4206 LogIO os( LogOrigin( "STMath", "getSpectrumFromTime", WHERE ) ) ; 4207 vector<float> sp ; 4208 4209 if ( s->nrow() == 0 ) { 4210 os << LogIO::SEVERE << "No spectra in the input scantable. Return empty spectrum." << LogIO::POST ; 4211 return sp ; 4212 } 4213 else if ( s->nrow() == 1 ) { 4214 //os << "use row " << 0 << " (scanno = " << s->getScan( 0 ) << ")" << LogIO::POST ; 4215 return s->getSpectrum( 0 ) ; 4216 } 4217 else { 4218 vector<int> idx = getRowIdFromTime( reftime, s ) ; 4219 if ( mode == "before" ) { 4220 int id = -1 ; 4221 if ( idx[0] != -1 ) { 4222 id = idx[0] ; 4223 } 4224 else if ( idx[1] != -1 ) { 4225 os << LogIO::WARN << "Failed to find a scan before reftime. return a spectrum just after the reftime." << LogIO::POST ; 4226 id = idx[1] ; 4227 } 4228 //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ; 4229 sp = s->getSpectrum( id ) ; 4230 } 4231 else if ( mode == "after" ) { 4232 int id = -1 ; 4233 if ( idx[1] != -1 ) { 4234 id = idx[1] ; 4235 } 4236 else if ( idx[0] != -1 ) { 4237 os << LogIO::WARN << "Failed to find a scan after reftime. return a spectrum just before the reftime." << LogIO::POST ; 4238 id = idx[1] ; 4239 } 4240 //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ; 4241 sp = s->getSpectrum( id ) ; 4242 } 4243 else if ( mode == "nearest" ) { 4244 int id = -1 ; 4245 if ( idx[0] == -1 ) { 4246 id = idx[1] ; 4247 } 4248 else if ( idx[1] == -1 ) { 4249 id = idx[0] ; 4250 } 4251 else if ( idx[0] == idx[1] ) { 4252 id = idx[0] ; 4253 } 4254 else { 4255 double t0 = getMJD( s->getTime( idx[0] ) ) ; 4256 double t1 = getMJD( s->getTime( idx[1] ) ) ; 4257 double tref = getMJD( reftime ) ; 4258 if ( abs( t0 - tref ) > abs( t1 - tref ) ) { 4259 id = idx[1] ; 4260 } 4261 else { 4262 id = idx[0] ; 4263 } 4264 } 4265 //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ; 4266 sp = s->getSpectrum( id ) ; 4267 } 4268 else if ( mode == "linear" ) { 4269 if ( idx[0] == -1 ) { 4270 // use after 4271 os << LogIO::WARN << "Failed to interpolate. return a spectrum just after the reftime." << LogIO::POST ; 4272 int id = idx[1] ; 4273 //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ; 4274 sp = s->getSpectrum( id ) ; 4275 } 4276 else if ( idx[1] == -1 ) { 4277 // use before 4278 os << LogIO::WARN << "Failed to interpolate. return a spectrum just before the reftime." << LogIO::POST ; 4279 int id = idx[0] ; 4280 //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ; 4281 sp = s->getSpectrum( id ) ; 4282 } 4283 else if ( idx[0] == idx[1] ) { 4284 // use before 4285 //os << "No need to interporate." << LogIO::POST ; 4286 int id = idx[0] ; 4287 //os << "use row " << id << " (scanno = " << s->getScan( id ) << ")" << LogIO::POST ; 4288 sp = s->getSpectrum( id ) ; 4289 } 4290 else { 4291 // do interpolation 4292 //os << "interpolate between " << idx[0] << " and " << idx[1] << " (scanno: " << s->getScan( idx[0] ) << ", " << s->getScan( idx[1] ) << ")" << LogIO::POST ; 4293 double t0 = getMJD( s->getTime( idx[0] ) ) ; 4294 double t1 = getMJD( s->getTime( idx[1] ) ) ; 4295 double tref = getMJD( reftime ) ; 4296 vector<float> sp0 = s->getSpectrum( idx[0] ) ; 4297 vector<float> sp1 = s->getSpectrum( idx[1] ) ; 4298 for ( unsigned int i = 0 ; i < sp0.size() ; i++ ) { 4299 float v = ( sp1[i] - sp0[i] ) / ( t1 - t0 ) * ( tref - t0 ) + sp0[i] ; 4300 sp.push_back( v ) ; 4301 } 4302 } 4303 } 4304 else { 4305 os << LogIO::SEVERE << "Unknown mode" << LogIO::POST ; 4306 } 4307 return sp ; 4308 } 4309 } 4310 4311 double STMath::getMJD( string strtime ) 4312 { 4313 if ( strtime.find("/") == string::npos ) { 4314 // MJD time string 4315 return atof( strtime.c_str() ) ; 4316 } 4317 else { 4318 // string in YYYY/MM/DD/HH:MM:SS format 4319 uInt year = atoi( strtime.substr( 0, 4 ).c_str() ) ; 4320 uInt month = atoi( strtime.substr( 5, 2 ).c_str() ) ; 4321 uInt day = atoi( strtime.substr( 8, 2 ).c_str() ) ; 4322 uInt hour = atoi( strtime.substr( 11, 2 ).c_str() ) ; 4323 uInt minute = atoi( strtime.substr( 14, 2 ).c_str() ) ; 4324 uInt sec = atoi( strtime.substr( 17, 2 ).c_str() ) ; 4325 Time t( year, month, day, hour, minute, sec ) ; 4326 return t.modifiedJulianDay() ; 4327 } 4328 } 4329 4330 vector<int> STMath::getRowIdFromTime( string reftime, CountedPtr<Scantable> &s ) 4331 { 4332 double reft = getMJD( reftime ) ; 4333 double dtmin = 1.0e100 ; 4334 double dtmax = -1.0e100 ; 4335 vector<double> dt ; 4336 int just_before = -1 ; 4337 int just_after = -1 ; 4338 for ( int i = 0 ; i < s->nrow() ; i++ ) { 4339 dt.push_back( getMJD( s->getTime( i ) ) - reft ) ; 4340 } 4341 for ( unsigned int i = 0 ; i < dt.size() ; i++ ) { 4342 if ( dt[i] > 0.0 ) { 4343 // after reftime 4344 if ( dt[i] < dtmin ) { 4345 just_after = i ; 4346 dtmin = dt[i] ; 4347 } 4348 } 4349 else if ( dt[i] < 0.0 ) { 4350 // before reftime 4351 if ( dt[i] > dtmax ) { 4352 just_before = i ; 4353 dtmax = dt[i] ; 4354 } 4355 } 4356 else { 4357 // just a reftime 4358 just_before = i ; 4359 just_after = i ; 4360 dtmax = 0 ; 4361 dtmin = 0 ; 4362 break ; 4363 } 4364 } 4365 4366 vector<int> v ; 4367 v.push_back( just_before ) ; 4368 v.push_back( just_after ) ; 4369 4370 return v ; 4371 } 4372 4373 vector<float> STMath::getTcalFromTime( string reftime, 4374 CountedPtr<Scantable>& s, 4375 string mode ) 4376 { 4377 LogIO os( LogOrigin( "STMath", "getTcalFromTime", WHERE ) ) ; 4378 vector<float> tcal ; 4379 STTcal tcalTable = s->tcal() ; 4380 String time ; 4381 Vector<Float> tcalval ; 4382 if ( s->nrow() == 0 ) { 4383 os << LogIO::SEVERE << "No row in the input scantable. Return empty tcal." << LogIO::POST ; 4384 return tcal ; 4385 } 4386 else if ( s->nrow() == 1 ) { 4387 uInt tcalid = s->getTcalId( 0 ) ; 4388 //os << "use row " << 0 << " (tcalid = " << tcalid << ")" << LogIO::POST ; 4389 tcalTable.getEntry( time, tcalval, tcalid ) ; 4390 tcalval.tovector( tcal ) ; 4391 return tcal ; 4392 } 4393 else { 4394 vector<int> idx = getRowIdFromTime( reftime, s ) ; 4395 if ( mode == "before" ) { 4396 int id = -1 ; 4397 if ( idx[0] != -1 ) { 4398 id = idx[0] ; 4399 } 4400 else if ( idx[1] != -1 ) { 4401 os << LogIO::WARN << "Failed to find a scan before reftime. return a spectrum just after the reftime." << LogIO::POST ; 4402 id = idx[1] ; 4403 } 4404 uInt tcalid = s->getTcalId( id ) ; 4405 //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ; 4406 tcalTable.getEntry( time, tcalval, tcalid ) ; 4407 tcalval.tovector( tcal ) ; 4408 } 4409 else if ( mode == "after" ) { 4410 int id = -1 ; 4411 if ( idx[1] != -1 ) { 4412 id = idx[1] ; 4413 } 4414 else if ( idx[0] != -1 ) { 4415 os << LogIO::WARN << "Failed to find a scan after reftime. return a spectrum just before the reftime." << LogIO::POST ; 4416 id = idx[1] ; 4417 } 4418 uInt tcalid = s->getTcalId( id ) ; 4419 //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ; 4420 tcalTable.getEntry( time, tcalval, tcalid ) ; 4421 tcalval.tovector( tcal ) ; 4422 } 4423 else if ( mode == "nearest" ) { 4424 int id = -1 ; 4425 if ( idx[0] == -1 ) { 4426 id = idx[1] ; 4427 } 4428 else if ( idx[1] == -1 ) { 4429 id = idx[0] ; 4430 } 4431 else if ( idx[0] == idx[1] ) { 4432 id = idx[0] ; 4433 } 4434 else { 4435 double t0 = getMJD( s->getTime( idx[0] ) ) ; 4436 double t1 = getMJD( s->getTime( idx[1] ) ) ; 4437 double tref = getMJD( reftime ) ; 4438 if ( abs( t0 - tref ) > abs( t1 - tref ) ) { 4439 id = idx[1] ; 4440 } 4441 else { 4442 id = idx[0] ; 4443 } 4444 } 4445 uInt tcalid = s->getTcalId( id ) ; 4446 //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ; 4447 tcalTable.getEntry( time, tcalval, tcalid ) ; 4448 tcalval.tovector( tcal ) ; 4449 } 4450 else if ( mode == "linear" ) { 4451 if ( idx[0] == -1 ) { 4452 // use after 4453 os << LogIO::WARN << "Failed to interpolate. return a spectrum just after the reftime." << LogIO::POST ; 4454 int id = idx[1] ; 4455 uInt tcalid = s->getTcalId( id ) ; 4456 //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ; 4457 tcalTable.getEntry( time, tcalval, tcalid ) ; 4458 tcalval.tovector( tcal ) ; 4459 } 4460 else if ( idx[1] == -1 ) { 4461 // use before 4462 os << LogIO::WARN << "Failed to interpolate. return a spectrum just before the reftime." << LogIO::POST ; 4463 int id = idx[0] ; 4464 uInt tcalid = s->getTcalId( id ) ; 4465 //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ; 4466 tcalTable.getEntry( time, tcalval, tcalid ) ; 4467 tcalval.tovector( tcal ) ; 4468 } 4469 else if ( idx[0] == idx[1] ) { 4470 // use before 4471 //os << "No need to interporate." << LogIO::POST ; 4472 int id = idx[0] ; 4473 uInt tcalid = s->getTcalId( id ) ; 4474 //os << "use row " << id << " (tcalid = " << tcalid << ")" << LogIO::POST ; 4475 tcalTable.getEntry( time, tcalval, tcalid ) ; 4476 tcalval.tovector( tcal ) ; 4477 } 4478 else { 4479 // do interpolation 4480 //os << "interpolate between " << idx[0] << " and " << idx[1] << " (scanno: " << s->getScan( idx[0] ) << ", " << s->getScan( idx[1] ) << ")" << LogIO::POST ; 4481 double t0 = getMJD( s->getTime( idx[0] ) ) ; 4482 double t1 = getMJD( s->getTime( idx[1] ) ) ; 4483 double tref = getMJD( reftime ) ; 4484 vector<float> tcal0 ; 4485 vector<float> tcal1 ; 4486 uInt tcalid0 = s->getTcalId( idx[0] ) ; 4487 uInt tcalid1 = s->getTcalId( idx[1] ) ; 4488 tcalTable.getEntry( time, tcalval, tcalid0 ) ; 4489 tcalval.tovector( tcal0 ) ; 4490 tcalTable.getEntry( time, tcalval, tcalid1 ) ; 4491 tcalval.tovector( tcal1 ) ; 4492 for ( unsigned int i = 0 ; i < tcal0.size() ; i++ ) { 4493 float v = ( tcal1[i] - tcal0[i] ) / ( t1 - t0 ) * ( tref - t0 ) + tcal0[i] ; 4494 tcal.push_back( v ) ; 4495 } 4496 } 4497 } 4498 else { 4499 os << LogIO::SEVERE << "Unknown mode" << LogIO::POST ; 4500 } 4501 return tcal ; 4502 } 4503 } 4504 4505 vector<float> STMath::getTsysFromTime( string reftime, 4506 CountedPtr<Scantable>& s, 4507 string mode ) 4508 { 4509 LogIO os( LogOrigin( "STMath", "getTsysFromTime", WHERE ) ) ; 4510 ArrayColumn<Float> tsysCol ; 4511 tsysCol.attach( s->table(), "TSYS" ) ; 4512 vector<float> tsys ; 4513 String time ; 4514 Vector<Float> tsysval ; 4515 if ( s->nrow() == 0 ) { 4516 os << LogIO::SEVERE << "No row in the input scantable. Return empty tsys." << LogIO::POST ; 4517 return tsys ; 4518 } 4519 else if ( s->nrow() == 1 ) { 4520 //os << "use row " << 0 << LogIO::POST ; 4521 tsysval = tsysCol( 0 ) ; 4522 tsysval.tovector( tsys ) ; 4523 return tsys ; 4524 } 4525 else { 4526 vector<int> idx = getRowIdFromTime( reftime, s ) ; 4527 if ( mode == "before" ) { 4528 int id = -1 ; 4529 if ( idx[0] != -1 ) { 4530 id = idx[0] ; 4531 } 4532 else if ( idx[1] != -1 ) { 4533 os << LogIO::WARN << "Failed to find a scan before reftime. return a spectrum just after the reftime." << LogIO::POST ; 4534 id = idx[1] ; 4535 } 4536 //os << "use row " << id << LogIO::POST ; 4537 tsysval = tsysCol( id ) ; 4538 tsysval.tovector( tsys ) ; 4539 } 4540 else if ( mode == "after" ) { 4541 int id = -1 ; 4542 if ( idx[1] != -1 ) { 4543 id = idx[1] ; 4544 } 4545 else if ( idx[0] != -1 ) { 4546 os << LogIO::WARN << "Failed to find a scan after reftime. return a spectrum just before the reftime." << LogIO::POST ; 4547 id = idx[1] ; 4548 } 4549 //os << "use row " << id << LogIO::POST ; 4550 tsysval = tsysCol( id ) ; 4551 tsysval.tovector( tsys ) ; 4552 } 4553 else if ( mode == "nearest" ) { 4554 int id = -1 ; 4555 if ( idx[0] == -1 ) { 4556 id = idx[1] ; 4557 } 4558 else if ( idx[1] == -1 ) { 4559 id = idx[0] ; 4560 } 4561 else if ( idx[0] == idx[1] ) { 4562 id = idx[0] ; 4563 } 4564 else { 4565 double t0 = getMJD( s->getTime( idx[0] ) ) ; 4566 double t1 = getMJD( s->getTime( idx[1] ) ) ; 4567 double tref = getMJD( reftime ) ; 4568 if ( abs( t0 - tref ) > abs( t1 - tref ) ) { 4569 id = idx[1] ; 4570 } 4571 else { 4572 id = idx[0] ; 4573 } 4574 } 4575 //os << "use row " << id << LogIO::POST ; 4576 tsysval = tsysCol( id ) ; 4577 tsysval.tovector( tsys ) ; 4578 } 4579 else if ( mode == "linear" ) { 4580 if ( idx[0] == -1 ) { 4581 // use after 4582 os << LogIO::WARN << "Failed to interpolate. return a spectrum just after the reftime." << LogIO::POST ; 4583 int id = idx[1] ; 4584 //os << "use row " << id << LogIO::POST ; 4585 tsysval = tsysCol( id ) ; 4586 tsysval.tovector( tsys ) ; 4587 } 4588 else if ( idx[1] == -1 ) { 4589 // use before 4590 os << LogIO::WARN << "Failed to interpolate. return a spectrum just before the reftime." << LogIO::POST ; 4591 int id = idx[0] ; 4592 //os << "use row " << id << LogIO::POST ; 4593 tsysval = tsysCol( id ) ; 4594 tsysval.tovector( tsys ) ; 4595 } 4596 else if ( idx[0] == idx[1] ) { 4597 // use before 4598 //os << "No need to interporate." << LogIO::POST ; 4599 int id = idx[0] ; 4600 //os << "use row " << id << LogIO::POST ; 4601 tsysval = tsysCol( id ) ; 4602 tsysval.tovector( tsys ) ; 4603 } 4604 else { 4605 // do interpolation 4606 //os << "interpolate between " << idx[0] << " and " << idx[1] << " (scanno: " << s->getScan( idx[0] ) << ", " << s->getScan( idx[1] ) << ")" << LogIO::POST ; 4607 double t0 = getMJD( s->getTime( idx[0] ) ) ; 4608 double t1 = getMJD( s->getTime( idx[1] ) ) ; 4609 double tref = getMJD( reftime ) ; 4610 vector<float> tsys0 ; 4611 vector<float> tsys1 ; 4612 tsysval = tsysCol( idx[0] ) ; 4613 tsysval.tovector( tsys0 ) ; 4614 tsysval = tsysCol( idx[1] ) ; 4615 tsysval.tovector( tsys1 ) ; 4616 for ( unsigned int i = 0 ; i < tsys0.size() ; i++ ) { 4617 float v = ( tsys1[i] - tsys0[i] ) / ( t1 - t0 ) * ( tref - t0 ) + tsys0[i] ; 4618 tsys.push_back( v ) ; 4619 } 4620 } 4621 } 4622 else { 4623 os << LogIO::SEVERE << "Unknown mode" << LogIO::POST ; 4624 } 4625 return tsys ; 4626 } 4627 } 4628 4629 vector<float> STMath::getCalibratedSpectra( CountedPtr<Scantable>& on, 4630 CountedPtr<Scantable>& off, 4631 CountedPtr<Scantable>& sky, 4632 CountedPtr<Scantable>& hot, 4633 CountedPtr<Scantable>& cold, 4634 int index, 4635 string antname ) 4636 { 4637 string reftime = on->getTime( index ) ; 4638 vector<int> ii( 1, on->getIF( index ) ) ; 4639 vector<int> ib( 1, on->getBeam( index ) ) ; 4640 vector<int> ip( 1, on->getPol( index ) ) ; 4641 vector<int> ic( 1, on->getScan( index ) ) ; 4642 STSelector sel = STSelector() ; 4643 sel.setIFs( ii ) ; 4644 sel.setBeams( ib ) ; 4645 sel.setPolarizations( ip ) ; 4646 sky->setSelection( sel ) ; 4647 hot->setSelection( sel ) ; 4648 //cold->setSelection( sel ) ; 4649 off->setSelection( sel ) ; 4650 vector<float> spsky = getSpectrumFromTime( reftime, sky, "linear" ) ; 4651 vector<float> sphot = getSpectrumFromTime( reftime, hot, "linear" ) ; 4652 //vector<float> spcold = getSpectrumFromTime( reftime, cold, "linear" ) ; 4653 vector<float> spoff = getSpectrumFromTime( reftime, off, "linear" ) ; 4654 vector<float> spec = on->getSpectrum( index ) ; 4655 vector<float> tcal = getTcalFromTime( reftime, sky, "linear" ) ; 4656 vector<float> sp( tcal.size() ) ; 4657 if ( antname.find( "APEX" ) != string::npos ) { 4658 // using gain array 4659 for ( unsigned int j = 0 ; j < tcal.size() ; j++ ) { 4660 float v = ( ( spec[j] - spoff[j] ) / spoff[j] ) 4661 * ( spsky[j] / ( sphot[j] - spsky[j] ) ) * tcal[j] ; 4662 sp[j] = v ; 4663 } 4664 } 4665 else { 4666 // Chopper-Wheel calibration (Ulich & Haas 1976) 4667 for ( unsigned int j = 0 ; j < tcal.size() ; j++ ) { 4668 float v = ( spec[j] - spoff[j] ) / ( sphot[j] - spsky[j] ) * tcal[j] ; 4669 sp[j] = v ; 4670 } 4671 } 4672 sel.reset() ; 4673 sky->unsetSelection() ; 4674 hot->unsetSelection() ; 4675 //cold->unsetSelection() ; 4676 off->unsetSelection() ; 4677 4678 return sp ; 4679 } 4680 4681 vector<float> STMath::getCalibratedSpectra( CountedPtr<Scantable>& on, 4682 CountedPtr<Scantable>& off, 4683 int index ) 4684 { 4685 string reftime = on->getTime( index ) ; 4686 vector<int> ii( 1, on->getIF( index ) ) ; 4687 vector<int> ib( 1, on->getBeam( index ) ) ; 4688 vector<int> ip( 1, on->getPol( index ) ) ; 4689 vector<int> ic( 1, on->getScan( index ) ) ; 4690 STSelector sel = STSelector() ; 4691 sel.setIFs( ii ) ; 4692 sel.setBeams( ib ) ; 4693 sel.setPolarizations( ip ) ; 4694 off->setSelection( sel ) ; 4695 vector<float> spoff = getSpectrumFromTime( reftime, off, "linear" ) ; 4696 vector<float> spec = on->getSpectrum( index ) ; 4697 //vector<float> tcal = getTcalFromTime( reftime, sky, "linear" ) ; 4698 //vector<float> tsys = on->getTsysVec( index ) ; 4699 ArrayColumn<Float> tsysCol( on->table(), "TSYS" ) ; 4700 Vector<Float> tsys = tsysCol( index ) ; 4701 vector<float> sp( spec.size() ) ; 4702 // ALMA Calibration 4703 // 4704 // Ta* = Tsys * ( ON - OFF ) / OFF 4705 // 4706 // 2010/01/07 Takeshi Nakazato 4707 unsigned int tsyssize = tsys.nelements() ; 4708 unsigned int spsize = sp.size() ; 4709 for ( unsigned int j = 0 ; j < sp.size() ; j++ ) { 4710 float tscale = 0.0 ; 4711 if ( tsyssize == spsize ) 4712 tscale = tsys[j] ; 4713 else 4714 tscale = tsys[0] ; 4715 float v = tscale * ( spec[j] - spoff[j] ) / spoff[j] ; 4716 sp[j] = v ; 4717 } 4718 sel.reset() ; 4719 off->unsetSelection() ; 4720 4721 return sp ; 4722 } 4723 4724 vector<float> STMath::getFSCalibratedSpectra( CountedPtr<Scantable>& sig, 4725 CountedPtr<Scantable>& ref, 4726 CountedPtr<Scantable>& sky, 4727 CountedPtr<Scantable>& hot, 4728 CountedPtr<Scantable>& cold, 4729 int index ) 4730 { 4731 string reftime = sig->getTime( index ) ; 4732 vector<int> ii( 1, sig->getIF( index ) ) ; 4733 vector<int> ib( 1, sig->getBeam( index ) ) ; 4734 vector<int> ip( 1, sig->getPol( index ) ) ; 4735 vector<int> ic( 1, sig->getScan( index ) ) ; 4736 STSelector sel = STSelector() ; 4737 sel.setIFs( ii ) ; 4738 sel.setBeams( ib ) ; 4739 sel.setPolarizations( ip ) ; 4740 sky->setSelection( sel ) ; 4741 hot->setSelection( sel ) ; 4742 //cold->setSelection( sel ) ; 4743 vector<float> spsky = getSpectrumFromTime( reftime, sky, "linear" ) ; 4744 vector<float> sphot = getSpectrumFromTime( reftime, hot, "linear" ) ; 4745 //vector<float> spcold = getSpectrumFromTime( reftime, cold, "linear" ) ; 4746 vector<float> spref = ref->getSpectrum( index ) ; 4747 vector<float> spsig = sig->getSpectrum( index ) ; 4748 vector<float> tcal = getTcalFromTime( reftime, sky, "linear" ) ; 4749 vector<float> sp( tcal.size() ) ; 4750 for ( unsigned int j = 0 ; j < tcal.size() ; j++ ) { 4751 float v = tcal[j] * spsky[j] / ( sphot[j] - spsky[j] ) * ( spsig[j] - spref[j] ) / spref[j] ; 4752 sp[j] = v ; 4753 } 4754 sel.reset() ; 4755 sky->unsetSelection() ; 4756 hot->unsetSelection() ; 4757 //cold->unsetSelection() ; 4758 4759 return sp ; 4760 } 4761 4762 vector<float> STMath::getFSCalibratedSpectra( CountedPtr<Scantable>& sig, 4763 CountedPtr<Scantable>& ref, 4764 vector< CountedPtr<Scantable> >& sky, 4765 vector< CountedPtr<Scantable> >& hot, 4766 vector< CountedPtr<Scantable> >& cold, 4767 int index ) 4768 { 4769 string reftime = sig->getTime( index ) ; 4770 vector<int> ii( 1, sig->getIF( index ) ) ; 4771 vector<int> ib( 1, sig->getBeam( index ) ) ; 4772 vector<int> ip( 1, sig->getPol( index ) ) ; 4773 vector<int> ic( 1, sig->getScan( index ) ) ; 4774 STSelector sel = STSelector() ; 4775 sel.setIFs( ii ) ; 4776 sel.setBeams( ib ) ; 4777 sel.setPolarizations( ip ) ; 4778 sky[0]->setSelection( sel ) ; 4779 hot[0]->setSelection( sel ) ; 4780 //cold[0]->setSelection( sel ) ; 4781 vector<float> spskys = getSpectrumFromTime( reftime, sky[0], "linear" ) ; 4782 vector<float> sphots = getSpectrumFromTime( reftime, hot[0], "linear" ) ; 4783 //vector<float> spcolds = getSpectrumFromTime( reftime, cold[0], "linear" ) ; 4784 vector<float> tcals = getTcalFromTime( reftime, sky[0], "linear" ) ; 4785 sel.reset() ; 4786 ii[0] = ref->getIF( index ) ; 4787 sel.setIFs( ii ) ; 4788 sel.setBeams( ib ) ; 4789 sel.setPolarizations( ip ) ; 4790 sky[1]->setSelection( sel ) ; 4791 hot[1]->setSelection( sel ) ; 4792 //cold[1]->setSelection( sel ) ; 4793 vector<float> spskyr = getSpectrumFromTime( reftime, sky[1], "linear" ) ; 4794 vector<float> sphotr = getSpectrumFromTime( reftime, hot[1], "linear" ) ; 4795 //vector<float> spcoldr = getSpectrumFromTime( reftime, cold[1], "linear" ) ; 4796 vector<float> tcalr = getTcalFromTime( reftime, sky[1], "linear" ) ; 4797 vector<float> spref = ref->getSpectrum( index ) ; 4798 vector<float> spsig = sig->getSpectrum( index ) ; 4799 vector<float> sp( tcals.size() ) ; 4800 for ( unsigned int j = 0 ; j < tcals.size() ; j++ ) { 4801 float v = tcals[j] * spsig[j] / ( sphots[j] - spskys[j] ) - tcalr[j] * spref[j] / ( sphotr[j] - spskyr[j] ) ; 4802 sp[j] = v ; 4803 } 4804 sel.reset() ; 4805 sky[0]->unsetSelection() ; 4806 hot[0]->unsetSelection() ; 4807 //cold[0]->unsetSelection() ; 4808 sky[1]->unsetSelection() ; 4809 hot[1]->unsetSelection() ; 4810 //cold[1]->unsetSelection() ; 4811 4812 return sp ; 4813 } -
branches/mergetest/src/STMath.h
r1689 r1779 119 119 const std::string& mode, bool tsys=false ); 120 120 121 // array operation 122 casa::CountedPtr<Scantable> 123 arrayOperate( const casa::CountedPtr<Scantable>& in, 124 const std::vector<float> val, 125 const std::string& mode, 126 const std::string& opmode="channel", 127 bool tsys=false ); 128 129 // channel operation 130 casa::CountedPtr<Scantable> 131 arrayOperateChannel( const casa::CountedPtr<Scantable>& in, 132 const std::vector<float> val, 133 const std::string& mode, bool tsys=false ); 134 135 // row operation 136 casa::CountedPtr<Scantable> 137 arrayOperateRow( const casa::CountedPtr<Scantable>& in, 138 const std::vector<float> val, 139 const std::string& mode, bool tsys=false ); 140 141 // 2d array operation 142 casa::CountedPtr<Scantable> 143 array2dOperate( const casa::CountedPtr<Scantable>& in, 144 const std::vector< std::vector<float> > val, 145 const std::string& mode, bool tsys=false ); 146 121 147 casa::CountedPtr<Scantable> 122 148 binaryOperate( const casa::CountedPtr<Scantable>& left, … … 134 160 /** 135 161 * Calibrate total power scans (translated from GBTIDL) 136 * @param calon uncalibrated Scantable with CAL noise signal 162 * @param calon uncalibrated Scantable with CAL noise signal 137 163 * @param caloff uncalibrated Scantable with no CAL signal 138 164 * @param tcal optional scalar Tcal, CAL temperature (K) 139 * @return casa::CountedPtr<Scantable> which holds a calibrated Scantable 165 * @return casa::CountedPtr<Scantable> which holds a calibrated Scantable 140 166 * (spectrum - average of the two CAL on and off spectra; 141 167 * tsys - mean Tsys = <caloff>*Tcal/<calon-caloff> + Tcal/2) 142 */ 168 */ 143 169 casa::CountedPtr<Scantable> dototalpower( const casa::CountedPtr<Scantable>& calon, 144 170 const casa::CountedPtr<Scantable>& caloff, … … 151 177 * @param smoothref optional Boxcar smooth width of the reference scans 152 178 * default: no smoothing (=1) 153 * @param tsysv optional scalar Tsys value at the zenith, required to 154 * set tau, as well 179 * @param tsysv optional scalar Tsys value at the zenith, required to 180 * set tau, as well 155 181 * @param tau optional scalar Tau value 156 182 * @return casa::CountedPtr<Scantable> which holds combined scans … … 163 189 casa::Float tau=0.0 ); 164 190 165 /**191 /** 166 192 * Calibrate GBT Nod scan pairs (translated from GBTIDL) 167 193 * @param s Scantable which contains Nod scans … … 170 196 * @param tsysv optional scalar Tsys value at the zenith, required to 171 197 * set tau, as well 172 * @param tau optional scalar Tau value 198 * @param tau optional scalar Tau value 173 199 * @param tcal optional scalar Tcal, CAL temperature (K) 174 200 * @return casa::CountedPtr<Scantable> which holds calibrated scans … … 199 225 casa::Float tcal=0.0 ); 200 226 227 /** 228 * Calibrate data with Chopper-Wheel like calibration method 229 * which adopts position switching by antenna motion, 230 * wobbler (nutator) switching and On-The-Fly observation. 231 * 232 * The method is applicable to APEX, and other telescopes other than GBT. 233 * 234 * @param a Scantable which contains ON and OFF scans 235 * @param a string that indicates calibration mode 236 * @param a string that indicates antenna name 237 **/ 238 casa::CountedPtr<Scantable> cwcal( const casa::CountedPtr<Scantable>& s, 239 const casa::String calmode, 240 const casa::String antname ); 241 242 /** 243 * Calibrate frequency switched scans with Chopper-Wheel like 244 * calibration method. 245 * 246 * The method is applicable to APEX, and other telescopes other than GBT. 247 * 248 * @param a Scantable which contains ON and OFF scans 249 * @param a string that indicates antenna name 250 **/ 251 casa::CountedPtr<Scantable> cwcalfs( const casa::CountedPtr<Scantable>& s, 252 const casa::String antname ); 253 254 255 /** 256 * Folding frequency-switch data 257 * @param sig 258 * @param ref 259 * @param choffset 260 **/ 261 casa::CountedPtr<Scantable> dofold( const casa::CountedPtr<Scantable> &sig, 262 const casa::CountedPtr<Scantable> &ref, 263 casa::Double choffset, 264 casa::Double choffset = 0.0 ); 265 266 /** 267 * ALMA calibration 268 **/ 269 casa::CountedPtr<Scantable> almacal( const casa::CountedPtr<Scantable>& s, 270 const casa::String calmode ) ; 271 casa::CountedPtr<Scantable> almacalfs( const casa::CountedPtr<Scantable>& s ) ; 201 272 202 273 casa::CountedPtr<Scantable> … … 206 277 const std::vector<bool>& mask, 207 278 const std::string& which); 279 280 std::vector< int > minMaxChan(const casa::CountedPtr<Scantable>& in, 281 const std::vector<bool>& mask, 282 const std::string& which); 208 283 209 284 casa::CountedPtr<Scantable> bin( const casa::CountedPtr<Scantable>& in, … … 266 341 double end, const std::string& mode="frequency"); 267 342 343 // test for average spectra with different channel/resolution 344 casa::CountedPtr<Scantable> 345 new_average( const std::vector<casa::CountedPtr<Scantable> >& in, 346 const bool& compel, 347 const std::vector<bool>& mask = std::vector<bool>(), 348 const std::string& weight = "NONE", 349 const std::string& avmode = "SCAN" ) 350 throw (casa::AipsError) ; 351 268 352 private: 269 353 casa::CountedPtr<Scantable> applyToPol( const casa::CountedPtr<Scantable>& in, … … 301 385 maskedArray( const casa::Vector<casa::Float>& s, 302 386 const casa::Vector<casa::uChar>& f ); 387 casa::MaskedArray<casa::Double> 388 maskedArray( const casa::Vector<casa::Double>& s, 389 const casa::Vector<casa::uChar>& f ); 303 390 casa::Vector<casa::uChar> 304 391 flagsFromMA(const casa::MaskedArray<casa::Float>& ma); 305 392 393 vector<float> getSpectrumFromTime( string reftime, casa::CountedPtr<Scantable>& s, string mode = "before" ) ; 394 vector<float> getTcalFromTime( string reftime, casa::CountedPtr<Scantable>& s, string mode="before" ) ; 395 vector<float> getTsysFromTime( string reftime, casa::CountedPtr<Scantable>& s, string mode="before" ) ; 396 vector<int> getRowIdFromTime( string reftime, casa::CountedPtr<Scantable>& s ) ; 397 398 // Chopper-Wheel type calibration 399 vector<float> getCalibratedSpectra( casa::CountedPtr<Scantable>& on, 400 casa::CountedPtr<Scantable>& off, 401 casa::CountedPtr<Scantable>& sky, 402 casa::CountedPtr<Scantable>& hot, 403 casa::CountedPtr<Scantable>& cold, 404 int index, 405 string antname ) ; 406 // Tsys * (ON-OFF)/OFF 407 vector<float> getCalibratedSpectra( casa::CountedPtr<Scantable>& on, 408 casa::CountedPtr<Scantable>& off, 409 int index ) ; 410 vector<float> getFSCalibratedSpectra( casa::CountedPtr<Scantable>& sig, 411 casa::CountedPtr<Scantable>& ref, 412 casa::CountedPtr<Scantable>& sky, 413 casa::CountedPtr<Scantable>& hot, 414 casa::CountedPtr<Scantable>& cold, 415 int index ) ; 416 vector<float> getFSCalibratedSpectra( casa::CountedPtr<Scantable>& sig, 417 casa::CountedPtr<Scantable>& ref, 418 vector< casa::CountedPtr<Scantable> >& sky, 419 vector< casa::CountedPtr<Scantable> >& hot, 420 vector< casa::CountedPtr<Scantable> >& cold, 421 int index ) ; 422 double getMJD( string strtime ) ; 423 306 424 bool insitu_; 307 425 }; -
branches/mergetest/src/STMathWrapper.h
r1689 r1779 73 73 { return ScantableWrapper(STMath::unaryOperate(in.getCP(), val, mode, tsys)); } 74 74 75 ScantableWrapper arrayOperate( const ScantableWrapper& in, 76 const std::vector<float> val, 77 const std::string& mode, 78 bool tsys=false ) 79 { return ScantableWrapper(STMath::arrayOperateChannel(in.getCP(), val, mode, tsys)); } 80 81 ScantableWrapper array2dOperate( const ScantableWrapper& in, 82 const std::vector< std::vector<float> > val, 83 const std::string& mode, bool tsys=false ) 84 { return ScantableWrapper(STMath::array2dOperate(in.getCP(), val, mode, tsys)); } 85 75 86 ScantableWrapper binaryOperate( const ScantableWrapper& left, 76 87 const ScantableWrapper& right, … … 121 132 { return STMath::statistic(in.getCP(), mask, which); } 122 133 134 std::vector<int> minMaxChan(const ScantableWrapper& in, 135 const std::vector<bool>& mask, 136 const std::string& which) 137 { return STMath::minMaxChan(in.getCP(), mask, which); } 138 123 139 ScantableWrapper bin( const ScantableWrapper& in, int width=5) 124 140 { return ScantableWrapper(STMath::bin(in.getCP(), width)); } … … 175 191 const std::string& refTime, 176 192 const std::string& method ) 177 { return ScantableWrapper(STMath::frequencyAlign(in.getCP() , refTime, method)); }193 { return ScantableWrapper(STMath::frequencyAlign(in.getCP())); } 178 194 179 195 ScantableWrapper convertPolarisation( const ScantableWrapper& in, … … 191 207 mode)); } 192 208 209 // test for average spectra with different channel/resolution 210 ScantableWrapper 211 new_average( const std::vector<ScantableWrapper>& in, 212 const bool& compel, 213 const std::vector<bool>& mask, 214 const std::string& weight, 215 const std::string& avmode ) 216 { 217 std::vector<casa::CountedPtr<Scantable> > sts; 218 for (unsigned int i=0; i<in.size(); ++i) sts.push_back(in[i].getCP()); 219 return ScantableWrapper(STMath::new_average(sts, compel, mask, weight, avmode)); 220 } 221 222 // cwcal 223 ScantableWrapper cwcal( const ScantableWrapper &in, 224 const std::string calmode, 225 const std::string antname ) 226 { 227 casa::CountedPtr<Scantable> tab = in.getCP() ; 228 casa::String mode( calmode ) ; 229 casa::String name( antname ) ; 230 return ScantableWrapper( STMath::cwcal( tab, mode, name ) ) ; 231 } 232 // almacal 233 ScantableWrapper almacal( const ScantableWrapper &in, 234 const std::string calmode ) 235 { 236 casa::CountedPtr<Scantable> tab = in.getCP() ; 237 casa::String mode( calmode ) ; 238 return ScantableWrapper( STMath::almacal( tab, mode ) ) ; 239 } 193 240 }; 194 241 -
branches/mergetest/src/STMolecules.cpp
r870 r1779 14 14 #include <tables/Tables/SetupNewTab.h> 15 15 #include <tables/Tables/ScaColDesc.h> 16 #include <tables/Tables/ArrColDesc.h> 16 17 #include <tables/Tables/TableRecord.h> 17 18 #include <tables/Tables/TableParse.h> 18 19 #include <tables/Tables/TableRow.h> 19 20 #include <casa/Containers/RecordField.h> 21 22 #include <tables/Tables/TableProxy.h> 20 23 21 24 #include "STMolecules.h" … … 59 62 { 60 63 // add to base class table 61 table_.addColumn(ScalarColumnDesc<Double>("RESTFREQUENCY")); 62 table_.addColumn(ScalarColumnDesc<String>("NAME")); 63 table_.addColumn(ScalarColumnDesc<String>("FORMATTEDNAME")); 64 //table_.addColumn(ScalarColumnDesc<Double>("RESTFREQUENCY")); 65 table_.addColumn(ArrayColumnDesc<Double>("RESTFREQUENCY")); 66 //table_.addColumn(ScalarColumnDesc<String>("NAME")); 67 table_.addColumn(ArrayColumnDesc<String>("NAME")); 68 //table_.addColumn(ScalarColumnDesc<String>("FORMATTEDNAME")); 69 table_.addColumn(ArrayColumnDesc<String>("FORMATTEDNAME")); 64 70 table_.rwKeywordSet().define("UNIT", String("Hz")); 65 71 // new cached columns … … 69 75 } 70 76 77 /*** 71 78 uInt STMolecules::addEntry( Double restfreq, const String& name, 72 79 const String& formattedname ) … … 94 101 return resultid; 95 102 } 96 103 ***/ 104 uInt STMolecules::addEntry( Vector<Double> restfreq, const Vector<String>& name, 105 const Vector<String>& formattedname ) 106 { 107 // How to handle this...? 108 Table result = 109 table_( nelements(table_.col("RESTFREQUENCY")) == uInt (restfreq.size()) && 110 all(table_.col("RESTFREQUENCY")== restfreq) ); 111 uInt resultid = 0; 112 if ( result.nrow() > 0) { 113 ROScalarColumn<uInt> c(result, "ID"); 114 c.get(0, resultid); 115 } else { 116 uInt rno = table_.nrow(); 117 table_.addRow(); 118 // get last assigned _id and increment 119 if ( rno > 0 ) { 120 idCol_.get(rno-1, resultid); 121 resultid++; 122 } 123 restfreqCol_.put(rno, restfreq); 124 nameCol_.put(rno, name); 125 formattednameCol_.put(rno, formattedname); 126 idCol_.put(rno, resultid); 127 } 128 return resultid; 129 } 130 131 132 133 134 /*** 97 135 void STMolecules::getEntry( Double& restfreq, String& name, 98 136 String& formattedname, uInt id ) const … … 104 142 ROTableRow row(t); 105 143 // get first row - there should only be one matching id 144 106 145 const TableRecord& rec = row.get(0); 107 146 restfreq = rec.asDouble("RESTFREQUENCY"); … … 109 148 formattedname = rec.asString("FORMATTEDNAME"); 110 149 } 150 ***/ 151 void STMolecules::getEntry( Vector<Double>& restfreq, Vector<String>& name, 152 Vector<String>& formattedname, uInt id ) const 153 { 154 Table t = table_(table_.col("ID") == Int(id) ); 155 if (t.nrow() == 0 ) { 156 throw(AipsError("STMolecules::getEntry - id out of range")); 157 } 158 ROTableRow row(t); 159 // get first row - there should only be one matching id 160 161 const TableRecord& rec = row.get(0); 162 //restfreq = rec.asDouble("RESTFREQUENCY"); 163 restfreq = rec.asArrayDouble("RESTFREQUENCY"); 164 //name = rec.asString("NAME"); 165 name = rec.asArrayString("NAME"); 166 //formattedname = rec.asString("FORMATTEDNAME"); 167 formattedname = rec.asArrayString("FORMATTEDNAME"); 168 } 111 169 112 170 std::vector< double > asap::STMolecules::getRestFrequencies( ) const 113 171 { 114 172 std::vector<double> out; 173 //TableProxy itsTable(table_); 174 //Record rec; 115 175 Vector<Double> rfs = restfreqCol_.getColumn(); 116 176 rfs.tovector(out); 177 //rec = itsTable.getVarColumn("RESTFREQUENCY", 0, 1, 1); 117 178 return out; 118 179 } 119 180 120 double asap::STMolecules::getRestFrequency( uInt id ) const 121 { 181 std::vector< double > asap::STMolecules::getRestFrequency( uInt id ) const 182 { 183 std::vector<double> out; 122 184 Table t = table_(table_.col("ID") == Int(id) ); 123 185 if (t.nrow() == 0 ) { … … 126 188 ROTableRow row(t); 127 189 const TableRecord& rec = row.get(0); 128 return double(rec.asDouble("RESTFREQUENCY")); 129 } 130 190 //return double(rec.asDouble("RESTFREQUENCY")); 191 Vector<Double> rfs = rec.asArrayDouble("RESTFREQUENCY"); 192 rfs.tovector(out); 193 return out; 194 } 195 196 int asap::STMolecules::nrow() const 197 { 198 return int(table_.nrow()); 199 } 131 200 132 201 }//namespace -
branches/mergetest/src/STMolecules.h
r1353 r1779 17 17 #include <tables/Tables/Table.h> 18 18 #include <tables/Tables/ScalarColumn.h> 19 #include <tables/Tables/ArrayColumn.h> 20 #include <casa/Arrays/Array.h> 19 21 20 22 #include "STSubTable.h" … … 37 39 STMolecules& operator=(const STMolecules& other); 38 40 41 /*** 39 42 casa::uInt addEntry( casa::Double restfreq, const casa::String& name="", 40 43 const casa::String& formattedname=""); 44 ***/ 41 45 46 casa::uInt addEntry( casa::Vector<casa::Double> restfreq, const casa::Vector<casa::String>& name=casa::Vector<casa::String>(0), 47 const casa::Vector<casa::String>& formattedname=casa::Vector<casa::String>(0)); 48 49 /*** 42 50 void getEntry( casa::Double& restfreq, casa::String& name, 43 51 casa::String& formattedname, casa::uInt id) const; 52 ***/ 53 void getEntry( casa::Vector<casa::Double>& restfreq, casa::Vector<casa::String>& name, 54 casa::Vector<casa::String>& formattedname, casa::uInt id) const; 44 55 45 56 std::vector<double> getRestFrequencies() const; 46 doublegetRestFrequency( casa::uInt id ) const;57 std::vector<double> getRestFrequency( casa::uInt id ) const; 47 58 const casa::String& name() const { return name_; } 59 int nrow() const; 48 60 49 61 private: … … 52 64 //casa::Table table_; 53 65 //casa::ScalarColumn<casa::uInt> freqidCol_; 54 casa::ScalarColumn<casa::Double> restfreqCol_; 55 casa::ScalarColumn<casa::String> nameCol_; 56 casa::ScalarColumn<casa::String> formattednameCol_; // e.g. latex 66 //casa::ScalarColumn<casa::Double> restfreqCol_; 67 casa::ArrayColumn<casa::Double> restfreqCol_; 68 //casa::ScalarColumn<casa::String> nameCol_; 69 casa::ArrayColumn<casa::String> nameCol_; 70 //casa::ScalarColumn<casa::String> formattednameCol_; // e.g. latex 71 casa::ArrayColumn<casa::String> formattednameCol_; // e.g. latex 57 72 58 73 }; -
branches/mergetest/src/STSelector.cpp
r1542 r1779 87 87 } 88 88 89 void STSelector::setTypes( const std::vector< int >& types ) 90 { 91 setint("SRCTYPE", types); 92 } 93 89 94 void STSelector::setint(const std::string& key, const std::vector< int >& val) 90 95 { … … 116 121 } 117 122 123 void STSelector::setRows( const std::vector< int >& rows ) 124 { 125 rowselection_ = rows; 126 } 127 128 // Table STSelector::apply( const Table& tab ) 129 // { 130 // if ( empty() ) { 131 // return sort(tab); 132 // } 133 // TableExprNode query; 134 // intidmap::const_iterator it; 135 // for (it = intselections_.begin(); it != intselections_.end(); ++it) { 136 // TableExprNode theset(Vector<Int>( (*it).second )); 137 // if ( query.isNull() ) { 138 // query = tab.col((*it).first).in(theset); 139 // } else { 140 // query = tab.col((*it).first).in(theset) && query; 141 // } 142 // } 143 // stringidmap::const_iterator it1; 144 // for (it1 = stringselections_.begin(); it1 != stringselections_.end(); ++it1) { 145 // TableExprNode theset(mathutil::toVectorString( (*it1).second )); 146 // if ( query.isNull() ) { 147 // query = tab.col((*it1).first).in(theset); 148 // } else { 149 // query = tab.col((*it1).first).in(theset) && query; 150 // } 151 // } 152 // // add taql query 153 // if ( taql_.size() > 0 ) { 154 // Table tmpt = tab; 155 // std::string pytaql = "USING STYLE PYTHON " + taql_; 156 157 // if ( !query.isNull() ) { // taql and selection 158 // tmpt = tableCommand(pytaql, tab(query)); 159 // } else { // taql only 160 // tmpt = tableCommand(pytaql, tab); 161 // } 162 // return sort(tmpt); 163 // } else { 164 // if ( query.isNull() ) { 165 // return sort(tab); 166 // } else { 167 // return sort(tab(query)); 168 // } 169 // } 170 // } 118 171 Table STSelector::apply( const Table& tab ) 119 172 { 120 173 if ( empty() ) { 121 174 return sort(tab); 175 } 176 Table basetab = tab; 177 // Important!! Be sure to apply row selection first. 178 if (rowselection_.size() > 0){ 179 //Vector<Int> intrownrs(rowselection_); 180 Vector<uInt> rownrs( rowselection_.size() ); 181 convertArray(rownrs, Vector<Int> ( rowselection_ )); 182 basetab = tab( rownrs ); 183 ///TableExprNode theset(Vector<Int>( rowselection_ )); 184 ///query = tab.nodeRownr().in(theset); 122 185 } 123 186 TableExprNode query; … … 126 189 TableExprNode theset(Vector<Int>( (*it).second )); 127 190 if ( query.isNull() ) { 128 query = tab.col((*it).first).in(theset); 191 //query = tab.col((*it).first).in(theset); 192 query = basetab.col((*it).first).in(theset); 129 193 } else { 130 query = tab.col((*it).first).in(theset) && query; 194 //query = tab.col((*it).first).in(theset) && query; 195 query = basetab.col((*it).first).in(theset) && query; 131 196 } 132 197 } … … 135 200 TableExprNode theset(mathutil::toVectorString( (*it1).second )); 136 201 if ( query.isNull() ) { 137 query = tab.col((*it1).first).in(theset); 202 //query = tab.col((*it1).first).in(theset); 203 query = basetab.col((*it1).first).in(theset); 138 204 } else { 139 query = tab.col((*it1).first).in(theset) && query; 205 //query = tab.col((*it1).first).in(theset) && query; 206 query = basetab.col((*it1).first).in(theset) && query; 140 207 } 141 208 } 142 209 // add taql query 143 210 if ( taql_.size() > 0 ) { 144 Table tmpt = tab; 211 //Table tmpt = tab; 212 Table tmpt = basetab; 145 213 std::string pytaql = "USING STYLE PYTHON " + taql_; 146 214 147 215 if ( !query.isNull() ) { // taql and selection 148 tmpt = tableCommand(pytaql, tab(query)); 216 //tmpt = tableCommand(pytaql, tab(query)); 217 tmpt = tableCommand(pytaql, basetab(query)); 149 218 } else { // taql only 150 tmpt = tableCommand(pytaql, tab); 219 //tmpt = tableCommand(pytaql, tab); 220 tmpt = tableCommand(pytaql, basetab); 151 221 } 152 222 return sort(tmpt); 153 223 } else { 154 224 if ( query.isNull() ) { 155 return sort(tab); 225 //return sort(tab); 226 return sort(basetab); 156 227 } else { 157 return sort(tab(query)); 228 //return sort(tab(query)); 229 return sort(basetab(query)); 158 230 } 159 231 } … … 191 263 { 192 264 return getint("CYCLENO"); 265 } 266 267 std::vector< int > asap::STSelector::getTypes( ) const 268 { 269 return getint("SRCTYPE") ; 193 270 } 194 271 … … 227 304 bool asap::STSelector::empty( ) const 228 305 { 229 return (intselections_.empty() && taql_.size() == 0 ); 306 //return (intselections_.empty() && taql_.size() == 0 ); 307 return (intselections_.empty() && taql_.size() == 0 && rowselection_.size() == 0); 230 308 } 231 309 -
branches/mergetest/src/STSelector.h
r939 r1779 45 45 void setCycles(const std::vector<int>& cycs); 46 46 void setName(const std::string&); 47 void setTypes(const std::vector<int>& types); 47 48 virtual void setTaQL(const std::string& taql); 48 49 49 50 void setSortOrder(const std::vector<std::string>& order); 51 void setRows(const std::vector<int>& rows); 50 52 51 53 std::vector<int> getScans() const; … … 54 56 std::vector<int> getPols() const; 55 57 std::vector<int> getCycles() const; 58 std::vector<int> getTypes() const; 56 59 std::vector<std::string> getPolTypes() const; 57 60 std::string getTaQL() const { return taql_; } … … 86 89 casa::Block<casa::String> order_; 87 90 std::string taql_; 91 std::vector<int> rowselection_; 88 92 }; 89 93 -
branches/mergetest/src/STWriter.cpp
r1688 r1779 42 42 #include <atnf/PKSIO/PKSMS2writer.h> 43 43 #include <atnf/PKSIO/PKSSDwriter.h> 44 #include <atnf/PKSIO/SrcType.h> 44 45 45 46 #include <tables/Tables/Table.h> … … 154 155 havexpol(ifs[i]) = nPol(ifs[i]) > 2; 155 156 } 156 Vector<String> obstypes(2);157 obstypes(0) = "TR";//on158 obstypes(1) = "RF TR";//off157 // Vector<String> obstypes(2); 158 // obstypes(0) = "TR";//on 159 // obstypes(1) = "RF TR";//off 159 160 const Table table = inst->table(); 160 161 … … 182 183 while (!beamit.pastEnd() ) { 183 184 Table btable = beamit.table(); 185 //MDirection::ScalarColumn dirCol(btable, "DIRECTION"); 186 //pksrec.direction = dirCol(0).getAngle("rad").getValue(); 184 187 TableIterator cycit(btable, "CYCLENO"); 185 188 ROArrayColumn<Double> srateCol(btable, "SCANRATE"); … … 188 191 Vector<Float> srateflt(sratedbl.nelements()); 189 192 convertArray(srateflt, sratedbl); 190 pksrec.scanRate = srateflt; 193 //pksrec.scanRate = srateflt; 194 pksrec.scanRate = sratedbl; 191 195 ROArrayColumn<Double> spmCol(btable, "SRCPROPERMOTION"); 192 196 spmCol.get(0, pksrec.srcPM); … … 200 204 while (!cycit.pastEnd() ) { 201 205 Table ctable = cycit.table(); 202 TableIterator ifit(ctable, "IFNO" );206 TableIterator ifit(ctable, "IFNO", TableIterator::Ascending, TableIterator::HeapSort); 203 207 MDirection::ScalarColumn dirCol(ctable, "DIRECTION"); 204 208 pksrec.direction = dirCol(0).getAngle("rad").getValue(); … … 213 217 uInt nchan = specCol(0).nelements(); 214 218 Double crval,crpix; 219 //Vector<Double> restfreq; 215 220 Float tmp0,tmp1,tmp2,tmp3,tmp4; 216 String stmp0,stmp1; 221 String tcalt; 222 Vector<String> stmp0, stmp1; 217 223 inst->frequencies().getEntry(crpix,crval, pksrec.freqInc, 218 224 rec.asuInt("FREQ_ID")); … … 239 245 pksrec.fieldName = rec.asString("FIELDNAME"); 240 246 pksrec.srcName = rec.asString("SRCNAME"); 241 pksrec.obsType = obstypes[rec.asInt("SRCTYPE")]; 247 //pksrec.obsType = obstypes[rec.asInt("SRCTYPE")]; 248 pksrec.obsType = getObsTypes( rec.asInt("SRCTYPE") ) ; 242 249 pksrec.bandwidth = nchan * abs(pksrec.freqInc); 243 250 pksrec.azimuth = rec.asFloat("AZIMUTH"); … … 253 260 pksrec.baseSub = 0.0f; 254 261 pksrec.xCalFctr = 0.0; 262 pksrec.flagrow = rec.asuInt("FLAGROW"); 255 263 256 264 status = writer_->write(pksrec); … … 348 356 } 349 357 350 } 358 // get obsType string from SRCTYPE value 359 String STWriter::getObsTypes( Int srctype ) 360 { 361 String obsType ; 362 switch( srctype ) { 363 case Int(SrcType::PSON): 364 obsType = "PSON" ; 365 break ; 366 case Int(SrcType::PSOFF): 367 obsType = "PSOFF" ; 368 break ; 369 case Int(SrcType::NOD): 370 obsType = "NOD" ; 371 break ; 372 case Int(SrcType::FSON): 373 obsType = "FSON" ; 374 break ; 375 case Int(SrcType::FSOFF): 376 obsType = "FSOFF" ; 377 break ; 378 case Int(SrcType::SKY): 379 obsType = "SKY" ; 380 break ; 381 case Int(SrcType::HOT): 382 obsType = "HOT" ; 383 break ; 384 case Int(SrcType::WARM): 385 obsType = "WARM" ; 386 break ; 387 case Int(SrcType::COLD): 388 obsType = "COLD" ; 389 break ; 390 case Int(SrcType::PONCAL): 391 obsType = "PSON:CALON" ; 392 break ; 393 case Int(SrcType::POFFCAL): 394 obsType = "PSOFF:CALON" ; 395 break ; 396 case Int(SrcType::NODCAL): 397 obsType = "NOD:CALON" ; 398 break ; 399 case Int(SrcType::FONCAL): 400 obsType = "FSON:CALON" ; 401 break ; 402 case Int(SrcType::FOFFCAL): 403 obsType = "FSOFF:CALOFF" ; 404 break ; 405 case Int(SrcType::FSLO): 406 obsType = "FSLO" ; 407 break ; 408 case Int(SrcType::FLOOFF): 409 obsType = "FS:LOWER:OFF" ; 410 break ; 411 case Int(SrcType::FLOSKY): 412 obsType = "FS:LOWER:SKY" ; 413 break ; 414 case Int(SrcType::FLOHOT): 415 obsType = "FS:LOWER:HOT" ; 416 break ; 417 case Int(SrcType::FLOWARM): 418 obsType = "FS:LOWER:WARM" ; 419 break ; 420 case Int(SrcType::FLOCOLD): 421 obsType = "FS:LOWER:COLD" ; 422 break ; 423 case Int(SrcType::FSHI): 424 obsType = "FSHI" ; 425 break ; 426 case Int(SrcType::FHIOFF): 427 obsType = "FS:HIGHER:OFF" ; 428 break ; 429 case Int(SrcType::FHISKY): 430 obsType = "FS:HIGHER:SKY" ; 431 break ; 432 case Int(SrcType::FHIHOT): 433 obsType = "FS:HIGHER:HOT" ; 434 break ; 435 case Int(SrcType::FHIWARM): 436 obsType = "FS:HIGHER:WARM" ; 437 break ; 438 case Int(SrcType::FHICOLD): 439 obsType = "FS:HIGHER:COLD" ; 440 break ; 441 default: 442 obsType = "NOTYPE" ; 443 } 444 445 return obsType ; 446 } 447 448 } -
branches/mergetest/src/STWriter.h
r1391 r1779 36 36 #include <casa/aips.h> 37 37 #include <casa/Utilities/CountedPtr.h> 38 #include <casa/BasicSL/String.h> 38 39 39 40 #include "Logger.h" … … 84 85 void replacePtTab(const casa::Table& tab, const std::string& fname); 85 86 87 casa::String getObsTypes( casa::Int srctype ) ; 88 86 89 std::string format_; 87 90 PKSwriter* writer_; -
branches/mergetest/src/Scantable.cpp
r1743 r1779 11 11 // 12 12 #include <map> 13 #include <fstream> 13 14 14 15 #include <casa/aips.h> … … 24 25 #include <casa/Arrays/Vector.h> 25 26 #include <casa/Arrays/VectorSTLIterator.h> 27 #include <casa/Arrays/Slice.h> 26 28 #include <casa/BasicMath/Math.h> 27 29 #include <casa/BasicSL/Constants.h> … … 29 31 #include <casa/Containers/RecordField.h> 30 32 #include <casa/Utilities/GenSort.h> 33 #include <casa/Logging/LogIO.h> 31 34 32 35 #include <tables/Tables/TableParse.h> … … 106 109 { 107 110 initFactories(); 111 108 112 Table tab(name, Table::Update); 109 113 uInt version = tab.keywordSet().asuInt("VERSION"); … … 121 125 attach(); 122 126 } 127 /* 128 Scantable::Scantable(const std::string& name, Table::TableType ttype) : 129 type_(ttype) 130 { 131 initFactories(); 132 Table tab(name, Table::Update); 133 uInt version = tab.keywordSet().asuInt("VERSION"); 134 if (version != version_) { 135 throw(AipsError("Unsupported version of ASAP file.")); 136 } 137 if ( type_ == Table::Memory ) { 138 table_ = tab.copyToMemoryTable(generateName()); 139 } else { 140 table_ = tab; 141 } 142 143 attachSubtables(); 144 originalTable_ = table_; 145 attach(); 146 } 147 */ 123 148 124 149 Scantable::Scantable( const Scantable& other, bool clear ) … … 201 226 td.addColumn(ScalarColumnDesc<Int>("REFBEAMNO")); 202 227 228 td.addColumn(ScalarColumnDesc<uInt>("FLAGROW")); 229 203 230 td.addColumn(ScalarColumnDesc<Double>("TIME")); 204 231 TableMeasRefDesc measRef(MEpoch::UTC); // UTC as default … … 257 284 originalTable_ = table_; 258 285 } 259 260 286 261 287 void Scantable::attach() … … 285 311 mfocusidCol_.attach(table_, "FOCUS_ID"); 286 312 mmolidCol_.attach(table_, "MOLECULE_ID"); 313 314 //Add auxiliary column for row-based flagging (CAS-1433 Wataru Kawasaki) 315 attachAuxColumnDef(flagrowCol_, "FLAGROW", 0); 316 317 } 318 319 template<class T, class T2> 320 void Scantable::attachAuxColumnDef(ScalarColumn<T>& col, 321 const String& colName, 322 const T2& defValue) 323 { 324 try { 325 col.attach(table_, colName); 326 } catch (TableError& err) { 327 String errMesg = err.getMesg(); 328 if (errMesg == "Table column " + colName + " is unknown") { 329 table_.addColumn(ScalarColumnDesc<T>(colName)); 330 col.attach(table_, colName); 331 col.fillColumn(static_cast<T>(defValue)); 332 } else { 333 throw; 334 } 335 } catch (...) { 336 throw; 337 } 338 } 339 340 template<class T, class T2> 341 void Scantable::attachAuxColumnDef(ArrayColumn<T>& col, 342 const String& colName, 343 const Array<T2>& defValue) 344 { 345 try { 346 col.attach(table_, colName); 347 } catch (TableError& err) { 348 String errMesg = err.getMesg(); 349 if (errMesg == "Table column " + colName + " is unknown") { 350 table_.addColumn(ArrayColumnDesc<T>(colName)); 351 col.attach(table_, colName); 352 353 int size = 0; 354 ArrayIterator<T2>& it = defValue.begin(); 355 while (it != defValue.end()) { 356 ++size; 357 ++it; 358 } 359 IPosition ip(1, size); 360 Array<T>& arr(ip); 361 for (int i = 0; i < size; ++i) 362 arr[i] = static_cast<T>(defValue[i]); 363 364 col.fillColumn(arr); 365 } else { 366 throw; 367 } 368 } catch (...) { 369 throw; 370 } 287 371 } 288 372 … … 627 711 } 628 712 713 void Scantable::clip(const Float uthres, const Float dthres, bool clipoutside, bool unflag) 714 { 715 for (uInt i=0; i<table_.nrow(); ++i) { 716 Vector<uChar> flgs = flagsCol_(i); 717 srchChannelsToClip(i, uthres, dthres, clipoutside, unflag, flgs); 718 flagsCol_.put(i, flgs); 719 } 720 } 721 722 std::vector<bool> Scantable::getClipMask(int whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag) 723 { 724 Vector<uChar> flags; 725 flagsCol_.get(uInt(whichrow), flags); 726 srchChannelsToClip(uInt(whichrow), uthres, dthres, clipoutside, unflag, flags); 727 Vector<Bool> bflag(flags.shape()); 728 convertArray(bflag, flags); 729 //bflag = !bflag; 730 731 std::vector<bool> mask; 732 bflag.tovector(mask); 733 return mask; 734 } 735 736 void Scantable::srchChannelsToClip(uInt whichrow, const Float uthres, const Float dthres, bool clipoutside, bool unflag, 737 Vector<uChar> flgs) 738 { 739 Vector<Float> spcs = specCol_(whichrow); 740 uInt nchannel = nchan(); 741 if (spcs.nelements() != nchannel) { 742 throw(AipsError("Data has incorrect number of channels")); 743 } 744 uChar userflag = 1 << 7; 745 if (unflag) { 746 userflag = 0 << 7; 747 } 748 if (clipoutside) { 749 for (uInt j = 0; j < nchannel; ++j) { 750 Float spc = spcs(j); 751 if ((spc >= uthres) || (spc <= dthres)) { 752 flgs(j) = userflag; 753 } 754 } 755 } else { 756 for (uInt j = 0; j < nchannel; ++j) { 757 Float spc = spcs(j); 758 if ((spc < uthres) && (spc > dthres)) { 759 flgs(j) = userflag; 760 } 761 } 762 } 763 } 764 629 765 void Scantable::flag(const std::vector<bool>& msk, bool unflag) 630 766 { … … 673 809 flagsCol_.put(i, flgs); 674 810 } 811 } 812 813 void Scantable::flagRow(const std::vector<uInt>& rows, bool unflag) 814 { 815 if ( selector_.empty() && (rows.size() == table_.nrow()) ) 816 throw(AipsError("Trying to flag whole scantable.")); 817 818 uInt rowflag = (unflag ? 0 : 1); 819 std::vector<uInt>::const_iterator it; 820 for (it = rows.begin(); it != rows.end(); ++it) 821 flagrowCol_.put(*it, rowflag); 675 822 } 676 823 … … 793 940 table_.keywordSet().get("FluxUnit", tmp); 794 941 oss << setw(15) << "Flux Unit:" << tmp << endl; 795 Vector<Double> vec(moleculeTable_.getRestFrequencies()); 942 //Vector<Double> vec(moleculeTable_.getRestFrequencies()); 943 int nid = moleculeTable_.nrow(); 944 Bool firstline = True; 796 945 oss << setw(15) << "Rest Freqs:"; 797 if (vec.nelements() > 0) { 798 oss << setprecision(10) << vec << " [Hz]" << endl; 799 } else { 800 oss << "none" << endl; 946 for (int i=0; i<nid; i++) { 947 Table t = table_(table_.col("MOLECULE_ID") == i); 948 if (t.nrow() > 0) { 949 Vector<Double> vec(moleculeTable_.getRestFrequency(i)); 950 if (vec.nelements() > 0) { 951 if (firstline) { 952 oss << setprecision(10) << vec << " [Hz]" << endl; 953 firstline=False; 954 } 955 else{ 956 oss << setw(15)<<" " << setprecision(10) << vec << " [Hz]" << endl; 957 } 958 } else { 959 oss << "none" << endl; 960 } 961 } 801 962 } 802 963 … … 901 1062 const MDirection& md = getDirection(whichrow); 902 1063 const MEpoch& me = timeCol_(whichrow); 903 Double rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow)); 1064 //Double rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow)); 1065 Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow)); 904 1066 return freqTable_.getSpectralCoordinate(md, mp, me, rf, 905 1067 mfreqidCol_(whichrow)); … … 975 1137 const MDirection& md = getDirection(whichrow); 976 1138 const MEpoch& me = timeCol_(whichrow); 977 const Double& rf = mmolidCol_(whichrow); 1139 //const Double& rf = mmolidCol_(whichrow); 1140 const Vector<Double> rf = moleculeTable_.getRestFrequency(mmolidCol_(whichrow)); 978 1141 SpectralCoordinate spc = 979 1142 freqTable_.getSpectralCoordinate(md, mp, me, rf, mfreqidCol_(whichrow)); … … 992 1155 } 993 1156 994 void Scantable::setRestFrequencies( double rf, const std::string& name, 1157 /** 1158 void asap::Scantable::setRestFrequencies( double rf, const std::string& name, 995 1159 const std::string& unit ) 1160 **/ 1161 void Scantable::setRestFrequencies( vector<double> rf, const vector<std::string>& name, 1162 const std::string& unit ) 1163 996 1164 { 997 1165 ///@todo lookup in line table to fill in name and formattedname 998 1166 Unit u(unit); 999 Quantum<Double> urf(rf, u); 1000 uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), name, ""); 1167 //Quantum<Double> urf(rf, u); 1168 Quantum<Vector<Double> >urf(rf, u); 1169 Vector<String> formattedname(0); 1170 //cerr<<"Scantable::setRestFrequnecies="<<urf<<endl; 1171 1172 //uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), name, ""); 1173 uInt id = moleculeTable_.addEntry(urf.getValue("Hz"), mathutil::toVectorString(name), formattedname); 1001 1174 TableVector<uInt> tabvec(table_, "MOLECULE_ID"); 1002 1175 tabvec = id; 1003 1176 } 1004 1177 1005 void Scantable::setRestFrequencies( const std::string& name ) 1178 /** 1179 void asap::Scantable::setRestFrequencies( const std::string& name ) 1006 1180 { 1007 1181 throw(AipsError("setRestFrequencies( const std::string& name ) NYI")); 1182 ///@todo implement 1183 } 1184 **/ 1185 void Scantable::setRestFrequencies( const vector<std::string>& name ) 1186 { 1187 throw(AipsError("setRestFrequencies( const vector<std::string>& name ) NYI")); 1008 1188 ///@todo implement 1009 1189 } … … 1044 1224 void Scantable::addFit( const STFitEntry& fit, int row ) 1045 1225 { 1046 cout << mfitidCol_(uInt(row)) << endl; 1226 //cout << mfitidCol_(uInt(row)) << endl; 1227 LogIO os( LogOrigin( "Scantable", "addFit()", WHERE ) ) ; 1228 os << mfitidCol_(uInt(row)) << LogIO::POST ; 1047 1229 uInt id = fitTable_.addEntry(fit, mfitidCol_(uInt(row))); 1048 1230 mfitidCol_.put(uInt(row), id); … … 1078 1260 Table subt = t( t.col("SCAN") == scanlist[i]+1 ); 1079 1261 if (subt.nrow()==0) { 1080 cerr <<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<endl; 1262 //cerr <<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<endl; 1263 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ; 1264 os <<LogIO::WARN<<"Scan "<<scanlist[i]<<" cannot be found in the scantable."<<LogIO::POST; 1081 1265 ret = 1; 1082 1266 break; … … 1090 1274 Table subt2 = t( t.col("SCAN") == scanlist[i+1]+1 ); 1091 1275 if ( subt2.nrow() == 0) { 1092 cerr<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<endl; 1276 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ; 1277 1278 //cerr<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<endl; 1279 os<<LogIO::WARN<<"Scan "<<scanlist[i+1]<<" cannot be found in the scantable."<<LogIO::POST; 1093 1280 ret = 1; 1094 1281 break; … … 1100 1287 if (scan1seqn == 1 && scan2seqn == 2) { 1101 1288 if (laston1 == laston2) { 1102 cerr<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl; 1289 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ; 1290 //cerr<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl; 1291 os<<"A valid scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST; 1103 1292 i +=1; 1104 1293 } 1105 1294 else { 1106 cerr<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl; 1295 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ; 1296 //cerr<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<endl; 1297 os<<LogIO::WARN<<"Incorrect scan pair ["<<scanlist[i]<<","<<scanlist[i+1]<<"]"<<LogIO::POST; 1107 1298 } 1108 1299 } 1109 1300 else if (scan1seqn==2 && scan2seqn == 1) { 1110 1301 if (laston1 == laston2) { 1111 cerr<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<endl; 1302 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ; 1303 //cerr<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<endl; 1304 os<<LogIO::WARN<<"["<<scanlist[i]<<","<<scanlist[i+1]<<"] is a valid scan pair but in incorrect order."<<LogIO::POST; 1112 1305 ret = 1; 1113 1306 break; … … 1115 1308 } 1116 1309 else { 1117 cerr<<"The other scan for "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<endl; 1310 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ; 1311 //cerr<<"The other scan for "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<endl; 1312 os<<LogIO::WARN<<"The other scan for "<<scanlist[i]<<" appears to be missing. Check the input scan numbers."<<LogIO::POST; 1118 1313 ret = 1; 1119 1314 break; … … 1122 1317 } 1123 1318 else { 1124 cerr<<"The scan does not appear to be standard obsevation."<<endl; 1319 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ; 1320 //cerr<<"The scan does not appear to be standard obsevation."<<endl; 1321 os<<LogIO::WARN<<"The scan does not appear to be standard obsevation."<<LogIO::POST; 1125 1322 } 1126 1323 //if ( i >= nscan ) break; … … 1128 1325 } 1129 1326 else { 1130 cerr<<"No reference to GBT_GO table."<<endl; 1327 LogIO os( LogOrigin( "Scantable", "checkScanInfo()", WHERE ) ) ; 1328 //cerr<<"No reference to GBT_GO table."<<endl; 1329 os<<LogIO::WARN<<"No reference to GBT_GO table."<<LogIO::POST; 1131 1330 ret = 1; 1132 1331 } … … 1142 1341 } 1143 1342 1343 void asap::Scantable::reshapeSpectrum( int nmin, int nmax ) 1344 throw( casa::AipsError ) 1345 { 1346 // assumed that all rows have same nChan 1347 Vector<Float> arr = specCol_( 0 ) ; 1348 int nChan = arr.nelements() ; 1349 1350 // if nmin < 0 or nmax < 0, nothing to do 1351 if ( nmin < 0 ) { 1352 throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ; 1353 } 1354 if ( nmax < 0 ) { 1355 throw( casa::indexError<int>( nmax, "asap::Scantable::reshapeSpectrum: Invalid range. Negative index is specified." ) ) ; 1356 } 1357 1358 // if nmin > nmax, exchange values 1359 if ( nmin > nmax ) { 1360 int tmp = nmax ; 1361 nmax = nmin ; 1362 nmin = tmp ; 1363 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ; 1364 os << "Swap values. Applied range is [" 1365 << nmin << ", " << nmax << "]" << LogIO::POST ; 1366 } 1367 1368 // if nmin exceeds nChan, nothing to do 1369 if ( nmin >= nChan ) { 1370 throw( casa::indexError<int>( nmin, "asap::Scantable::reshapeSpectrum: Invalid range. Specified minimum exceeds nChan." ) ) ; 1371 } 1372 1373 // if nmax exceeds nChan, reset nmax to nChan 1374 if ( nmax >= nChan ) { 1375 if ( nmin == 0 ) { 1376 // nothing to do 1377 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ; 1378 os << "Whole range is selected. Nothing to do." << LogIO::POST ; 1379 return ; 1380 } 1381 else { 1382 LogIO os( LogOrigin( "Scantable", "reshapeSpectrum()", WHERE ) ) ; 1383 os << "Specified maximum exceeds nChan. Applied range is [" 1384 << nmin << ", " << nChan-1 << "]." << LogIO::POST ; 1385 nmax = nChan - 1 ; 1386 } 1387 } 1388 1389 // reshape specCol_ and flagCol_ 1390 for ( int irow = 0 ; irow < nrow() ; irow++ ) { 1391 reshapeSpectrum( nmin, nmax, irow ) ; 1392 } 1393 1394 // update FREQUENCIES subtable 1395 Double refpix ; 1396 Double refval ; 1397 Double increment ; 1398 int freqnrow = freqTable_.table().nrow() ; 1399 Vector<uInt> oldId( freqnrow ) ; 1400 Vector<uInt> newId( freqnrow ) ; 1401 for ( int irow = 0 ; irow < freqnrow ; irow++ ) { 1402 freqTable_.getEntry( refpix, refval, increment, irow ) ; 1403 /*** 1404 * need to shift refpix to nmin 1405 * note that channel nmin in old index will be channel 0 in new one 1406 ***/ 1407 refval = refval - ( refpix - nmin ) * increment ; 1408 refpix = 0 ; 1409 freqTable_.setEntry( refpix, refval, increment, irow ) ; 1410 } 1411 1412 // update nchan 1413 int newsize = nmax - nmin + 1 ; 1414 table_.rwKeywordSet().define( "nChan", newsize ) ; 1415 1416 // update bandwidth 1417 // assumed all spectra in the scantable have same bandwidth 1418 table_.rwKeywordSet().define( "Bandwidth", increment * newsize ) ; 1419 1420 return ; 1421 } 1422 1423 void asap::Scantable::reshapeSpectrum( int nmin, int nmax, int irow ) 1424 { 1425 // reshape specCol_ and flagCol_ 1426 Vector<Float> oldspec = specCol_( irow ) ; 1427 Vector<uChar> oldflag = flagsCol_( irow ) ; 1428 uInt newsize = nmax - nmin + 1 ; 1429 specCol_.put( irow, oldspec( Slice( nmin, newsize, 1 ) ) ) ; 1430 flagsCol_.put( irow, oldflag( Slice( nmin, newsize, 1 ) ) ) ; 1431 1432 return ; 1433 } 1434 1435 void asap::Scantable::regridChannel( int nChan, double dnu ) 1436 { 1437 LogIO os( LogOrigin( "Scantable", "regridChannel()", WHERE ) ) ; 1438 os << "Regrid abcissa with channel number " << nChan << " and spectral resoultion " << dnu << "Hz." << LogIO::POST ; 1439 // assumed that all rows have same nChan 1440 Vector<Float> arr = specCol_( 0 ) ; 1441 int oldsize = arr.nelements() ; 1442 1443 // if oldsize == nChan, nothing to do 1444 if ( oldsize == nChan ) { 1445 os << "Specified channel number is same as current one. Nothing to do." << LogIO::POST ; 1446 return ; 1447 } 1448 1449 // if oldChan < nChan, unphysical operation 1450 if ( oldsize < nChan ) { 1451 os << "Unphysical operation. Nothing to do." << LogIO::POST ; 1452 return ; 1453 } 1454 1455 // change channel number for specCol_ and flagCol_ 1456 Vector<Float> newspec( nChan, 0 ) ; 1457 Vector<uChar> newflag( nChan, false ) ; 1458 vector<string> coordinfo = getCoordInfo() ; 1459 string oldinfo = coordinfo[0] ; 1460 coordinfo[0] = "Hz" ; 1461 setCoordInfo( coordinfo ) ; 1462 for ( int irow = 0 ; irow < nrow() ; irow++ ) { 1463 regridChannel( nChan, dnu, irow ) ; 1464 } 1465 coordinfo[0] = oldinfo ; 1466 setCoordInfo( coordinfo ) ; 1467 1468 1469 // NOTE: this method does not update metadata such as 1470 // FREQUENCIES subtable, nChan, Bandwidth, etc. 1471 1472 return ; 1473 } 1474 1475 void asap::Scantable::regridChannel( int nChan, double dnu, int irow ) 1476 { 1477 // logging 1478 //ofstream ofs( "average.log", std::ios::out | std::ios::app ) ; 1479 //ofs << "IFNO = " << getIF( irow ) << " irow = " << irow << endl ; 1480 1481 Vector<Float> oldspec = specCol_( irow ) ; 1482 Vector<uChar> oldflag = flagsCol_( irow ) ; 1483 Vector<Float> newspec( nChan, 0 ) ; 1484 Vector<uChar> newflag( nChan, false ) ; 1485 1486 // regrid 1487 vector<double> abcissa = getAbcissa( irow ) ; 1488 int oldsize = abcissa.size() ; 1489 double olddnu = abcissa[1] - abcissa[0] ; 1490 //int refChan = 0 ; 1491 //double frac = 0.0 ; 1492 //double wedge = 0.0 ; 1493 //double pile = 0.0 ; 1494 int ichan = 0 ; 1495 double wsum = 0.0 ; 1496 Vector<Float> z( nChan ) ; 1497 z[0] = abcissa[0] - 0.5 * olddnu + 0.5 * dnu ; 1498 for ( int ii = 1 ; ii < nChan ; ii++ ) 1499 z[ii] = z[ii-1] + dnu ; 1500 Vector<Float> zi( nChan+1 ) ; 1501 Vector<Float> yi( oldsize + 1 ) ; 1502 zi[0] = z[0] - 0.5 * dnu ; 1503 zi[1] = z[0] + 0.5 * dnu ; 1504 for ( int ii = 2 ; ii < nChan ; ii++ ) 1505 zi[ii] = zi[ii-1] + dnu ; 1506 zi[nChan] = z[nChan-1] + 0.5 * dnu ; 1507 yi[0] = abcissa[0] - 0.5 * olddnu ; 1508 yi[1] = abcissa[1] + 0.5 * olddnu ; 1509 for ( int ii = 2 ; ii < oldsize ; ii++ ) 1510 yi[ii] = abcissa[ii-1] + olddnu ; 1511 yi[oldsize] = abcissa[oldsize-1] + 0.5 * olddnu ; 1512 if ( dnu > 0.0 ) { 1513 for ( int ii = 0 ; ii < nChan ; ii++ ) { 1514 double zl = zi[ii] ; 1515 double zr = zi[ii+1] ; 1516 for ( int j = ichan ; j < oldsize ; j++ ) { 1517 double yl = yi[j] ; 1518 double yr = yi[j+1] ; 1519 if ( yl <= zl ) { 1520 if ( yr <= zl ) { 1521 continue ; 1522 } 1523 else if ( yr <= zr ) { 1524 newspec[ii] += oldspec[j] * ( yr - zl ) ; 1525 newflag[ii] = newflag[ii] || oldflag[j] ; 1526 wsum += ( yr - zl ) ; 1527 } 1528 else { 1529 newspec[ii] += oldspec[j] * dnu ; 1530 newflag[ii] = newflag[ii] || oldflag[j] ; 1531 wsum += dnu ; 1532 ichan = j ; 1533 break ; 1534 } 1535 } 1536 else if ( yl < zr ) { 1537 if ( yr <= zr ) { 1538 newspec[ii] += oldspec[j] * ( yr - yl ) ; 1539 newflag[ii] = newflag[ii] || oldflag[j] ; 1540 wsum += ( yr - yl ) ; 1541 } 1542 else { 1543 newspec[ii] += oldspec[j] * ( zr - yl ) ; 1544 newflag[ii] = newflag[ii] || oldflag[j] ; 1545 wsum += ( zr - yl ) ; 1546 ichan = j ; 1547 break ; 1548 } 1549 } 1550 else { 1551 ichan = j - 1 ; 1552 break ; 1553 } 1554 } 1555 newspec[ii] /= wsum ; 1556 wsum = 0.0 ; 1557 } 1558 } 1559 else if ( dnu < 0.0 ) { 1560 for ( int ii = 0 ; ii < nChan ; ii++ ) { 1561 double zl = zi[ii] ; 1562 double zr = zi[ii+1] ; 1563 for ( int j = ichan ; j < oldsize ; j++ ) { 1564 double yl = yi[j] ; 1565 double yr = yi[j+1] ; 1566 if ( yl >= zl ) { 1567 if ( yr >= zl ) { 1568 continue ; 1569 } 1570 else if ( yr >= zr ) { 1571 newspec[ii] += oldspec[j] * abs( yr - zl ) ; 1572 newflag[ii] = newflag[ii] || oldflag[j] ; 1573 wsum += abs( yr - zl ) ; 1574 } 1575 else { 1576 newspec[ii] += oldspec[j] * abs( dnu ) ; 1577 newflag[ii] = newflag[ii] || oldflag[j] ; 1578 wsum += abs( dnu ) ; 1579 ichan = j ; 1580 break ; 1581 } 1582 } 1583 else if ( yl > zr ) { 1584 if ( yr >= zr ) { 1585 newspec[ii] += oldspec[j] * abs( yr - yl ) ; 1586 newflag[ii] = newflag[ii] || oldflag[j] ; 1587 wsum += abs( yr - yl ) ; 1588 } 1589 else { 1590 newspec[ii] += oldspec[j] * abs( zr - yl ) ; 1591 newflag[ii] = newflag[ii] || oldflag[j] ; 1592 wsum += abs( zr - yl ) ; 1593 ichan = j ; 1594 break ; 1595 } 1596 } 1597 else { 1598 ichan = j - 1 ; 1599 break ; 1600 } 1601 } 1602 newspec[ii] /= wsum ; 1603 wsum = 0.0 ; 1604 } 1605 } 1606 // * ichan = 0 1607 // ***/ 1608 // //ofs << "olddnu = " << olddnu << ", dnu = " << dnu << endl ; 1609 // pile += dnu ; 1610 // wedge = olddnu * ( refChan + 1 ) ; 1611 // while ( wedge < pile ) { 1612 // newspec[0] += olddnu * oldspec[refChan] ; 1613 // newflag[0] = newflag[0] || oldflag[refChan] ; 1614 // //ofs << "channel " << refChan << " is included in new channel 0" << endl ; 1615 // refChan++ ; 1616 // wedge += olddnu ; 1617 // wsum += olddnu ; 1618 // //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ; 1619 // } 1620 // frac = ( wedge - pile ) / olddnu ; 1621 // wsum += ( 1.0 - frac ) * olddnu ; 1622 // newspec[0] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ; 1623 // newflag[0] = newflag[0] || oldflag[refChan] ; 1624 // //ofs << "channel " << refChan << " is partly included in new channel 0" << " with fraction of " << ( 1.0 - frac ) << endl ; 1625 // //ofs << "newspec[0] = " << newspec[0] << " wsum = " << wsum << endl ; 1626 // newspec[0] /= wsum ; 1627 // //ofs << "newspec[0] = " << newspec[0] << endl ; 1628 // //ofs << "wedge = " << wedge << ", pile = " << pile << endl ; 1629 1630 // /*** 1631 // * ichan = 1 - nChan-2 1632 // ***/ 1633 // for ( int ichan = 1 ; ichan < nChan - 1 ; ichan++ ) { 1634 // pile += dnu ; 1635 // newspec[ichan] += frac * olddnu * oldspec[refChan] ; 1636 // newflag[ichan] = newflag[ichan] || oldflag[refChan] ; 1637 // //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << frac << endl ; 1638 // refChan++ ; 1639 // wedge += olddnu ; 1640 // wsum = frac * olddnu ; 1641 // //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ; 1642 // while ( wedge < pile ) { 1643 // newspec[ichan] += olddnu * oldspec[refChan] ; 1644 // newflag[ichan] = newflag[ichan] || oldflag[refChan] ; 1645 // //ofs << "channel " << refChan << " is included in new channel " << ichan << endl ; 1646 // refChan++ ; 1647 // wedge += olddnu ; 1648 // wsum += olddnu ; 1649 // //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ; 1650 // } 1651 // frac = ( wedge - pile ) / olddnu ; 1652 // wsum += ( 1.0 - frac ) * olddnu ; 1653 // newspec[ichan] += ( 1.0 - frac ) * olddnu * oldspec[refChan] ; 1654 // newflag[ichan] = newflag[ichan] || oldflag[refChan] ; 1655 // //ofs << "channel " << refChan << " is partly included in new channel " << ichan << " with fraction of " << ( 1.0 - frac ) << endl ; 1656 // //ofs << "wedge = " << wedge << ", pile = " << pile << endl ; 1657 // //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << " wsum = " << wsum << endl ; 1658 // newspec[ichan] /= wsum ; 1659 // //ofs << "newspec[" << ichan << "] = " << newspec[ichan] << endl ; 1660 // } 1661 1662 // /*** 1663 // * ichan = nChan-1 1664 // ***/ 1665 // // NOTE: Assumed that all spectra have the same bandwidth 1666 // pile += dnu ; 1667 // newspec[nChan-1] += frac * olddnu * oldspec[refChan] ; 1668 // newflag[nChan-1] = newflag[nChan-1] || oldflag[refChan] ; 1669 // //ofs << "channel " << refChan << " is partly included in new channel " << nChan-1 << " with fraction of " << frac << endl ; 1670 // refChan++ ; 1671 // wedge += olddnu ; 1672 // wsum = frac * olddnu ; 1673 // //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ; 1674 // for ( int jchan = refChan ; jchan < oldsize ; jchan++ ) { 1675 // newspec[nChan-1] += olddnu * oldspec[jchan] ; 1676 // newflag[nChan-1] = newflag[nChan-1] || oldflag[jchan] ; 1677 // wsum += olddnu ; 1678 // //ofs << "channel " << jchan << " is included in new channel " << nChan-1 << " with fraction of " << frac << endl ; 1679 // //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ; 1680 // } 1681 // //ofs << "wedge = " << wedge << ", pile = " << pile << endl ; 1682 // //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << " wsum = " << wsum << endl ; 1683 // newspec[nChan-1] /= wsum ; 1684 // //ofs << "newspec[" << nChan - 1 << "] = " << newspec[nChan-1] << endl ; 1685 1686 // specCol_.put( irow, newspec ) ; 1687 // flagsCol_.put( irow, newflag ) ; 1688 1689 // // ofs.close() ; 1690 1691 1692 return ; 1693 } 1694 1144 1695 std::vector<float> Scantable::getWeather(int whichrow) const 1145 1696 { … … 1154 1705 1155 1706 } 1156 1707 //namespace asap -
branches/mergetest/src/Scantable.h
r1730 r1779 29 29 30 30 #include <coordinates/Coordinates/SpectralCoordinate.h> 31 32 #include <casa/Arrays/Vector.h> 33 #include <casa/Quanta/Quantum.h> 34 35 #include <casa/Exceptions/Error.h> 31 36 32 37 #include "Logger.h" … … 226 231 227 232 /** 233 * Flag the data in a row-based manner. (CAS-1433 Wataru Kawasaki) 234 * param[in] rows list of row numbers to be flagged 235 */ 236 void flagRow( const std::vector<casa::uInt>& rows = std::vector<casa::uInt>(), bool unflag=false); 237 238 /** 239 * Get flagRow info at the specified row. If true, the whole data 240 * at the row should be flagged. 241 */ 242 bool getFlagRow(int whichrow) const 243 { return (flagrowCol_(whichrow) > 0); } 244 245 /** 246 * Flag the data outside a specified range (in a channel-based manner). 247 * (CAS-1807 Wataru Kawasaki) 248 */ 249 void clip(const casa::Float uthres, const casa::Float dthres, bool clipoutside, bool unflag); 250 251 /** 252 * Return a list of booleans with the size of nchan for a specified row, to get info 253 * about which channel is clipped. 254 */ 255 std::vector<bool> getClipMask(int whichrow, const casa::Float uthres, const casa::Float dthres, bool clipoutside, bool unflag); 256 void srchChannelsToClip(casa::uInt whichrow, const casa::Float uthres, const casa::Float dthres, bool clipoutside, bool unflag, 257 casa::Vector<casa::uChar> flgs); 258 259 /** 228 260 * Return a list of row numbers with respect to the original table. 229 261 * @return a list of unsigned ints … … 276 308 std::vector<uint> getScanNos() const { return getNumbers(scanCol_); } 277 309 int getScan(int whichrow) const { return scanCol_(whichrow); } 310 311 //TT addition 312 std::vector<uint> getMolNos() {return getNumbers(mmolidCol_); } 278 313 279 314 /** … … 300 335 { return azCol_(whichrow); } 301 336 float getParAngle(int whichrow) const 302 { return focus().getParAngle(mfocusidCol_(whichrow)); } 337 { return focus().getParAngle(mfocusidCol_(whichrow)); } 338 int getTcalId(int whichrow) const 339 { return mtcalidCol_(whichrow); } 303 340 304 341 std::string getSourceName(int whichrow) const … … 353 390 std::vector<double> getRestFrequencies() const 354 391 { return moleculeTable_.getRestFrequencies(); } 355 392 std::vector<double> getRestFrequency(int id) const 393 { return moleculeTable_.getRestFrequency(id); } 394 395 /** 356 396 void setRestFrequencies(double rf, const std::string& name = "", 357 397 const std::string& = "Hz"); 358 void setRestFrequencies(const std::string& name); 398 **/ 399 // Modified by Takeshi Nakazato 05/09/2008 400 /*** 401 void setRestFrequencies(vector<double> rf, const vector<std::string>& name = "", 402 const std::string& = "Hz"); 403 ***/ 404 void setRestFrequencies(vector<double> rf, 405 const vector<std::string>& name = vector<std::string>(1,""), 406 const std::string& = "Hz"); 407 408 //void setRestFrequencies(const std::string& name); 409 void setRestFrequencies(const vector<std::string>& name); 359 410 360 411 void shift(int npix); … … 415 466 { focus().setParallactify(flag); } 416 467 468 /** 469 * Reshape spectrum 470 * @param[in] nmin, nmax minimum and maximum channel 471 * @param[in] irow row number 472 * 473 * 30/07/2008 Takeshi Nakazato 474 **/ 475 void reshapeSpectrum( int nmin, int nmax ) throw( casa::AipsError ); 476 void reshapeSpectrum( int nmin, int nmax, int irow ) ; 477 478 /** 479 * Change channel number under fixed bandwidth 480 * @param[in] nchan, dnu new channel number and spectral resolution 481 * @param[in] irow row number 482 * 483 * 27/08/2008 Takeshi Nakazato 484 **/ 485 void regridChannel( int nchan, double dnu ) ; 486 void regridChannel( int nchan, double dnu, int irow ) ; 487 488 417 489 private: 418 490 … … 489 561 casa::ScalarColumn<casa::Float> elCol_; 490 562 casa::ScalarColumn<casa::String> srcnCol_, fldnCol_; 491 casa::ScalarColumn<casa::uInt> scanCol_, beamCol_, ifCol_, polCol_, cycleCol_ ;563 casa::ScalarColumn<casa::uInt> scanCol_, beamCol_, ifCol_, polCol_, cycleCol_, flagrowCol_; 492 564 casa::ScalarColumn<casa::Int> rbeamCol_, srctCol_; 493 565 casa::ArrayColumn<casa::Float> specCol_, tsysCol_; … … 510 582 void initFactories(); 511 583 584 /** 585 * Add an auxiliary column to the main table and attach it to a 586 * cached column. Use for adding new columns that the original asap2 587 * tables do not have. 588 * @param[in] col reference to the cached column to be attached 589 * @param[in] colName column name in asap table 590 * @param[in] defValue default value to fill in the column 591 * 592 * 25/10/2009 Wataru Kawasaki 593 */ 594 template<class T, class T2> void attachAuxColumnDef(casa::ScalarColumn<T>&, 595 const casa::String&, 596 const T2&); 597 template<class T, class T2> void attachAuxColumnDef(casa::ArrayColumn<T>&, 598 const casa::String&, 599 const casa::Array<T2>&); 512 600 }; 513 601 -
branches/mergetest/src/ScantableWrapper.h
r1730 r1779 109 109 { table_->flag(msk, unflag); } 110 110 111 void flagRow(const std::vector<casa::uInt>& rows=std::vector<casa::uInt>(), bool unflag=false) 112 { table_->flagRow(rows, unflag); } 113 114 bool getFlagRow(int whichrow=0) const 115 { return table_->getFlagRow(whichrow); } 116 117 void clip(const casa::Float uthres, const casa::Float dthres, bool clipoutside=true, bool unflag=false) 118 { table_->clip(uthres, dthres, clipoutside, unflag); } 119 120 std::vector<bool> getClipMask(int whichrow, const casa::Float uthres, const casa::Float dthres, bool clipoutside, bool unflag) const 121 { return table_->getClipMask(whichrow, uthres, dthres, clipoutside, unflag); } 122 111 123 std::string getSourceName(int whichrow=0) const 112 124 { return table_->getSourceName(whichrow); } … … 134 146 std::vector<uint> getScanNos() { return table_->getScanNos(); } 135 147 int getScan(int whichrow) const {return table_->getScan(whichrow);} 148 std::vector<uint> getMolNos() { return table_->getMolNos();} 136 149 137 150 STSelector getSelection() const { return table_->getSelection(); } … … 158 171 { table_->shift(npix); } 159 172 173 /** 174 commented out by TT 160 175 void setRestFrequencies(double rf, const std::string& name, 161 176 const std::string& unit) 162 177 { table_->setRestFrequencies(rf, name, unit); } 178 **/ 179 void setRestFrequencies(vector<double> rf, const vector<std::string>& name, 180 const std::string& unit) 181 { table_->setRestFrequencies(rf, name, unit); } 182 163 183 /* 164 184 void setRestFrequencies(const std::string& name) { … … 167 187 */ 168 188 189 /* 169 190 std::vector<double> getRestFrequencies() const 170 191 { return table_->getRestFrequencies(); } 192 */ 193 std::vector<double> getRestFrequency(int id) const 194 { return table_->getRestFrequency(id); } 171 195 172 196 void setCoordInfo(std::vector<string> theinfo) { … … 209 233 int checkScanInfo(const vector<int>& scanlist) const 210 234 { return table_->checkScanInfo(scanlist); } 211 235 212 236 std::vector<double> getDirectionVector(int whichrow) const 213 237 { return table_->getDirectionVector(whichrow); } … … 222 246 std::vector<float> getWeather(int whichrow) const 223 247 { return table_->getWeather(whichrow); } 248 249 void reshapeSpectrum( int nmin, int nmax ) 250 { table_->reshapeSpectrum( nmin, nmax ); } 224 251 225 252 private: … … 229 256 } // namespace 230 257 #endif 258 -
branches/mergetest/src/python_STMath.cpp
r1391 r1779 49 49 .def("_averagebeams", &STMathWrapper::averageBeams) 50 50 .def("_unaryop", &STMathWrapper::unaryOperate) 51 .def("_arrayop", &STMathWrapper::arrayOperate) 52 //.def("_array2dop", &STMathWrapper::array2dOperate) 51 53 .def("_binaryop", &STMathWrapper::binaryOperate) 52 54 .def("_auto_quotient", &STMathWrapper::autoQuotient) … … 57 59 .def("_dofs", &STMathWrapper::dofs) 58 60 .def("_stats", &STMathWrapper::statistic) 61 .def("_minmaxchan", &STMathWrapper::minMaxChan) 59 62 .def("_freqswitch", &STMathWrapper::freqSwitch) 60 63 .def("_bin", &STMathWrapper::bin) … … 73 76 .def("_mx_extract", &STMathWrapper::mxExtract) 74 77 .def("_lag_flag", &STMathWrapper::lagFlag) 78 // testing average spectra with different channel/resolution 79 .def("_new_average", &STMathWrapper::new_average) 80 // cwcal 81 .def("cwcal", &STMathWrapper::cwcal) 82 .def("almacal", &STMathWrapper::almacal) 75 83 ; 76 84 }; -
branches/mergetest/src/python_STSelector.cpp
r939 r1779 29 29 .def("_getscans", &STSelector::getScans) 30 30 .def("_getcycles", &STSelector::getCycles) 31 .def("_gettypes", &STSelector::getTypes) 31 32 .def("_gettaql", &STSelector::getTaQL) 32 33 .def("_getorder", &STSelector::getSortOrder) … … 41 42 .def("_settaql", &STSelector::setTaQL) 42 43 .def("_setorder", &STSelector::setSortOrder) 44 .def("_setrows", &STSelector::setRows) 45 .def("_settypes", &STSelector::setTypes) 43 46 .def("_empty", &STSelector::empty) 44 47 ; -
branches/mergetest/src/python_Scantable.cpp
r1730 r1779 58 58 .def("getscannos", &ScantableWrapper::getScanNos) 59 59 .def("getcycle", &ScantableWrapper::getCycle) 60 .def("getmolnos", &ScantableWrapper::getMolNos) 60 61 .def("nif", &ScantableWrapper::nif, 61 62 (boost::python::arg("scanno")=-1) ) … … 87 88 .def("_getmask", &ScantableWrapper::getMask, 88 89 (boost::python::arg("whichrow")=0) ) 90 .def("_getclipmask", &ScantableWrapper::getClipMask, 91 (boost::python::arg("whichrow")=0) ) 89 92 .def("_gettsys", &ScantableWrapper::getTsys) 90 93 .def("_getsourcename", &ScantableWrapper::getSourceName, … … 103 106 (boost::python::arg("whichrow")=0) ) 104 107 .def("get_antennaname", &ScantableWrapper::getAntennaName) 105 .def("_flag", &ScantableWrapper::flag, 106 (boost::python::arg("unflag") = false) ) 108 .def("_flag", &ScantableWrapper::flag) 109 .def("_flag_row", &ScantableWrapper::flagRow) 110 .def("_getflagrow", &ScantableWrapper::getFlagRow, 111 (boost::python::arg("whichrow")=0) ) 112 .def("_clip", &ScantableWrapper::clip, 113 (boost::python::arg("clipoutside")=true, 114 boost::python::arg("unflag")=false) ) 107 115 .def("_save", &ScantableWrapper::makePersistent) 108 116 .def("_summary", &ScantableWrapper::summary, 109 117 (boost::python::arg("verbose")=true) ) 110 .def("_getrestfreqs", &ScantableWrapper::getRestFrequencies) 118 //.def("_getrestfreqs", &ScantableWrapper::getRestFrequencies) 119 .def("_getrestfreqs", &ScantableWrapper::getRestFrequency) 111 120 .def("_setrestfreqs", &ScantableWrapper::setRestFrequencies) 112 121 .def("shift_refpix", &ScantableWrapper::shift) … … 127 136 .def("get_coordinate", &ScantableWrapper::getCoordinate) 128 137 .def("_get_weather", &ScantableWrapper::getWeather) 138 .def("_reshape", &ScantableWrapper::reshapeSpectrum, 139 (boost::python::arg("nmin")=-1, 140 boost::python::arg("nmax")=-1) ) 129 141 ; 130 142 }; -
branches/mergetest/src/python_asap.cpp
r1777 r1779 75 75 asap::python::python_LineCatalog(); 76 76 asap::python::python_Logger(); 77 asap::python::python_LogSink();78 77 asap::python::python_STCoordinate(); 79 78 asap::python::python_STAtmosphere(); 79 asap::python::python_SrcType(); 80 80 81 81 #ifndef HAVE_LIBPYRAP -
branches/mergetest/src/python_asap.h
r1777 r1779 47 47 void python_LineCatalog(); 48 48 void python_Logger(); 49 void python_LogSink();50 49 void python_STCoordinate(); 51 50 void python_STAtmosphere(); 51 void python_SrcType(); 52 52 53 53 } // python
Note:
See TracChangeset
for help on using the changeset viewer.