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