Changes in trunk [1849:1949]
- Location:
- trunk
- Files:
-
- 19 added
- 2 deleted
- 73 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/Makefile
- Property svn:mergeinfo changed (with no actual effect on merging)
r1849 r1949 7 7 #for linux 8 8 PREFIX := $(word 1, $(CASAPATH))/$(word 2,$(CASAPATH)) 9 PYDIR := $(PREFIX)/python/2.5 9 PYTHONVER := $(shell $(shell make -s -f $(PREFIX)/makedefs VARS=PYTHONVER eval_vars) && echo $$PYTHONVER) 10 PYDIR := $(PREFIX)/python/$(PYTHONVER) 10 11 11 12 ifndef ASAPROOT 12 13 ASAPROOT := $(shell pwd) 13 14 endif 15 ATNFD := external-alma 16 PYRAPD := external/libpyrap 14 17 15 18 #PY := $(wildcard python/*.py) … … 27 30 module: 28 31 @if ( test -f getsvnrev.sh ) ; then /bin/bash getsvnrev.sh ; fi 32 @cd $(ASAPROOT)/$(PYRAPD); make 33 @cd $(ASAPROOT)/$(ATNFD); make 29 34 @cd $(ASAPROOT)/src; make 30 35 @cd $(ASAPROOT)/apps; make … … 38 43 @if ( test ! -d $(PYDIR)/asap ) ; then mkdir -p $(PYDIR)/asap ; fi 39 44 @if ( test ! -d $(PREFIX)/bin ) ; then mkdir -p $(PREFIX)/bin ; fi 45 @cd $(ASAPROOT)/$(ATNFD); make install 46 @cd $(ASAPROOT)/$(PYRAPD); make install 40 47 @for file in $(LIBS) ; do cp -f $$file $(PYDIR)/asap ; done 41 48 @for file in $(BINS) ; do cp -f $$file $(PREFIX)/bin ; done 42 49 @for file in $(PY) ; do cp -f $$file $(PYDIR)/asap ; done 43 @for file in $(APPS) ; do cp -f $$file $(PREFIX)/bin ; done44 50 @if ( test ! -d $(PREFIX)/share/asap ) ; then mkdir -p $(PREFIX)/share/asap ; fi 45 51 @cp -f share/ipythonrc-asap $(PREFIX)/share/asap/ 52 @for file in $(APPS) ; do cp -f $$file $(PREFIX)/bin ; done 46 53 @echo "Successfully installed asap module to" $(PYDIR) 47 54 48 55 clean: 49 56 @cd $(ASAPROOT)/src; make clean 50 @cd $(ASAPROOT)/doc; make clean 57 # @cd $(ASAPROOT)/doc; make clean 58 @cd $(ASAPROOT)/$(ATNFD); make realclean 59 @cd $(ASAPROOT)/apps; make clean 60 @cd $(ASAPROOT)/$(PYRAPD); make clean 51 61 52 62 datadist: -
trunk/SConstruct
- Property svn:mergeinfo changed (with no actual effect on merging)
r1849 r1949 4 4 import platform 5 5 import SCons 6 7 # try to autodetect numpy 8 def get_numpy_incdir(): 9 try: 10 # try to find an egg 11 from pkg_resources import require 12 tmp = require("numpy") 13 import numpy 14 return numpy.__path__[0]+"/core/include" 15 except Exception: 16 # now try standard package 17 try: 18 import numpy 19 return numpy.__path__[0]+"/core/include" 20 except ImportError: 21 pass 22 return "" 6 23 7 24 moduledir = distutils.sysconfig.get_python_lib() … … 58 75 ("pyraproot", "The root directory where libpyrap is installed", 59 76 None), 77 ("numpyincdir", "numpy header file directory", 78 get_numpy_incdir()), 60 79 ("pyraplib", "The name of the pyrap library", "pyrap"), 61 80 ("pyraplibdir", "The directory where libpyrap is installed", … … 128 147 129 148 conf.env.AddCustomPackage('pyrap') 130 if conf.env.get("enable_pyrap") and conf.CheckLib(conf.env["pyraplib"], 131 language='c++', 132 autoadd=0): 133 conf.env.Append(CPPFLAGS=['-DHAVE_PYRAP']) 149 if conf.CheckLib(conf.env["pyraplib"], language='c++', autoadd=0): 150 conf.env.Append(CPPFLAGS=['-DHAVE_LIBPYRAP']) 134 151 conf.env.PrependUnique(LIBS=env['pyraplib']) 135 152 else: 153 conf.env.AppendUnique(CPPPATH=[conf.env["numpyincdir"]]) 154 # numpy 1.0 uses config.h; numpy >= 1.1 uses numpyconfig.h 155 if conf.CheckHeader("numpy/config.h") or \ 156 conf.CheckHeader("numpy/numpyconfig.h"): 157 conf.env.Append(CPPDEFINES=["-DAIPS_USENUMPY"]) 158 else: 159 conf.env.Exit(1) 160 conf.env.Append(CPPFLAGS=['-DHAVE_LIBPYRAP']) 161 # compile in pyrap here... 162 conf.env["pyrapint"] = "#/external/libpyrap/pyrap-0.3.2" 136 163 # test for cfitsio 137 164 if not conf.CheckLib("m"): Exit(1) -
trunk/apps
- Property svn:mergeinfo changed (with no actual effect on merging)
-
trunk/apps/Makefile
r1849 r1949 8 8 CASAARCH := $(word 2, $(CASAPATH)) 9 9 10 CORELIB := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=CORELIB eval_vars) && echo $$CORELIB) 10 11 COREINCD := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=COREINCD eval_vars) && echo $$COREINCD) 11 12 CASALIB := $(CASAROOT)/$(CASAARCH)/lib … … 17 18 18 19 # compiler flags 19 CXXFLAGS := -fPIC -O3 -g 20 CXXFLAGS += -ansi -Wno-long-long -Wall 21 CXXFLAGS := -Xlinker -rpath -Xlinker $(CASALIB) 20 CXXFLAGS := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=CXXFLAGS eval_vars) && echo $$CXXFLAGS) 21 CXXFLAGS += -fPIC -O3 -Xlinker -rpath -Xlinker $(CASALIB) 22 22 23 23 24 24 INCDIRS := -I$(COREINCD) 25 LIBS := -L$(CASALIB) -lcasa_tables -lcasa_casa25 LIBS := -L$(CASALIB) $(CORELIB) 26 26 27 27 OBJECTS := asap2to3 -
trunk/apps/asap2to3.cpp
r1849 r1949 29 29 Int verid=tab.rwKeywordSet().fieldNumber("VERSION"); 30 30 tab.rwKeywordSet().define(verid,uInt(3)); 31 tab.tableInfo().setType("Scantable"); 31 32 cout << "WARNING: This has invalidated the parallactic angle in the data. Reprocess the data in ASAP 3 " 32 33 << "if you need to handle polarisation conversions" -
trunk/external-alma
- Property svn:mergeinfo changed
/branches/asap4casa3.1.0/external-alma (added) merged: 1940
- Property svn:mergeinfo changed
-
trunk/external-alma/atnf/PKSIO/ASTEDataset.cc
r1849 r1949 124 124 + sizeof( char ) * 116 // CDMY1 125 125 + sizeof( double ) * ASTE_ARYMAX ; // DSBFC 126 127 refFreq_.resize( ASTE_ARYMAX, 0.0 ) ; 126 128 } 127 129 -
trunk/external-alma/atnf/PKSIO/ASTEFXDataset.cc
r1849 r1949 124 124 + sizeof( char ) * 116 // CDMY1 125 125 + sizeof( double ) * ASTE_ARYMAX_FX ; // DSBFC 126 127 refFreq_.resize( ASTE_ARYMAX_FX, 0.0 ) ; 126 128 } 127 129 -
trunk/external-alma/atnf/PKSIO/ASTEReader.cc
r1849 r1949 88 88 // Ref.: Ezawa, H. et al. 2004, Proc. SPIE, 5489, 763 89 89 // 90 double elon = -67. - 42. / 60. - 11. / 3600. ; 91 double nlat = -22. - 58. / 60. - 18. / 3600. ; 92 double alti = 2400. ; 90 // double elon = -67. - 42. / 60. - 11. / 3600. ; 91 // double nlat = -22. - 58. / 60. - 18. / 3600. ; 92 // double alti = 2400. ; 93 double elon = -67.7031 ; 94 double nlat = -22.9717 ; 95 double alti = 4800.0 ; 93 96 94 97 // APEX value … … 101 104 Quantity( nlat, "deg" ) ), 102 105 MPosition::Ref( MPosition::WGS84 ) ) ; 106 103 107 MeasFrame frame( p ) ; 104 108 MVPosition mvp ; -
trunk/external-alma/atnf/PKSIO/MBFITSreader.cc
r1849 r1949 146 146 if (rpfitsin(jstat)) { 147 147 sprintf(cMsg, "Failed to open MBFITS file\n%s", rpname); 148 os << LogIO::SEVERE << cMsg << LogIO::POST ;148 //os << LogIO::SEVERE << cMsg << LogIO::POST ; 149 149 return 1; 150 150 } … … 165 165 sprintf(cMsg, "Failed to read MBFITS header in file\n" 166 166 "%s", rpname); 167 os << LogIO::SEVERE << cMsg << LogIO::POST ;167 //os << LogIO::SEVERE << cMsg << LogIO::POST ; 168 168 close(); 169 169 return 1; -
trunk/external-alma/atnf/PKSIO/MBrecord.cc
r1849 r1949 37 37 38 38 #include <atnf/PKSIO/MBrecord.h> 39 #include <atnf/PKSIO/SrcType.h> 39 40 40 41 #include <string.h> … … 58 59 decRate = 0.0f; 59 60 nIF = 0; 61 62 srcType = SrcType::NOTYPE ; 63 srcVelocity = 0.0 ; 60 64 } 61 65 … … 325 329 srcVelocity = other.srcVelocity ; 326 330 331 srcType = other.srcType ; 332 327 333 return *this; 328 334 } … … 442 448 srcVelocity = other.srcVelocity ; 443 449 450 srcType = other.srcType ; 451 444 452 return 0; 445 453 } -
trunk/external-alma/atnf/PKSIO/MBrecord.h
r1849 r1949 167 167 // mode (added 1999/03/17). 168 168 int polNo ; // polarization ID 169 float srcVelocity ; // source velocity w.r.t. reference frame 169 double srcVelocity ; // source velocity w.r.t. reference frame 170 171 int srcType ; // source type 170 172 171 173 private: -
trunk/external-alma/atnf/PKSIO/NRO45Reader.cc
r1849 r1949 93 93 // (conversion is done by http://vldb.gsi.go.jp/sokuchi/tky2jgd/) 94 94 95 double elon = 138. + 28. / 60. + 9.96444 / 3600. ;96 double nlat = 35. + 56. / 60. + 52.3314 / 3600. ;97 double alti = 1350. ;95 // double elon = 138. + 28. / 60. + 9.96444 / 3600. ; 96 // double nlat = 35. + 56. / 60. + 52.3314 / 3600. ; 97 // double alti = 1350. ; 98 98 99 MPosition p( MVPosition( Quantity( alti, "m" ), 100 Quantity( elon, "deg" ), 101 Quantity( nlat, "deg" ) ), 102 MPosition::Ref( MPosition::WGS84 ) ) ; 99 // Double elon = 138.4725 ; 100 // Double nlat = 35.9445 ; 101 // Double alti = 1412.599 ; 102 103 // MPosition p( MVPosition( Quantity( alti, "m" ), 104 // Quantity( elon, "deg" ), 105 // Quantity( nlat, "deg" ) ), 106 // MPosition::Ref( MPosition::WGS84 ) ) ; 107 108 Double posx = -3.8710235e6 ; 109 Double posy = 3.4281068e6 ; 110 Double posz = 3.7240395e6 ; 111 MPosition p( MVPosition( posx, posy, posz ), 112 MPosition::ITRF ) ; 113 103 114 MeasFrame frame( p ) ; 104 115 MVPosition mvp ; -
trunk/external-alma/atnf/PKSIO/NRODataset.cc
r1849 r1949 34 34 #include <casa/OS/Time.h> 35 35 #include <scimath/Mathematics/InterpolateArray1D.h> 36 37 #include <measures/Measures/MeasConvert.h> 38 #include <measures/Measures/MCFrequency.h> 39 #include <measures/Measures/MFrequency.h> 40 #include <measures/Measures/MPosition.h> 41 #include <measures/Measures/MEpoch.h> 42 #include <measures/Measures/MDirection.h> 36 43 37 44 #include <math.h> … … 796 803 } 797 804 805 // conversion from TOPO to LSRK 806 v[1] = toLSR( v[1], getStartIntTime( i ), record_->SCX, record_->SCY ) ; 807 808 if ( refFreq_[ib] != 0.0 ) { 809 v[1] = refFreq_[ib] ; 810 } 811 else { 812 refFreq_[ib] = v[1] ; 813 } 814 798 815 return v ; 799 816 } … … 820 837 821 838 } 839 840 double NRODataset::toLSR( double v, double t, double x, double y ) 841 { 842 double vlsr ; 843 844 // get epoch 845 double tcent = t + 0.5*getIPTIM()/86400.0 ; 846 MEpoch me( Quantity( tcent, "d" ), MEpoch::UTC ) ; 847 848 // get antenna position 849 MPosition mp ; 850 if ( SITE.find( "45" ) != string::npos ) { 851 // 45m telescope 852 Double posx = -3.8710235e6 ; 853 Double posy = 3.4281068e6 ; 854 Double posz = 3.7240395e6 ; 855 mp = MPosition( MVPosition( posx, posy, posz ), 856 MPosition::ITRF ) ; 857 } 858 else { 859 // ASTE 860 Vector<Double> pos( 2 ) ; 861 pos[0] = -67.7031 ; 862 pos[1] = -22.9717 ; 863 Double sitealt = 4800.0 ; 864 mp = MPosition( MVPosition( Quantity( sitealt, "m" ), 865 Quantum< Vector<Double> >( pos, "deg" ) ), 866 MPosition::WGS84 ) ; 867 } 868 869 // get direction 870 MDirection md ; 871 if ( SCNCD == 0 ) { 872 // RADEC 873 if ( EPOCH == "B1950" ) { 874 md = MDirection( Quantity( Double(x), "rad" ), Quantity( Double(y), "rad" ), 875 MDirection::B1950 ) ; 876 } 877 else { 878 md = MDirection( Quantity( Double(x), "rad" ), Quantity( Double(y), "rad" ), 879 MDirection::J2000 ) ; 880 } 881 } 882 else if ( SCNCD == 1 ) { 883 // LB 884 md = MDirection( Quantity( Double(x), "rad" ), Quantity( Double(y), "rad" ), 885 MDirection::GALACTIC ) ; 886 } 887 else { 888 // AZEL 889 md = MDirection( Quantity( Double(x), "rad" ), Quantity( Double(y), "rad" ), 890 MDirection::AZEL ) ; 891 } 892 893 // to LSR 894 MeasFrame mf( me, mp, md ) ; 895 MFrequency::Convert tolsr( MFrequency::TOPO, MFrequency::Ref( MFrequency::LSRK, mf ) ) ; 896 vlsr = (double)(tolsr( Double(v) ).get( "Hz" ).getValue()) ; 897 898 return vlsr ; 899 } -
trunk/external-alma/atnf/PKSIO/NRODataset.h
r1849 r1949 233 233 void show() ; 234 234 235 // convert frequency frame 236 virtual double toLSR( double v, double t, double x, double y ) ; 237 235 238 // Type of file record 236 239 string LOFIL ; … … 506 509 // Logger 507 510 //LogIO os ; 511 512 // reference frequency for each array 513 vector<double> refFreq_ ; 508 514 } ; 509 515 -
trunk/external-alma/atnf/PKSIO/NROFITSDataset.cc
r1849 r1949 179 179 + sizeof( double ) * ARYNM * 10 * 3 // FQCAL, CHCAL, CWCAL 180 180 + sizeof( char ) * 180 ; // CDMY1 181 182 refFreq_.resize( ARYNM, 0.0 ) ; 181 183 } 182 184 … … 1165 1167 } 1166 1168 else { 1167 sprintf( record_->LAVST, "% d%d%d%d%d%d.000", itmp[0], itmp[1], itmp[2], itmp[3], itmp[4], itmp[5] ) ;1169 sprintf( record_->LAVST, "%4d%02d%02d%02d%02d%02d.000", itmp[0], itmp[1], itmp[2], itmp[3], itmp[4], itmp[5] ) ; 1168 1170 } 1169 1171 // DEBUG … … 1460 1462 // //cout << endl ; 1461 1463 // 1464 1465 1466 // Update IPTIM since it depends on the row for NROFITS 1467 int integ ; 1468 status = readTable( integ, "INTEG", same_, i ) ; 1469 if ( !status ) { 1470 IPTIM = (double)integ ; 1471 } 1472 1462 1473 return status ; 1463 1474 } … … 1513 1524 // debug 1514 1525 //cout << "i=" << i << endl ; 1515 if ( i == 16 ) {1516 ofstream ofs0( "spgrid0.dat" ) ;1517 for ( int ii = 0 ; ii < getNUMCH() ; ii++ )1518 ofs0 << xout[ii] << "," ;1519 ofs0 << endl ;1520 for ( int ii = 0 ; ii < getNUMCH() ; ii++ )1521 ofs0 << setprecision(16) << record->FREQ0+yout[ii] << "," ;1522 ofs0 << endl ;1523 ofs0.close() ;1524 }1526 // if ( i == 16 ) { 1527 // ofstream ofs0( "spgrid0.dat" ) ; 1528 // for ( int ii = 0 ; ii < getNUMCH() ; ii++ ) 1529 // ofs0 << xout[ii] << "," ; 1530 // ofs0 << endl ; 1531 // for ( int ii = 0 ; ii < getNUMCH() ; ii++ ) 1532 // ofs0 << setprecision(16) << record->FREQ0+yout[ii] << "," ; 1533 // ofs0 << endl ; 1534 // ofs0.close() ; 1535 // } 1525 1536 // 1526 1537 Vector<Double> z( nchan ) ; … … 2715 2726 return ib ; 2716 2727 } 2728 2729 double NROFITSDataset::getStartIntTime( int i ) 2730 { 2731 double v ; 2732 readTable( v, "MJDST", same_, i ) ; 2733 return v/86400.0 ; 2734 } 2735 2736 // double NROFITSDataset::toLSR( double v, double t, double x, double y ) 2737 // { 2738 // return v ; 2739 // } -
trunk/external-alma/atnf/PKSIO/NROFITSDataset.h
r1849 r1949 95 95 virtual int getPolarizationNum() ; 96 96 virtual uInt getArrayId( string type ) ; 97 virtual double getStartIntTime( int i ) ; 97 98 98 99 protected: … … 153 154 int getOffset( char *name ) ; 154 155 156 // convert frequency frame 157 // virtual double toLSR( double v, double t, double x, double y ) ; 158 155 159 // number of column for scan header 156 160 int numField_ ; -
trunk/external-alma/atnf/PKSIO/NROOTFDataset.cc
r1849 r1949 128 128 + sizeof( double ) * NRO_ARYMAX * 10 * 3 // FQCAL, CHCAL, CWCAL 129 129 + sizeof( char ) * 180 ; // CDMY1 130 131 refFreq_.resize( NRO_ARYMAX, 0.0 ) ; 130 132 } 131 133 -
trunk/external-alma/atnf/PKSIO/NROReader.cc
r1849 r1949 455 455 } 456 456 } 457 freqref = vref ; 458 // DEBUG 459 freqref = "TOPO" ; 460 // 457 //freqref = vref ; 458 freqref = "LSRK" ; 461 459 //cout << "freqref = " << freqref << endl ; 462 460 NRODataRecord *record = dataset_->getRecord( 0 ) ; -
trunk/external-alma/atnf/PKSIO/PKSFITSreader.cc
r1849 r1949 36 36 #include <atnf/PKSIO/MBFITSreader.h> 37 37 #include <atnf/PKSIO/SDFITSreader.h> 38 #include <atnf/PKSIO/GBTFITSreader.h> 38 39 #include <atnf/PKSIO/PKSFITSreader.h> 39 40 #include <atnf/PKSIO/PKSrecord.h> … … 58 59 if (fitsType == "SDFITS") { 59 60 cReader = new SDFITSreader(); 61 } else if (fitsType == "GBTFITS") { 62 cReader = new GBTFITSreader(); 60 63 } else { 61 64 cReader = new MBFITSreader(retry, interpolate ? 1 : 0); … … 429 432 } 430 433 } 434 435 pksrec.srcType = cMBrec.srcType ; 431 436 432 437 pksrec.srcDir.resize(2); -
trunk/external-alma/atnf/PKSIO/PKSMS2reader.cc
r1849 r1949 101 101 if ( antenna.length() == 0 ) { 102 102 cAntId.resize( 1 ) ; 103 cAntId[0] = 0 ; 103 //cAntId[0] = 0 ; 104 ROScalarColumn<Int> ant1Col( cPKSMS, "ANTENNA1" ) ; 105 cAntId[0] = ant1Col(0) ; 104 106 } 105 107 else { -
trunk/external-alma/atnf/PKSIO/PKSMS2writer.cc
r1849 r1949 732 732 // Extend the DATA_DESCRIPTION subtable. 733 733 while (Int(cDataDescription.nrow()) < IFno) { 734 cDataDescription.addRow( );734 cDataDescription.addRow(1,True); 735 735 } 736 736 Int n = IFno - 1; … … 966 966 { 967 967 // Extend the POLARIZATION subtable. 968 Int nr = cPolarization.nrow() ; 968 969 while (Int(cPolarization.nrow()) < IFno) { 969 cPolarization.addRow( );970 cPolarization.addRow(1,True); 970 971 } 971 972 Int n = IFno - 1; … … 985 986 corrType(1) = Stokes::YY; 986 987 } 988 // initialization 989 for ( Int i = nr ; i < n ; i++ ) 990 cPolarizationCols->corrType().put( i, corrType ) ; 987 991 cPolarizationCols->corrType().put(n, corrType); 988 992 … … 1092 1096 { 1093 1097 // Extend the SPECTRAL_WINDOW subtable. 1098 Int nr = cSpectralWindow.nrow() ; 1094 1099 while (Int(cSpectralWindow.nrow()) < IFno) { 1095 cSpectralWindow.addRow( );1100 cSpectralWindow.addRow(1,True); 1096 1101 } 1097 1102 Int n = IFno - 1; … … 1111 1116 freqs(i) = refFreq + (i - refChan)*freqInc; 1112 1117 } 1118 // initialization 1119 for ( Int i = nr ; i < n ; i++ ) 1120 cSpWindowCols->chanFreq().put( i, freqs ) ; 1113 1121 cSpWindowCols->chanFreq().put(n, freqs); 1114 1122 1115 1123 Vector<Double> chanWidths(nChan, freqInc); 1124 // initialization 1125 for ( Int i = nr ; i < n ; i++ ) { 1126 cSpWindowCols->chanWidth().put( i, chanWidths ) ; 1127 cSpWindowCols->effectiveBW().put( i, chanWidths ) ; 1128 } 1116 1129 cSpWindowCols->chanWidth().put(n, chanWidths); 1117 1130 … … 1120 1133 1121 1134 Vector<Double> resolution(nChan, fabs(freqInc)); 1135 // initialization 1136 for ( Int i = nr ; i < n ; i++ ) 1137 cSpWindowCols->resolution().put( i, resolution ) ; 1122 1138 cSpWindowCols->resolution().put(n, resolution); 1123 1139 -
trunk/external-alma/atnf/PKSIO/PKSreader.cc
r1849 r1949 81 81 buf[30] = '\0'; 82 82 if (String(buf) == "SIMPLE = T") { 83 // Looks like SDFITS. 84 format = "SDFITS"; 85 reader = new PKSFITSreader("SDFITS"); 86 83 file.seek(560); 84 file.read(26, buf, False); 85 buf[26] = '\0' ; 86 if ( String(buf) == "ORIGIN = 'NRAO Green Bank" ) { 87 // Looks like GBT SDFITS 88 format = "GBTFITS" ; 89 reader = new PKSFITSreader("GBTFITS") ; 90 } 91 else { 92 // Looks like SDFITS. 93 format = "SDFITS"; 94 reader = new PKSFITSreader("SDFITS"); 95 } 87 96 } else { 88 97 // Assume it's MBFITS. … … 93 102 94 103 } else if (inFile.isDirectory()) { 95 if (File(name + "/DATA_DESCRIPTION").exists()) { 104 Bool isMS = ( (File(name+"/table.info").exists()) 105 && File(name+"/table.dat").exists() ); 106 if (isMS) { 107 RegularFileIO ifs(name+"/table.info") ; 108 char buf[128] ; 109 ifs.read(sizeof(buf),buf,False) ; 110 if ( strstr( buf, "Measurement Set" ) == NULL ) 111 isMS = False ; 112 } 113 //if (File(name + "/DATA_DESCRIPTION").exists()) { 114 if (isMS) { 96 115 // MS version 2. 97 116 #ifdef NOPKSMS -
trunk/external-alma/atnf/pks/pks_maths.cc
- Property svn:mergeinfo changed (with no actual effect on merging)
-
trunk/getsvnrev.sh
- Property svn:mergeinfo changed (with no actual effect on merging)
-
trunk/python
- Property svn:mergeinfo changed
/branches/asap4casa3.1.0/python (added) merged: 1935-1936
- Property svn:mergeinfo changed
-
trunk/python/__init__.py
r1849 r1949 16 16 from asap.utils import _n_bools, _is_sequence_or_number, _to_list 17 17 18 19 18 if is_ipython(): 20 19 from ipysupport import * 21 20 22 # use rc parameter to enable/disable logging 23 asaplog.enable(rcParams['verbose']) 21 # Only use rcParams['verbose'] in standard asap cli mode 22 # not in scripts or casapy 23 if not is_asap_cli(): 24 rcParams['verbose'] = False 24 25 25 26 setup_env() … … 38 39 plotter = asapplotter(gui) 39 40 except ImportError: 40 asaplog.p ost( "Matplotlib not installed. No plotting available")41 print_log('WARN')41 asaplog.push( "Matplotlib not installed. No plotting available") 42 asaplog.post('WARN') 42 43 43 44 from selector import selector … … 51 52 from opacity import skydip 52 53 from opacity import model as opacity_model 54 from _asap import srctype 53 55 54 56 __date__ = '$Date$'.split()[1] -
trunk/python/asapfitter.py
r1849 r1949 1 1 import _asap 2 2 from asap.parameters import rcParams 3 from asap.logging import asaplog, print_log, print_log_dec3 from asap.logging import asaplog, asaplog_post_dec 4 4 from asap.utils import _n_bools, mask_and 5 5 … … 9 9 The fitting class for ASAP. 10 10 """ 11 12 11 def __init__(self): 13 12 """ … … 49 48 return 50 49 50 @asaplog_post_dec 51 51 def set_scan(self, thescan=None, mask=None): 52 52 """ … … 58 58 if not thescan: 59 59 msg = "Please give a correct scan" 60 if rcParams['verbose']: 61 #print msg 62 asaplog.push(msg) 63 print_log('ERROR') 64 return 65 else: 66 raise TypeError(msg) 60 raise TypeError(msg) 67 61 self.fitted = False 68 62 self.data = thescan … … 74 68 return 75 69 70 @asaplog_post_dec 76 71 def set_function(self, **kwargs): 77 72 """ … … 92 87 if kwargs.has_key('poly'): 93 88 self.fitfunc = 'poly' 89 self.fitfuncs = ['poly'] 94 90 n = kwargs.get('poly') 95 self.components = [n ]91 self.components = [n+1] 96 92 self.uselinear = False 97 93 elif kwargs.has_key('lpoly'): 98 94 self.fitfunc = 'poly' 95 self.fitfuncs = ['lpoly'] 99 96 n = kwargs.get('lpoly') 100 self.components = [n ]97 self.components = [n+1] 101 98 self.uselinear = True 102 99 elif kwargs.has_key('gauss'): … … 114 111 else: 115 112 msg = "Invalid function type." 116 if rcParams['verbose']: 117 #print msg 118 asaplog.push(msg) 119 print_log('ERROR') 120 return 121 else: 122 raise TypeError(msg) 113 raise TypeError(msg) 123 114 124 115 self.fitter.setexpression(self.fitfunc,n) … … 126 117 return 127 118 128 @ print_log_dec119 @asaplog_post_dec 129 120 def fit(self, row=0, estimate=False): 130 121 """ … … 146 137 or self.fitfunc is None: 147 138 msg = "Fitter not yet initialised. Please set data & fit function" 148 if rcParams['verbose']: 149 #print msg 150 asaplog.push(msg) 151 print_log('ERROR') 152 return 153 else: 154 raise RuntimeError(msg) 139 raise RuntimeError(msg) 155 140 156 141 else: … … 172 157 if len(ps) == 0 or estimate: 173 158 self.fitter.estimate() 174 try: 175 fxdpar = list(self.fitter.getfixedparameters()) 176 if len(fxdpar) and fxdpar.count(0) == 0: 177 raise RuntimeError,"No point fitting, if all parameters are fixed." 178 if self.uselinear: 179 converged = self.fitter.lfit() 180 else: 181 converged = self.fitter.fit() 182 if not converged: 183 raise RuntimeError,"Fit didn't converge." 184 except RuntimeError, msg: 185 if rcParams['verbose']: 186 #print msg 187 print_log() 188 asaplog.push(str(msg)) 189 print_log('ERROR') 190 else: 191 raise 159 fxdpar = list(self.fitter.getfixedparameters()) 160 if len(fxdpar) and fxdpar.count(0) == 0: 161 raise RuntimeError,"No point fitting, if all parameters are fixed." 162 if self.uselinear: 163 converged = self.fitter.lfit() 164 else: 165 converged = self.fitter.fit() 166 if not converged: 167 raise RuntimeError,"Fit didn't converge." 192 168 self._fittedrow = row 193 169 self.fitted = True 194 print_log()195 170 return 196 171 … … 221 196 self.data._addfit(fit,self._fittedrow) 222 197 223 @ print_log_dec198 @asaplog_post_dec 224 199 def set_parameters(self,*args,**kwargs): 225 200 """ … … 229 204 fixed: a vector of which parameters are to be held fixed 230 205 (default is none) 231 component: in case of multiple gaussians , the index of the232 component206 component: in case of multiple gaussians/lorentzians, 207 the index of the component 233 208 """ 234 209 component = None … … 244 219 if self.fitfunc is None: 245 220 msg = "Please specify a fitting function first." 246 if rcParams['verbose']: 247 #print msg 248 asaplog.push(msg) 249 print_log('ERROR') 250 return 251 else: 252 raise RuntimeError(msg) 221 raise RuntimeError(msg) 253 222 if (self.fitfunc == "gauss" or self.fitfunc == 'lorentz') and component is not None: 254 223 if not self.fitted and sum(self.fitter.getparameters()) == 0: … … 266 235 if fixed is not None: 267 236 self.fitter.setfixedparameters(fixed) 268 print_log()269 237 return 270 238 239 @asaplog_post_dec 271 240 def set_gauss_parameters(self, peak, centre, fwhm, 272 241 peakfixed=0, centrefixed=0, … … 288 257 if self.fitfunc != "gauss": 289 258 msg = "Function only operates on Gaussian components." 290 if rcParams['verbose']: 291 #print msg 292 asaplog.push(msg) 293 print_log('ERROR') 294 return 295 else: 296 raise ValueError(msg) 259 raise ValueError(msg) 297 260 if 0 <= component < len(self.components): 298 261 d = {'params':[peak, centre, fwhm], … … 301 264 else: 302 265 msg = "Please select a valid component." 303 if rcParams['verbose']: 304 #print msg 305 asaplog.push(msg) 306 print_log('ERROR') 307 return 308 else: 309 raise ValueError(msg) 310 266 raise ValueError(msg) 267 268 @asaplog_post_dec 311 269 def set_lorentz_parameters(self, peak, centre, fwhm, 312 270 peakfixed=0, centrefixed=0, … … 316 274 Set the Parameters of a 'Lorentzian' component, set with set_function. 317 275 Parameters: 318 peak, centre, fwhm: The gaussian parameters276 peak, centre, fwhm: The lorentzian parameters 319 277 peakfixed, 320 278 centrefixed, … … 328 286 if self.fitfunc != "lorentz": 329 287 msg = "Function only operates on Lorentzian components." 330 if rcParams['verbose']: 331 #print msg 332 asaplog.push(msg) 333 print_log('ERROR') 334 return 335 else: 336 raise ValueError(msg) 288 raise ValueError(msg) 337 289 if 0 <= component < len(self.components): 338 290 d = {'params':[peak, centre, fwhm], … … 341 293 else: 342 294 msg = "Please select a valid component." 343 if rcParams['verbose']: 344 #print msg 345 asaplog.push(msg) 346 print_log('ERROR') 347 return 348 else: 349 raise ValueError(msg) 295 raise ValueError(msg) 350 296 351 297 def get_area(self, component=None): … … 378 324 return sum(areas) 379 325 326 @asaplog_post_dec 380 327 def get_errors(self, component=None): 381 328 """ … … 387 334 if not self.fitted: 388 335 msg = "Not yet fitted." 389 if rcParams['verbose']: 390 #print msg 391 asaplog.push(msg) 392 print_log('ERROR') 393 return 394 else: 395 raise RuntimeError(msg) 336 raise RuntimeError(msg) 396 337 errs = list(self.fitter.geterrors()) 397 338 cerrs = errs … … 403 344 return cerrs 404 345 346 347 @asaplog_post_dec 405 348 def get_parameters(self, component=None, errors=False): 406 349 """ … … 412 355 if not self.fitted: 413 356 msg = "Not yet fitted." 414 if rcParams['verbose']: 415 #print msg 416 asaplog.push(msg) 417 print_log('ERROR') 418 return 419 else: 420 raise RuntimeError(msg) 357 raise RuntimeError(msg) 421 358 pars = list(self.fitter.getparameters()) 422 359 fixed = list(self.fitter.getfixedparameters()) … … 444 381 area += [a for i in range(3)] 445 382 fpars = self._format_pars(cpars, cfixed, errors and cerrs, area) 446 if rcParams['verbose']: 447 #print fpars 448 asaplog.push(fpars) 449 print_log() 383 asaplog.push(fpars) 450 384 return {'params':cpars, 'fixed':cfixed, 'formatted': fpars, 451 385 'errors':cerrs} … … 481 415 return out 482 416 417 418 @asaplog_post_dec 483 419 def get_estimate(self): 484 420 """ … … 487 423 pars = self.fitter.getestimate() 488 424 fixed = self.fitter.getfixedparameters() 489 if rcParams['verbose']: 490 #print self._format_pars(pars,fixed,None) 491 asaplog.push(self._format_pars(pars,fixed,None)) 492 print_log() 425 asaplog.push(self._format_pars(pars,fixed,None,None)) 493 426 return pars 494 427 428 @asaplog_post_dec 495 429 def get_residual(self): 496 430 """ … … 499 433 if not self.fitted: 500 434 msg = "Not yet fitted." 501 if rcParams['verbose']: 502 #print msg 503 asaplog.push(msg) 504 print_log('ERROR') 505 return 506 else: 507 raise RuntimeError(msg) 435 raise RuntimeError(msg) 508 436 return self.fitter.getresidual() 509 437 438 @asaplog_post_dec 510 439 def get_chi2(self): 511 440 """ … … 514 443 if not self.fitted: 515 444 msg = "Not yet fitted." 516 if rcParams['verbose']: 517 #print msg 518 asaplog.push(msg) 519 print_log('ERROR') 520 return 521 else: 522 raise RuntimeError(msg) 445 raise RuntimeError(msg) 523 446 ch2 = self.fitter.getchi2() 524 if rcParams['verbose']: 525 #print 'Chi^2 = %3.3f' % (ch2) 526 asaplog.push( 'Chi^2 = %3.3f' % (ch2) ) 527 print_log() 447 asaplog.push( 'Chi^2 = %3.3f' % (ch2) ) 528 448 return ch2 529 449 450 @asaplog_post_dec 530 451 def get_fit(self): 531 452 """ … … 534 455 if not self.fitted: 535 456 msg = "Not yet fitted." 536 if rcParams['verbose']: 537 #print msg 538 asaplog.push(msg) 539 print_log('ERROR') 540 return 541 else: 542 raise RuntimeError(msg) 457 raise RuntimeError(msg) 543 458 return self.fitter.getfit() 544 459 545 @ print_log_dec460 @asaplog_post_dec 546 461 def commit(self): 547 462 """ … … 550 465 if not self.fitted: 551 466 msg = "Not yet fitted." 552 if rcParams['verbose']: 553 #print msg 554 asaplog.push(msg) 555 print_log('ERROR') 556 return 557 else: 558 raise RuntimeError(msg) 467 raise RuntimeError(msg) 559 468 from asap import scantable 560 469 if not isinstance(self.data, scantable): 561 470 msg = "Not a scantable" 562 if rcParams['verbose']: 563 #print msg 564 asaplog.push(msg) 565 print_log('ERROR') 566 return 567 else: 568 raise TypeError(msg) 471 raise TypeError(msg) 569 472 scan = self.data.copy() 570 473 scan._setspectrum(self.fitter.getresidual()) 571 print_log()572 474 return scan 573 475 574 @ print_log_dec476 @asaplog_post_dec 575 477 def plot(self, residual=False, components=None, plotparms=False, 576 478 filename=None): … … 671 573 if (not rcParams['plotter.gui']): 672 574 self._p.save(filename) 673 print_log() 674 675 @print_log_dec 575 576 @asaplog_post_dec 676 577 def auto_fit(self, insitu=None, plot=False): 677 578 """ … … 683 584 if not isinstance(self.data, scantable) : 684 585 msg = "Data is not a scantable" 685 if rcParams['verbose']: 686 #print msg 687 asaplog.push(msg) 688 print_log('ERROR') 689 return 690 else: 691 raise TypeError(msg) 586 raise TypeError(msg) 692 587 if insitu is None: insitu = rcParams['insitu'] 693 588 if not insitu: … … 725 620 self._p.unmap() 726 621 self._p = None 727 print_log()728 622 return scan -
trunk/python/asaplotbase.py
r1849 r1949 14 14 15 15 from asap.parameters import rcParams as asaprcParams 16 from asap.logging import asaplog , print_log16 from asap.logging import asaplog 17 17 18 18 # API change in mpl >= 0.98 … … 25 25 #print "Warning: matplotlib version < 0.87. This might cause errors. Please upgrade." 26 26 asaplog.push( "matplotlib version < 0.99. This might cause errors. Please upgrade." ) 27 print_log( 'WARN' )27 asaplog.post( 'WARN' ) 28 28 29 29 class asaplotbase: … … 417 417 fname = 'asap'+dstr+'.png' 418 418 419 d = ['png','.ps','eps' ]419 d = ['png','.ps','eps', 'svg'] 420 420 421 421 from os.path import expandvars … … 456 456 except IOError, msg: 457 457 #print 'Failed to save %s: Error msg was\n\n%s' % (fname, err) 458 print_log()458 asaplog.post() 459 459 asaplog.push('Failed to save %s: Error msg was\n\n%s' % (fname, str(msg))) 460 print_log( 'ERROR' )460 asaplog.post( 'ERROR' ) 461 461 return 462 462 else: … … 464 464 #print "'ps', 'eps', 'png'" 465 465 asaplog.push( "Invalid image type. Valid types are:" ) 466 asaplog.push( "'ps', 'eps', 'png' " )467 print_log('WARN')466 asaplog.push( "'ps', 'eps', 'png', 'svg'" ) 467 asaplog.post('WARN') 468 468 469 469 … … 669 669 for tick in self.subplots[i]['axes'].xaxis.majorTicks: 670 670 tick.label1On = False 671 self.subplots[i]['axes'].xaxis.label.set_visible(False)671 #self.subplots[i]['axes'].xaxis.label.set_visible(False) 672 672 if i%cols: 673 673 # Suppress y-labels for frames not in the left column. 674 674 for tick in self.subplots[i]['axes'].yaxis.majorTicks: 675 675 tick.label1On = False 676 self.subplots[i]['axes'].yaxis.label.set_visible(False)676 #self.subplots[i]['axes'].yaxis.label.set_visible(False) 677 677 # disable the first tick of [1:ncol-1] of the last row 678 678 #if i+1 < nplots: 679 679 # self.subplots[i]['axes'].xaxis.majorTicks[0].label1On = False 680 self.rows = rows 681 self.cols = cols 680 # set axes label state for interior subplots. 681 if i%cols: 682 self.subplots[i]['axes'].yaxis.label.set_visible(False) 683 if (i <= (rows-1)*cols - 1) and (i+cols < nplots): 684 self.subplots[i]['axes'].xaxis.label.set_visible(False) 685 self.rows = rows 686 self.cols = cols 682 687 self.subplot(0) 683 688 del rows,cols,n,nplots,layout,ganged,i 689 684 690 685 691 def tidy(self): … … 694 700 if i != 0: 695 701 ax.yaxis.majorTicks[-1].label1On = False 696 702 ## set axes label state for interior subplots. 703 #innerax=False 704 #if i%self.cols: 705 # ax.yaxis.label.set_visible(innerax) 706 #if (i <= (self.rows-1)*self.cols - 1) and (i+self.cols < nplots): 707 # ax.xaxis.label.set_visible(innerax) 708 697 709 698 710 def set_title(self, title=None): … … 733 745 sp['axes'].legend(tuple(lines), tuple(labels), 734 746 self.loc, prop=fp) 735 else:736 sp['axes'].legend((' '))747 #else: 748 # sp['axes'].legend((' ')) 737 749 738 750 from matplotlib.artist import setp -
trunk/python/asapmath.py
r1849 r1949 1 1 from asap.scantable import scantable 2 2 from asap.parameters import rcParams 3 from asap.logging import asaplog, print_log, print_log_dec3 from asap.logging import asaplog, asaplog_post_dec 4 4 from asap.selector import selector 5 5 from asap import asaplotgui 6 6 7 @ print_log_dec7 @asaplog_post_dec 8 8 def average_time(*args, **kwargs): 9 9 """ … … 67 67 if not isinstance(s,scantable): 68 68 msg = "Please give a list of scantables" 69 if rcParams['verbose']: 70 #print msg 71 asaplog.push(msg) 72 print_log('ERROR') 73 return 74 else: 75 raise TypeError(msg) 69 raise TypeError(msg) 76 70 if scanav: scanav = "SCAN" 77 71 else: scanav = "NONE" … … 96 90 s = scantable(stm._new_average(alignedlst, compel, mask, weight.upper(), scanav)) 97 91 s._add_history("average_time",varlist) 98 print_log() 92 99 93 return s 100 94 95 @asaplog_post_dec 101 96 def quotient(source, reference, preserve=True): 102 97 """ … … 119 114 s = scantable(stm._quotient(source, reference, preserve)) 120 115 s._add_history("quotient",varlist) 121 print_log()122 116 return s 123 117 124 @ print_log_dec118 @asaplog_post_dec 125 119 def dototalpower(calon, caloff, tcalval=0.0): 126 120 """ … … 138 132 s = scantable(stm._dototalpower(calon, caloff, tcalval)) 139 133 s._add_history("dototalpower",varlist) 140 print_log()141 134 return s 142 135 143 @ print_log_dec136 @asaplog_post_dec 144 137 def dosigref(sig, ref, smooth, tsysval=0.0, tauval=0.0): 145 138 """ … … 159 152 s = scantable(stm._dosigref(sig, ref, smooth, tsysval, tauval)) 160 153 s._add_history("dosigref",varlist) 161 print_log()162 154 return s 163 155 164 @ print_log_dec156 @asaplog_post_dec 165 157 def calps(scantab, scannos, smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False): 166 158 """ 167 159 Calibrate GBT position switched data 168 160 Adopted from GBTIDL getps 169 Currently calps identify the scans as position switched data if they170 contain '_ps' in the source name. The data must contains 'CAL' signal171 on/off in each integration. To identify 'CAL' on state, the word, 'calon'172 need to be present in the source name field.161 Currently calps identify the scans as position switched data if source 162 type enum is pson or psoff. The data must contains 'CAL' signal 163 on/off in each integration. To identify 'CAL' on state, the source type 164 enum of poncal and poffcal need to be present in the source name field. 173 165 (GBT MS data reading process to scantable automatically append these 174 166 id names to the source names) … … 184 176 tcalval: optional user specified Tcal (default is 0.0, 185 177 use Tcal value in the data) 178 verify: Verify calibration if true 186 179 """ 187 180 varlist = vars() … … 190 183 ## if s is None: 191 184 ## msg = "The input data appear to contain no position-switch mode data." 192 ## if rcParams['verbose']: 193 ## #print msg 194 ## asaplog.push(msg) 195 ## print_log('ERROR') 196 ## return 197 ## else: 198 ## raise TypeError(msg) 185 ## raise TypeError(msg) 199 186 s = scantab.copy() 200 187 from asap._asap import srctype … … 205 192 except Exception, e: 206 193 msg = "The input data appear to contain no position-switch mode data." 207 if rcParams['verbose']: 208 #print msg 209 asaplog.push(msg) 210 print_log('ERROR') 211 return 212 else: 213 raise TypeError(msg) 194 raise TypeError(msg) 214 195 s.set_selection() 215 196 sel.reset() … … 217 198 if ssub is None: 218 199 msg = "No data was found with given scan numbers!" 219 if rcParams['verbose']: 220 #print msg 221 asaplog.push(msg) 222 print_log('ERROR') 223 return 224 else: 225 raise TypeError(msg) 200 raise TypeError(msg) 226 201 #ssubon = ssub.get_scan('*calon') 227 202 #ssuboff = ssub.get_scan('*[^calon]') … … 238 213 if ssubon.nrow() != ssuboff.nrow(): 239 214 msg = "mismatch in numbers of CAL on/off scans. Cannot calibrate. Check the scan numbers." 240 if rcParams['verbose']: 241 #print msg 242 asaplog.push(msg) 243 print_log('ERROR') 244 return 245 else: 246 raise TypeError(msg) 215 raise TypeError(msg) 247 216 cals = dototalpower(ssubon, ssuboff, tcalval) 248 217 #sig = cals.get_scan('*ps') … … 260 229 if sig.nscan() != ref.nscan(): 261 230 msg = "mismatch in numbers of on/off scans. Cannot calibrate. Check the scan numbers." 262 if rcParams['verbose']: 263 #print msg 264 asaplog.push(msg) 265 print_log('ERROR') 266 return 267 else: 268 raise TypeError(msg) 231 raise TypeError(msg) 269 232 270 233 #for user supplied Tsys … … 272 235 if tauval<=0.0: 273 236 msg = "Need to supply a valid tau to use the supplied Tsys" 274 if rcParams['verbose']: 275 #print msg 276 asaplog.push(msg) 277 print_log('ERROR') 278 return 279 else: 280 raise TypeError(msg) 237 raise TypeError(msg) 281 238 else: 282 239 sig.recalc_azel() 283 240 ref.recalc_azel() 284 241 #msg = "Use of user specified Tsys is not fully implemented yet." 285 #if rcParams['verbose']: 286 # print msg 287 # return 288 #else: 289 # raise TypeError(msg) 242 #raise TypeError(msg) 290 243 # use get_elevation to get elevation and 291 244 # calculate a scaling factor using the formula … … 355 308 del sel 356 309 # plot 357 print_log()310 asaplog.post() 358 311 asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.') 359 print_log('WARN')312 asaplog.post('WARN') 360 313 p=asaplotgui.asaplotgui() 361 314 #nr=min(6,len(ifnos)*len(polnos)) … … 384 337 btics.append(b) 385 338 else: 386 print_log()339 asaplog.post() 387 340 asaplog.push('Only first 6 [if,pol] pairs are plotted.') 388 print_log('WARN')341 asaplog.post('WARN') 389 342 nr=6 390 343 for i in range(2*nr): … … 442 395 ### 443 396 ress._add_history("calps", varlist) 444 print_log()445 397 return ress 446 398 447 @ print_log_dec399 @asaplog_post_dec 448 400 def calnod(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False): 449 401 """ … … 458 410 tauval: optional user specified tau value (not implemented yet) 459 411 tcalval: optional user specified Tcal value 412 verify: Verify calibration if true 460 413 """ 461 414 varlist = vars() … … 469 422 ## if s is None: 470 423 ## msg = "The input data appear to contain no Nod observing mode data." 471 ## if rcParams['verbose']: 472 ## #print msg 473 ## asaplog.push(msg) 474 ## print_log('ERROR') 475 ## return 476 ## else: 477 ## raise TypeError(msg) 424 ## raise TypeError(msg) 478 425 s = scantab.copy() 479 426 sel = selector() … … 483 430 except Exception, e: 484 431 msg = "The input data appear to contain no Nod observing mode data." 485 if rcParams['verbose']: 486 #print msg 487 asaplog.push(msg) 488 print_log('ERROR') 489 return 490 else: 491 raise TypeError(msg) 432 raise TypeError(msg) 492 433 sel.reset() 493 434 del sel … … 511 452 #if len(scannos)>2: 512 453 # msg = "calnod can only process a pair of nod scans at time." 513 # if rcParams['verbose']: 514 # print msg 515 # return 516 # else: 517 # raise TypeError(msg) 454 # raise TypeError(msg) 518 455 # 519 456 #if len(scannos)==2: … … 525 462 if tauval<=0.0: 526 463 msg = "Need to supply a valid tau to use the supplied Tsys" 527 if rcParams['verbose']: 528 #print msg 529 asaplog.push(msg) 530 print_log('ERROR') 531 return 532 else: 533 raise TypeError(msg) 464 raise TypeError(msg) 534 465 else: 535 466 scantab.recalc_azel() … … 596 527 del sel 597 528 # plot 598 print_log()529 asaplog.post() 599 530 asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.') 600 print_log('WARN')531 asaplog.post('WARN') 601 532 p=asaplotgui.asaplotgui() 602 533 #nr=min(6,len(ifnos)*len(polnos)) … … 625 556 btics.append(b) 626 557 else: 627 print_log()558 asaplog.post() 628 559 asaplog.push('Only first 6 [if,pol] pairs are plotted.') 629 print_log('WARN')560 asaplog.post('WARN') 630 561 nr=6 631 562 for i in range(2*nr): … … 683 614 ### 684 615 resspec._add_history("calnod",varlist) 685 print_log()686 616 return resspec 687 617 688 @ print_log_dec618 @asaplog_post_dec 689 619 def calfs(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False): 690 620 """ 691 621 Calibrate GBT frequency switched data. 692 622 Adopted from GBTIDL getfs. 693 Currently calfs identify the scans as frequency switched data if they694 contain '_fs' in the source name. The data must contains 'CAL' signal695 on/off in each integration. To identify 'CAL' on state, the word, 'calon'696 need to be present in the source name field.623 Currently calfs identify the scans as frequency switched data if source 624 type enum is fson and fsoff. The data must contains 'CAL' signal 625 on/off in each integration. To identify 'CAL' on state, the source type 626 enum of foncal and foffcal need to be present in the source name field. 697 627 (GBT MS data reading via scantable automatically append these 698 628 id names to the source names) … … 706 636 use Tsys in the data) 707 637 tauval: optional user specified Tau 638 verify: Verify calibration if true 708 639 """ 709 640 varlist = vars() … … 716 647 # if check is None: 717 648 # msg = "The input data appear to contain no Nod observing mode data." 718 # if rcParams['verbose']: 719 # print msg 720 # return 721 # else: 722 # raise TypeError(msg) 649 # raise TypeError(msg) 723 650 s = scantab.get_scan(scannos) 724 651 del scantab … … 812 739 del sel 813 740 # plot 814 print_log()741 asaplog.post() 815 742 asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.') 816 print_log('WARN')743 asaplog.post('WARN') 817 744 p=asaplotgui.asaplotgui() 818 745 #nr=min(6,len(ifnos)*len(polnos)) … … 821 748 btics=[] 822 749 if nr>3: 823 print_log()750 asaplog.post() 824 751 asaplog.push('Only first 3 [if,pol] pairs are plotted.') 825 print_log('WARN')752 asaplog.post('WARN') 826 753 nr=3 827 754 p.set_panels(rows=nr,cols=3,nplots=3*nr,ganged=False) … … 891 818 ### 892 819 resspec._add_history("calfs",varlist) 893 print_log()894 820 return resspec 895 821 896 @ print_log_dec822 @asaplog_post_dec 897 823 def merge(*args): 898 824 """ … … 921 847 if not isinstance(s,scantable): 922 848 msg = "Please give a list of scantables" 923 if rcParams['verbose']: 924 #print msg 925 asaplog.push(msg) 926 print_log('ERROR') 927 return 928 else: 929 raise TypeError(msg) 849 raise TypeError(msg) 930 850 s = scantable(stm._merge(lst)) 931 851 s._add_history("merge", varlist) 932 print_log()933 852 return s 934 853 854 @asaplog_post_dec 935 855 def calibrate( scantab, scannos=[], calmode='none', verify=None ): 936 856 """ … … 946 866 if ( calmode == 'nod' ): 947 867 asaplog.push( 'Calibrating nod data.' ) 948 print_log()949 868 scal = calnod( scantab, scannos=scannos, verify=verify ) 950 869 elif ( calmode == 'quotient' ): 951 870 asaplog.push( 'Calibrating using quotient.' ) 952 print_log()953 871 scal = scantab.auto_quotient( verify=verify ) 954 872 elif ( calmode == 'ps' ): 955 873 asaplog.push( 'Calibrating %s position-switched data.' % antname ) 956 print_log()957 874 if ( antname.find( 'APEX' ) != -1 ): 958 875 scal = apexcal( scantab, scannos, calmode, verify ) … … 963 880 elif ( calmode == 'fs' or calmode == 'fsotf' ): 964 881 asaplog.push( 'Calibrating %s frequency-switched data.' % antname ) 965 print_log()966 882 if ( antname.find( 'APEX' ) != -1 ): 967 883 scal = apexcal( scantab, scannos, calmode, verify ) … … 972 888 elif ( calmode == 'otf' ): 973 889 asaplog.push( 'Calibrating %s On-The-Fly data.' % antname ) 974 print_log()975 890 scal = almacal( scantab, scannos, calmode, verify ) 976 891 else: … … 1015 930 return scal 1016 931 932 @asaplog_post_dec 1017 933 def splitant(filename, outprefix='',overwrite=False): 1018 934 """ … … 1032 948 """ 1033 949 # Import the table toolkit from CASA 1034 try: 1035 import casac 1036 except ImportError: 1037 if rcParams['verbose']: 1038 #print "failed to load casa" 1039 print_log() 1040 asaplog.push("failed to load casa") 1041 print_log('ERROR') 1042 else: raise 1043 return False 1044 try: 1045 tbtool = casac.homefinder.find_home_by_name('tableHome') 1046 tb = tbtool.create() 1047 tb2 = tbtool.create() 1048 except: 1049 if rcParams['verbose']: 1050 #print "failed to load a table tool:\n", e 1051 print_log() 1052 asaplog.push("failed to load table tool") 1053 print_log('ERROR') 1054 else: raise 1055 return False 950 import casac 951 from asap.scantable import is_ms 952 tbtool = casac.homefinder.find_home_by_name('tableHome') 953 tb = tbtool.create() 1056 954 # Check the input filename 1057 955 if isinstance(filename, str): … … 1061 959 if not os.path.exists(filename): 1062 960 s = "File '%s' not found." % (filename) 1063 if rcParams['verbose']:1064 print_log()1065 asaplog.push(s)1066 print_log('ERROR')1067 return1068 961 raise IOError(s) 1069 962 # check if input file is MS 1070 if not os.path.isdir(filename) \ 1071 or not os.path.exists(filename+'/ANTENNA') \ 1072 or not os.path.exists(filename+'/table.f1'): 963 #if not os.path.isdir(filename) \ 964 # or not os.path.exists(filename+'/ANTENNA') \ 965 # or not os.path.exists(filename+'/table.f1'): 966 if not is_ms(filename): 1073 967 s = "File '%s' is not a Measurement set." % (filename) 1074 if rcParams['verbose']:1075 print_log()1076 asaplog.push(s)1077 print_log('ERROR')1078 return1079 968 raise IOError(s) 1080 969 else: 1081 970 s = "The filename should be string. " 1082 if rcParams['verbose']:1083 print_log()1084 asaplog.push(s)1085 print_log('ERROR')1086 return1087 971 raise TypeError(s) 1088 972 # Check out put file name … … 1096 980 nant=tb.nrows() 1097 981 antnames=tb.getcol('NAME',0,nant,1) 1098 antpos=tb.getcol('POSITION',0,nant,1).transpose()1099 982 tb.close() 1100 983 tb.open(tablename=filename,nomodify=True) 1101 984 ant1=tb.getcol('ANTENNA1',0,-1,1) 1102 985 tb.close() 986 tmpname='asapmath.splitant.tmp' 1103 987 for antid in set(ant1): 1104 scan=scantable(filename,average=False,getpt=True,antenna=int(antid)) 988 tb.open(tablename=filename,nomodify=True) 989 tbsel=tb.query('ANTENNA1 == %s && ANTENNA2 == %s'%(antid,antid),tmpname) 990 scan=scantable(tmpname,average=False,getpt=True,antenna=int(antid)) 1105 991 outname=prefix+antnames[antid]+'.asap' 1106 992 scan.save(outname,format='ASAP',overwrite=overwrite) 993 tbsel.close() 994 tb.close() 995 del tbsel 1107 996 del scan 1108 997 outfiles.append(outname) 1109 del tb, tb2 998 os.system('rm -rf '+tmpname) 999 del tb 1110 1000 return outfiles 1111 1001 1002 @asaplog_post_dec 1112 1003 def _array2dOp( scan, value, mode="ADD", tsys=False ): 1113 1004 """ … … 1128 1019 del stm 1129 1020 elif len( value ) != nrow: 1130 asaplog.push( 'len(value) must be 1 or conform to scan.nrow()' ) 1131 print_log( 'ERROR' ) 1021 raise ValueError( 'len(value) must be 1 or conform to scan.nrow()' ) 1132 1022 else: 1133 1023 from asap._asap import stmath -
trunk/python/asapplotter.py
r1849 r1949 2 2 from asap.selector import selector 3 3 from asap.scantable import scantable 4 from asap.logging import asaplog, print_log, print_log_dec4 from asap.logging import asaplog, asaplog_post_dec 5 5 import matplotlib.axes 6 6 from matplotlib.font_manager import FontProperties … … 14 14 By default the plotter is set up to plot polarisations 15 15 'colour stacked' and scantables across panels. 16 Note: 16 17 .. note:: 18 17 19 Currenly it only plots 'spectra' not Tsys or 18 20 other variables. 21 19 22 """ 20 23 def __init__(self, visible=None , **kwargs): … … 48 51 self._fp = FontProperties() 49 52 self._panellayout = self.set_panellayout(refresh=False) 53 self._offset = None 54 self._rowcount = 0 55 self._panelcnt = 0 50 56 51 57 def _translate(self, instr): 52 keys = "s b i p t ".split()58 keys = "s b i p t r".split() 53 59 if isinstance(instr, str): 54 60 for key in keys: … … 78 84 else: return None 79 85 80 @ print_log_dec86 @asaplog_post_dec 81 87 def plot(self, scan=None): 82 88 """ … … 90 96 are consistent e.g. all 'channel' or all 'velocity' etc. 91 97 """ 98 self._rowcount = self._panelcnt = 0 92 99 if self._plotter.is_dead: 93 100 if hasattr(self._plotter.figmgr,'casabar'): … … 96 103 self._plotter.figmgr.casabar=self._newcasabar() 97 104 self._plotter.hold() 98 self._plotter.clear()105 #self._plotter.clear() 99 106 if not self._data and not scan: 100 107 msg = "Input is not a scantable" 101 if rcParams['verbose']:102 #print msg103 asaplog.push( msg )104 print_log( 'ERROR' )105 return106 108 raise TypeError(msg) 107 if scan: self.set_data(scan,refresh=False) 109 if scan: 110 self.set_data(scan, refresh=False) 108 111 self._plot(self._data) 109 112 if self._minmaxy is not None: … … 113 116 self._plotter.tidy() 114 117 self._plotter.show(hardrefresh=False) 115 print_log()116 118 return 117 119 … … 125 127 def create_mask(self, nwin=1, panel=0, color=None): 126 128 """ 127 Interactively define a mask. It retruns a mask that is equivalent to129 Interactively define a mask. It retruns a mask that is equivalent to 128 130 the one created manually with scantable.create_mask. 129 131 Parameters: … … 275 277 # end matplotlib.axes fowarding functions 276 278 279 @asaplog_post_dec 277 280 def set_data(self, scan, refresh=True): 278 281 """ … … 295 298 # reset 296 299 self._reset() 297 msg = "A new scantable is set to the plotter. The masks and data selections are reset." 300 msg = "A new scantable is set to the plotter. "\ 301 "The masks and data selections are reset." 298 302 asaplog.push( msg ) 299 print_log( 'INFO' )300 303 else: 301 304 self._data = scan … … 303 306 else: 304 307 msg = "Input is not a scantable" 305 if rcParams['verbose']:306 #print msg307 asaplog.push( msg )308 print_log( 'ERROR' )309 return310 308 raise TypeError(msg) 311 309 … … 318 316 if refresh: self.plot() 319 317 320 318 @asaplog_post_dec 321 319 def set_mode(self, stacking=None, panelling=None, refresh=True): 322 320 """ … … 341 339 if not self.set_panelling(panelling) or \ 342 340 not self.set_stacking(stacking): 343 if rcParams['verbose']: 344 #print msg 345 asaplog.push( msg ) 346 print_log( 'ERROR' ) 347 return 348 else: 349 raise TypeError(msg) 341 raise TypeError(msg) 342 if self._panelling == 'r': 343 self._stacking = '_r' 344 elif self._stacking == 'r': 345 self._panelling = '_r' 350 346 if refresh and self._data: self.plot(self._data) 351 347 return 352 348 353 349 def set_panelling(self, what=None): 350 """Set the 'panelling' mode i.e. which type of spectra should be 351 spread across different panels. 352 """ 353 354 354 mode = what 355 355 if mode is None: … … 359 359 self._panelling = md 360 360 self._title = None 361 if md == 'r': 362 self._stacking = '_r' 361 363 return True 362 364 return False … … 382 384 383 385 def set_stacking(self, what=None): 386 """Set the 'stacking' mode i.e. which type of spectra should be 387 overlayed. 388 """ 384 389 mode = what 385 390 if mode is None: … … 389 394 self._stacking = md 390 395 self._lmap = None 396 if md == 'r': 397 self._panelling = '_r' 391 398 return True 392 399 return False 393 400 394 def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True ):401 def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True, offset=None): 395 402 """ 396 403 Set the range of interest on the abcissa of the plot … … 400 407 replotted based on the new parameter setting(s). 401 408 Otherwise,the parameter(s) are set without replotting. 409 offset: shift the abcissa by the given amount. The abcissa label will 410 have '(relative)' appended to it. 402 411 Note: 403 412 These become non-sensical when the unit changes. … … 405 414 406 415 """ 416 self._offset = offset 407 417 if xstart is None and xend is None: 408 418 self._minmaxx = None … … 650 660 deltachan: the number of channels to include each side of the 651 661 line to determine a local maximum/minimum 652 rotate: the rotation (in degrees) )for the text label (default 90.0)662 rotate: the rotation (in degrees) for the text label (default 90.0) 653 663 location: the location of the line annotation from the 'top', 654 664 'bottom' or alternate (None - the default) … … 720 730 def save(self, filename=None, orientation=None, dpi=None): 721 731 """ 722 Save the plot to a file. The know formats are 'png', 'ps', 'eps'.732 Save the plot to a file. The known formats are 'png', 'ps', 'eps'. 723 733 Parameters: 724 734 filename: The name of the output file. This is optional … … 736 746 return 737 747 738 748 @asaplog_post_dec 739 749 def set_mask(self, mask=None, selection=None, refresh=True): 740 750 """ … … 754 764 if not self._data: 755 765 msg = "Can only set mask after a first call to plot()" 756 if rcParams['verbose']: 757 #print msg 758 asaplog.push( msg ) 759 print_log( 'ERROR' ) 760 return 761 else: 762 raise RuntimeError(msg) 766 raise RuntimeError(msg) 763 767 if len(mask): 764 768 if isinstance(mask, list) or isinstance(mask, tuple): … … 817 821 self._usermask = [] 818 822 self._usermaskspectra = None 823 self._offset = None 819 824 self.set_selection(None, False) 820 825 … … 822 827 savesel = scan.get_selection() 823 828 sel = savesel + self._selection 824 d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO', 825 'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME' } 826 order = [d0[self._panelling],d0[self._stacking]] 827 sel.set_order(order) 829 order = self._get_sortstring([self._panelling,self._stacking]) 830 if order: 831 sel.set_order(order) 828 832 scan.set_selection(sel) 829 833 d = {'b': scan.getbeam, 's': scan.getscan, 830 'i': scan.getif, 'p': scan.getpol, 't': scan._gettime } 834 #'i': scan.getif, 'p': scan.getpol, 't': scan._gettime, 835 'i': scan.getif, 'p': scan.getpol, 't': scan.get_time, 836 'r': int, '_r': int} 831 837 832 838 polmodes = dict(zip(self._selection.get_pols(), … … 839 845 if isinstance(nstack0, int): nstack = nstack0 840 846 else: nstack = len(nstack0) 847 nptot = n 841 848 maxpanel, maxstack = 16,16 842 if n > maxpanel or nstack > maxstack: 843 maxn = 0 844 if nstack > maxstack: maxn = maxstack 845 if n > maxpanel: maxn = maxpanel 846 msg ="Scan to be plotted contains more than %d selections.\n" \ 847 "Selecting first %d selections..." % (maxn, maxn) 849 if nstack > maxstack: 850 msg ="Scan to be overlayed contains more than %d selections.\n" \ 851 "Selecting first %d selections..." % (maxstack, maxstack) 848 852 asaplog.push(msg) 849 print_log('WARN') 850 n = min(n,maxpanel) 853 asaplog.post('WARN') 851 854 nstack = min(nstack,maxstack) 855 n = min(n,maxpanel) 856 852 857 if n > 1: 853 858 ganged = rcParams['plotter.ganged'] … … 865 870 # self._plotter.set_panels() 866 871 self._plotter.set_panels(layout=self._panellayout) 867 r=0 872 #r = 0 873 r = self._rowcount 868 874 nr = scan.nrow() 869 875 a0,b0 = -1,-1 … … 882 888 xlab = self._abcissa and self._abcissa[panelcount] \ 883 889 or scan._getabcissalabel() 890 if self._offset and not self._abcissa: 891 xlab += " (relative)" 884 892 ylab = self._ordinate and self._ordinate[panelcount] \ 885 893 or scan._get_ordinate_label() … … 887 895 self._plotter.set_axes('ylabel', ylab) 888 896 lbl = self._get_label(scan, r, self._panelling, self._title) 897 #if self._panelling == 'r': lbl = '' 889 898 if isinstance(lbl, list) or isinstance(lbl, tuple): 890 899 if 0 <= panelcount < len(lbl): … … 895 904 self._plotter.set_axes('title',lbl) 896 905 newpanel = True 897 stackcount = 0906 stackcount = 0 898 907 panelcount += 1 899 if (b > b0 or newpanel) and stackcount < nstack: 908 #if (b > b0 or newpanel) and stackcount < nstack: 909 if stackcount < nstack and (newpanel or (a == a0 and b > b0)): 900 910 y = [] 901 911 if len(polmodes): … … 908 918 if d[self._stacking](r) in self._maskselection[self._stacking]: 909 919 m = logical_and(m, self._usermask) 910 x = scan._getabcissa(r)911 920 from numpy import ma, array 921 x = array(scan._getabcissa(r)) 922 if self._offset: 923 x += self._offset 912 924 y = ma.masked_array(y,mask=logical_not(array(m,copy=False))) 913 925 if self._minmaxx is not None: … … 960 972 break 961 973 r+=1 # next row 974 ###-S 975 self._rowcount = r+1 976 self._panelcnt += panelcount 977 if self._plotter.figmgr.casabar: 978 if self._panelcnt >= nptot-1: 979 self._plotter.figmgr.casabar.disable_next() 980 else: 981 self._plotter.figmgr.casabar.enable_next() 982 #if self._panelcnt - panelcount > 0: 983 # self._plotter.figmgr.casabar.enable_prev() 984 #else: 985 # self._plotter.figmgr.casabar.disable_prev() 986 ###-E 962 987 #reset the selector to the scantable's original 963 988 scan.set_selection(savesel) … … 968 993 for o in self._plotter.figure.findobj(Text): 969 994 o.set_fontproperties(self._fp) 995 996 def _get_sortstring(self, lorders): 997 d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO', 998 'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME', 'r':None, '_r':None } 999 if not (type(lorders) == list) and not (type(lorders) == tuple): 1000 return None 1001 if len(lorders) > 0: 1002 lsorts = [] 1003 for order in lorders: 1004 ssort = d0[order] 1005 if ssort: 1006 lsorts.append(ssort) 1007 return lsorts 1008 return None 970 1009 971 1010 def set_selection(self, selection=None, refresh=True, **kw): … … 992 1031 raise TypeError("'selection' is not of type selector") 993 1032 994 d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO', 995 'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME' } 996 order = [d0[self._panelling],d0[self._stacking]] 997 self._selection.set_order(order) 1033 order = self._get_sortstring([self._panelling,self._stacking]) 1034 if order: 1035 self._selection.set_order(order) 998 1036 if refresh and self._data: self.plot(self._data) 999 1037 1000 1038 def _get_selected_n(self, scan): 1001 1039 d1 = {'b': scan.getbeamnos, 's': scan.getscannos, 1002 'i': scan.getifnos, 'p': scan.getpolnos, 't': scan.ncycle } 1040 'i': scan.getifnos, 'p': scan.getpolnos, 't': scan.ncycle, 1041 'r': scan.nrow, '_r': False} 1003 1042 d2 = { 'b': self._selection.get_beams(), 1004 1043 's': self._selection.get_scans(), 1005 1044 'i': self._selection.get_ifs(), 1006 1045 'p': self._selection.get_pols(), 1007 't': self._selection.get_cycles() } 1046 't': self._selection.get_cycles(), 1047 'r': False, '_r': 1} 1008 1048 n = d2[self._panelling] or d1[self._panelling]() 1009 1049 nstack = d2[self._stacking] or d1[self._stacking]() … … 1024 1064 'i': "IF"+str(scan.getif(row)), 1025 1065 'p': poleval, 1026 't': str(scan.get_time(row)) } 1066 't': str(scan.get_time(row)), 1067 'r': "row "+str(row), 1068 #'_r': str(scan.get_time(row))+",\nIF"+str(scan.getif(row))+", "+poleval+", Beam"+str(scan.getbeam(row)) } 1069 '_r': "" } 1027 1070 return userlabel or d[mode] 1028 1071 1029 1072 def plotazel(self, scan=None, outfile=None): 1030 #def plotazel(self):1031 1073 """ 1032 1074 plot azimuth and elevation versus time of a scantable 1033 1075 """ 1076 visible = rcParams['plotter.gui'] 1034 1077 from matplotlib import pylab as PL 1035 1078 from matplotlib.dates import DateFormatter, timezone … … 1037 1080 from matplotlib.ticker import MultipleLocator 1038 1081 from numpy import array, pi 1082 if not visible or not self._visible: 1083 PL.ioff() 1084 from matplotlib.backends.backend_agg import FigureCanvasAgg 1085 PL.gcf().canvas.switch_backends(FigureCanvasAgg) 1039 1086 self._data = scan 1040 1087 self._outfile = outfile … … 1046 1093 PL.clf() 1047 1094 # Adjust subplot layouts 1048 if len(self._panellayout) !=6: self.set_panellayout(refresh=False) 1095 if len(self._panellayout) != 6: 1096 self.set_panellayout(refresh=False) 1049 1097 lef, bot, rig, top, wsp, hsp = self._panellayout 1050 1098 PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top, … … 1126 1174 1127 1175 def plotpointing(self, scan=None, outfile=None): 1128 #def plotpointing(self):1129 1176 """ 1130 1177 plot telescope pointings 1131 1178 """ 1179 visible = rcParams['plotter.gui'] 1132 1180 from matplotlib import pylab as PL 1133 1181 from numpy import array, pi 1182 if not visible or not self._visible: 1183 PL.ioff() 1184 from matplotlib.backends.backend_agg import FigureCanvasAgg 1185 PL.gcf().canvas.switch_backends(FigureCanvasAgg) 1134 1186 self._data = scan 1135 1187 self._outfile = outfile … … 1141 1193 PL.clf() 1142 1194 # Adjust subplot layouts 1143 if len(self._panellayout) !=6: self.set_panellayout(refresh=False) 1195 if len(self._panellayout) != 6: 1196 self.set_panellayout(refresh=False) 1144 1197 lef, bot, rig, top, wsp, hsp = self._panellayout 1145 1198 PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top, … … 1162 1215 # plot total power data 1163 1216 # plotting in time is not yet implemented.. 1217 @asaplog_post_dec 1164 1218 def plottp(self, scan=None, outfile=None): 1165 1219 if self._plotter.is_dead: … … 1173 1227 if not self._data and not scan: 1174 1228 msg = "Input is not a scantable" 1175 if rcParams['verbose']:1176 #print msg1177 asaplog.push( msg )1178 print_log( 'ERROR' )1179 return1180 1229 raise TypeError(msg) 1181 1230 if isinstance(scan, scantable): … … 1207 1256 self._plotter.tidy() 1208 1257 self._plotter.show(hardrefresh=False) 1209 print_log()1210 1258 return 1211 1259 … … 1268 1316 1269 1317 # printing header information 1318 @asaplog_post_dec 1270 1319 def print_header(self, plot=True, fontsize=9, logger=False, selstr='', extrastr=''): 1271 1320 """ … … 1274 1323 plot: whether or not print header info on the plot. 1275 1324 fontsize: header font size (valid only plot=True) 1276 autoscale: whether or not autoscale the plot (valid only plot=True)1277 1325 logger: whether or not print header info on the logger. 1278 1326 selstr: additional selection string (not verified) 1279 1327 extrastr: additional string to print (not verified) 1280 1328 """ 1281 if not plot and not logger: return 1282 if not self._data: raise RuntimeError("No scantable has been set yet.") 1329 if not plot and not logger: 1330 return 1331 if not self._data: 1332 raise RuntimeError("No scantable has been set yet.") 1283 1333 # Now header will be printed on plot and/or logger. 1284 1334 # Get header information and format it. … … 1313 1363 asaplog.push(extrastr) 1314 1364 asaplog.push(ssum[ssum.find('Beams:'):]) 1315 print_log()1316 1365 del ssum -
trunk/python/casatoolbar.py
r1849 r1949 1 1 import os 2 2 import matplotlib 3 3 4 ###################################### 4 5 ## Add CASA custom toolbar ## … … 144 145 mymask.select_mask(once=True,showmask=False) 145 146 147 def _mod_note(self,event): 148 # Do not fire event when in zooming/panning mode 149 if not self.figmgr.toolbar.mode == '': 150 return 151 if event.button ==1: 152 self.notewin.load_textwindow(event) 153 elif event.button == 3 and self._note_picked(event): 154 self.notewin.load_modmenu(event) 155 return 156 157 def _note_picked(self,event): 158 # just briefly check if any texts are picked 159 for textobj in self.canvas.figure.texts: 160 if textobj.contains(event)[0]: 161 return True 162 for ax in self.canvas.figure.axes: 163 for textobj in ax.texts: 164 if textobj.contains(event)[0]: 165 return True 166 #print "No text picked" 167 return False 168 169 def _new_page(self,next=True): 170 self.plotter._plotter.hold() 171 #self.plotter._plotter.clear() 172 self.plotter._plot(self.plotter._data) 173 self.plotter._plotter.release() 174 self.plotter._plotter.tidy() 175 self.plotter._plotter.show(hardrefresh=False) 176 pass 177 146 178 ##################################### 147 179 ## Backend dependent Classes ## … … 150 182 if matplotlib.get_backend() == 'TkAgg': 151 183 import Tkinter as Tk 184 from notationwindow import NotationWindowTkAgg 152 185 153 186 class CustomToolbarTkAgg(CustomToolbarCommon, Tk.Frame): … … 164 197 self.button=True 165 198 self._add_custom_toolbar() 199 self.notewin=NotationWindowTkAgg(master=self.canvas) 166 200 CustomToolbarCommon.__init__(self,parent) 167 201 … … 174 208 text='statistics', 175 209 command=self.stat_cal) 210 self.bNote=self._NewButton(master=self, 211 text='notation', 212 command=self.modify_note) 213 #self.bPrev=self._NewButton(master=self, 214 # text='- page', 215 # command=self.prev_page) 216 self.bNext=self._NewButton(master=self, 217 text='+ page', 218 command=self.next_page) 219 if os.uname()[0] != 'Darwin': 220 #self.bPrev.config(padx=5) 221 self.bNext.config(padx=5) 176 222 self.bQuit=self._NewButton(master=self, 177 223 text='Quit', … … 198 244 self.bStat.config(relief='raised') 199 245 self.bSpec.config(relief='sunken') 246 self.bNote.config(relief='raised') 200 247 self.mode='spec' 248 self.notewin.close_widgets() 201 249 self.__disconnect_event() 202 250 #self.canvas.mpl_connect('button_press_event',self._select_spectrum) … … 209 257 self.bSpec.config(relief='raised') 210 258 self.bStat.config(relief='sunken') 259 self.bNote.config(relief='raised') 211 260 self.mode='stat' 261 self.notewin.close_widgets() 212 262 self.__disconnect_event() 213 263 self._p.register('button_press',self._single_mask) 264 265 def modify_note(self): 266 if not self.figmgr.toolbar.mode == '': return 267 self.figmgr.toolbar.set_message('text: select a position/text') 268 if self.mode == 'note': return 269 self.bSpec.config(relief='raised') 270 self.bStat.config(relief='raised') 271 self.bNote.config(relief='sunken') 272 self.mode='note' 273 self.__disconnect_event() 274 self._p.register('button_press',self._mod_note) 275 276 def prev_page(self): 277 self.figmgr.toolbar.set_message('plotting the previous page') 278 self._new_page(next=False) 279 280 def next_page(self): 281 self.figmgr.toolbar.set_message('plotting the next page') 282 self._new_page(next=True) 214 283 215 284 def quit(self): … … 230 299 self.bStat.config(relief='raised', state=Tk.DISABLED) 231 300 self.bSpec.config(relief='raised', state=Tk.DISABLED) 301 #self.bPrev.config(state=Tk.DISABLED) 302 #self.bNext.config(state=Tk.DISABLED) 232 303 self.button=False 233 304 self.mode='' 234 305 self.__disconnect_event() 306 307 def enable_next(self): 308 self.bNext.config(state=Tk.NORMAL) 309 310 def disable_next(self): 311 self.bNext.config(state=Tk.DISABLED) 312 313 def enable_prev(self): 314 #self.bPrev.config(state=Tk.NORMAL) 315 pass 316 317 def disable_prev(self): 318 #self.bPrev.config(state=Tk.DISABLED) 319 pass 235 320 236 321 def delete_bar(self): -
trunk/python/env.py
r1849 r1949 1 __all__ = ["is_casapy", "is_ipython", "setup_env", "get_revision"] 1 """This module has various functions for environment specific setings. 2 """ 3 __all__ = ["is_casapy", "is_ipython", "setup_env", "get_revision", 4 "is_asap_cli"] 2 5 3 6 import sys … … 7 10 8 11 def is_casapy(): 12 """Are we running inside casapy?""" 9 13 try: 10 14 from taskinit import casalog … … 14 18 15 19 def is_ipython(): 20 """Are we running inside IPython?""" 16 21 return 'IPython' in sys.modules.keys() 17 22 23 def is_asap_cli(): 24 """Are we running inside asap ipython (but not casapy)""" 25 return is_ipython() and not is_casapy() 26 18 27 def setup_env(): 28 """Set-up environment variables for casa and initialise ~/.asap on first 29 use. 30 """ 19 31 # Set up CASAPATH and first time use of asap i.e. ~/.asap/* 20 32 plf = None … … 59 71 60 72 def get_revision(): 73 """Get the revision of the software. Only useful within casapy.""" 61 74 if not is_casapy: 62 75 return ' unknown ' -
trunk/python/linecatalog.py
r1849 r1949 1 """ 1 """\ 2 2 A representation of a spectral line catalog. 3 4 Author: Malte Marquarding5 6 3 """ 7 4 __revision__ = "$Revision$" 8 5 from asap._asap import linecatalog as lcbase 9 from asap.parameters import rcParams10 6 from asap.logging import asaplog 11 7 import os 12 8 13 9 class linecatalog(lcbase): 14 """ 10 """\ 15 11 This class is a warpper for line catalogs. These can be either ASCII tables 16 12 or the tables saved from this class. 13 17 14 ASCII tables have the following restrictions: 18 Comments can be present through lines starting with '#'. 19 The first column contains the name of the Molecule. This can't contain spaces, 20 if it does it has to be wrapped in "" 21 The second column contains the frequency of the transition. 22 The third column contains the error in frequency. 23 The fourth column contains a value describing the intensity 15 16 * Comments can be present through lines starting with '#'. 17 18 * The first column contains the name of the Molecule. This can't contain 19 spaces, if it does it has to be wrapped in double-quotes. 20 21 * The second column contains the frequency of the transition. 22 23 * The third column contains the error in frequency. 24 25 * The fourth column contains a value describing the intensity. 26 24 27 """ 25 28 … … 30 33 else: 31 34 msg = "File '%s' not found" % fpath 32 if rcParams['verbose']: 33 #print msg 34 asaplog.push( msg ) 35 print_log( 'ERROR' ) 36 return 37 else: 38 raise IOError(msg) 35 raise IOError(msg) 39 36 40 37 def __repr__(self): … … 52 49 53 50 def set_name(self, name, mode="pattern"): 54 """ 51 """\ 55 52 Set a name restriction on the table. This can be a standard unix-style 56 53 pattern or a regular expression. 54 57 55 Parameters: 56 58 57 name: the name patterrn/regex 58 59 59 mode: the matching mode, i.e. "pattern" (default) or "regex" 60 60 61 """ 61 62 validmodes = "pattern regex".split() … … 65 66 66 67 def set_frequency_limits(self, fmin=1.0, fmax=120.0, unit="GHz"): 67 """ 68 """\ 68 69 Set frequency limits on the table. 70 69 71 Parameters: 72 70 73 fmin: the lower bound 74 71 75 fmax: the upper bound 76 72 77 unit: the frequency unit (default "GHz") 73 78 74 Note: 75 The underlying table conatins frequency values in MHz 79 .. note:: The underlying table contains frequency values in MHz 76 80 """ 77 81 base = { "GHz": 1000.0, "MHz": 1.0 } … … 82 86 83 87 def set_strength_limits(self, smin, smax): 84 """ 88 """\ 85 89 Set line strength limits on the table (arbitrary units) 90 86 91 Parameters: 92 87 93 smin: the lower bound 94 88 95 smax: the upper bound 96 89 97 """ 90 98 lcbase.set_strength_limits(self, smin, smax) 91 99 92 100 def save(self, name, overwrite=False): 93 """ 101 """\ 94 102 Save the subset of the table to disk. This uses an internal data format 95 103 and can be read in again. … … 99 107 if not overwrite: 100 108 msg = "File %s exists." % name 101 if rcParams['verbose']: 102 #print msg 103 asaplog.push( msg ) 104 print_log( 'ERROR' ) 105 return 106 else: 107 raise IOError(msg) 109 raise IOError(msg) 108 110 lcbase.save(self, name) 109 111 110 112 def reset(self): 111 """ 112 Reset the table to its initial state, i.e. undo all calls to set_113 """\ 114 Reset the table to its initial state, i.e. undo all calls to ``set_``. 113 115 """ 114 116 lcbase.reset(self) 115 117 116 118 def get_row(self, row=0): 119 """\ 120 Get the values in a specified row of the table. 121 122 Parameters: 123 124 row: the row to retrieve 125 117 126 """ 118 Get the values in a specified row of the table. 119 Parameters: 120 row: the row to retrieve 121 """ 127 if row < 0 or row > len(self)-1: 128 raise IndexError("Row index out of bounds.") 122 129 freq = lcbase.get_frequency(self, row) 123 130 name = lcbase.get_name(self, row) … … 128 135 129 136 def __getitem__(self, k): 130 if k < 0: k = self.nrow()-k 137 if k < 0: 138 k = self.nrow()-k 131 139 return self.get_row(k) -
trunk/python/logging.py
r1849 r1949 1 __all__ = ["asaplog", "print_log", "print_log_dec"] 1 """This module presents a logging abstraction layer on top of casa. 2 """ 3 __all__ = ["asaplog", "asaplog_post_dec", "AsapLogger"] 2 4 5 import inspect 3 6 from asap.env import is_casapy 4 7 from asap.parameters import rcParams … … 10 13 11 14 12 class _asaplog(object): 13 """Wrapper object to allow for both casapy and asap logging""" 15 class AsapLogger(object): 16 """Wrapper object to allow for both casapy and asap logging. 17 18 Inside casapy this will connect to `taskinit.casalog`. Otherwise it will 19 create its own casa log sink. 20 21 .. note:: Do instantiate a new one - use the :obj:`asaplog` instead. 22 23 """ 14 24 def __init__(self): 15 self._enabled = False25 self._enabled = True 16 26 self._log = "" 17 27 if is_casapy(): … … 22 32 set_global_sink(self.logger) 23 33 24 def post(self, level ):34 def post(self, level='INFO', origin=""): 25 35 """Post the messages to the logger. This will clear the buffered 26 36 logs. 37 38 Parameters: 39 40 level: The log level (severity). One of INFO, WARN, ERROR. 41 27 42 """ 28 43 if not self._enabled: 29 44 return 30 if not rcParams['verbose']:31 return32 45 46 if not origin: 47 origin = inspect.getframeinfo(inspect.currentframe().f_back)[2] 33 48 logs = self._log.strip() 34 49 if len(logs) > 0: 35 self.logger.post(logs, priority=level) 50 if isinstance(self.logger, LogSink): 51 #can't handle unicode in boost signature 52 logs = str(logs) 53 self.logger.post(logs, priority=level, origin=origin) 36 54 if isinstance(self.logger, LogSink): 37 55 logs = self.logger.pop().strip() … … 41 59 42 60 def push(self, msg, newline=True): 43 """Push logs into the buffer. post needs to be called to send them.""" 44 from asap import rcParams 61 """Push logs into the buffer. post needs to be called to send them. 62 63 Parameters: 64 65 msg: the log message (string) 66 67 newline: should we terminate with a newline (default yes) 68 69 """ 45 70 if self._enabled: 46 if rcParams["verbose"]: 47 sep = "" 48 self._log = sep.join([self._log, msg]) 49 if newline: 50 self._log += "\n" 71 sep = "" 72 self._log = sep.join([self._log, msg]) 73 if newline: 74 self._log += "\n" 51 75 52 76 def enable(self, flag=True): … … 58 82 self._enabled = flag 59 83 60 asaplog = _asaplog() 84 def is_enabled(self): 85 return self._enabled 61 86 62 def print_log_dec(f, level='INFO'): 87 asaplog = AsapLogger() 88 """Default asap logger""" 89 90 def asaplog_post_dec(f): 91 """Decorator which posts log at completion of the wrapped method. 92 93 Example:: 94 95 @asaplog_post_dec 96 def test(self): 97 do_stuff() 98 asaplog.push('testing...', False) 99 do_more_stuff() 100 asaplog.push('finished') 101 """ 63 102 @wraps_dec(f) 64 103 def wrap_it(*args, **kw): 65 val = f(*args, **kw) 66 print_log(level) 67 return val 104 level = "INFO" 105 try: 106 val = f(*args, **kw) 107 return val 108 except Exception, ex: 109 level = "ERROR" 110 asaplog.push(str(ex)) 111 if rcParams['verbose']: 112 pass 113 else: 114 raise 115 finally: 116 asaplog.post(level, f.func_name) 117 #asaplog.post(level, ".".join([f.__module__,f.func_name])) 68 118 return wrap_it 69 119 70 def print_log(level='INFO'):71 """Alias for asaplog.post."""72 asaplog.post(level) -
trunk/python/opacity.py
r1849 r1949 6 6 from asap.asapfitter import fitter 7 7 from asap.selector import selector 8 from asap.parameters import rcParams9 8 from asap._asap import atmosphere 10 9 … … 51 50 52 51 def get_opacities(self, freq, elevation=None): 53 """Get the opacity value(s) for the fiven frequency(ies).52 """Get the opacity value(s) for the given frequency(ies). 54 53 If no elevation is given the opacities for the zenith are returned. 55 54 If an elevation is specified refraction is also taken into account. … … 148 147 is corrupted (Mopra). If set to 'False', an opacity value 149 148 per polarisation is returned. 150 t ksy: The sky temperature (default 300.0K). This might149 tsky: The sky temperature (default 300.0K). This might 151 150 be read from the data in the future. 152 151 plot: Plot each fit (airmass vs. Tsys). Default is 'False' 153 152 """ 154 rcsave = rcParams['verbose']155 rcParams['verbose'] = False156 153 if plot: 157 154 from matplotlib import pylab … … 222 219 223 220 scan.set_selection(basesel) 224 rcParams['verbose'] = rcsave225 221 if plot: 226 222 pylab.close() -
trunk/python/parameters.py
r1849 r1949 1 """This module provides functions to set up resource parameters (rc). 2 These can be set in a file .asaprc or using functions. 3 """ 1 4 __all__ = ["rc", "list_rcparameters", "rcParams", "rcParamsDefault"] 2 5 … … 82 85 print """ 83 86 # general 84 # print verbose output 87 # only valid in asap standard mode not in scripts or casapy 88 # It will disable exceptions and just print the messages 85 89 verbose : True 86 90 … … 173 177 print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname)) 174 178 #asaplog.push('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname)) 175 # print_log('WARN')179 #asaplog.post('WARN') 176 180 continue 177 181 … … 181 185 print ('Bad key "%s" on line %d in %s' % (key, cnt, fname)) 182 186 #asaplog.push('Bad key "%s" on line %d in %s' % (key, cnt, fname)) 183 # print_log('WARN')187 #asaplog.post('WARN') 184 188 continue 185 189 … … 193 197 print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg)) 194 198 #asaplog.push('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, str(msg))) 195 # print_log('WARN')199 #asaplog.post('WARN') 196 200 continue 197 201 else: -
trunk/python/scantable.py
r1849 r1949 2 2 3 3 import os 4 import numpy 4 5 try: 5 6 from functools import wraps as wraps_dec … … 11 12 from asap._asap import filler 12 13 from asap.parameters import rcParams 13 from asap.logging import asaplog, print_log, print_log_dec14 from asap.logging import asaplog, asaplog_post_dec 14 15 from asap.selector import selector 15 16 from asap.linecatalog import linecatalog 16 17 from asap.coordinate import coordinate 17 from asap.utils import _n_bools, mask_not, mask_and, mask_or 18 from asap.utils import _n_bools, mask_not, mask_and, mask_or, page 19 from asap.asapfitter import fitter 18 20 19 21 … … 22 24 def wrap(obj, *args, **kw): 23 25 basesel = obj.get_selection() 24 val = func(obj, *args, **kw) 25 obj.set_selection(basesel) 26 try: 27 val = func(obj, *args, **kw) 28 finally: 29 obj.set_selection(basesel) 26 30 return val 27 31 return wrap … … 35 39 36 40 """ 37 return (os.path.isdir(filename) 38 and not os.path.exists(filename+'/table.f1') 39 and os.path.exists(filename+'/table.info')) 40 41 41 if ( os.path.isdir(filename) 42 and os.path.exists(filename+'/table.info') 43 and os.path.exists(filename+'/table.dat') ): 44 f=open(filename+'/table.info') 45 l=f.readline() 46 f.close() 47 #if ( l.find('Scantable') != -1 ): 48 if ( l.find('Measurement Set') == -1 ): 49 return True 50 else: 51 return False 52 else: 53 return False 54 ## return (os.path.isdir(filename) 55 ## and not os.path.exists(filename+'/table.f1') 56 ## and os.path.exists(filename+'/table.info')) 57 58 def is_ms(filename): 59 """Is the given file a MeasurementSet? 60 61 Parameters: 62 63 filename: the name of the file/directory to test 64 65 """ 66 if ( os.path.isdir(filename) 67 and os.path.exists(filename+'/table.info') 68 and os.path.exists(filename+'/table.dat') ): 69 f=open(filename+'/table.info') 70 l=f.readline() 71 f.close() 72 if ( l.find('Measurement Set') != -1 ): 73 return True 74 else: 75 return False 76 else: 77 return False 78 42 79 class scantable(Scantable): 43 80 """\ … … 45 82 """ 46 83 47 @print_log_dec 48 def __init__(self, filename, average=None, unit=None, getpt=None, 49 antenna=None, parallactify=None): 84 @asaplog_post_dec 85 #def __init__(self, filename, average=None, unit=None, getpt=None, 86 # antenna=None, parallactify=None): 87 def __init__(self, filename, average=None, unit=None, parallactify=None, **args): 50 88 """\ 51 89 Create a scantable from a saved one or make a reference … … 73 111 the MS data faster in some cases. 74 112 75 antenna: Antenna selection. integer (id) or string (name or id). 113 antenna: for MeasurementSet input data only: 114 Antenna selection. integer (id) or string (name or id). 76 115 77 116 parallactify: Indicate that the data had been parallatified. Default … … 81 120 if average is None: 82 121 average = rcParams['scantable.autoaverage'] 83 if getpt is None: 84 getpt = True 85 if antenna is not None: 86 asaplog.push("Antenna selection currently unsupported." 87 "Using '0'") 88 print_log('WARN') 89 if antenna is None: 90 antenna = '' 91 elif type(antenna) == int: 92 antenna = '%s' % antenna 93 elif type(antenna) == list: 94 tmpstr = '' 95 for i in range( len(antenna) ): 96 if type(antenna[i]) == int: 97 tmpstr = tmpstr + ('%s,'%(antenna[i])) 98 elif type(antenna[i]) == str: 99 tmpstr=tmpstr+antenna[i]+',' 100 else: 101 asaplog.push('Bad antenna selection.') 102 print_log('ERROR') 103 return 104 antenna = tmpstr.rstrip(',') 122 #if getpt is None: 123 # getpt = True 124 #if antenna is not None: 125 # asaplog.push("Antenna selection currently unsupported." 126 # "Using ''") 127 # asaplog.post('WARN') 128 #if antenna is None: 129 # antenna = '' 130 #elif type(antenna) == int: 131 # antenna = '%s' % antenna 132 #elif type(antenna) == list: 133 # tmpstr = '' 134 # for i in range( len(antenna) ): 135 # if type(antenna[i]) == int: 136 # tmpstr = tmpstr + ('%s,'%(antenna[i])) 137 # elif type(antenna[i]) == str: 138 # tmpstr=tmpstr+antenna[i]+',' 139 # else: 140 # raise TypeError('Bad antenna selection.') 141 # antenna = tmpstr.rstrip(',') 105 142 parallactify = parallactify or rcParams['scantable.parallactify'] 106 143 varlist = vars() … … 115 152 if not os.path.exists(filename): 116 153 s = "File '%s' not found." % (filename) 117 if rcParams['verbose']:118 asaplog.push(s)119 print_log('ERROR')120 return121 154 raise IOError(s) 122 155 if is_scantable(filename): … … 127 160 # do not reset to the default freqframe 128 161 #self.set_freqframe(rcParams['scantable.freqframe']) 129 elif os.path.isdir(filename) \ 130 and not os.path.exists(filename+'/table.f1'): 162 #elif os.path.isdir(filename) \ 163 # and not os.path.exists(filename+'/table.f1'): 164 elif is_ms(filename): 165 # Measurement Set 166 opts={'ms': {}} 167 mskeys=['getpt','antenna'] 168 for key in mskeys: 169 if key in args.keys(): 170 opts['ms'][key] = args[key] 171 #self._fill([filename], unit, average, getpt, antenna) 172 self._fill([filename], unit, average, opts) 173 elif os.path.isfile(filename): 174 #self._fill([filename], unit, average, getpt, antenna) 175 self._fill([filename], unit, average) 176 else: 131 177 msg = "The given file '%s'is not a valid " \ 132 178 "asap table." % (filename) 133 if rcParams['verbose']: 134 #print msg 135 asaplog.push( msg ) 136 print_log( 'ERROR' ) 137 return 138 else: 139 raise IOError(msg) 140 else: 141 self._fill([filename], unit, average, getpt, antenna) 179 raise IOError(msg) 142 180 elif (isinstance(filename, list) or isinstance(filename, tuple)) \ 143 181 and isinstance(filename[-1], str): 144 self._fill(filename, unit, average, getpt, antenna) 182 #self._fill(filename, unit, average, getpt, antenna) 183 self._fill(filename, unit, average) 145 184 self.parallactify(parallactify) 146 185 self._add_history("scantable", varlist) 147 print_log() 148 149 @print_log_dec 186 187 @asaplog_post_dec 150 188 def save(self, name=None, format=None, overwrite=False): 151 189 """\ … … 158 196 this is the root file name (data in 'name'.txt 159 197 and header in 'name'_header.txt) 198 160 199 format: an optional file format. Default is ASAP. 161 Allowed are - 'ASAP' (save as ASAP [aips++] Table), 162 'SDFITS' (save as SDFITS file) 163 'ASCII' (saves as ascii text file) 164 'MS2' (saves as an aips++ 165 MeasurementSet V2) 166 'FITS' (save as image FITS - not 167 readable by class) 168 'CLASS' (save as FITS readable by CLASS) 200 Allowed are: 201 202 * 'ASAP' (save as ASAP [aips++] Table), 203 * 'SDFITS' (save as SDFITS file) 204 * 'ASCII' (saves as ascii text file) 205 * 'MS2' (saves as an casacore MeasurementSet V2) 206 * 'FITS' (save as image FITS - not readable by class) 207 * 'CLASS' (save as FITS readable by CLASS) 208 169 209 overwrite: If the file should be overwritten if it exists. 170 210 The default False is to return with warning 171 211 without writing the output. USE WITH CARE. 212 172 213 Example:: 173 214 … … 187 228 if not overwrite: 188 229 msg = "File %s exists." % name 189 if rcParams['verbose']: 190 #print msg 191 asaplog.push( msg ) 192 print_log( 'ERROR' ) 193 return 194 else: 195 raise IOError(msg) 230 raise IOError(msg) 196 231 format2 = format.upper() 197 232 if format2 == 'ASAP': … … 201 236 writer = stw(format2) 202 237 writer.write(self, name) 203 print_log()204 238 return 205 239 … … 233 267 from asap import unique 234 268 if not _is_valid(scanid): 235 if rcParams['verbose']: 236 #print "Please specify a scanno to drop from the scantable" 237 asaplog.push( 'Please specify a scanno to drop from the scantable' ) 238 print_log( 'ERROR' ) 239 return 240 else: 241 raise RuntimeError("No scan given") 242 try: 243 scanid = _to_list(scanid) 244 allscans = unique([ self.getscan(i) for i in range(self.nrow())]) 245 for sid in scanid: allscans.remove(sid) 246 if len(allscans) == 0: 247 raise ValueError("Can't remove all scans") 248 except ValueError: 249 if rcParams['verbose']: 250 #print "Couldn't find any match." 251 print_log() 252 asaplog.push( "Couldn't find any match." ) 253 print_log( 'ERROR' ) 254 return 255 else: raise 256 try: 257 sel = selector(scans=allscans) 258 return self._select_copy(sel) 259 except RuntimeError: 260 if rcParams['verbose']: 261 #print "Couldn't find any match." 262 print_log() 263 asaplog.push( "Couldn't find any match." ) 264 print_log( 'ERROR' ) 265 else: 266 raise 269 raise RuntimeError( 'Please specify a scanno to drop from the scantable' ) 270 scanid = _to_list(scanid) 271 allscans = unique([ self.getscan(i) for i in range(self.nrow())]) 272 for sid in scanid: allscans.remove(sid) 273 if len(allscans) == 0: 274 raise ValueError("Can't remove all scans") 275 sel = selector(scans=allscans) 276 return self._select_copy(sel) 267 277 268 278 def _select_copy(self, selection): … … 274 284 275 285 def get_scan(self, scanid=None): 276 """ 286 """\ 277 287 Return a specific scan (by scanno) or collection of scans (by 278 288 source name) in a new scantable. … … 299 309 """ 300 310 if scanid is None: 301 if rcParams['verbose']: 302 #print "Please specify a scan no or name to " \ 303 # "retrieve from the scantable" 304 asaplog.push( 'Please specify a scan no or name to retrieve' 305 ' from the scantable' ) 306 print_log( 'ERROR' ) 307 return 308 else: 309 raise RuntimeError("No scan given") 310 311 raise RuntimeError( 'Please specify a scan no or name to ' 312 'retrieve from the scantable' ) 311 313 try: 312 314 bsel = self.get_selection() … … 323 325 else: 324 326 msg = "Illegal scanid type, use 'int' or 'list' if ints." 325 if rcParams['verbose']: 326 #print msg 327 asaplog.push( msg ) 328 print_log( 'ERROR' ) 329 else: 330 raise TypeError(msg) 327 raise TypeError(msg) 331 328 except RuntimeError: 332 if rcParams['verbose']: 333 #print "Couldn't find any match." 334 print_log() 335 asaplog.push( "Couldn't find any match." ) 336 print_log( 'ERROR' ) 337 else: raise 329 raise 338 330 339 331 def __str__(self): … … 362 354 else: 363 355 msg = "Illegal file name '%s'." % (filename) 364 if rcParams['verbose']: 365 #print msg 366 asaplog.push( msg ) 367 print_log( 'ERROR' ) 368 else: 369 raise IOError(msg) 370 if rcParams['verbose']: 371 try: 372 from IPython.genutils import page as pager 373 except ImportError: 374 from pydoc import pager 375 pager(info) 376 else: 377 return info 356 raise IOError(msg) 357 return page(info) 378 358 379 359 def get_spectrum(self, rowno): … … 398 378 399 379 def set_spectrum(self, spec, rowno): 400 """Return the spectrum for the current row in the scantable as a list. 401 402 Parameters: 403 404 spec: the spectrum 405 rowno: the row number to set the spectrum for 380 """Set the spectrum for the current row in the scantable. 381 382 Parameters: 383 384 spec: the new spectrum 385 386 rowno: the row number to set the spectrum for 406 387 407 388 """ … … 517 498 return workscan 518 499 519 #def stats(self, stat='stddev', mask=None):520 def stats(self, stat='stddev', mask=None, form='3.3f' ):500 @asaplog_post_dec 501 def stats(self, stat='stddev', mask=None, form='3.3f', row=None): 521 502 """\ 522 503 Determine the specified statistic of the current beam/if/pol … … 528 509 stat: 'min', 'max', 'min_abc', 'max_abc', 'sumsq', 'sum', 529 510 'mean', 'var', 'stddev', 'avdev', 'rms', 'median' 511 530 512 mask: an optional mask specifying where the statistic 531 513 should be determined. 514 532 515 form: format string to print statistic values 533 516 534 Example:: 535 517 row: row number of spectrum to process. 518 (default is None: for all rows) 519 520 Example: 536 521 scan.set_unit('channel') 537 522 msk = scan.create_mask([100, 200], [500, 600]) … … 551 536 getchan = True 552 537 statvals = [] 553 if not rtnabc: statvals = self._math._stats(self, mask, stat) 538 if not rtnabc: 539 if row == None: 540 statvals = self._math._stats(self, mask, stat) 541 else: 542 statvals = self._math._statsrow(self, mask, stat, int(row)) 554 543 555 544 #def cb(i): … … 563 552 #outvec = [] 564 553 sep = '-'*50 565 for i in range(self.nrow()): 554 555 if row == None: 556 rows = xrange(self.nrow()) 557 elif isinstance(row, int): 558 rows = [ row ] 559 560 for i in rows: 566 561 refstr = '' 567 562 statunit= '' … … 579 574 out += 'Scan[%d] (%s) ' % (self.getscan(i), src) 580 575 out += 'Time[%s]:\n' % (tm) 581 if self.nbeam(-1) > 1: 582 out += ' Beam[%d] ' % (self.getbeam(i)) 583 if self.nif(-1) > 1: out += ' IF[%d] ' % (self.getif(i)) 584 if self.npol(-1) > 1: out += ' Pol[%d] ' % (self.getpol(i)) 576 if self.nbeam(-1) > 1: out += ' Beam[%d] ' % (self.getbeam(i)) 577 if self.nif(-1) > 1: out += ' IF[%d] ' % (self.getif(i)) 578 if self.npol(-1) > 1: out += ' Pol[%d] ' % (self.getpol(i)) 585 579 #outvec.append(callback(i)) 586 #out += ('= %'+form) % (outvec[i]) +' '+refstr+'\n' 587 out += ('= %'+form) % (statvals[i]) +' '+refstr+'\n' 580 if len(rows) > 1: 581 # out += ('= %'+form) % (outvec[i]) +' '+refstr+'\n' 582 out += ('= %'+form) % (statvals[i]) +' '+refstr+'\n' 583 else: 584 # out += ('= %'+form) % (outvec[0]) +' '+refstr+'\n' 585 out += ('= %'+form) % (statvals[0]) +' '+refstr+'\n' 588 586 out += sep+"\n" 589 587 590 if rcParams['verbose']: 591 import os 592 if os.environ.has_key( 'USER' ): 593 usr=os.environ['USER'] 594 else: 595 import commands 596 usr=commands.getoutput( 'whoami' ) 597 tmpfile='/tmp/tmp_'+usr+'_casapy_asap_scantable_stats' 598 f=open(tmpfile,'w') 599 print >> f, sep 600 print >> f, ' %s %s' % (label, statunit) 601 print >> f, sep 602 print >> f, out 603 f.close() 604 f=open(tmpfile,'r') 605 x=f.readlines() 606 f.close() 607 blanc='' 608 asaplog.push(blanc.join(x), False) 609 #for xx in x: 610 # asaplog.push( xx, False ) 611 print_log() 588 import os 589 if os.environ.has_key( 'USER' ): 590 usr = os.environ['USER'] 591 else: 592 import commands 593 usr = commands.getoutput( 'whoami' ) 594 tmpfile = '/tmp/tmp_'+usr+'_casapy_asap_scantable_stats' 595 f = open(tmpfile,'w') 596 print >> f, sep 597 print >> f, ' %s %s' % (label, statunit) 598 print >> f, sep 599 print >> f, out 600 f.close() 601 f = open(tmpfile,'r') 602 x = f.readlines() 603 f.close() 604 asaplog.push(''.join(x), False) 605 612 606 return statvals 613 607 … … 621 615 rowno: a row number in the scantable. Default is the 622 616 first row, i.e. rowno=0 617 623 618 chan: a channel in the scantable. Default is the first 624 619 channel, i.e. pos=0 … … 723 718 out += '= %3.3f\n' % (outvec[i]) 724 719 out += sep+'\n' 725 if rcParams['verbose']: 726 727 728 729 730 print_log()720 721 asaplog.push(sep) 722 asaplog.push(" %s" % (label)) 723 asaplog.push(sep) 724 asaplog.push(out) 725 asaplog.post() 731 726 return outvec 732 727 733 def _get_column(self, callback, row=-1 ):728 def _get_column(self, callback, row=-1, *args): 734 729 """ 735 730 """ 736 731 if row == -1: 737 return [callback(i ) for i in range(self.nrow())]732 return [callback(i, *args) for i in range(self.nrow())] 738 733 else: 739 734 if 0 <= row < self.nrow(): 740 return callback(row )741 742 743 def get_time(self, row=-1, asdatetime=False ):735 return callback(row, *args) 736 737 738 def get_time(self, row=-1, asdatetime=False, prec=-1): 744 739 """\ 745 740 Get a list of time stamps for the observations. 746 Return a datetime object for each integration time stamp in the scantable. 741 Return a datetime object or a string (default) for each 742 integration time stamp in the scantable. 747 743 748 744 Parameters: 749 745 750 746 row: row no of integration. Default -1 return all rows 747 751 748 asdatetime: return values as datetime objects rather than strings 752 749 753 """ 754 from time import strptime 750 prec: number of digits shown. Default -1 to automatic calculation. 751 Note this number is equals to the digits of MVTime, 752 i.e., 0<prec<3: dates with hh:: only, 753 <5: with hh:mm:, <7 or 0: with hh:mm:ss, 754 and 6> : with hh:mm:ss.tt... (prec-6 t's added) 755 756 """ 755 757 from datetime import datetime 756 times = self._get_column(self._gettime, row) 758 if prec < 0: 759 # automagically set necessary precision +1 760 prec = 7 - numpy.floor(numpy.log10(min(self.get_inttime()))) 761 prec = max(6, int(prec)) 762 else: 763 prec = max(0, prec) 764 if asdatetime: 765 #precision can be 1 millisecond at max 766 prec = min(12, prec) 767 768 times = self._get_column(self._gettime, row, prec) 757 769 if not asdatetime: 758 770 return times 759 format = "%Y/%m/%d/%H:%M:%S" 771 format = "%Y/%m/%d/%H:%M:%S.%f" 772 if prec < 7: 773 nsub = 1 + (((6-prec)/2) % 3) 774 substr = [".%f","%S","%M"] 775 for i in range(nsub): 776 format = format.replace(substr[i],"") 760 777 if isinstance(times, list): 761 return [datetime (*strptime(i, format)[:6]) for i in times]762 else: 763 return datetime (*strptime(times, format)[:6])778 return [datetime.strptime(i, format) for i in times] 779 else: 780 return datetime.strptime(times, format) 764 781 765 782 … … 827 844 Get a list of Positions on the sky (direction) for the observations. 828 845 Return a string for each integration in the scantable. 829 Parameters: 846 847 Parameters: 848 830 849 row: row no of integration. Default -1 return all rows 831 Example: 832 none 850 833 851 """ 834 852 return self._get_column(self._getdirection, row) … … 846 864 return self._get_column(self._getdirectionvec, row) 847 865 848 @ print_log_dec866 @asaplog_post_dec 849 867 def set_unit(self, unit='channel'): 850 868 """\ … … 865 883 self._add_history("set_unit", varlist) 866 884 867 @ print_log_dec885 @asaplog_post_dec 868 886 def set_instrument(self, instr): 869 887 """\ … … 878 896 self._setInstrument(instr) 879 897 self._add_history("set_instument", vars()) 880 print_log() 881 882 @print_log_dec 898 899 @asaplog_post_dec 883 900 def set_feedtype(self, feedtype): 884 901 """\ … … 892 909 self._setfeedtype(feedtype) 893 910 self._add_history("set_feedtype", vars()) 894 print_log() 895 896 @print_log_dec 911 912 @asaplog_post_dec 897 913 def set_doppler(self, doppler='RADIO'): 898 914 """\ … … 909 925 self._setcoordinfo(inf) 910 926 self._add_history("set_doppler", vars()) 911 print_log() 912 913 @print_log_dec 927 928 @asaplog_post_dec 914 929 def set_freqframe(self, frame=None): 915 930 """\ … … 942 957 else: 943 958 msg = "Please specify a valid freq type. Valid types are:\n", valid 944 if rcParams['verbose']: 945 #print msg 946 asaplog.push( msg ) 947 print_log( 'ERROR' ) 948 else: 949 raise TypeError(msg) 950 print_log() 951 959 raise TypeError(msg) 960 961 @asaplog_post_dec 952 962 def set_dirframe(self, frame=""): 953 963 """\ … … 965 975 """ 966 976 varlist = vars() 967 try: 968 Scantable.set_dirframe(self, frame) 969 except RuntimeError, msg: 970 if rcParams['verbose']: 971 #print msg 972 print_log() 973 asaplog.push( str(msg) ) 974 print_log( 'ERROR' ) 975 else: 976 raise 977 Scantable.set_dirframe(self, frame) 977 978 self._add_history("set_dirframe", varlist) 978 979 … … 991 992 return unit 992 993 994 @asaplog_post_dec 993 995 def get_abcissa(self, rowno=0): 994 996 """\ … … 1008 1010 abc = self._getabcissa(rowno) 1009 1011 lbl = self._getabcissalabel(rowno) 1010 print_log()1011 1012 return abc, lbl 1012 1013 1014 @asaplog_post_dec 1013 1015 def flag(self, mask=None, unflag=False): 1014 1016 """\ … … 1019 1021 mask: an optional channel mask, created with create_mask. Default 1020 1022 (no mask) is all channels. 1023 1021 1024 unflag: if True, unflag the data 1022 1025 … … 1024 1027 varlist = vars() 1025 1028 mask = mask or [] 1026 try: 1027 self._flag(mask, unflag) 1028 except RuntimeError, msg: 1029 if rcParams['verbose']: 1030 #print msg 1031 print_log() 1032 asaplog.push( str(msg) ) 1033 print_log( 'ERROR' ) 1034 return 1035 else: raise 1029 self._flag(mask, unflag) 1036 1030 self._add_history("flag", varlist) 1037 1031 1032 @asaplog_post_dec 1038 1033 def flag_row(self, rows=[], unflag=False): 1039 1034 """\ … … 1044 1039 rows: list of row numbers to be flagged. Default is no row 1045 1040 (must be explicitly specified to execute row-based flagging). 1041 1046 1042 unflag: if True, unflag the data. 1047 1043 1048 1044 """ 1049 1045 varlist = vars() 1050 try: 1051 self._flag_row(rows, unflag) 1052 except RuntimeError, msg: 1053 if rcParams['verbose']: 1054 print_log() 1055 asaplog.push( str(msg) ) 1056 print_log('ERROR') 1057 return 1058 else: raise 1046 self._flag_row(rows, unflag) 1059 1047 self._add_history("flag_row", varlist) 1060 1048 1049 @asaplog_post_dec 1061 1050 def clip(self, uthres=None, dthres=None, clipoutside=True, unflag=False): 1062 1051 """\ … … 1066 1055 1067 1056 uthres: upper threshold. 1057 1068 1058 dthres: lower threshold 1069 1059 1070 1060 clipoutside: True for flagging data outside the range [dthres:uthres]. 1071 False for glagging data inside the range. 1061 False for flagging data inside the range. 1062 1072 1063 unflag: if True, unflag the data. 1073 1064 1074 1065 """ 1075 1066 varlist = vars() 1076 try: 1077 self._clip(uthres, dthres, clipoutside, unflag) 1078 except RuntimeError, msg: 1079 if rcParams['verbose']: 1080 print_log() 1081 asaplog.push(str(msg)) 1082 print_log('ERROR') 1083 return 1084 else: raise 1067 self._clip(uthres, dthres, clipoutside, unflag) 1085 1068 self._add_history("clip", varlist) 1086 1069 1087 @ print_log_dec1070 @asaplog_post_dec 1088 1071 def lag_flag(self, start, end, unit="MHz", insitu=None): 1089 1072 """\ … … 1096 1079 start: the start frequency (really a period within the 1097 1080 bandwidth) or period to remove 1081 1098 1082 end: the end frequency or period to remove 1083 1099 1084 unit: the frequency unit (default "MHz") or "" for 1100 1085 explicit lag channels … … 1112 1097 if not (unit == "" or base.has_key(unit)): 1113 1098 raise ValueError("%s is not a valid unit." % unit) 1114 try: 1115 if unit == "": 1116 s = scantable(self._math._lag_flag(self, start, end, "lags")) 1117 else: 1118 s = scantable(self._math._lag_flag(self, start*base[unit], 1119 end*base[unit], "frequency")) 1120 except RuntimeError, msg: 1121 if rcParams['verbose']: 1122 #print msg 1123 print_log() 1124 asaplog.push( str(msg) ) 1125 print_log( 'ERROR' ) 1126 return 1127 else: raise 1099 if unit == "": 1100 s = scantable(self._math._lag_flag(self, start, end, "lags")) 1101 else: 1102 s = scantable(self._math._lag_flag(self, start*base[unit], 1103 end*base[unit], "frequency")) 1128 1104 s._add_history("lag_flag", varlist) 1129 print_log()1130 1105 if insitu: 1131 1106 self._assign(s) … … 1133 1108 return s 1134 1109 1135 @ print_log_dec1110 @asaplog_post_dec 1136 1111 def create_mask(self, *args, **kwargs): 1137 1112 """\ … … 1145 1120 Pairs of start/end points (inclusive)specifying the regions 1146 1121 to be masked 1122 1147 1123 invert: optional argument. If specified as True, 1148 1124 return an inverted mask, i.e. the regions 1149 1125 specified are EXCLUDED 1126 1150 1127 row: create the mask using the specified row for 1151 1128 unit conversions, default is row=0 … … 1173 1150 data = self._getabcissa(row) 1174 1151 u = self._getcoordinfo()[0] 1175 if rcParams['verbose']:1176 if u == "":u = "channel"1177 1178 1179 1180 1181 1152 if u == "": 1153 u = "channel" 1154 msg = "The current mask window unit is %s" % u 1155 i = self._check_ifs() 1156 if not i: 1157 msg += "\nThis mask is only valid for IF=%d" % (self.getif(i)) 1158 asaplog.push(msg) 1182 1159 n = self.nchan() 1183 1160 msk = _n_bools(n, False) … … 1201 1178 if kwargs.get('invert'): 1202 1179 msk = mask_not(msk) 1203 print_log()1204 1180 return msk 1205 1181 1206 def get_masklist(self, mask=None, row=0 ):1182 def get_masklist(self, mask=None, row=0, silent=False): 1207 1183 """\ 1208 1184 Compute and return a list of mask windows, [min, max]. … … 1211 1187 1212 1188 mask: channel mask, created with create_mask. 1189 1213 1190 row: calcutate the masklist using the specified row 1214 1191 for unit conversions, default is row=0 … … 1231 1208 data = self._getabcissa(row) 1232 1209 u = self._getcoordinfo()[0] 1233 if rcParams['verbose']: 1234 if u == "": u = "channel" 1235 msg = "The current mask window unit is %s" % u 1236 i = self._check_ifs() 1237 if not i: 1238 msg += "\nThis mask is only valid for IF=%d" % (self.getif(i)) 1210 if u == "": 1211 u = "channel" 1212 msg = "The current mask window unit is %s" % u 1213 i = self._check_ifs() 1214 if not i: 1215 msg += "\nThis mask is only valid for IF=%d" % (self.getif(i)) 1216 if not silent: 1239 1217 asaplog.push(msg) 1240 1218 masklist=[] … … 1251 1229 """\ 1252 1230 Compute and Return lists of mask start indices and mask end indices. 1253 Parameters: 1231 1232 Parameters: 1233 1254 1234 mask: channel mask, created with create_mask. 1255 1235 … … 1326 1306 """\ 1327 1307 Set or replace the restfrequency specified and 1328 If the 'freqs' argument holds a scalar,1308 if the 'freqs' argument holds a scalar, 1329 1309 then that rest frequency will be applied to all the selected 1330 1310 data. If the 'freqs' argument holds … … 1342 1322 1343 1323 freqs: list of rest frequency values or string idenitfiers 1324 1344 1325 unit: unit for rest frequency (default 'Hz') 1345 1326 … … 1452 1433 Scantable.shift_refpix(self, delta) 1453 1434 1435 @asaplog_post_dec 1454 1436 def history(self, filename=None): 1455 1437 """\ … … 1458 1440 Parameters: 1459 1441 1460 filename: The name 1442 filename: The name of the file to save the history to. 1461 1443 1462 1444 """ … … 1465 1447 for h in hist: 1466 1448 if h.startswith("---"): 1467 out += "\n"+h1449 out = "\n".join([out, h]) 1468 1450 else: 1469 1451 items = h.split("##") … … 1474 1456 out += "Function: %s\n Parameters:" % (func) 1475 1457 for i in items: 1458 if i == '': 1459 continue 1476 1460 s = i.split("=") 1477 1461 out += "\n %s = %s" % (s[0], s[1]) 1478 out += "\n"+"-"*801462 out = "\n".join([out, "-"*80]) 1479 1463 if filename is not None: 1480 1464 if filename is "": … … 1488 1472 else: 1489 1473 msg = "Illegal file name '%s'." % (filename) 1490 if rcParams['verbose']: 1491 #print msg 1492 asaplog.push( msg ) 1493 print_log( 'ERROR' ) 1494 else: 1495 raise IOError(msg) 1496 if rcParams['verbose']: 1497 try: 1498 from IPython.genutils import page as pager 1499 except ImportError: 1500 from pydoc import pager 1501 pager(out) 1502 else: 1503 return out 1504 return 1474 raise IOError(msg) 1475 return page(out) 1505 1476 # 1506 1477 # Maths business 1507 1478 # 1508 @ print_log_dec1479 @asaplog_post_dec 1509 1480 def average_time(self, mask=None, scanav=False, weight='tint', align=False): 1510 1481 """\ … … 1519 1490 mask: an optional mask (only used for 'var' and 'tsys' 1520 1491 weighting) 1492 1521 1493 scanav: True averages each scan separately 1522 1494 False (default) averages all scans together, 1495 1523 1496 weight: Weighting scheme. 1524 1497 'none' (mean no weight) … … 1529 1502 'median' ( median averaging) 1530 1503 The default is 'tint' 1504 1531 1505 align: align the spectra in velocity before averaging. It takes 1532 1506 the time of the first spectrum as reference time. … … 1543 1517 scanav = (scanav and 'SCAN') or 'NONE' 1544 1518 scan = (self, ) 1545 try: 1546 if align: 1547 scan = (self.freq_align(insitu=False), ) 1548 s = None 1549 if weight.upper() == 'MEDIAN': 1550 s = scantable(self._math._averagechannel(scan[0], 'MEDIAN', 1551 scanav)) 1552 else: 1553 s = scantable(self._math._average(scan, mask, weight.upper(), 1554 scanav)) 1555 except RuntimeError, msg: 1556 if rcParams['verbose']: 1557 #print msg 1558 print_log() 1559 asaplog.push( str(msg) ) 1560 print_log( 'ERROR' ) 1561 return 1562 else: raise 1519 1520 if align: 1521 scan = (self.freq_align(insitu=False), ) 1522 s = None 1523 if weight.upper() == 'MEDIAN': 1524 s = scantable(self._math._averagechannel(scan[0], 'MEDIAN', 1525 scanav)) 1526 else: 1527 s = scantable(self._math._average(scan, mask, weight.upper(), 1528 scanav)) 1563 1529 s._add_history("average_time", varlist) 1564 print_log()1565 1530 return s 1566 1531 1567 @ print_log_dec1532 @asaplog_post_dec 1568 1533 def convert_flux(self, jyperk=None, eta=None, d=None, insitu=None): 1569 1534 """\ … … 1578 1543 1579 1544 jyperk: the Jy / K conversion factor 1545 1580 1546 eta: the aperture efficiency 1581 d: the geomtric diameter (metres) 1547 1548 d: the geometric diameter (metres) 1549 1582 1550 insitu: if False a new scantable is returned. 1583 1551 Otherwise, the scaling is done in-situ … … 1593 1561 s = scantable(self._math._convertflux(self, d, eta, jyperk)) 1594 1562 s._add_history("convert_flux", varlist) 1595 print_log()1596 1563 if insitu: self._assign(s) 1597 1564 else: return s 1598 1565 1599 @ print_log_dec1566 @asaplog_post_dec 1600 1567 def gain_el(self, poly=None, filename="", method="linear", insitu=None): 1601 1568 """\ … … 1614 1581 gain-elevation correction as a function of 1615 1582 elevation (in degrees). 1583 1616 1584 filename: The name of an ascii file holding correction factors. 1617 1585 The first row of the ascii file must give the column … … 1632 1600 0.5 80 0.8 1633 1601 0.6 90 0.75 1602 1634 1603 method: Interpolation method when correcting from a table. 1635 1604 Values are "nearest", "linear" (default), "cubic" 1636 1605 and "spline" 1606 1637 1607 insitu: if False a new scantable is returned. 1638 1608 Otherwise, the scaling is done in-situ … … 1649 1619 s = scantable(self._math._gainel(self, poly, filename, method)) 1650 1620 s._add_history("gain_el", varlist) 1651 print_log()1652 1621 if insitu: 1653 1622 self._assign(s) … … 1655 1624 return s 1656 1625 1657 @ print_log_dec1626 @asaplog_post_dec 1658 1627 def freq_align(self, reftime=None, method='cubic', insitu=None): 1659 1628 """\ … … 1663 1632 1664 1633 Parameters: 1634 1665 1635 reftime: reference time to align at. By default, the time of 1666 1636 the first row of data is used. 1637 1667 1638 method: Interpolation method for regridding the spectra. 1668 1639 Choose from "nearest", "linear", "cubic" (default) 1669 1640 and "spline" 1641 1670 1642 insitu: if False a new scantable is returned. 1671 1643 Otherwise, the scaling is done in-situ … … 1679 1651 s = scantable(self._math._freq_align(self, reftime, method)) 1680 1652 s._add_history("freq_align", varlist) 1681 print_log()1682 1653 if insitu: self._assign(s) 1683 1654 else: return s 1684 1655 1685 @ print_log_dec1656 @asaplog_post_dec 1686 1657 def opacity(self, tau=None, insitu=None): 1687 1658 """\ … … 1690 1661 1691 1662 Parameters: 1663 1692 1664 tau: (list of) opacity from which the correction factor is 1693 1665 exp(tau*ZD) … … 1698 1670 if tau is `None` the opacities are determined from a 1699 1671 model. 1672 1700 1673 insitu: if False a new scantable is returned. 1701 1674 Otherwise, the scaling is done in-situ … … 1710 1683 s = scantable(self._math._opacity(self, tau)) 1711 1684 s._add_history("opacity", varlist) 1712 print_log()1713 1685 if insitu: self._assign(s) 1714 1686 else: return s 1715 1687 1716 @ print_log_dec1688 @asaplog_post_dec 1717 1689 def bin(self, width=5, insitu=None): 1718 1690 """\ … … 1722 1694 1723 1695 width: The bin width (default=5) in pixels 1696 1724 1697 insitu: if False a new scantable is returned. 1725 1698 Otherwise, the scaling is done in-situ … … 1732 1705 s = scantable(self._math._bin(self, width)) 1733 1706 s._add_history("bin", varlist) 1734 print_log()1735 1707 if insitu: 1736 1708 self._assign(s) … … 1738 1710 return s 1739 1711 1740 @ print_log_dec1712 @asaplog_post_dec 1741 1713 def resample(self, width=5, method='cubic', insitu=None): 1742 1714 """\ … … 1746 1718 1747 1719 width: The bin width (default=5) in pixels 1720 1748 1721 method: Interpolation method when correcting from a table. 1749 1722 Values are "nearest", "linear", "cubic" (default) 1750 1723 and "spline" 1724 1751 1725 insitu: if False a new scantable is returned. 1752 1726 Otherwise, the scaling is done in-situ … … 1759 1733 s = scantable(self._math._resample(self, method, width)) 1760 1734 s._add_history("resample", varlist) 1761 print_log()1762 1735 if insitu: self._assign(s) 1763 1736 else: return s 1764 1737 1765 @ print_log_dec1738 @asaplog_post_dec 1766 1739 def average_pol(self, mask=None, weight='none'): 1767 1740 """\ … … 1773 1746 averaging will be applied. The output will have all 1774 1747 specified points masked. 1748 1775 1749 weight: Weighting scheme. 'none' (default), 'var' (1/var(spec) 1776 1750 weighted), or 'tsys' (1/Tsys**2 weighted) … … 1781 1755 s = scantable(self._math._averagepol(self, mask, weight.upper())) 1782 1756 s._add_history("average_pol", varlist) 1783 print_log()1784 1757 return s 1785 1758 1786 @ print_log_dec1759 @asaplog_post_dec 1787 1760 def average_beam(self, mask=None, weight='none'): 1788 1761 """\ … … 1793 1766 averaging will be applied. The output will have all 1794 1767 specified points masked. 1768 1795 1769 weight: Weighting scheme. 'none' (default), 'var' (1/var(spec) 1796 1770 weighted), or 'tsys' (1/Tsys**2 weighted) … … 1801 1775 s = scantable(self._math._averagebeams(self, mask, weight.upper())) 1802 1776 s._add_history("average_beam", varlist) 1803 print_log()1804 1777 return s 1805 1778 … … 1810 1783 1811 1784 Parameters: 1785 1812 1786 pflag: Bool indicating whether to turn this on (True) or 1813 1787 off (False) … … 1818 1792 self._add_history("parallactify", varlist) 1819 1793 1820 @ print_log_dec1794 @asaplog_post_dec 1821 1795 def convert_pol(self, poltype=None): 1822 1796 """\ … … 1825 1799 1826 1800 Parameters: 1801 1827 1802 poltype: The new polarisation type. Valid types are: 1828 1803 "linear", "circular", "stokes" and "linpol" … … 1830 1805 """ 1831 1806 varlist = vars() 1832 try: 1833 s = scantable(self._math._convertpol(self, poltype)) 1834 except RuntimeError, msg: 1835 if rcParams['verbose']: 1836 #print msg 1837 print_log() 1838 asaplog.push( str(msg) ) 1839 print_log( 'ERROR' ) 1840 return 1841 else: 1842 raise 1807 s = scantable(self._math._convertpol(self, poltype)) 1843 1808 s._add_history("convert_pol", varlist) 1844 print_log()1845 1809 return s 1846 1810 1847 @ print_log_dec1811 @asaplog_post_dec 1848 1812 def smooth(self, kernel="hanning", width=5.0, order=2, plot=False, insitu=None): 1849 1813 """\ … … 1855 1819 'hanning' (default), 'gaussian', 'boxcar', 'rmedian' 1856 1820 or 'poly' 1821 1857 1822 width: The width of the kernel in pixels. For hanning this is 1858 1823 ignored otherwise it defauls to 5 pixels. … … 1860 1825 Maximum. For 'boxcar' it is the full width. 1861 1826 For 'rmedian' and 'poly' it is the half width. 1827 1862 1828 order: Optional parameter for 'poly' kernel (default is 2), to 1863 1829 specify the order of the polnomial. Ignored by all other 1864 1830 kernels. 1831 1865 1832 plot: plot the original and the smoothed spectra. 1866 1833 In this each indivual fit has to be approved, by 1867 1834 typing 'y' or 'n' 1835 1868 1836 insitu: if False a new scantable is returned. 1869 1837 Otherwise, the scaling is done in-situ … … 1916 1884 del orgscan 1917 1885 1918 print_log()1919 1886 if insitu: self._assign(s) 1920 1887 else: return s 1921 1888 1922 @print_log_dec 1923 def poly_baseline(self, mask=None, order=0, plot=False, uselin=False, 1924 insitu=None): 1889 @asaplog_post_dec 1890 def old_poly_baseline(self, mask=None, order=0, plot=False, uselin=False, insitu=None, rows=None): 1925 1891 """\ 1926 1892 Return a scan which has been baselined (all rows) by a polynomial. 1927 1893 1928 1894 Parameters: 1929 1895 1930 1896 mask: an optional mask 1897 1931 1898 order: the order of the polynomial (default is 0) 1899 1932 1900 plot: plot the fit and the residual. In this each 1933 1901 indivual fit has to be approved, by typing 'y' 1934 1902 or 'n' 1903 1935 1904 uselin: use linear polynomial fit 1905 1936 1906 insitu: if False a new scantable is returned. 1937 1907 Otherwise, the scaling is done in-situ 1938 1908 The default is taken from .asaprc (False) 1939 1909 1940 Example:: 1941 1910 rows: row numbers of spectra to be processed. 1911 (default is None: for all rows) 1912 1913 Example: 1942 1914 # return a scan baselined by a third order polynomial, 1943 1915 # not using a mask … … 1952 1924 varlist = vars() 1953 1925 if mask is None: 1954 mask = [True for i in xrange(self.nchan(-1))] 1955 1956 from asap.asapfitter import fitter 1926 mask = [True for i in xrange(self.nchan())] 1927 1957 1928 try: 1958 1929 f = fitter() … … 1962 1933 f.set_function(poly=order) 1963 1934 1964 rows = range(workscan.nrow()) 1935 if rows == None: 1936 rows = xrange(workscan.nrow()) 1937 elif isinstance(rows, int): 1938 rows = [ rows ] 1939 1965 1940 if len(rows) > 0: 1966 1941 self.blpars = [] 1967 1942 self.masklists = [] 1943 self.actualmask = [] 1944 1968 1945 for r in rows: 1969 # take into account flagtra info (CAS-1434)1970 flagtra = workscan._getmask(r)1971 actualmask = mask[:]1972 if len(actualmask) == 0:1973 actualmask = list(flagtra[:])1974 else:1975 if len(actualmask) != len(flagtra):1976 raise RuntimeError, "Mask and flagtra have different length"1977 else:1978 for i in range(0, len(actualmask)):1979 actualmask[i] = actualmask[i] and flagtra[i]1980 f.set_scan(workscan, actualmask)1981 1946 f.x = workscan._getabcissa(r) 1982 1947 f.y = workscan._getspectrum(r) 1948 f.mask = mask_and(mask, workscan._getmask(r)) # (CAS-1434) 1983 1949 f.data = None 1984 1950 f.fit() … … 1988 1954 if x.upper() == 'N': 1989 1955 self.blpars.append(None) 1956 self.masklists.append(None) 1957 self.actualmask.append(None) 1990 1958 continue 1991 1959 workscan._setspectrum(f.fitter.getresidual(), r) 1992 1960 self.blpars.append(f.get_parameters()) 1961 self.masklists.append(workscan.get_masklist(f.mask, row=r, silent=True)) 1962 self.actualmask.append(f.mask) 1993 1963 1994 1964 if plot: … … 1996 1966 f._p = None 1997 1967 workscan._add_history("poly_baseline", varlist) 1998 print_log() 1999 if insitu: self._assign(workscan) 2000 else: return workscan 1968 if insitu: 1969 self._assign(workscan) 1970 else: 1971 return workscan 2001 1972 except RuntimeError: 2002 1973 msg = "The fit failed, possibly because it didn't converge." 2003 if rcParams['verbose']: 2004 #print msg 2005 print_log() 2006 asaplog.push( str(msg) ) 2007 print_log( 'ERROR' ) 1974 raise RuntimeError(msg) 1975 1976 @asaplog_post_dec 1977 def poly_baseline(self, mask=None, order=0, plot=False, batch=False, insitu=None, rows=None): 1978 """\ 1979 Return a scan which has been baselined (all rows) by a polynomial. 1980 Parameters: 1981 mask: an optional mask 1982 order: the order of the polynomial (default is 0) 1983 plot: plot the fit and the residual. In this each 1984 indivual fit has to be approved, by typing 'y' 1985 or 'n'. Ignored if batch = True. 1986 batch: if True a faster algorithm is used and logs 1987 including the fit results are not output 1988 (default is False) 1989 insitu: if False a new scantable is returned. 1990 Otherwise, the scaling is done in-situ 1991 The default is taken from .asaprc (False) 1992 rows: row numbers of spectra to be baselined. 1993 (default is None: for all rows) 1994 Example: 1995 # return a scan baselined by a third order polynomial, 1996 # not using a mask 1997 bscan = scan.poly_baseline(order=3) 1998 """ 1999 2000 varlist = vars() 2001 2002 if insitu is None: insitu = rcParams["insitu"] 2003 if insitu: 2004 workscan = self 2005 else: 2006 workscan = self.copy() 2007 2008 nchan = workscan.nchan() 2009 2010 if mask is None: 2011 mask = [True for i in xrange(nchan)] 2012 2013 try: 2014 if rows == None: 2015 rows = xrange(workscan.nrow()) 2016 elif isinstance(rows, int): 2017 rows = [ rows ] 2018 2019 if len(rows) > 0: 2020 workscan.blpars = [] 2021 workscan.masklists = [] 2022 workscan.actualmask = [] 2023 2024 if batch: 2025 workscan._poly_baseline_batch(mask, order) 2026 elif plot: 2027 f = fitter() 2028 f.set_function(lpoly=order) 2029 for r in rows: 2030 f.x = workscan._getabcissa(r) 2031 f.y = workscan._getspectrum(r) 2032 f.mask = mask_and(mask, workscan._getmask(r)) # (CAS-1434) 2033 f.data = None 2034 f.fit() 2035 2036 f.plot(residual=True) 2037 accept_fit = raw_input("Accept fit ( [y]/n ): ") 2038 if accept_fit.upper() == "N": 2039 self.blpars.append(None) 2040 self.masklists.append(None) 2041 self.actualmask.append(None) 2042 continue 2043 workscan._setspectrum(f.fitter.getresidual(), r) 2044 workscan.blpars.append(f.get_parameters()) 2045 workscan.masklists.append(workscan.get_masklist(f.mask, row=r)) 2046 workscan.actualmask.append(f.mask) 2047 2048 f._p.unmap() 2049 f._p = None 2050 else: 2051 for r in rows: 2052 fitparams = workscan._poly_baseline(mask, order, r) 2053 params = fitparams.getparameters() 2054 fmtd = ", ".join(["p%d = %3.6f" % (i, v) for i, v in enumerate(params)]) 2055 errors = fitparams.geterrors() 2056 fmask = mask_and(mask, workscan._getmask(r)) 2057 2058 workscan.blpars.append({"params":params, 2059 "fixed": fitparams.getfixedparameters(), 2060 "formatted":fmtd, "errors":errors}) 2061 workscan.masklists.append(workscan.get_masklist(fmask, r, silent=True)) 2062 workscan.actualmask.append(fmask) 2063 2064 asaplog.push(fmtd) 2065 2066 workscan._add_history("poly_baseline", varlist) 2067 2068 if insitu: 2069 self._assign(workscan) 2070 else: 2071 return workscan 2072 2073 except RuntimeError, e: 2074 msg = "The fit failed, possibly because it didn't converge." 2075 if rcParams["verbose"]: 2076 asaplog.push(str(e)) 2077 asaplog.push(str(msg)) 2008 2078 return 2009 2079 else: 2010 raise RuntimeError( msg)2011 2012 2013 def auto_poly_baseline(self, mask= [], edge=(0, 0), order=0,2080 raise RuntimeError(str(e)+'\n'+msg) 2081 2082 2083 def auto_poly_baseline(self, mask=None, edge=(0, 0), order=0, 2014 2084 threshold=3, chan_avg_limit=1, plot=False, 2015 insitu=None ):2085 insitu=None, rows=None): 2016 2086 """\ 2017 2087 Return a scan which has been baselined (all rows) by a polynomial. … … 2054 2124 Otherwise, the scaling is done in-situ 2055 2125 The default is taken from .asaprc (False) 2126 rows: row numbers of spectra to be processed. 2127 (default is None: for all rows) 2056 2128 2057 2129 … … 2063 2135 if insitu is None: insitu = rcParams['insitu'] 2064 2136 varlist = vars() 2065 from asap.asapfitter import fitter2066 2137 from asap.asaplinefind import linefinder 2067 2138 from asap import _is_sequence_or_number as _is_valid … … 2087 2158 curedge = edge; 2088 2159 2160 if not insitu: 2161 workscan = self.copy() 2162 else: 2163 workscan = self 2164 2089 2165 # setup fitter 2090 2166 f = fitter() 2091 f.set_function( poly=order)2167 f.set_function(lpoly=order) 2092 2168 2093 2169 # setup line finder … … 2095 2171 fl.set_options(threshold=threshold,avg_limit=chan_avg_limit) 2096 2172 2097 if not insitu:2098 workscan = self.copy()2099 else:2100 workscan = self2101 2102 2173 fl.set_scan(workscan) 2103 2174 2104 rows = range(workscan.nrow()) 2175 if mask is None: 2176 mask = _n_bools(workscan.nchan(), True) 2177 2178 if rows is None: 2179 rows = xrange(workscan.nrow()) 2180 elif isinstance(rows, int): 2181 rows = [ rows ] 2182 2105 2183 # Save parameters of baseline fits & masklists as a class attribute. 2106 2184 # NOTICE: It does not reflect changes in scantable! … … 2108 2186 self.blpars=[] 2109 2187 self.masklists=[] 2188 self.actualmask=[] 2110 2189 asaplog.push("Processing:") 2111 2190 for r in rows: … … 2122 2201 curedge = edge[workscan.getif(r)] 2123 2202 2124 # take into account flagtra info (CAS-1434) 2125 flagtra = workscan._getmask(r) 2126 actualmask = mask[:] 2127 if len(actualmask) == 0: 2128 actualmask = list(flagtra[:]) 2129 else: 2130 if len(actualmask) != len(flagtra): 2131 raise RuntimeError, "Mask and flagtra have different length" 2132 else: 2133 for i in range(0, len(actualmask)): 2134 actualmask[i] = actualmask[i] and flagtra[i] 2203 actualmask = mask_and(mask, workscan._getmask(r)) # (CAS-1434) 2135 2204 2136 2205 # setup line finder 2137 2206 fl.find_lines(r, actualmask, curedge) 2138 outmask=fl.get_mask() 2139 f.set_scan(workscan, fl.get_mask()) 2207 2140 2208 f.x = workscan._getabcissa(r) 2141 2209 f.y = workscan._getspectrum(r) 2210 f.mask = fl.get_mask() 2142 2211 f.data = None 2143 2212 f.fit() 2144 2213 2145 2214 # Show mask list 2146 masklist=workscan.get_masklist(f l.get_mask(),row=r)2215 masklist=workscan.get_masklist(f.mask, row=r, silent=True) 2147 2216 msg = "mask range: "+str(masklist) 2148 2217 asaplog.push(msg, False) … … 2154 2223 self.blpars.append(None) 2155 2224 self.masklists.append(None) 2225 self.actualmask.append(None) 2156 2226 continue 2157 2227 … … 2159 2229 self.blpars.append(f.get_parameters()) 2160 2230 self.masklists.append(masklist) 2231 self.actualmask.append(f.mask) 2161 2232 if plot: 2162 2233 f._p.unmap() … … 2168 2239 return workscan 2169 2240 2170 @ print_log_dec2241 @asaplog_post_dec 2171 2242 def rotate_linpolphase(self, angle): 2172 2243 """\ … … 2187 2258 self._math._rotate_linpolphase(self, angle) 2188 2259 self._add_history("rotate_linpolphase", varlist) 2189 print_log()2190 2260 return 2191 2261 2192 @ print_log_dec2262 @asaplog_post_dec 2193 2263 def rotate_xyphase(self, angle): 2194 2264 """\ … … 2209 2279 self._math._rotate_xyphase(self, angle) 2210 2280 self._add_history("rotate_xyphase", varlist) 2211 print_log()2212 2281 return 2213 2282 2214 @ print_log_dec2283 @asaplog_post_dec 2215 2284 def swap_linears(self): 2216 2285 """\ … … 2221 2290 self._math._swap_linears(self) 2222 2291 self._add_history("swap_linears", varlist) 2223 print_log()2224 2292 return 2225 2293 2226 @ print_log_dec2294 @asaplog_post_dec 2227 2295 def invert_phase(self): 2228 2296 """\ … … 2234 2302 return 2235 2303 2236 @ print_log_dec2304 @asaplog_post_dec 2237 2305 def add(self, offset, insitu=None): 2238 2306 """\ … … 2242 2310 2243 2311 offset: the offset 2312 2244 2313 insitu: if False a new scantable is returned. 2245 2314 Otherwise, the scaling is done in-situ … … 2257 2326 return s 2258 2327 2259 @ print_log_dec2328 @asaplog_post_dec 2260 2329 def scale(self, factor, tsys=True, insitu=None): 2261 2330 """\ 2262 2331 2263 Return a scan where all spectra are scaled by the give 'factor'2332 Return a scan where all spectra are scaled by the given 'factor' 2264 2333 2265 2334 Parameters: 2266 2335 2267 2336 factor: the scaling factor (float or 1D float list) 2337 2268 2338 insitu: if False a new scantable is returned. 2269 2339 Otherwise, the scaling is done in-situ 2270 2340 The default is taken from .asaprc (False) 2341 2271 2342 tsys: if True (default) then apply the operation to Tsys 2272 2343 as well as the data … … 2287 2358 s = scantable(self._math._unaryop(self.copy(), factor, "MUL", tsys)) 2288 2359 s._add_history("scale", varlist) 2289 print_log()2290 2360 if insitu: 2291 2361 self._assign(s) … … 2302 2372 2303 2373 match: a Unix style pattern, regular expression or selector 2374 2304 2375 matchtype: 'pattern' (default) UNIX style pattern or 2305 2376 'regex' regular expression 2377 2306 2378 sourcetype: the type of the source to use (source/reference) 2307 2379 … … 2332 2404 self._add_history("set_sourcetype", varlist) 2333 2405 2334 @print_log_dec 2406 @asaplog_post_dec 2407 @preserve_selection 2335 2408 def auto_quotient(self, preserve=True, mode='paired', verify=False): 2336 2409 """\ … … 2343 2416 preserve: you can preserve (default) the continuum or 2344 2417 remove it. The equations used are 2418 2345 2419 preserve: Output = Toff * (on/off) - Toff 2420 2346 2421 remove: Output = Toff * (on/off) - Ton 2422 2347 2423 mode: the on/off detection mode 2348 2424 'paired' (default) … … 2354 2430 finds the closest off in time 2355 2431 2356 """ 2432 .. todo:: verify argument is not implemented 2433 2434 """ 2435 varlist = vars() 2357 2436 modes = ["time", "paired"] 2358 2437 if not mode in modes: 2359 2438 msg = "please provide valid mode. Valid modes are %s" % (modes) 2360 2439 raise ValueError(msg) 2361 varlist = vars()2362 2440 s = None 2363 2441 if mode.lower() == "paired": 2364 basesel = self.get_selection() 2365 sel = selector()+basesel 2366 sel.set_query("SRCTYPE==1") 2442 sel = self.get_selection() 2443 sel.set_query("SRCTYPE==psoff") 2367 2444 self.set_selection(sel) 2368 2445 offs = self.copy() 2369 sel.set_query("SRCTYPE== 0")2446 sel.set_query("SRCTYPE==pson") 2370 2447 self.set_selection(sel) 2371 2448 ons = self.copy() 2372 2449 s = scantable(self._math._quotient(ons, offs, preserve)) 2373 self.set_selection(basesel)2374 2450 elif mode.lower() == "time": 2375 2451 s = scantable(self._math._auto_quotient(self, mode, preserve)) 2376 2452 s._add_history("auto_quotient", varlist) 2377 print_log()2378 2453 return s 2379 2454 2380 @ print_log_dec2455 @asaplog_post_dec 2381 2456 def mx_quotient(self, mask = None, weight='median', preserve=True): 2382 2457 """\ … … 2386 2461 2387 2462 mask: an optional mask to be used when weight == 'stddev' 2463 2388 2464 weight: How to average the off beams. Default is 'median'. 2465 2389 2466 preserve: you can preserve (default) the continuum or 2390 remove it. The equations used are 2391 preserve: Output = Toff * (on/off) - Toff 2392 remove: Output = Toff * (on/off) - Ton 2467 remove it. The equations used are: 2468 2469 preserve: Output = Toff * (on/off) - Toff 2470 2471 remove: Output = Toff * (on/off) - Ton 2393 2472 2394 2473 """ … … 2401 2480 q = quotient(on, off, preserve) 2402 2481 q._add_history("mx_quotient", varlist) 2403 print_log()2404 2482 return q 2405 2483 2406 @ print_log_dec2484 @asaplog_post_dec 2407 2485 def freq_switch(self, insitu=None): 2408 2486 """\ … … 2421 2499 s = scantable(self._math._freqswitch(self)) 2422 2500 s._add_history("freq_switch", varlist) 2423 print_log() 2424 if insitu: self._assign(s) 2425 else: return s 2426 2427 @print_log_dec 2501 if insitu: 2502 self._assign(s) 2503 else: 2504 return s 2505 2506 @asaplog_post_dec 2428 2507 def recalc_azel(self): 2429 2508 """Recalculate the azimuth and elevation for each position.""" … … 2431 2510 self._recalcazel() 2432 2511 self._add_history("recalc_azel", varlist) 2433 print_log()2434 2512 return 2435 2513 2436 @ print_log_dec2514 @asaplog_post_dec 2437 2515 def __add__(self, other): 2438 2516 varlist = vars() … … 2447 2525 return s 2448 2526 2449 @ print_log_dec2527 @asaplog_post_dec 2450 2528 def __sub__(self, other): 2451 2529 """ … … 2463 2541 return s 2464 2542 2465 @ print_log_dec2543 @asaplog_post_dec 2466 2544 def __mul__(self, other): 2467 2545 """ … … 2480 2558 2481 2559 2482 @ print_log_dec2560 @asaplog_post_dec 2483 2561 def __div__(self, other): 2484 2562 """ … … 2498 2576 return s 2499 2577 2578 @asaplog_post_dec 2500 2579 def get_fit(self, row=0): 2501 2580 """\ … … 2511 2590 from asap.asapfit import asapfit 2512 2591 fit = asapfit(self._getfit(row)) 2513 if rcParams['verbose']: 2514 #print fit 2515 asaplog.push( '%s' %(fit) ) 2516 print_log() 2517 return 2518 else: 2519 return fit.as_dict() 2592 asaplog.push( '%s' %(fit) ) 2593 return fit.as_dict() 2520 2594 2521 2595 def flag_nans(self): … … 2611 2685 return (sum(nchans)/len(nchans) == nchans[0]) 2612 2686 2613 def _fill(self, names, unit, average, getpt, antenna): 2687 @asaplog_post_dec 2688 #def _fill(self, names, unit, average, getpt, antenna): 2689 def _fill(self, names, unit, average, opts={}): 2614 2690 first = True 2615 2691 fullnames = [] … … 2619 2695 if not os.path.exists(name): 2620 2696 msg = "File '%s' does not exists" % (name) 2621 if rcParams['verbose']:2622 asaplog.push(msg)2623 print_log( 'ERROR' )2624 return2625 2697 raise IOError(msg) 2626 2698 fullnames.append(name) … … 2635 2707 msg = "Importing %s..." % (name) 2636 2708 asaplog.push(msg, False) 2637 print_log()2638 r.open(name )# antenna, -1, -1, getpt)2709 #opts = {'ms': {'antenna' : antenna, 'getpt': getpt} } 2710 r.open(name, opts)# antenna, -1, -1, getpt) 2639 2711 r.fill() 2640 2712 if average: … … 2646 2718 del r, tbl 2647 2719 first = False 2720 #flush log 2721 asaplog.post() 2648 2722 if unit is not None: 2649 2723 self.set_fluxunit(unit) -
trunk/python/selector.py
r1849 r1949 1 from asap._asap import selector as _selector 1 import re 2 from asap._asap import selector as _selector, srctype 2 3 from asap.utils import unique, _to_list 3 4 … … 7 8 scantables to specific rows. 8 9 """ 9 fields = ["pols", "ifs", "beams", "scans", "cycles", "name", "query" ]10 fields = ["pols", "ifs", "beams", "scans", "cycles", "name", "query", "types", "rows"] 10 11 11 12 def __init__(self, *args, **kw): … … 148 149 Example: 149 150 # select all off scans with integration times over 60 seconds. 150 selection.set_query("SRCTYPE == 1 AND INTERVAL > 60.0") 151 """ 151 selection.set_query("SRCTYPE == PSOFF AND INTERVAL > 60.0") 152 """ 153 rx = re.compile("((SRCTYPE *[!=][=] *)([a-zA-Z.]+))", re.I) 154 for r in rx.findall(query): 155 sval = None 156 stype = r[-1].lower() 157 if stype.find('srctype.') == -1: 158 stype = ".".join(["srctype", stype]) 159 try: 160 sval = eval(stype) 161 sval = "%s%d" % (r[1], sval) 162 except: 163 continue 164 query = query.replace(r[0], sval) 152 165 taql = "SELECT FROM $1 WHERE " + query 153 166 self._settaql(taql) … … 203 216 def get_types(self): 204 217 return list(self._gettypes()) 218 def get_rows(self): 219 return list(self._getrows()) 205 220 def get_query(self): 206 221 prefix = "SELECT FROM $1 WHERE " … … 220 235 "POLNO": self.get_pols(), 221 236 "QUERY": self.get_query(), 237 "SRCTYPE": self.get_types(), 238 "ROWS": self.get_rows(), 222 239 "Sort Order": self.get_order() 223 240 } -
trunk/python/utils.py
r1849 r1949 61 61 if not os.path.isdir(path): 62 62 return None 63 valid = " rpf rpf.1 rpf.2 sdf sdfits mbf asap".split()63 valid = "ms rpf rpf.1 rpf.2 sdf sdfits mbf asap".split() 64 64 if not suffix in valid: 65 65 return None 66 66 files = [os.path.expanduser(os.path.expandvars(path+"/"+f)) for f in os.listdir(path)] 67 67 return filter(lambda x: x.endswith(suffix),files) 68 69 def page(message): 70 """Run the input message through a pager. This is only done if 71 ``rcParams["verbose"]`` is set. 72 """ 73 verbose = False 74 try: 75 from asap.parameters import rcParams 76 verbose = rcParams['verbose'] 77 except: 78 pass 79 if verbose: 80 try: 81 from IPython.genutils import page as pager 82 except ImportError: 83 from pydoc import pager 84 pager(message) 85 return None 86 else: 87 return message -
trunk/src
- Property svn:mergeinfo changed (with no actual effect on merging)
-
trunk/src/AsapLogSink.cpp
r1849 r1949 21 21 22 22 void AsapLogSink::postMessage(const std::string& msg, 23 const std::string& location,24 const std::string& priority)23 const std::string& priority, 24 const std::string& origin) 25 25 { 26 26 LogMessage::Priority p; … … 32 32 p = LogMessage::SEVERE; 33 33 } 34 LogMessage message(msg, LogOrigin( location), p);34 LogMessage message(msg, LogOrigin(origin), p); 35 35 36 36 MemoryLogSink::postLocally(message); -
trunk/src/AsapLogSink.h
r1849 r1949 37 37 38 38 virtual void postMessage(const std::string& msg, 39 const std::string& location="",40 const std::string& priority="INFO");39 const std::string& priority="INFO", 40 const std::string& origin=""); 41 41 42 42 std::string popMessages(); -
trunk/src/FillerBase.cpp
r1849 r1949 38 38 RecordFieldPtr< Array<Float> > tsysCol(row_.record(), "TSYS"); 39 39 40 *specCol = spectrum; 41 *flagCol = flags; 42 *tsysCol = tsys; 40 //*specCol = spectrum; 41 //*flagCol = flags; 42 //*tsysCol = tsys; 43 specCol.define(spectrum); 44 flagCol.define(flags); 45 tsysCol.define(tsys); 43 46 } 44 47 -
trunk/src/FillerBase.h
r1849 r1949 43 43 virtual ~FillerBase() {;} 44 44 45 // virtual bool open(const std::string& filename, constRecord& rec) = 0;46 virtual bool open(const std::string& filename) = 0;45 virtual bool open(const std::string& filename, const casa::Record& rec) = 0; 46 // virtual bool open(const std::string& filename) = 0; 47 47 virtual void fill() = 0; 48 48 virtual void close() = 0; -
trunk/src/FillerWrapper.h
r1849 r1949 16 16 #include <casa/Exceptions.h> 17 17 #include <casa/Utilities/CountedPtr.h> 18 #include <casa/Containers/Record.h> 18 19 #include <casa/OS/File.h> 19 20 … … 38 39 39 40 40 // void open(const std::string& filename, casa::Recordrec) {41 void open(const std::string& filename) {41 void open(const std::string& filename, const casa::Record& rec) { 42 // void open(const std::string& filename) { 42 43 casa::File file(filename); 43 44 if ( !file.exists() ) { … … 45 46 } 46 47 filler_ = new PKSFiller(stable_); 47 //if (filler_->open(filename, rec)) {48 if (filler_->open(filename)) {48 if (filler_->open(filename, rec)) { 49 // if (filler_->open(filename)) { 49 50 attached_ = true; 50 51 return; 51 52 } 52 53 filler_ = new NROFiller(stable_); 53 //if (filler_->open(filename, rec)) {54 if (filler_->open(filename)) {54 if (filler_->open(filename, rec)) { 55 // if (filler_->open(filename)) { 55 56 attached_ = true; 56 57 return; -
trunk/src/Makefile
r1849 r1949 7 7 ### 3. Replase library names in G2CARCH '-lcasa_*' with '-l*'. 8 8 ### 4. Comment-IN the definition of 'CXXOPTS'. 9 #TARGET := /tmp/_asap.so 10 TARGET := /home/nakazato/tmp/_asap.so 9 TARGET := /tmp/_asap.so 10 11 ifndef ASAPROOT 12 ASAPROOT := $(abspath ..) 13 endif 14 ATNFD := external-alma 11 15 12 16 # the casa environment AIPSPATH has to be defined 13 17 CASAROOT := $(word 1, $(CASAPATH)) 14 18 CASAARCH := $(word 2, $(CASAPATH)) 19 20 CXXFLAGS := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=CXXFLAGS eval_vars) && echo $$CXXFLAGS) 21 CXXOPTS := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=COPTFLAGS eval_vars) && echo $$COPTFLAGS) 22 LDFLAGS := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=LD_FLAGS eval_vars) && echo $$LD_FLAGS) 15 23 16 24 COREINCD := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=COREINCD eval_vars) && echo $$COREINCD) … … 22 30 PYTHONINCD := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=PYTHONINCD eval_vars) && echo $$PYTHONINCD) 23 31 PYTHONLIB := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=PYTHONLIB eval_vars) && echo $$PYTHONLIB) 24 #PYTHONVER := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=PYTHONVER eval_vars) && echo $$PYTHONVER)25 32 BOOSTROOT := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=BOOSTROOT eval_vars) && echo $$BOOSTROOT) 26 33 RPFITSLIBD := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=RPFITSLIBD eval_vars) && echo $$RPFITSLIBD) 34 CFITSIOLIBD := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=CFITSIOLIBD eval_vars) && echo $$CFITSIOLIBD) 35 CFITSIOINCD := $(shell $(shell make -s -f $(CASAROOT)/$(CASAARCH)/makedefs VARS=CFITSIOINCD eval_vars) && echo $$CFITSIOINCD) 27 36 28 37 CASAINC := -I$(CASAROOT)/code/include -I$(COREINCD) -I$(CASAROOT)/$(CASAARCH)/include 29 38 CASALIB := $(CASAROOT)/$(CASAARCH)/lib 30 #USELIB := lib6431 USELIB := lib32 39 33 40 # the compiler … … 37 44 38 45 # compiler flags 39 CXXFLAGS := -fPIC -O3 -g 40 CXXFLAGS += -ansi -Wno-long-long -Wall 41 #CXXOPTS := -DAIPS_64B 42 43 # darwin specific flags 44 ifeq "$(CASAARCH)" "darwin" 45 #CXXFLAGS +=-DAIPS_DARWIN -arch i386 #For 10.6 46 CXXFLAGS +=-DAIPS_DARWIN 47 #CXXFLAGS += -Wno-long-double 48 endif 49 50 # cfitsio 51 CFITSIOROOT := /usr 52 CFITSIOINC := -I$(CFITSIOROOT)/include/cfitsio 46 CXXFLAGS += -fPIC -DHAVE_LIBPYRAP 47 48 PYRAPD := $(ASAPROOT)/external/libpyrap 49 PYRAPLIBD := $(PYRAPD) 50 PYRAPINCD := $(PYRAPD)/pyrap-0.3.2 51 PYRAPLIB := -L$(PYRAPLIBD) -lpyrap 52 53 53 54 CFITSIOLIB := -lcfitsio 54 55 55 56 #rpfits 56 RPFITSROOT := /usr57 57 RPFITSLIB := -lrpfits 58 58 … … 60 60 G2CLIB := -lgfortran 61 61 62 # This assumes all casa libs are static only (*.a) 63 # if not than there might by symbol resolution errors. 64 CASAPPLIB := -L$(CASALIB) -latnf $(CORELIB) \ 62 # links to external libraries 63 CASAPPLIB := -L$(ASAPROOT)/$(ATNFD) -latnf $(CORELIB) $(PYRAPLIB)\ 65 64 -L$(WCSLIBLIBD) $(WCSLIBLIB) \ 66 65 -L$(RPFITSLIBD) $(RPFITSLIB) $(CFITSIOLIB) $(G2CLIB) -lstdc++ 67 66 68 67 # darwin specific CASA flags 69 ifeq "$(CASAARCH)" "darwin"68 ifeq ($(shell uname), Darwin) 70 69 CASAPPLIB += -framework vecLib 71 70 else … … 73 72 endif 74 73 75 # python76 PYTHONINC := $(addprefix -I,$(PYTHONINCD))77 PYTHONLIB := -L$(PYTHONLIBD) $(PYTHONLIB)78 79 # use python universal build80 #ifeq "$(CASAARCH)" "darwin"81 # PYVERSION := 2.582 # PYTHONROOT := /Library/Frameworks/Python.framework/Versions/$(PYVERSION)83 # PYTHONINC := -I$(PYTHONROOT)/include/python$(PYVERSION)84 # PYTHONLIB := -L$(PYTHONROOT)/lib -framework Python85 #endif86 87 # the linker88 74 LD := $(CXX) 89 75 … … 92 78 BOOSTINC := -I$(BOOSTROOT)/include/boost -I$(BOOSTROOT)/include 93 79 94 LDFLAGS := -shared -Wl$(TARGET) -s -Xlinker -rpath -Xlinker $(BOOSTROOT)/lib:$(PYTHONROOT)/lib:$(CASALIB) 95 ifeq "$(CASAARCH)" "darwin" 96 LDFLAGS := -bundle 97 endif 80 LDFLAGS += -shared 98 81 99 82 100 83 # DO NOT MODIFY AFTER THIS 101 INCDIRS := -I. $(CASAINC) $(CFITSIOINC) $(BOOSTINC) $(PYTHONINC)84 INCDIRS := -I. $(CASAINC) -I$(CFITSIOINCD) $(BOOSTINC) $(addprefix -I, $(PYTHONINCD)) -I$(ASAPROOT)/$(ATNFD) -I$(PYRAPINCD) 102 85 LIBS := $(PYTHONLIB) $(BOOSTLIB) $(CASAPPLIB) 103 86 -
trunk/src/NROFiller.cpp
r1849 r1949 20 20 #include "NROFiller.h" 21 21 #include "STHeader.h" 22 #include <casa/Containers/Record.h> 22 23 #include <atnf/PKSIO/SrcType.h> 23 24 … … 36 37 } 37 38 38 bool NROFiller::open(const std::string& filename)39 bool NROFiller::open(const std::string& filename, const Record& rec) 39 40 { 40 41 bool status = true ; -
trunk/src/NROFiller.h
r1849 r1949 45 45 virtual ~NROFiller(); 46 46 47 bool open(const std::string& filename ) ;47 bool open(const std::string& filename, const casa::Record& rec) ; 48 48 void fill() ; 49 49 void close() ; -
trunk/src/PKSFiller.cpp
r1849 r1949 20 20 #include <casa/Arrays/ArrayLogical.h> 21 21 #include <casa/Utilities/Regex.h> 22 #include <casa/Utilities/DataType.h> 22 23 #include <casa/Logging/LogIO.h> 23 24 25 #include <casa/Containers/Record.h> 24 26 #include <measures/Measures/MDirection.h> 25 27 #include <measures/Measures/MeasConvert.h> … … 34 36 35 37 #include <time.h> 38 #include <sstream> 36 39 37 40 #include "STDefs.h" … … 58 61 } 59 62 60 bool PKSFiller::open( const std::string& filename )63 bool PKSFiller::open( const std::string& filename, const Record& rec) 61 64 { 62 65 Bool haveBase, haveSpectra; … … 74 77 Vector<uInt> nchans,npols; 75 78 76 String antenna("0"); 79 String antenna(""); 80 Bool getPt = False; 81 82 // parsing MS options 83 if ( rec.isDefined( "ms" ) ) { 84 Record msrec = rec.asRecord( "ms" ) ; 85 //msrec.print( cout ) ; 86 if ( msrec.isDefined( "getpt" ) ) { 87 getPt = msrec.asBool( "getpt" ) ; 88 } 89 if ( msrec.isDefined( "antenna" ) ) { 90 if ( msrec.type( msrec.fieldNumber( "antenna" ) ) == TpInt ) { 91 Int antInt = msrec.asInt( "antenna" ) ; 92 ostringstream oss ; 93 oss << antInt ; 94 antenna = String( oss ) ; 95 } 96 else { 97 antenna = msrec.asString( "antenna" ) ; 98 } 99 } 100 } 77 101 78 102 reader_ = getPKSreader(inName, antenna, 0, 0, format, beams, ifs, … … 146 170 Vector<Int> start(nIF_, 1); 147 171 Vector<Int> end(nIF_, 0); 148 Bool getPt = False;149 172 reader_->select(beams, ifs, start, end, ref, True, haveXPol_[0], False, getPt); 150 173 setHeader(header); … … 263 286 Int match = pksrec.srcName.matches(rx); 264 287 std::string srcname; 288 Int srctype = Int(SrcType::NOTYPE); 265 289 if (match) { 266 290 srcname = pksrec.srcName; 291 srctype = Int(SrcType::PSOFF); 267 292 } else { 268 293 srcname = pksrec.srcName.before(rx2); 269 }270 Int srctype = match;271 if ( pksrec.srcType != -1) {294 srctype = Int(SrcType::PSON); 295 } 296 if ( pksrec.srcType != Int(SrcType::NOTYPE)) { 272 297 srctype = pksrec.srcType ; 273 298 } -
trunk/src/PKSFiller.h
r1849 r1949 20 20 #include <casa/Arrays/Vector.h> 21 21 22 22 23 #include "FillerBase.h" 23 24 #include "Scantable.h" 24 25 26 class casa::Record; 25 27 class PKSreader; 26 28 … … 34 36 virtual ~PKSFiller(); 35 37 36 // bool open(const std::string& filename, const Record& rec)=0;37 bool open(const std::string& filename);38 bool open(const std::string& filename, const casa::Record& rec); 39 // bool open(const std::string& filename); 38 40 void fill(); 39 41 void close(); -
trunk/src/SConscript
- Property svn:mergeinfo changed (with no actual effect on merging)
r1849 r1949 8 8 cpps = env.SGlob("*.cpp") 9 9 pycpps = env.SGlob("python_*.cpp") 10 for pf in pycpps: cpps.remove(pf) 10 for pf in pycpps: 11 cpps.remove(pf) 11 12 12 13 # location of libcasav.a … … 18 19 myenv.Prepend( LIBS = ['asap'] ) 19 20 21 shenv = myenv.Clone() 22 pyrapdir = shenv.get("pyrapint", None) 23 if pyrapdir: 24 shenv.PrependUnique(CPPPATH=pyrapdir) 25 pycpps += shenv.Glob('%s/pyrap/*/*.cc' % pyrapdir) 20 26 # Finally create the library for the module 21 if not hasattr( myenv, "LoadableModule"):22 myenv.LoadableModule = myenv.SharedLibrary23 so = myenv.LoadableModule( target = "_asap.so", source = pycpps, SHLIBSUFFIX="" )24 #test = myenv.Program("test", cpps)27 if not hasattr(shenv, "LoadableModule"): 28 shenv.LoadableModule = shenv.SharedLibrary 29 so = shenv.LoadableModule( target = "_asap.so", source = pycpps, SHLIBSUFFIX="" ) 30 #test = shenv.Program("test", cpps) 25 31 Return("so") 26 32 -
trunk/src/STFit.cpp
r1849 r1949 70 70 table_.addColumn(ArrayColumnDesc<Int>("COMPONENTS")); 71 71 table_.addColumn(ArrayColumnDesc<Double>("PARAMETERS")); 72 // table_.addColumn(ArrayColumnDesc<Double>("ERRORS")); 72 73 table_.addColumn(ArrayColumnDesc<Bool>("PARMASKS")); 73 74 table_.addColumn(ArrayColumnDesc<String>("FRAMEINFO")); … … 77 78 compCol_.attach(table_,"COMPONENTS"); 78 79 parCol_.attach(table_,"PARAMETERS"); 80 // errCol_.attach(table_,"ERRORS"); 79 81 maskCol_.attach(table_,"PARMASKS"); 80 82 frameCol_.attach(table_,"FRAMEINFO"); … … 102 104 // add new row if new id 103 105 if ( !foundentry ) table_.addRow(); 106 104 107 funcCol_.put(rno, mathutil::toVectorString(fit.getFunctions())); 105 108 compCol_.put(rno, Vector<Int>(fit.getComponents())); 106 parCol_.put(rno, Vector<Double>(fit.getParameters())); 109 const std::vector<float>& pvec = fit.getParameters(); 110 Vector<Double> dvec(pvec.size()); 111 for (size_t i=0; i < dvec.nelements(); ++i) { 112 dvec[i] = Double(pvec[i]); 113 } 114 parCol_.put(rno, dvec); 115 /* 116 const std::vector<double>& evec = fit.getErrors(); 117 for (size_t i=0; i < dvec.nelements(); ++i) { 118 dvec[i] = Double(evec[i]); 119 } 120 errCol_.put(rno, dvec); 121 */ 107 122 maskCol_.put(rno, Vector<Bool>(fit.getParmasks())); 108 123 frameCol_.put(rno, mathutil::toVectorString(fit.getFrameinfo())); 109 124 idCol_.put(rno, resultid); 125 110 126 return resultid; 111 127 } … … 130 146 fit.setComponents(istl); 131 147 Vector<Double> dvec; 132 std::vector<double> dstl;133 148 rec.get("PARAMETERS", dvec); 149 std::vector<float> dstl(dvec.begin(), dvec.end()); 150 fit.setParameters(dstl); 151 /* 134 152 dvec.tovector(dstl); 135 153 fit.setParameters(dstl); 154 dvec.resize(); 155 rec.get("ERRORS", dvec); 156 dvec.tovector(dstl); 157 fit.setErrors(dstl); 158 */ 136 159 Vector<Bool> bvec; 137 160 std::vector<bool> bstl; -
trunk/src/STFit.h
r1849 r1949 49 49 casa::ArrayColumn<casa::Int> compCol_; 50 50 casa::ArrayColumn<casa::Double> parCol_; 51 // casa::ArrayColumn<casa::Double> errCol_; 51 52 casa::ArrayColumn<casa::Bool> maskCol_; 52 53 casa::ArrayColumn<casa::String> frameCol_; -
trunk/src/STFitEntry.cpp
r1849 r1949 11 11 // 12 12 #include "STFitEntry.h" 13 #include <casa/iostream.h> 13 14 15 using namespace casa; 14 16 namespace asap { 15 17 16 STFitEntry::STFitEntry() 18 STFitEntry::STFitEntry() 19 /* : 20 functions_( std::vector<std::string>()), 21 components_(std::vector<int>()), 22 parameters_(std::vector<float>()), 23 errors_(std::vector<float>()), 24 parmasks_(std::vector<bool>()), 25 frameinfo_(std::vector<std::string>()) 26 */ 17 27 { 18 28 } … … 20 30 { 21 31 if ( this != &other ) { 22 this->functions_ = other.functions_;32 this->functions_ = std::vector<std::string>(); 23 33 this->components_ = other.components_; 24 34 this->parameters_ = other.parameters_; 25 this-> parmasks_ = other.parmasks_;35 this->errors_ = other.errors_; 26 36 this->frameinfo_ = other.frameinfo_; 27 37 } 28 38 } 29 39 40 STFitEntry& STFitEntry::operator=(const STFitEntry& other) 41 { 42 if ( this != &other ) { 43 this->functions_ = other.functions_; 44 this->components_ = other.components_; 45 this->parameters_ = other.parameters_; 46 this->errors_ = other.errors_; 47 this->parmasks_ = other.parmasks_; 48 this->frameinfo_ = other.frameinfo_; 49 } 50 return *this; 51 } 30 52 31 53 STFitEntry::~STFitEntry() -
trunk/src/STFitEntry.h
r1849 r1949 28 28 STFitEntry(const STFitEntry& other); 29 29 30 STFitEntry& operator=(const STFitEntry& other); 31 30 32 ~STFitEntry(); 31 33 … … 34 36 void setComponents(const std::vector<int>& c) 35 37 { components_ = c; } 36 void setParameters(const std::vector< double>& p)38 void setParameters(const std::vector<float>& p) 37 39 { parameters_ = p; } 40 void setErrors(const std::vector<float>& p) 41 { errors_ = p; } 38 42 void setParmasks(const std::vector<bool>& m) 39 43 { parmasks_ = m; } 40 44 void setFrameinfo(const std::vector<std::string>& f) 41 45 { frameinfo_ = f; } 42 43 46 std::vector<std::string> getFunctions() const { return functions_; } 44 47 std::vector<int> getComponents() const { return components_; } 45 std::vector<double> getParameters() const { return parameters_; } 48 std::vector<float> getParameters() const { return parameters_; } 49 std::vector<float> getErrors() const { return errors_; } 46 50 std::vector<bool> getParmasks() const { return parmasks_; } 47 51 std::vector<std::string> getFrameinfo() const { return frameinfo_; } 48 52 49 53 private: 54 50 55 std::vector<std::string> functions_; 51 56 std::vector<int> components_; 52 std::vector<double> parameters_; 57 std::vector<float> parameters_; 58 std::vector<float> errors_; 53 59 std::vector<bool> parmasks_; 54 60 std::vector<std::string> frameinfo_; -
trunk/src/STFitter.cpp
r1849 r1949 142 142 if (ncomp < 1) throw (AipsError("Need at least one gaussian to fit.")); 143 143 funcs_.resize(ncomp); 144 funcnames_.clear(); 145 funccomponents_.clear(); 144 146 for (Int k=0; k<ncomp; ++k) { 145 147 funcs_[k] = new Gaussian1D<Float>(); 148 funcnames_.push_back(expr); 149 funccomponents_.push_back(3); 146 150 } 147 151 } else if (expr == "poly") { 148 152 funcs_.resize(1); 153 funcnames_.clear(); 154 funccomponents_.clear(); 149 155 funcs_[0] = new Polynomial<Float>(ncomp); 156 funcnames_.push_back(expr); 157 funccomponents_.push_back(ncomp); 150 158 } else if (expr == "lorentz") { 151 159 if (ncomp < 1) throw (AipsError("Need at least one lorentzian to fit.")); 152 160 funcs_.resize(ncomp); 161 funcnames_.clear(); 162 funccomponents_.clear(); 153 163 for (Int k=0; k<ncomp; ++k) { 154 164 funcs_[k] = new Lorentzian1D<Float>(); 165 funcnames_.push_back(expr); 166 funccomponents_.push_back(3); 155 167 } 156 168 } else { … … 409 421 } 410 422 423 STFitEntry Fitter::getFitEntry() const 424 { 425 STFitEntry fit; 426 fit.setParameters(getParameters()); 427 fit.setErrors(getErrors()); 428 fit.setComponents(funccomponents_); 429 fit.setFunctions(funcnames_); 430 fit.setParmasks(getFixedParameters()); 431 return fit; 432 } -
trunk/src/STFitter.h
r1849 r1949 40 40 #include <scimath/Functionals/CompoundFunction.h> 41 41 42 #include "STFitEntry.h" 43 42 44 namespace asap { 43 45 … … 69 71 70 72 std::vector<float> evaluate(int whichComp) const; 73 74 STFitEntry getFitEntry() const; 75 71 76 private: 72 77 void clear(); … … 75 80 casa::Vector<casa::Bool> m_; 76 81 casa::PtrBlock<casa::Function<casa::Float>* > funcs_; 82 std::vector<std::string> funcnames_; 83 std::vector<int> funccomponents_; 84 77 85 //Bool estimateSet_; 78 86 casa::Float chisquared_; -
trunk/src/STMath.cpp
r1849 r1949 1796 1796 out.push_back(outstat); 1797 1797 } 1798 return out; 1799 } 1800 1801 std::vector< float > STMath::statisticRow( const CountedPtr< Scantable > & in, 1802 const std::vector< bool > & mask, 1803 const std::string& which, 1804 int row ) 1805 { 1806 1807 Vector<Bool> m(mask); 1808 const Table& tab = in->table(); 1809 ROArrayColumn<Float> specCol(tab, "SPECTRA"); 1810 ROArrayColumn<uChar> flagCol(tab, "FLAGTRA"); 1811 std::vector<float> out; 1812 1813 Vector<Float> spec; specCol.get(row, spec); 1814 Vector<uChar> flag; flagCol.get(row, flag); 1815 MaskedArray<Float> ma = maskedArray(spec, flag); 1816 float outstat = 0.0; 1817 if ( spec.nelements() == m.nelements() ) { 1818 outstat = mathutil::statistics(which, ma(m)); 1819 } else { 1820 outstat = mathutil::statistics(which, ma); 1821 } 1822 out.push_back(outstat); 1823 1798 1824 return out; 1799 1825 } -
trunk/src/STMath.h
r1849 r1949 262 262 const casa::CountedPtr<Scantable> &ref, 263 263 casa::Double choffset, 264 casa::Double choffset = 0.0 );264 casa::Double choffset2 = 0.0 ); 265 265 266 266 /** … … 277 277 const std::vector<bool>& mask, 278 278 const std::string& which); 279 280 std::vector<float> statisticRow(const casa::CountedPtr<Scantable>& in, 281 const std::vector<bool>& mask, 282 const std::string& which, 283 int row); 279 284 280 285 std::vector< int > minMaxChan(const casa::CountedPtr<Scantable>& in, -
trunk/src/STMathWrapper.h
r1849 r1949 132 132 { return STMath::statistic(in.getCP(), mask, which); } 133 133 134 std::vector<float> statisticRow(const ScantableWrapper& in, 135 const std::vector<bool>& mask, 136 const std::string& which, 137 int row) 138 { return STMath::statisticRow(in.getCP(), mask, which, row); } 139 134 140 std::vector<int> minMaxChan(const ScantableWrapper& in, 135 141 const std::vector<bool>& mask, -
trunk/src/STSelector.cpp
r1849 r1949 270 270 } 271 271 272 std::vector< int > asap::STSelector::getRows( ) const 273 { 274 return rowselection_ ; 275 } 276 272 277 std::string asap::STSelector::print( ) 273 278 { -
trunk/src/STSelector.h
r1849 r1949 57 57 std::vector<int> getCycles() const; 58 58 std::vector<int> getTypes() const; 59 std::vector<int> getRows() const; 59 60 std::vector<std::string> getPolTypes() const; 60 61 std::string getTaQL() const { return taql_; } -
trunk/src/Scantable.cpp
r1849 r1949 101 101 fitTable_ = STFit(*this); 102 102 table_.rwKeywordSet().defineTable("FIT", fitTable_.table()); 103 table_.tableInfo().setType( "Scantable" ) ; 103 104 originalTable_ = table_; 104 105 attach(); … … 120 121 table_ = tab; 121 122 } 123 table_.tableInfo().setType( "Scantable" ) ; 122 124 123 125 attachSubtables(); … … 165 167 table_.markForDelete(); 166 168 } 169 table_.tableInfo().setType( "Scantable" ) ; 167 170 /// @todo reindex SCANNO, recompute nbeam, nif, npol 168 171 if ( clear ) copySubtables(other); … … 681 684 std::string Scantable::formatTime(const MEpoch& me, bool showdate) const 682 685 { 686 return formatTime(me, showdate, 0); 687 } 688 689 std::string Scantable::formatTime(const MEpoch& me, bool showdate, uInt prec) const 690 { 683 691 MVTime mvt(me.getValue()); 684 692 if (showdate) 685 mvt.setFormat(MVTime::YMD); 693 //mvt.setFormat(MVTime::YMD); 694 mvt.setFormat(MVTime::YMD, prec); 686 695 else 687 mvt.setFormat(MVTime::TIME); 696 //mvt.setFormat(MVTime::TIME); 697 mvt.setFormat(MVTime::TIME, prec); 688 698 ostringstream oss; 689 699 oss << mvt; … … 1032 1042 } 1033 1043 1034 std::string Scantable::getTime(int whichrow, bool showdate) const 1035 { 1036 MEpoch::ROScalarColumn timeCol(table_, "TIME"); 1044 // std::string Scantable::getTime(int whichrow, bool showdate) const 1045 // { 1046 // MEpoch::ROScalarColumn timeCol(table_, "TIME"); 1047 // MEpoch me; 1048 // if (whichrow > -1) { 1049 // me = timeCol(uInt(whichrow)); 1050 // } else { 1051 // Double tm; 1052 // table_.keywordSet().get("UTC",tm); 1053 // me = MEpoch(MVEpoch(tm)); 1054 // } 1055 // return formatTime(me, showdate); 1056 // } 1057 1058 std::string Scantable::getTime(int whichrow, bool showdate, uInt prec) const 1059 { 1037 1060 MEpoch me; 1038 if (whichrow > -1) { 1039 me = timeCol(uInt(whichrow)); 1040 } else { 1041 Double tm; 1042 table_.keywordSet().get("UTC",tm); 1043 me = MEpoch(MVEpoch(tm)); 1044 } 1045 return formatTime(me, showdate); 1061 me = getEpoch(whichrow); 1062 return formatTime(me, showdate, prec); 1046 1063 } 1047 1064 … … 1709 1726 } 1710 1727 1728 bool Scantable::getFlagtraFast(int whichrow) 1729 { 1730 uChar flag; 1731 Vector<uChar> flags; 1732 flagsCol_.get(uInt(whichrow), flags); 1733 for (int i = 0; i < flags.size(); i++) { 1734 if (i==0) { 1735 flag = flags[i]; 1736 } 1737 else { 1738 flag &= flags[i]; 1739 } 1740 return ((flag >> 7) == 1); 1741 } 1742 } 1743 1744 void Scantable::doPolyBaseline(const std::vector<bool>& mask, int order, int rowno, Fitter& fitter) 1745 { 1746 fitter.setExpression("poly", order); 1747 1748 std::vector<double> abcsd = getAbcissa(rowno); 1749 std::vector<float> abcs; 1750 for (int i = 0; i < abcsd.size(); i++) { 1751 abcs.push_back((float)abcsd[i]); 1752 } 1753 std::vector<float> spec = getSpectrum(rowno); 1754 std::vector<bool> fmask = getMask(rowno); 1755 if (fmask.size() != mask.size()) { 1756 throw(AipsError("different mask sizes")); 1757 } 1758 for (int i = 0; i < fmask.size(); i++) { 1759 fmask[i] = fmask[i] && mask[i]; 1760 } 1761 fitter.setData(abcs, spec, fmask); 1762 1763 fitter.lfit(); 1764 } 1765 1766 void Scantable::polyBaselineBatch(const std::vector<bool>& mask, int order) 1767 { 1768 Fitter fitter = Fitter(); 1769 for (uInt rowno=0; rowno < nrow(); ++rowno) { 1770 doPolyBaseline(mask, order, rowno, fitter); 1771 setSpectrum(fitter.getResidual(), rowno); 1772 } 1773 } 1774 1775 STFitEntry Scantable::polyBaseline(const std::vector<bool>& mask, int order, int rowno) 1776 { 1777 Fitter fitter = Fitter(); 1778 doPolyBaseline(mask, order, rowno, fitter); 1779 setSpectrum(fitter.getResidual(), rowno); 1780 return fitter.getFitEntry(); 1781 } 1782 1711 1783 } 1712 1784 //namespace asap -
trunk/src/Scantable.h
r1849 r1949 18 18 // AIPS++ 19 19 #include <casa/aips.h> 20 #include <casa/Containers/Record.h> 20 21 #include <casa/Arrays/MaskedArray.h> 21 22 #include <casa/BasicSL/String.h> … … 47 48 #include "STFit.h" 48 49 #include "STFitEntry.h" 50 #include "STFitter.h" 49 51 50 52 namespace asap { … … 366 368 367 369 std::string summary(bool verbose=false); 368 std::string getTime(int whichrow=-1, bool showdate=true) const; 370 //std::string getTime(int whichrow=-1, bool showdate=true) const; 371 std::string getTime(int whichrow=-1, bool showdate=true, casa::uInt prec=0) const; 369 372 double getIntTime(int whichrow) const { return integrCol_(whichrow); } 370 373 … … 486 489 void regridChannel( int nchan, double dnu, int irow ) ; 487 490 491 bool getFlagtraFast(int whichrow); 492 493 void polyBaselineBatch(const std::vector<bool>& mask, int order); 494 STFitEntry polyBaseline(const std::vector<bool>& mask, int order, int rowno); 488 495 489 496 private: … … 499 506 500 507 std::string formatTime(const casa::MEpoch& me, bool showdate)const; 508 std::string formatTime(const casa::MEpoch& me, bool showdate, casa::uInt prec)const; 501 509 502 510 /** … … 506 514 */ 507 515 std::string formatDirection(const casa::MDirection& md) const; 508 509 516 510 517 /** … … 598 605 const casa::String&, 599 606 const casa::Array<T2>&); 607 608 void doPolyBaseline(const std::vector<bool>& mask, int order, int rowno, Fitter& fitter); 600 609 }; 601 610 -
trunk/src/ScantableWrapper.h
r1849 r1949 19 19 #include "MathUtils.h" 20 20 #include "STFit.h" 21 #include "STFitEntry.h" 21 22 #include "Scantable.h" 22 23 #include "STCoordinate.h" … … 83 84 { return table_->getTsys(whichrow); } 84 85 85 std::string getTime(int whichrow=0) const 86 { return table_->getTime(whichrow); } 86 //std::string getTime(int whichrow=0) const 87 // { return table_->getTime(whichrow); } 88 std::string getTime(int whichrow=0, int prec = 0) const 89 { return table_->getTime(whichrow, true, casa::uInt(prec)); } 87 90 88 91 double getIntTime(int whichrow=0) const … … 250 253 { table_->reshapeSpectrum( nmin, nmax ); } 251 254 255 STFitEntry polyBaseline(const std::vector<bool>& mask, int order, int rowno) 256 { return table_->polyBaseline(mask, order, rowno); } 257 258 void polyBaselineBatch(const std::vector<bool>& mask, int order) 259 { table_->polyBaselineBatch(mask, order); } 260 261 bool getFlagtraFast(int whichrow=0) const 262 { return table_->getFlagtraFast(whichrow); } 263 264 252 265 private: 253 266 casa::CountedPtr<Scantable> table_; -
trunk/src/python_LogSink.cpp
r1849 r1949 41 41 .def( init <> () ) 42 42 .def("post", &AsapLogSink::postMessage, 43 (boost::python::arg(" location")="",44 boost::python::arg(" priority")="INFO"))43 (boost::python::arg("priority")="INFO", 44 boost::python::arg("origin")="")) 45 45 .def("pop", &AsapLogSink::popMessages) 46 46 ; -
trunk/src/python_STFitEntry.cpp
r1849 r1949 44 44 .def("getfixedparameters", &STFitEntry::getParmasks) 45 45 .def("getparameters", &STFitEntry::getParameters) 46 .def("geterrors", &STFitEntry::getErrors) 46 47 .def("getfunctions", &STFitEntry::getFunctions) 47 48 .def("getcomponents", &STFitEntry::getComponents) … … 49 50 .def("setfixedparameters", &STFitEntry::setParmasks) 50 51 .def("setparameters", &STFitEntry::setParameters) 52 .def("seterrors", &STFitEntry::setErrors) 51 53 .def("setfunctions", &STFitEntry::setFunctions) 52 54 .def("setcomponents", &STFitEntry::setComponents) -
trunk/src/python_STMath.cpp
r1849 r1949 59 59 .def("_dofs", &STMathWrapper::dofs) 60 60 .def("_stats", &STMathWrapper::statistic) 61 .def("_statsrow", &STMathWrapper::statisticRow) 61 62 .def("_minmaxchan", &STMathWrapper::minMaxChan) 62 63 .def("_freqswitch", &STMathWrapper::freqSwitch) -
trunk/src/python_STSelector.cpp
r1849 r1949 30 30 .def("_getcycles", &STSelector::getCycles) 31 31 .def("_gettypes", &STSelector::getTypes) 32 .def("_getrows", &STSelector::getRows) 32 33 .def("_gettaql", &STSelector::getTaQL) 33 34 .def("_getorder", &STSelector::getSortOrder) -
trunk/src/python_Scantable.cpp
r1849 r1949 99 99 .def("_getparangle", &ScantableWrapper::getParAngle, 100 100 (boost::python::arg("whichrow")=0) ) 101 //.def("_gettime", &ScantableWrapper::getTime, 102 // (boost::python::arg("whichrow")=0) ) 101 103 .def("_gettime", &ScantableWrapper::getTime, 102 (boost::python::arg("whichrow")=0) ) 104 (boost::python::arg("whichrow")=0, 105 boost::python::arg("prec")=0) ) 103 106 .def("_getinttime", &ScantableWrapper::getIntTime, 104 107 (boost::python::arg("whichrow")=0) ) … … 139 142 (boost::python::arg("nmin")=-1, 140 143 boost::python::arg("nmax")=-1) ) 144 .def("_poly_baseline", &ScantableWrapper::polyBaseline) 145 .def("_poly_baseline_batch", &ScantableWrapper::polyBaselineBatch) 146 .def("_getflagtrafast", &ScantableWrapper::getFlagtraFast, 147 (boost::python::arg("whichrow")=0) ) 141 148 ; 142 149 }; -
trunk/src/python_asap.cpp
r1849 r1949 44 44 #include <pyrap/Converters/PycExcp.h> 45 45 #include <pyrap/Converters/PycBasicData.h> 46 #include <pyrap/Converters/PycValueHolder.h> 47 #include <pyrap/Converters/PycRecord.h> 46 48 #endif 47 49 … … 108 110 casa::pyrap::register_convert_basicdata(); 109 111 casa::pyrap::register_convert_std_vector<asap::ScantableWrapper>(); 112 casa::pyrap::register_convert_std_vector<int>(); 113 casa::pyrap::register_convert_std_vector<uint>(); 114 casa::pyrap::register_convert_std_vector<float>(); 115 casa::pyrap::register_convert_std_vector<double>(); 116 casa::pyrap::register_convert_std_vector<std::string>(); 117 casa::pyrap::register_convert_std_vector<bool>(); 118 casa::pyrap::register_convert_casa_valueholder(); 119 casa::pyrap::register_convert_casa_record(); 110 120 #endif 111 121 } -
trunk/test/test_scantable.py
r1849 r1949 3 3 import shutil 4 4 import datetime 5 from nose.tools import * 5 6 from asap import scantable, selector, mask_not 6 7 from asap.logging import asaplog 8 # no need for log messages 7 9 asaplog.disable() 8 9 from nose.tools import *10 10 11 11 def tempdir_setup(): … … 72 72 sel.set_polarisations("YY") 73 73 self.st.set_selection(sel) 74 assert_equal(self.st.getpolnos(), (1,))74 assert_equal(self.st.getpolnos(), [1]) 75 75 sel1 = self.st.get_selection() 76 76 assert_equal(sel1.get_pols(), [1]) 77 77 self.st.set_selection(pols="XX") 78 assert_equal(self.st.getpolnos(), (0,))78 assert_equal(self.st.getpolnos(), [0]) 79 79 80 80 … … 165 165 def test_drop_scan(self): 166 166 s0 = self.st.drop_scan(1) 167 assert_equal(s0.getscannos(), (0,))167 assert_equal(s0.getscannos(), [0]) 168 168 s1 = self.st.drop_scan([0]) 169 assert_equal(s1.getscannos(), (1,))169 assert_equal(s1.getscannos(), [1]) 170 170 171 171 def test_flag(self): … … 206 206 for spec in ds: 207 207 assert_almost_equals(sum(spec)/len(spec), 0.0, 5) 208 209 def test_auto_poly_baseline(self): 210 q = self.st.auto_quotient() 211 b = q.auto_poly_baseline(insitu=False) 212 res_rms = (q-b).stats('rms') 213 assert_almost_equals(res_rms[0], 0.38370, 5) 214 assert_almost_equals(res_rms[1], 0.38780, 5) 215 216 217 def test_poly_baseline(self): 218 q = self.st.auto_quotient() 219 msk = q.create_mask([0.0, 1471.0], [1745.0, 4095.0]) 220 b = q.poly_baseline(order=0, mask=msk,insitu=False) 221 res_rms = (q-b).stats('rms') 222 assert_almost_equals(res_rms[0], 0.38346, 5) 223 assert_almost_equals(res_rms[1], 0.38780, 5)
Note:
See TracChangeset
for help on using the changeset viewer.