Changeset 404
- Timestamp:
- 06/08/09 13:48:16 (4 years ago)
- Location:
- MGET/Branches/Jason/PythonPackage/src/GeoEco
- Files:
-
- 2 added
- 8 removed
- 33 modified
-
ArcGIS.py (modified) (4 diffs)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2030.pyd (deleted)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2031.pyd (deleted)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2040.pyd (deleted)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2041.pyd (deleted)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2050.pyd (added)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2051.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2060.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2061.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2062.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2070.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2071.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2072.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2080.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2081.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python24/_rpy2090.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2030.pyd (deleted)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2031.pyd (deleted)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2040.pyd (deleted)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2041.pyd (deleted)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2050.pyd (added)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2051.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2060.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2061.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2062.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2070.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2071.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2072.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2080.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2081.pyd (modified) (previous)
-
AssimilatedModules/rpy/lib/win32/Python25/_rpy2090.pyd (modified) (previous)
-
AssimilatedModules/rpy/src-rpy-1.0.3/BUILDING_FOR_GEOECO.txt (modified) (1 diff)
-
AssimilatedModules/rpy/src-rpy-1.0.3/src/io.c (modified) (2 diffs)
-
AssimilatedModules/rpy/src-rpy-1.0.3/src/rpymodule.c (modified) (2 diffs)
-
DataManagement/ArcGISRasters.py (modified) (3 diffs)
-
DataManagement/Directories.py (modified) (1 diff)
-
DataProducts/Aviso.py (modified) (5 diffs)
-
DataProducts/NOAA/CoastWatchAVHRR.py (modified) (1 diff)
-
Documentation/GettingStarted.xsl (modified) (3 diffs)
-
R.py (modified) (4 diffs)
-
Statistics/Exploratory.py (modified) (3 diffs)
-
Statistics/Modeling.py (modified) (25 diffs)
-
Statistics/PredictLMForArcGISRasters.r (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
-
MGET/Branches/Jason/PythonPackage/src/GeoEco/ArcGIS.py
r380 r404 933 933 # turn on debug logging.) 934 934 935 if invokedFromArcGISApplication and GeoprocessorManager._ArcGISMajorVersion == 9 and GeoprocessorManager._ArcGISMinorVersion >= 3: 935 if invokedFromArcGISApplication and (GeoprocessorManager._ArcGISMajorVersion > 9 or GeoprocessorManager._ArcGISMajorVersion == 9 and GeoprocessorManager._ArcGISMinorVersion >= 3): 936 _ShutdownLoggingToAvoidArcGIS93MemoryLeak() 937 GeoprocessorManager.SetGeoprocessor(None) 936 938 raise 937 939 else: … … 940 942 if caughtException: 941 943 Logger.Debug(_(u'Python script %s exiting with return value 1, indicating failure.') % sys.argv[0]) 944 GeoprocessorManager.SetGeoprocessor(None) 942 945 sys.exit(1) 943 946 … … 945 948 946 949 Logger.Debug(_(u'Python script %s completed successfully.') % sys.argv[0]) 950 951 if invokedFromArcGISApplication and (GeoprocessorManager._ArcGISMajorVersion > 9 or GeoprocessorManager._ArcGISMajorVersion == 9 and GeoprocessorManager._ArcGISMinorVersion >= 3): 952 _ShutdownLoggingToAvoidArcGIS93MemoryLeak() 953 GeoprocessorManager.SetGeoprocessor(None) 954 955 def _ShutdownLoggingToAvoidArcGIS93MemoryLeak(): 956 957 # Clean up objects allocated by the logging module that leak when 958 # tools are run "in process" under ArcGIS 9.3. For a detailed 959 # discussion, see MGET ticket #361. 960 961 try: 962 logging.raiseExceptions = 0 963 logging.shutdown() 964 while len(logging._handlerList) > 0: 965 del logging._handlerList[0] 966 import atexit 967 for i in range(len(atexit._exithandlers)): 968 if atexit._exithandlers[i][0] == logging.shutdown: 969 del atexit._exithandlers[i] 970 break 971 except: 972 pass 947 973 948 974 … … 1386 1412 geoprocessor = GeoprocessorManager.GetGeoprocessor() 1387 1413 if geoprocessor is not None: 1388 while i < geoprocessor.MessageCount: 1389 sev = geoprocessor.GetSeverity(i) 1390 if sev == 0: 1391 self._LogInfo(geoprocessor.GetMessage(i)) 1392 elif sev == 1: 1393 self._LogWarning(geoprocessor.GetMessage(i)) 1394 else: 1395 self._LogError(geoprocessor.GetMessage(i)) 1396 i += 1 1414 try: 1415 while i < geoprocessor.MessageCount: 1416 sev = geoprocessor.GetSeverity(i) 1417 if sev == 0: 1418 self._LogInfo(geoprocessor.GetMessage(i)) 1419 elif sev == 1: 1420 self._LogWarning(geoprocessor.GetMessage(i)) 1421 else: 1422 self._LogError(geoprocessor.GetMessage(i)) 1423 i += 1 1424 finally: 1425 del geoprocessor 1397 1426 except: 1398 1427 pass -
MGET/Branches/Jason/PythonPackage/src/GeoEco/AssimilatedModules/rpy/src-rpy-1.0.3/BUILDING_FOR_GEOECO.txt
r389 r404 57 57 14. For each version of Python supported by GeoEco (assume version number is XY, e.g. 25): 58 58 59 a. Run: \pythonXY\python.exe setup.py build59 a. Run: C:\pythonXY\python.exe setup.py build 60 60 b. Run: copy build\lib.win32-X.Y\_rpy2081.pyd ..\lib\win32\PythonXY 61 61 c. Add ..\lib\win32\PythonXY\_rpy2081.pyd to subversion (e.g. right click on the file, select TortoiseSVN --> Add) -
MGET/Branches/Jason/PythonPackage/src/GeoEco/AssimilatedModules/rpy/src-rpy-1.0.3/src/io.c
r320 r404 192 192 193 193 argformat = (char *)PyMem_Malloc((strlen(name)+3)*sizeof(char)); 194 if (!argformat) 195 return PyErr_NoMemory(); 194 196 sprintf(argformat, "O:%s", name); 195 if (!PyArg_ParseTuple(args, argformat, &func)) 196 return NULL; 197 197 if (!PyArg_ParseTuple(args, argformat, &func)) { 198 PyMem_Free(argformat); 199 PyErr_SetString(PyExc_ValueError, "Invalid arguments"); 200 return NULL; 201 } 202 PyMem_Free(argformat); 203 204 Py_XDECREF(*var); 198 205 Py_INCREF(func); 199 206 *var = func; … … 224 231 { 225 232 if (o) { 233 Py_INCREF(o); 226 234 return o; 227 235 } else { -
MGET/Branches/Jason/PythonPackage/src/GeoEco/AssimilatedModules/rpy/src-rpy-1.0.3/src/rpymodule.c
r320 r404 1779 1779 R_RunExitFinalizers(); 1780 1780 CleanEd(); 1781 #if (R_VERSION >= R_Version(2, 7,0))1781 #if (R_VERSION >= R_Version(2,5,0)) 1782 1782 Rf_KillAllDevices(); 1783 1783 #else … … 1842 1842 use_numeric = i; 1843 1843 1844 /* jason.roberts@duke.edu: only initialize numpy the first time we are called; always succeed on subsequent calls*/ 1845 1846 if(first==1) 1847 { 1848 first=0; 1844 1849 #ifdef WITH_NUMERIC 1845 if(use_numeric) 1846 init_numeric(); 1847 #endif 1848 1849 if(first==1) 1850 { 1851 first=0; 1852 Py_INCREF(Py_None); 1853 return Py_None; 1854 } 1855 else 1856 { 1857 PyErr_SetString(PyExc_RuntimeError, "Only one R object may be instantiated per session"); 1858 return NULL; 1859 } 1850 if(use_numeric) 1851 init_numeric(); 1852 #endif 1853 } 1854 1855 Py_INCREF(Py_None); 1856 return Py_None; 1860 1857 } 1861 1858 -
MGET/Branches/Jason/PythonPackage/src/GeoEco/DataManagement/ArcGISRasters.py
r398 r404 74 74 finally: 75 75 cls.DeleteTemporaryRastersThatPreventedArcGISCrash(tempRasters) 76 77 @classmethod 78 def CopySilent(cls, sourceRaster, destinationRaster, overwriteExisting=False): 79 oldLogInfoAsDebug = Logger.GetLogInfoAsDebug() 80 Logger.SetLogInfoAsDebug(True) 81 try: 82 cls.Copy(sourceRaster, destinationRaster, overwriteExisting) 83 finally: 84 Logger.SetLogInfoAsDebug(oldLogInfoAsDebug) 76 85 77 86 @classmethod … … 1167 1176 1168 1177 AddArgumentMetadata(ArcGISRaster.Copy, u'sourceRaster', 1169 typeMetadata=ArcGISRaster TypeMetadata(mustExist=True),1178 typeMetadata=ArcGISRasterLayerTypeMetadata(mustExist=True), 1170 1179 description=_(u'Raster to copy.'), 1171 1180 arcGISDisplayName=_(u'Source raster')) … … 1188 1197 exists."""), 1189 1198 initializeToArcGISGeoprocessorVariable=u'OverwriteOutput') 1199 1200 # Public method: ArcGISRaster.CopySilent 1201 1202 AddMethodMetadata(ArcGISRaster.CopySilent, 1203 shortDescription=_(u'Copies an ArcGIS raster and logs a debug message rather than an informational message.'), 1204 longDescription=_( 1205 u"""This method does the same thing as the Copy method, except it logs 1206 a debug message rather than an informational message. It is intended 1207 for use when the raster-copy operation is not imporant enough to 1208 warrent notifying the user (for example, when an output raster is 1209 extracted from a temporary directory to the final location)."""), 1210 isExposedToPythonCallers=True, 1211 isExposedByCOM=True, 1212 dependencies=[ArcGISDependency(9, 1)]) 1213 1214 CopyArgumentMetadata(ArcGISRaster.Copy, u'cls', ArcGISRaster.CopySilent, u'cls') 1215 CopyArgumentMetadata(ArcGISRaster.Copy, u'sourceRaster', ArcGISRaster.CopySilent, u'sourceRaster') 1216 CopyArgumentMetadata(ArcGISRaster.Copy, u'destinationRaster', ArcGISRaster.CopySilent, u'destinationRaster') 1217 CopyArgumentMetadata(ArcGISRaster.Copy, u'overwriteExisting', ArcGISRaster.CopySilent, u'overwriteExisting') 1190 1218 1191 1219 # Public method: ArcGISRaster.CreateTemporaryRastersToPreventArcGISCrash -
MGET/Branches/Jason/PythonPackage/src/GeoEco/DataManagement/Directories.py
r131 r404 151 151 152 152 gp = GeoprocessorManager.GetWrappedGeoprocessor() 153 if gp is not None and isinstance(gp.ScratchWorkspace, basestring) and len(gp.ScratchWorkspace) > 0 and os.path.isdir(gp.ScratchWorkspace):153 if gp is not None and hasattr(gp, 'ScratchWorkspace') and isinstance(gp.ScratchWorkspace, basestring) and len(gp.ScratchWorkspace) > 0 and os.path.isdir(gp.ScratchWorkspace): 154 154 parentDirectory = os.path.join(gp.ScratchWorkspace, u'GeoEcoTemp') 155 155 -
MGET/Branches/Jason/PythonPackage/src/GeoEco/DataProducts/Aviso.py
r350 r404 21 21 import datetime 22 22 import os 23 import time 23 24 24 25 from GeoEco.DataManagement.ArcGISRasters import ArcGISRaster … … 153 154 coordinateSystem = "PROJCS['Sphere_Mercator',GEOGCS['GCS_Sphere',DATUM['D_Sphere',SPHEROID['Sphere',6371000.0,0.0]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Mercator'],PARAMETER['False_Easting',0.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',180.0],PARAMETER['Standard_Parallel_1',0.0],UNIT['Meter',1.0]]" 154 155 155 # Look up the minimum longitude and latitude and the step156 # size. All of these are in degrees.156 # Look up the minimum longitude and latitude, max latitude, 157 # and the step size (all in degrees). 157 158 158 159 if not ds.has_key('LatLonMin'): … … 163 164 minLon = ds['LatLonMin'][1] 164 165 minLat = ds['LatLonMin'][0] 166 maxLat = max(ds['NbLatitudes'][:]) 165 167 step = ds['LatLonStep'][0] 166 168 167 169 Logger.Debug(_(u'Minimum longitude = %s (on 0-to-360 coordinate system)') % str(minLon)) 168 170 Logger.Debug(_(u'Minimum latitude = %s') % str(minLat)) 171 Logger.Debug(_(u'Maximum latitude = %s') % str(maxLat)) 169 172 Logger.Debug(_(u'Cell size = %s degrees') % str(step)) 170 173 … … 393 396 # Download the image as a numpy array. 394 397 395 image = ds[gridNames[j]][startIndex + i] 398 retries = 0 399 while True: 400 try: 401 image = ds[gridNames[j]][startIndex + i] 402 except Exception, e: 403 if retries < 3 and isinstance(e, ValueError) and str(e).lower() in ['substring not found', 'string length not a multiple of item size']: 404 if retries == 0: 405 Logger.Warning(_(u'Failed to download %(grid)s for %(date)s (time slice %(slice)i) from the Aviso OPeNDAP server. Sleeping for 5 seconds and retrying the download (retry 1 of 3). Error details: the pydap library reported %(error)s: %(msg)s') % {u'grid': gridNames[j], u'date': str(availableDates[i]), u'slice': startIndex + i, u'error': e.__class__.__name__, u'msg': unicode(e)}) 406 time.sleep(5) 407 else: 408 Logger.Warning(_(u'Failed to download %(grid)s for %(date)s (time slice %(slice)i) from the Aviso OPeNDAP server. Sleeping for 60 seconds and retrying the download (retry %(ret)i of 3). Error details: the pydap library reported %(error)s: %(msg)s') % {u'grid': gridNames[j], u'date': str(availableDates[i]), u'slice': startIndex + i, u'error': e.__class__.__name__, u'msg': unicode(e), u'ret': retries+1}) 409 time.sleep(60) 410 retries += 1 411 else: 412 Logger.RaiseException(RuntimeError(_(u'Failed to download %(grid)s for %(date)s (time slice %(slice)i) from the Aviso OPeNDAP server. The download was attempted four times without success. Most likely, a temporary network problem is affecting communication with the server. Please try again later. If this problem continues to occur, contact the MGET development team for more help. Error details: the pydap library reported %(error)s: %(msg)s') % {u'grid': gridNames[j], u'date': str(availableDates[i]), u'slice': startIndex + i, u'error': e.__class__.__name__, u'msg': unicode(e)})) 413 else: 414 break 396 415 397 416 # Transpose and flip the image, so it is in the … … 423 442 # expected map extent. If so, strip it too. 424 443 425 if isGlobal and max (ds['NbLatitudes'][:])== 90.:444 if isGlobal and maxLat == 90.: 426 445 image = image[1:, :] 427 446 -
MGET/Branches/Jason/PythonPackage/src/GeoEco/DataProducts/NOAA/CoastWatchAVHRR.py
r350 r404 81 81 82 82 if self.GetBinariesPath() is None: 83 Logger.RaiseException(SoftwareNotInstalledError(_(u'This function requires the NOAA CoastWatch Utilities version 3.2 or later. Download and install the Utilities from http://coastwatch.noaa.gov/cw _software.html. Be sure you enable the Command Line Tools option; you must explicitly it, as it is disabled by default. Also, if you elect to install the Utilities to a directory other than the default, after the installation is complete you must add the path to the Utilities\' "bin" directory to the PATH environment variable by following the instructions in the "Installation Notes" section of the CoastWatch Utilities User\'s Guide.')))83 Logger.RaiseException(SoftwareNotInstalledError(_(u'This function requires the NOAA CoastWatch Utilities version 3.2 or later. Download and install the Utilities from http://coastwatch.noaa.gov/cwn/cw_software.html. Be sure you enable the Command Line Tools option; you must explicitly it, as it is disabled by default. Also, if you elect to install the Utilities to a directory other than the default, after the installation is complete you must add the path to the Utilities\' "bin" directory to the PATH environment variable by following the instructions in the "Installation Notes" section of the CoastWatch Utilities User\'s Guide.'))) 84 84 85 85 if sys.platform == 'win32' and not os.path.isfile(os.path.join(CoastWatchUtilitiesDependency._BinariesPath, u'cwinfo.exe')) or sys.platform != 'win32' and not os.path.isfile(os.path.join(CoastWatchUtilitiesDependency._BinariesPath, u'cwinfo')): 86 Logger.RaiseException(SoftwareNotInstalledError(_(u'This function requires the NOAA CoastWatch Utilities version 3.2 or later. The Utilities appear to be installed, but when the installation was performed, the Command Line Tools option was not enabled. You must reinstall the Utilities with this option enabled. First uninstall your existing version. Then download the Utilities from http://coastwatch.noaa.gov/cw _software.html and install them. Be sure you enable the Command Line Tools option; you must explicitly it, as it is disabled by default. Also, if you elect to install the Utilities to a directory other than the default, after the installation is complete you must add the path to the Utilities\' "bin" directory to the PATH environment variable by following the instructions in the "Installation Notes" section of the CoastWatch Utilities User\'s Guide.')))86 Logger.RaiseException(SoftwareNotInstalledError(_(u'This function requires the NOAA CoastWatch Utilities version 3.2 or later. The Utilities appear to be installed, but when the installation was performed, the Command Line Tools option was not enabled. You must reinstall the Utilities with this option enabled. First uninstall your existing version. Then download the Utilities from http://coastwatch.noaa.gov/cwn/cw_software.html and install them. Be sure you enable the Command Line Tools option; you must explicitly it, as it is disabled by default. Also, if you elect to install the Utilities to a directory other than the default, after the installation is complete you must add the path to the Utilities\' "bin" directory to the PATH environment variable by following the instructions in the "Installation Notes" section of the CoastWatch Utilities User\'s Guide.'))) 87 87 88 88 CoastWatchUtilitiesDependency._CommandLineUtilitiesInstalled = True -
MGET/Branches/Jason/PythonPackage/src/GeoEco/Documentation/GettingStarted.xsl
r397 r404 1 <?xml version="1.0" encoding="utf-8"?>1 <?xml version="1.0" encoding="utf-8"?> 2 2 3 3 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> … … 456 456 consult an ArcGIS expert for more information.</li> 457 457 458 <li style="margin-top: 1em;"><a href="http://www.r-project.org/"><b>R statistics program</b></a>, version 2.5. 1to 2.9.0 -458 <li style="margin-top: 1em;"><a href="http://www.r-project.org/"><b>R statistics program</b></a>, version 2.5.0 to 2.9.0 - 459 459 this is required by GeoEco tools that perform statistical calculations. You 460 460 must have a version in the range indicated. Newer or older versions will not … … 468 468 do not have MATLAB, download the MATLAB Component Runtime from the link above.</li> 469 469 470 <li style="margin-top: 1em;"><a href="http://coastwatch.noaa.gov/cw _cwfv3.html"><b>NOAA CoastWatch Utilities</b></a>-470 <li style="margin-top: 1em;"><a href="http://coastwatch.noaa.gov/cwn/cw_software.html"><b>NOAA CoastWatch Utilities</b></a>, version 3.2 or later - 471 471 these are required if you want to use any of the GeoEco tools that process 472 472 CoastWatch data. In the CoastWatch Utilities setup, be sure to you enable the -
MGET/Branches/Jason/PythonPackage/src/GeoEco/R.py
r402 r404 106 106 107 107 r = cls.GetInterpreter() 108 if variableNames is not None:109 for i in range(len(variableNames)):110 if isinstance(variableValues[i], (datetime.datetime, datetime.date)) and timeZone is not None:111 r[variableNames[i]] = RInterpreter.PreconvertPythonObjectToRObject(variableValues[i], timeZone=timeZone)112 else:113 r[variableNames[i]] = variableValues[i]114 115 # If the caller passed us tables to load as data frames, load116 # them now.117 118 if tables is not None:119 for i in range(len(tables)):120 cls.LoadDataFrameFromArcGISTable(tables[i], dataFrameNamesForTables[i], xColumnName=xColumnName, yColumnName=yColumnName, zColumnName=zColumnName, mColumnName=mColumnName, stringsAsFactors=stringsAsFactors, timeZone=timeZone)121 122 # Evaluate the caller's statements and return the last one.123 124 oldTracebackLogLevel = RInterpreter.GetLogTracebackAsInfo()125 RInterpreter.SetLogTracebackAsInfo(True)126 108 try: 127 for i in range(len(statements)): 109 if variableNames is not None: 110 for i in range(len(variableNames)): 111 if isinstance(variableValues[i], (datetime.datetime, datetime.date)) and timeZone is not None: 112 r[variableNames[i]] = RInterpreter.PreconvertPythonObjectToRObject(variableValues[i], timeZone=timeZone) 113 else: 114 r[variableNames[i]] = variableValues[i] 115 116 # If the caller passed us tables to load as data frames, load 117 # them now. 118 119 if tables is not None: 120 for i in range(len(tables)): 121 cls.LoadDataFrameFromArcGISTable(tables[i], dataFrameNamesForTables[i], xColumnName=xColumnName, yColumnName=yColumnName, zColumnName=zColumnName, mColumnName=mColumnName, stringsAsFactors=stringsAsFactors, timeZone=timeZone) 122 123 # Evaluate the caller's statements and return the last one. 124 125 oldTracebackLogLevel = RInterpreter.GetLogTracebackAsInfo() 126 RInterpreter.SetLogTracebackAsInfo(True) 127 try: 128 for i in range(len(statements)): 129 try: 130 result = r(statements[i]) 131 except: 132 if len(statements) > 1: 133 Logger.Error(_(u'The failure occurred in statement %(num)i of %(total)i.') % {u'num': i+1, u'total': len(statements)}) 134 raise 135 finally: 136 RInterpreter.SetLogTracebackAsInfo(oldTracebackLogLevel) 137 138 # If the caller requested that we clear the global 139 # environment, do it now. 140 141 finally: 142 if clearGlobalEnv: 128 143 try: 129 result = r(statements[i]) 130 except: 131 if len(statements) > 1: 132 Logger.Error(_(u'The failure occurred in statement %(num)i of %(total)i.') % {u'num': i+1, u'total': len(statements)}) 133 raise 134 finally: 135 RInterpreter.SetLogTracebackAsInfo(oldTracebackLogLevel) 144 r('rm(list=ls())') 145 finally: 146 pass 147 148 # Return the result of the last statement. 136 149 137 150 return result … … 418 431 419 432 if major is None: 420 Logger.RaiseException(SoftwareNotInstalledError(_(u'This functionrequires R %i.%i.%i or a later version, but it is not installed. Please download and install a compatible version from http://www.r-project.org/.') % (self.MinimumMajorVersion, self.MinimumMinorVersion, self.MinimumPatchVersion)))433 Logger.RaiseException(SoftwareNotInstalledError(_(u'This tool requires R %i.%i.%i or a later version, but it is not installed. Please download and install a compatible version from http://www.r-project.org/.') % (self.MinimumMajorVersion, self.MinimumMinorVersion, self.MinimumPatchVersion))) 421 434 422 435 if self.MinimumMajorVersion > major or self.MinimumMajorVersion == major and self.MinimumMinorVersion > minor or self.MinimumMajorVersion == major and self.MinimumMinorVersion == minor and self.MinimumPatchVersion > patch: 423 Logger.RaiseException(SoftwareNotInstalledError(_(u'This function requires R %i.%i.%i or a later version, but verison %i.%i.%i is installed. Please upgrade R to a compatible version. You may download newer versions from http://www.r-project.org/.') % (self.MinimumMajorVersion, self.MinimumMinorVersion, self.MinimumPatchVersion, major, minor, patch))) 436 Logger.RaiseException(SoftwareNotInstalledError(_(u'This tool requires R %i.%i.%i or a later version, but version %i.%i.%i is installed. Please upgrade R to a compatible version. You may download newer versions from http://www.r-project.org/.') % (self.MinimumMajorVersion, self.MinimumMinorVersion, self.MinimumPatchVersion, major, minor, patch))) 437 438 (maxMajor, maxMinor, maxPatch) = self.GetGeoEcoMaxSupportedVersion() 439 440 if major > maxMajor or major == maxMajor and minor > maxMinor or major == maxMajor and minor == maxMinor and patch > maxPatch: 441 Logger.RaiseException(SoftwareNotInstalledError(_(u'This tool requires R, but the version of R that is installed (%i.%i.%i) is not yet supported by this tool. Please remove this version of R, install a compatible version (%i.%i.%i through %i.%i.%i), and try again. You can download R from http://www.r-project.org/. Alternatively, visit the MGET website to see if a new version of MGET is available that supports your version of R. If not, contact the MGET development team and request that support be added.') % (major, minor, patch, self.MinimumMajorVersion, self.MinimumMinorVersion, self.MinimumPatchVersion, maxMajor, maxMinor, maxPatch))) 424 442 425 443 # If we haven't import the rpy module yet, import it. rpy … … 522 540 523 541 rpy.set_default_mode(rpy.PROC_CONVERSION) 542 rpy.proc_table.clear() 524 543 rpy.proc_table[lambda o: True] = RDependency._ConvertRObjectToPythonObject 525 544 … … 559 578 560 579 rpy.r('.libPaths("%s")' % RDependency._PerUserPackageDir.replace('\\', '\\\\')) 580 581 _GeoEcoMaxSupportedRMajorVersion = None 582 _GeoEcoMaxSupportedRMinorVersion = None 583 _GeoEcoMaxSupportedRPatchVersion = None 584 585 @classmethod 586 def GetGeoEcoMaxSupportedVersion(cls): 587 588 # Return immediately if we already obtained the version numbers. 589 590 if RDependency._GeoEcoMaxSupportedRMajorVersion is not None: 591 return (RDependency._GeoEcoMaxSupportedRMajorVersion, RDependency._GeoEcoMaxSupportedRMinorVersion, RDependency._GeoEcoMaxSupportedRPatchVersion) 592 593 # Enumerate the _rpy*.pyd files in the rpy directory. 594 595 import GeoEco 596 rpyDir = os.path.join(os.path.dirname(sys.modules[u'GeoEco'].__file__), 'AssimilatedModules', 'rpy') 597 598 import glob 599 if sys.platform.lower() == 'win32': 600 extensionModules = glob.glob(os.path.join(rpyDir, '_rpy[0123456789][0123456789][0123456789][0123456789].pyd')) 601 else: 602 Logger.RaiseException(NotImplementedError('Tools that use the R statistical program are not currently supported on non-Win32 platforms.')) 603 604 # Extract the version number from the last file. 605 606 extensionModules.sort() 607 608 major = int(extensionModules[-1][-8:-7]) 609 minor = int(extensionModules[-1][-7:-5]) 610 patch = int(extensionModules[-1][-5:-4]) 611 612 RDependency._GeoEcoMaxSupportedRMajorVersion = major 613 RDependency._GeoEcoMaxSupportedRMinorVersion = minor 614 RDependency._GeoEcoMaxSupportedRPatchVersion = patch 615 616 Logger.Debug(_(u'The latest version of R supported by this version of GeoEco is R %i.%i.%i.') % (major, minor, patch)) 617 618 # Return successfully. 619 620 return (major, minor, patch) 561 621 562 622 _RMajorVersion = None -
MGET/Branches/Jason/PythonPackage/src/GeoEco/Statistics/Exploratory.py
r400 r404 61 61 r('%s <- NULL' % transformsName) 62 62 63 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'ScatterplotMatrixForDataframe.r') )63 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'ScatterplotMatrixForDataframe.r'), False) 64 64 if outputFile is None: 65 65 r('ScatterplotMatrix(%s, transforms=%s, .diag="%s", lower="%s", upper="%s")' % (dataFrameName, transformsName, str(diagonal), str(lower), str(upper))) … … 99 99 Logger.RaiseException(ValueError(_(u'The table %(table)s is empty.') % {u'table': table})) 100 100 101 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'DensityHistogramForDataframe.r') )101 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'DensityHistogramForDataframe.r'), False) 102 102 103 103 if transform is None: … … 175 175 Logger.RaiseException(ValueError(_(u'The table %(table)s is empty.') % {u'table': table})) 176 176 177 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'DensityHistogramForDataframe.r') )177 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'DensityHistogramForDataframe.r'), False) 178 178 179 179 if transform is None: -
MGET/Branches/Jason/PythonPackage/src/GeoEco/Statistics/Modeling.py
r400 r404 57 57 58 58 try: 59 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'SummarizeModel.r') )60 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'FitGLMForDataframe.r') )59 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'SummarizeModel.r'), False) 60 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'FitGLMForDataframe.r'), False) 61 61 62 62 tempDir = TemporaryDirectory() … … 134 134 135 135 try: 136 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'SummarizeModel.r') )137 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'FitGAMForDataframe.r') )136 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'SummarizeModel.r'), False) 137 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'FitGAMForDataframe.r'), False) 138 138 139 139 tempDir = TemporaryDirectory() … … 207 207 # Log a summery of the model, to remind the user what it is. 208 208 209 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[GLM.__module__].__file__), 'SummarizeModel.r') )209 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[GLM.__module__].__file__), 'SummarizeModel.r'), False) 210 210 211 211 r('writeLines("")') … … 233 233 # no way to suppress these messages from within R. 234 234 235 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[GLM.__module__].__file__), 'BayesPredictGAMForArcGISRasters.r') )235 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[GLM.__module__].__file__), 'BayesPredictGAMForArcGISRasters.r'), False) 236 236 237 237 oldLoggingLevel = r.LogInfoAsDebug … … 260 260 gp.BuildPyramids_Management(tempOutputRaster) 261 261 262 # Movethe output rasters to the requested destinations.262 # Copy the output rasters to the requested destinations. 263 263 264 264 for i in range(len(outputProbabilityRasters)): 265 ArcGISRaster. MoveSilent(os.path.join(tempDir.Path, u'output%i' % i), outputProbabilityRasters[i], overwriteExisting=overwriteExisting)265 ArcGISRaster.CopySilent(os.path.join(tempDir.Path, u'output%i' % i), outputProbabilityRasters[i], overwriteExisting=overwriteExisting) 266 266 267 267 # Delete R variables assigned by this function. … … 315 315 # Create the plot. 316 316 317 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'PerfPlotForBinaryModel.r') )317 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'PerfPlotForBinaryModel.r'), False) 318 318 319 319 if measure2 is None: … … 398 398 # Create the plot. 399 399 400 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'ROCPlotForBinaryModel.r') )400 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[cls.__module__].__file__), 'ROCPlotForBinaryModel.r'), False) 401 401 402 402 if cutoffValue is None: … … 832 832 # Log a summery of the model, to remind the user what it is. 833 833 834 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[GLM.__module__].__file__), 'SummarizeModel.r') )834 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[GLM.__module__].__file__), 'SummarizeModel.r'), False) 835 835 836 836 r('writeLines("")') … … 885 885 Logger.Info(_(u'Predicting...')) 886 886 887 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[GLM.__module__].__file__), 'PredictLMForArcGISRasters.r') )887 R.EvaluateFile(os.path.join(os.path.dirname(sys.modules[GLM.__module__].__file__), 'PredictLMForArcGISRasters.r'), False) 888 888 889 889 oldLoggingLevel = r.LogInfoAsDebug … … 926 926 # Move the output rasters to the requested destinations. 927 927 928 ArcGISRaster. MoveSilent(tempResponseRaster, outputResponseRaster, overwriteExisting=overwriteExisting)928 ArcGISRaster.CopySilent(tempResponseRaster, outputResponseRaster, overwriteExisting=overwriteExisting) 929 929 930 930 if outputErrorRaster is not None: 931 ArcGISRaster. MoveSilent(tempErrorRaster, outputErrorRaster, overwriteExisting=overwriteExisting)931 ArcGISRaster.CopySilent(tempErrorRaster, outputErrorRaster, overwriteExisting=overwriteExisting) 932 932 933 933 if outputBinaryResponseRaster is not None: 934 ArcGISRaster. MoveSilent(tempBinaryRaster, outputBinaryResponseRaster, overwriteExisting=overwriteExisting)934 ArcGISRaster.CopySilent(tempBinaryRaster, outputBinaryResponseRaster, overwriteExisting=overwriteExisting) 935 935 936 936 # Delete R variables assigned by this function. … … 995 995 rastersForPredictors[r['yVar']] = yRaster 996 996 997 # Check each predictor raster. If it has a different coordinate 998 # system, extent, or cell size than that of the template raster, 999 # project it in the temp directory. 1000 # 1001 # Note that ArcGIS does not always seem to represent the cell size 1002 # and extent of rasters at the fullest possible precision, so we 1003 # perform comparisons at less than full precision. 1004 1005 Logger.Info('Checking projections, extents, and cell sizes of predictor rasters and reprojecting and clipping as needed...') 997 # Check each predictor raster to see if it needs to be copied, 998 # projected or clipped before we can use it. 999 1000 Logger.Info(_('Checking coordinate systems, extents, and cell sizes of predictor rasters and reprojecting and clipping as needed to make them conform to the template raster...')) 1006 1001 1007 1002 from GeoEco.Types import EnvelopeTypeMetadata … … 1010 1005 vars = copy.deepcopy(rastersForPredictors.keys()) # I'm going to modify the dictionary in the loop below; not sure if deepcopy is needed, but playing it safe. 1011 1006 rasters = copy.deepcopy(rastersForPredictors.values()) 1012 arc93SnapRaster = None1013 1007 1014 1008 for i in range(len(vars)): 1015 if rasters[i] == templateRaster: 1016 continue 1017 1009 needToCopy = False 1018 1010 needToProject = False 1019 1011 needToClip = False 1012 1013 # If this is predictor raster is a raster layer, we need to 1014 # make a copy of it in the file system so that it can be read 1015 # by the R code using the rgdal package. 1016 1020 1017 d = gp.Describe(rasters[i]) 1021 cs = gp.CreateSpatialReference_management(d.SpatialReference).split(u';')[0] 1022 1023 if cs != coordinateSystem: 1024 Logger.Debug(_(u'%(raster)s must be projected because its coordinate system (%(cs1)s) does not match the output coordinate system (%(cs2)s.') % {u'raster': rasters[i], u'cs1': cs, u'cs2': coordinateSystem}) 1025 Logger.Info(_(u'Projecting and clipping %(raster)s because its coordinate system does not match that of the template raster.') % {u'raster': rasters[i]}) 1026 needToProject = True 1027 1028 else: 1029 [rasterLeft, rasterBottom, rasterRight, rasterTop] = EnvelopeTypeMetadata.ParseCoordinatesFromString(d.Extent) 1030 1031 if rasterLeft > templateLeft: 1032 Logger.RaiseException(_(u'The template raster is too large; its left edge falls outside the left edge of the predictor raster %(raster)s. Please reduce the extent of the template raster such that it does not exceed the extents of any of the predictor rasters.') % {u'raster': rasters[i]}) 1033 if rasterRight < templateRight: 1034 Logger.RaiseException(_(u'The template raster is too large; its right edge falls outside the right edge of the predictor raster %(raster)s. Please reduce the extent of the template raster such that it does not exceed the extents of any of the predictor rasters.') % {u'raster': rasters[i]}) 1035 if rasterTop > templateTop: 1036 Logger.RaiseException(_(u'The template raster is too large; its top edge falls outside the top edge of the predictor raster %(raster)s. Please reduce the extent of the template raster such that it does not exceed the extents of any of the predictor rasters.') % {u'raster': rasters[i]}) 1037 if rasterBottom < templateBottom: 1038 Logger.RaiseException(_(u'The template raster is too large; its bottom edge falls outside the bottom edge of the predictor raster %(raster)s. Please reduce the extent of the template raster such that it does not exceed the extents of any of the predictor rasters.') % {u'raster': rasters[i]}) 1039 1018 if d.DataType.lower() == u'rasterlayer': 1019 needToCopy = True 1020 1021 # If this is not the template raster, check to see whether it 1022 # needs to be projected or clipped. 1023 1024 if rasters[i] != templateRaster: 1025 cs = gp.CreateSpatialReference_management(d.SpatialReference).split(u';')[0] 1026 1027 if cs.lower() != coordinateSystem.lower(): 1028 Logger.Info(_(u'Projecting and clipping %(raster)s. Its coordinate system does not match that of the template raster.') % {u'raster': rasters[i]}) 1029 needToProject = True 1030 1040 1031 elif abs(1.0 - cellSize / d.MeanCellWidth) > 0.00001: 1041 Logger.Debug(_(u'%(raster)s must be projected because its cell size (%(cs1)f) does not match the output cell size (%(cs2)f).') % {u'raster': rasters[i], u'cs1': d.MeanCellWidth, u'cs2': cellSize}) 1042 Logger.Info(_(u'Projecting and clipping %(raster)s because its cell size does not match that of the template raster.') % {u'raster': rasters[i]}) 1032 Logger.Info(_(u'Projecting and clipping %(raster)s. Its cell size (%(cs1)s) does not match the cell size of the template raster (%(cs2)s).') % {u'raster': rasters[i], u'cs1': repr(d.MeanCellWidth), u'cs2': repr(cellSize)}) 1043 1033 needToProject = True 1044 1034 1045 1035 else: 1036 [rasterLeft, rasterBottom, rasterRight, rasterTop] = EnvelopeTypeMetadata.ParseCoordinatesFromString(d.Extent) 1037 1046 1038 deltaLeft = (float(extent.split()[0]) - float(d.Extent.split()[0])) / cellSize # Difference, in cells, between the left edge of the template and this raster 1047 1039 deltaBottom = (float(extent.split()[1]) - float(d.Extent.split()[1])) / cellSize # Difference, in cells, between the bottom edge of the template and this raster … … 1050 1042 1051 1043 if deltaLeft < -0.01: 1052 Logger.RaiseException(_(u'The template raster is too large. The left edge of the predictor raster %(raster)s is inside the left edge of the template raster. Please reduce the extent of the template raster such that it does not exceed the extents of any of the predictor rasters.') % {u'raster': rasters[i]}) 1053 if deltaRight > -0.01: 1054 Logger.RaiseException(_(u'The template raster is too large. The left edge of the predictor raster %(raster)s is inside the left edge of the template raster. Please reduce the extent of the template raster such that it does not exceed the extents of any of the predictor rasters.') % {u'raster': rasters[i]}) 1055 1056 if deltaLeft < 0.01 and deltaBottom < 0.01 and deltaRight < 0.01 and deltaTop < 0.01: 1057 Logger.Debug(_(u'%(raster)s has the same coordinate system, cell size, and extent as the template raster.') % {u'raster': rasters[i]}) 1044 Logger.RaiseException(ValueError(_(u'The template raster is too large; its left edge falls (%(e1)s) outside the left edge of the predictor raster %(raster)s (%(e2)s). Please reduce the extent of the template raster such that it does not exceed the extents of any of the predictor rasters.') % {u'raster': rasters[i], u'e1': repr(templateLeft), u'e2': repr(rasterLeft)})) 1045 if deltaRight > 0.01: 1046 Logger.RaiseException(ValueError(_(u'The template raster is too large; its right edge falls (%(e1)s) outside the right edge of the predictor raster %(raster)s (%(e2)s). Please reduce the extent of the template raster such that it does not exceed the extents of any of the predictor rasters.') % {u'raster': rasters[i], u'e1': repr(templateRight), u'e2': repr(rasterRight)})) 1047 if deltaTop > 0.01: 1048 Logger.RaiseException(ValueError(_(u'The template raster is too large; its top edge falls (%(e1)s) outside the top edge of the predictor raster %(raster)s (%(e2)s). Please reduce the extent of the template raster such that it does not exceed the extents of any of the predictor rasters.') % {u'raster': rasters[i], u'e1': repr(templateTop), u'e2': repr(rasterTop)})) 1049 if deltaBottom < -0.01: 1050 Logger.RaiseException(ValueError(_(u'The template raster is too large; its bottom edge falls (%(e1)s) outside the bottom edge of the predictor raster %(raster)s (%(e2)s). Please reduce the extent of the template raster such that it does not exceed the extents of any of the predictor rasters.') % {u'raster': rasters[i], u'e1': repr(templateBottom), u'e2': repr(rasterBottom)})) 1051 1052 if abs(deltaLeft) < 0.01 and abs(deltaBottom) < 0.01 and abs(deltaRight) < 0.01 and abs(deltaTop) < 0.01 and d.Width == templateDescribe.Width and d.Height == templateDescribe.Height: 1053 Logger.Info(_(u'%(raster)s has the same coordinate system, cell size, and extent as the template raster.') % {u'raster': rasters[i]}) 1058 1054 1059 1055 elif abs(deltaLeft - round(deltaLeft)) < 0.01 and abs(deltaBottom - round(deltaBottom)) < 0.01 and abs(deltaRight - round(deltaRight)) < 0.01 and abs(deltaTop - round(deltaTop)) < 0.01: 1060 Logger.Debug(_(u'%(raster)s must be clipped because it has the same coordinate system and cell size as the template raster, and is aligned on the same grid coordinates, but has a different extent.') % {u'raster': rasters[i]}) 1061 Logger.Info(_(u'Clipping %(raster)s to the extent of the template raster.') % {u'raster': rasters[i]}) 1056 Logger.Info(_(u'Clipping %(raster)s. Although it has the same coordinate system and cell size as the template raster and is aligned on the same grid coordinates, it has a different extent.') % {u'raster': rasters[i]}) 1062 1057 needToClip = True 1063 1058 1064 1059 else: 1065 Logger.Debug(_(u'%(raster)s must be clipped because it has the same coordinate system and cell size as the template raster, and is aligned on the same grid coordinates, but has a different extent.') % {u'raster': rasters[i]}) 1066 Logger.Info(_(u'Clipping %(raster)s to the extent of the template raster.') % {u'raster': rasters[i]}) 1060 Logger.Info(_(u'Projecting and clipping %(raster)s. Although it has the same coordinate system and cell size as the template raster, it is aligned on different grid coordinates and has a different extent.') % {u'raster': rasters[i]}) 1067 1061 needToProject = True 1068 1069 1070 if abs(offsetX) > 0.01 or abs(offsetY) > 0.01: 1071 if abs(offsetX - round(offsetX)) > 0.01 or abs(offsetX - round(offsetX)) > 0.01: 1072 Logger.Debug(_(u'%(raster)s must be projected because its cell size (%(cs1)f) does not match the output cell size (%(cs2)f).') % {u'raster': rasters[i], u'cs1': d.MeanCellWidth, u'cs2': cellSize}) 1073 Logger.Info(_(u'Projecting and clipping %(raster)s because its cell size does not match that of the template raster.') % {u'raster': rasters[i]}) 1074 needToProject = True 1062 1063 # If this raster does not need to be copied, projected, or 1064 # clipped, go on to the next one. 1065 1066 if not (needToCopy or needToProject or needToClip): 1067 continue 1068 1069 # If we need to project, do it now. This will also take care 1070 # of copying and clipping the raster, if needed. 1075 1071 1076 1072 if needToProject: 1077 1073 1078 # Use the caller's resampling technique, if 1079 # one was provided. 1074 # Use the caller's resampling technique, if one was 1075 # provided. Otherwise use BILINEAR if it is a 1076 # floating-point raster, or NEAREST if it is not. 1080 1077 1081 resamplingTechnique = u'BILINEAR'1082 1078 if resamplingTechniques is not None and vars[i] in variableNames and variableNames.index(vars[i]) < len(resamplingTechniques): 1083 resamplingTechnique= resamplingTechniques[variableNames.index(vars[i])] 1084 1085 # If this is ArcGIS 9.3, we need to create a snap raster 1086 # with the caller's requested output extent and cell size. 1087 # If we already created an X or Y coordinate raster, reuse 1088 # it. Otherwise create one. Note that the values of the 1089 # snap raster don't matter, just the extent and cell size. 1090 # We call ArcGISRaster.CreateXRaster just because its an 1091 # easy way to create a raster. 1092 1093 if (GeoprocessorManager.GetArcGISMajorVersion() > 9 or GeoprocessorManager.GetArcGISMajorVersion() == 9 and GeoprocessorManager.GetArcGISMinorVersion() >= 3) and arc93SnapRaster is None: 1094 if createXRaster: 1095 arc93SnapRaster = xRaster 1096 elif createYRaster: 1097 arc93SnapRaster = yRaster 1098 else: 1099 arc93SnapRaster = os.path.join(tempDir.Path, u'snapraster') 1100 oldLogInfoAsDebug = Logger.GetLogInfoAsDebug() 1101 Logger.SetLogInfoAsDebug(True) 1102 try: 1103 ArcGISRaster.CreateXRaster(arc93SnapRaster, extent, cellSize, u'Center', coordinateSystem) 1104 finally: 1105 Logger.SetLogInfoAsDebug(oldLogInfoAsDebug) 1079 resamplingTechnique = resamplingTechniques[variableNames.index(vars[i])] 1080 elif d.PixelType[0] in ['F', 'f']: 1081 resamplingTechnique = u'BILINEAR' 1082 else: 1083 resamplingTechnique = u'NEAREST' 1106 1084 1107 1085 # Set the geoprocessor's Extent environment … … 1117 1095 try: 1118 1096 # If this is ArcGIS 9.3, set the SnapRaster 1119 # environment variable as well.1097 # environment variable to the template raster. 1120 1098 1121 1099 if GeoprocessorManager.GetArcGISMajorVersion() > 9 or GeoprocessorManager.GetArcGISMajorVersion() == 9 and GeoprocessorManager.GetArcGISMinorVersion() >= 3: … … 1123 1101 if oldSnapRaster is None: 1124 1102 oldSnapRaster = u'' 1125 gp.SnapRaster = arc93SnapRaster1103 gp.SnapRaster = templateRaster 1126 1104 1127 1105 # Project the raster. If this is ArcGIS 9.3 or later, … … 1139 1117 else: 1140 1118 gp.ProjectRaster_management(rasters[i], tempRaster, coordinateSystem, resamplingTechnique, cellSize, None, extent.rsplit(' ', 2)[0]) 1119 1120 # Even though we provided an extent and cell size 1121 # of an existing raster (the template raster), 1122 # using values we obtained through ArcGIS APIs, 1123 # the ProjectRaster tool will not necessarily 1124 # create a raster that has exactly that extent. It 1125 # may be one cell larger or smaller in any of the 1126 # four directions. Different versions of ArcGIS 1127 # seem to work differently in this respect. It is 1128 # probably due to whether it uses 32-bit or 64-bit 1129 # floats, and other various floating-point 1130 # rounding issues. 1131 # 1132 # The prediction code in R requires that all 1133 # predictor rasters have the same extent (really, 1134 # the same number of rows and columns). If ArcGIS 1135 # produced a raster that was too small or large in 1136 # any dimension, try ProjectRaster again with 1137 # values that will hopefully yield what we want. 1138 1139 describeTemp = gp.Describe(tempRaster) 1140 newEdges = _CheckResultingEdges(tempRaster, describeTemp.Extent, templateLeft, templateBottom, templateRight, templateTop, cellSize) 1141 1142 if newEdges is not None: 1143 Logger.Debug(_(u'Reprojecting because the first attempt produced a raster with an extent (%(e1)s) that did not match the extent of the template raster (%(e2)s).') % {u'e1': describeTemp.Extent, u'e2': extent}) 1144 gp.Extent = u' '.join(map(unicode, newEdges)) 1145 tempRaster = os.path.join(tempDir.Path, u'projected%ia' % i) 1146 if GeoprocessorManager.GetArcGISMajorVersion() > 9 or GeoprocessorManager.GetArcGISMajorVersion() == 9 and GeoprocessorManager.GetArcGISMinorVersion() >= 3: 1147 gp.ProjectRaster_management(rasters[i], tempRaster, coordinateSystem, resamplingTechnique, cellSize) 1148 else: 1149 gp.ProjectRaster_management(rasters[i], tempRaster, coordinateSystem, resamplingTechnique, cellSize, None, extent.rsplit(' ', 2)[0]) 1150 1151 # Check the extent of the new attempt. If we 1152 # still did not get it, report an error. 1153 1154 describeTemp = gp.Describe(tempRaster) 1155 [projectedLeft, projectedBottom, projectedRight, projectedTop] = EnvelopeTypeMetadata.ParseCoordinatesFromString(describeTemp.Extent) 1156 1157 if projectedLeft != templateLeft or projectedBottom != templateBottom or projectedRight != templateRight or projectedTop != templateTop: 1158 Logger.RaiseException(RuntimeError(_(u'This tool was unable to project %(raster)s to the coordinate system of the template raster and obtain a projected raster with an extent that matched that of the template raster. The extent of the projected raster was %(e1)s, while the extent of the template raster is %(e2)s. (The extent values are ordered LEFT, BOTTOM, RIGHT, TOP.) If the extent of the template is larger than the projected raster, it may mean that the template is too large (i.e. that the predictor raster does not cover the entire extent of the template). In that case, try reducing the extent of the template. If that is not the problem, try projecting the predictor raster yourself prior to providing it to this tool, such that its coordinate system, cell size, and extent match that of the template.') % {u'raster': rasters[i], u'e1': describeTemp.Extent, u'e2': extent})) 1141 1159 1142 1160 # If this is ArcGIS 9.3, reset the SnapRaster ArcGIS … … 1159 1177 pass 1160 1178 1161 # Update our dictionary to use the projected 1162 # raster. 1163 1164 rastersForPredictors[vars[i]] = tempRaster 1179 # If we need to clip (but not project), do it now. This will 1180 # also take care of copying the raster, if needed. 1181 1182 elif needToClip: 1183 1184 # Clip the raster. If this is ArcGIS 9.2, pass rasters[i] 1185 # for the in_template_dataset parameter, to work around 1186 # the 9.2 bug described in 1187 # http://forums.esri.com/Thread.asp?c=93&f=1729&t=230897&mc=11. 1188 1189 tempRaster = os.path.join(tempDir.Path, u'clipped%i' % i) 1190 if GeoprocessorManager.GetArcGISMajorVersion() == 9 and GeoprocessorManager.GetArcGISMinorVersion() == 2: 1191 gp.Clip_management(rasters[i], extent, tempRaster, rasters[i]) 1192 else: 1193 gp.Clip_management(rasters[i], extent, tempRaster) 1194 1195 # Even though we provided an extent of an existing raster 1196 # (the template raster) that has the same cell size and is 1197 # aligned on the same coordinates, using values we 1198 # obtained through ArcGIS APIs, the Clip tool will not 1199 # necessarily create a raster that has exactly that 1200 # extent. It may be one cell larger or smaller in any of 1201 # the four directions. Different versions of ArcGIS seem 1202 # to work differently in this respect. It is probably due 1203 # to whether it uses 32-bit or 64-bit floats, and other 1204 # various floating-point rounding issues. 1205 # 1206 # The prediction code in R requires that all predictor 1207 # rasters have the same extent (really, the same number of 1208 # rows and columns). If ArcGIS produced a raster that was 1209 # too small or large in any dimension, try Clip again with 1210 # values that will hopefully yield what we want. 1211 1212 describeTemp = gp.Describe(tempRaster) 1213 newEdges = _CheckResultingEdges(tempRaster, describeTemp.Extent, templateLeft, templateBottom, templateRight, templateTop, cellSize) 1214 1215 if newEdges is not None: 1216 Logger.Debug(_(u'Reclipping because the first attempt produced a raster with an extent (%(e1)s) that did not match the extent of the template raster (%(e2)s).') % {u'e1': describeTemp.Extent, u'e2': extent}) 1217 tempRaster = os.path.join(tempDir.Path, u'clipped%ia' % i) 1218 if GeoprocessorManager.GetArcGISMajorVersion() == 9 and GeoprocessorManager.GetArcGISMinorVersion() == 2: 1219 gp.Clip_management(rasters[i], u' '.join(map(unicode, newEdges)), tempRaster, rasters[i]) 1220 else: 1221 gp.Clip_management(rasters[i], u' '.join(map(unicode, newEdges)), tempRaster) 1222 1223 # If we got here but did not need to project or clip, we 1224 # needed to copy. Create a copy of the raster in ArcInfo 1225 # binary grid format. 1226 1227 else: 1228 tempRaster = os.path.join(tempDir.Path, u'copied%i' % i) 1229 ArcGISRaster.CopySilent(rasters[i], tempRaster) 1230 1231 # If we had to project or clip, make absolutely sure that the 1232 # projected or clipped raster has the expected number of rows 1233 # and columns. 1234 1235 if needToProject or needToClip: 1236 d = gp.Describe(tempRaster) 1237 if d.Height != templateDescribe.Height or d.Width != templateDescribe.Width: 1238 Logger.RaiseException(RuntimeError(_(u'Internal error in this tool. Please contact the MGET development team for assistance. Error details: after %(raster)s was projected and/or clipped, the resulting raster had %(cols1)i columns and %(rows1)i rows, while the template raster has %(cols2)i columns and %(rows2)i rows. This tool expected that the resulting raster would have the same number of rows and columns as the template raster. You can work around this problem by projecting and/or clipping the raster yourself, so it has the same coordinate system, cell size, and extent as the template raster.') % {u'raster': rasters[i], u'rows1': d.Height, u'cols1': d.Width, u'rows2': templateDescribe.Height, u'cols2': templateDescribe.Width})) 1239 1240 # Update our dictionary to use the projected/clipped/copied 1241 # raster. 1242 1243 rastersForPredictors[vars[i]] = tempRaster 1244 1245 # Pass the dictionary that maps predictor variables to rasters to 1246 # R, so the R code can read it. 1165 1247 1166 1248 r['rastersForPredictors'] = rastersForPredictors 1249 1250 def _CheckResultingEdges(resultingRaster, resultingExtent, templateLeft, templateBottom, templateRight, templateTop, cellSize): 1251 from GeoEco.Types import EnvelopeTypeMetadata 1252 1253 [resultingLeft, resultingBottom, resultingRight, resultingTop] = EnvelopeTypeMetadata.ParseCoordinatesFromString(resultingExtent) 1254 needToTryAgain = False 1255 newEdges = [None, None, None, None] 1256 1257 if resultingLeft < templateLeft - cellSize * 0.01: 1258 needToTryAgain = True 1259 newEdges[0] = templateLeft + cellSize 1260 elif resultingLeft > templateLeft + cellSize * 0.01: 1261 needToTryAgain = True 1262 newEdges[0] = templateLeft - cellSize 1263 else: 1264 newEdges[0] = templateLeft 1265 1266 if resultingBottom < templateBottom - cellSize * 0.01: 1267 needToTryAgain = True 1268 newEdges[1] = templateBottom + cellSize 1269 elif resultingBottom > templateBottom + cellSize * 0.01: 1270 needToTryAgain = True 1271 newEdges[1] = templateBottom - cellSize 1272 else: 1273 newEdges[1] = templateBottom 1274 1275 if resultingRight < templateRight - cellSize * 0.01: 1276 needToTryAgain = True 1277 newEdges[2] = templateRight + cellSize 1278 elif resultingRight > templateRight + cellSize * 0.01: 1279 needToTryAgain = True 1280 newEdges[2] = templateRight - cellSize 1281 else: 1282 newEdges[2] = templateRight 1283 1284 if resultingTop < templateTop - cellSize * 0.01: 1285 needToTryAgain = True 1286 newEdges[3] = templateTop + cellSize 1287 elif resultingTop > templateTop + cellSize * 0.01: 1288 needToTryAgain = True 1289 newEdges[3] = templateTop - cellSize 1290 else: 1291 newEdges[3] = templateTop 1292 1293 if needToTryAgain: 1294 return newEdges 1295 return None 1167 1296 1168 1297 … … 1199 1328 arcGISDisplayName=_(u'Fit GLM'), 1200 1329 arcGISToolCategory=_(u'Statistics\\Model Data\\Generalized Linear Models'), 1201 dependencies=[ArcGISDependency(9, 1), RDependency(2, 5, 0)])1330 dependencies=[ArcGISDependency(9, 1), RDependency(2, 6, 0)]) 1202 1331 1203 1332 AddArgumentMetadata(GLM.FitToArcGISTable, u'cls', … … 1623 1752 arcGISDisplayName=_(u'Predict GLM From Rasters'), 1624 1753 arcGISToolCategory=_(u'Statistics\\Model Data\\Generalized Linear Models'), 1625 dependencies=[ArcGISDependency(9, 2), RDependency(2, 5, 0), RPackageDependency(u'rgdal')])1754 dependencies=[ArcGISDependency(9, 2), RDependency(2, 6, 0), RPackageDependency(u'rgdal')]) 1626 1755 1627 1756 CopyArgumentMetadata(GLM.FitToArcGISTable, u'cls', GLM.PredictFromArcGISRasters, u'cls') … … 1719 1848 1720 1849 AddArgumentMetadata(GLM.PredictFromArcGISRasters, u'templateRaster', 1721 typeMetadata=ArcGISRaster TypeMetadata(mustExist=True, mustBeDifferentThanArguments=[u'inputModelFile', u'outputResponseRaster'], canBeNone=True),1850 typeMetadata=ArcGISRasterLayerTypeMetadata(mustExist=True, mustBeDifferentThanArguments=[u'inputModelFile', u'outputResponseRaster'], canBeNone=True), 1722 1851 description=_( 1723 1852 u"""Template raster that defines the coordinate system, extent, and … … 1877 2006 arcGISDisplayName=_(u'Fit GAM'), 1878 2007 arcGISToolCategory=_(u'Statistics\\Model Data\\Generalized Additive Models'), 1879 dependencies=[ArcGISDependency(9, 1), RDependency(2, 5, 0)])2008 dependencies=[ArcGISDependency(9, 1), RDependency(2, 6, 0)]) 1880 2009 1881 2010 AddArgumentMetadata(GAM.FitToArcGISTable, u'cls', … … 2059 2188 arcGISDisplayName=_(u'Predict GAM From Rasters'), 2060 2189 arcGISToolCategory=_(u'Statistics\\Model Data\\Generalized Additive Models'), 2061 dependencies=[ArcGISDependency(9, 2), RDependency(2, 5, 0), RPackageDependency(u'rgdal')])2190 dependencies=[ArcGISDependency(9, 2), RDependency(2, 6, 0), RPackageDependency(u'rgdal')]) 2062 2191 2063 2192 CopyArgumentMetadata(GAM.FitToArcGISTable, u'cls', GAM.PredictFromArcGISRasters, u'cls') … … 2091 2220 arcGISDisplayName=_(u'Predict Bayesian Probabilities for GAM From Rasters'), 2092 2221 arcGISToolCategory=_(u'Statistics\\Model Data\\Generalized Additive Models'), 2093 dependencies=[ArcGISDependency(9, 2), RDependency(2, 5, 0), RPackageDependency(u'mgcv'), RPackageDependency(u'MASS'), RPackageDependency(u'rgdal')])2222 dependencies=[ArcGISDependency(9, 2), RDependency(2, 6, 0), RPackageDependency(u'mgcv'), RPackageDependency(u'MASS'), RPackageDependency(u'rgdal')]) 2094 2223 2095 2224 CopyArgumentMetadata(GAM.FitToArcGISTable, u'cls', GAM.BayesPredictFromArcGISRasters, u'cls') … … 2209 2338 arcGISDisplayName=_(u'Plot Performance of Binary Classification Model'), 2210 2339 arcGISToolCategory=_(u'Statistics\\Model Data\\Evaluate Model Performance'), 2211 dependencies=[RDependency(2, 5, 0), RPackageDependency(u'ROCR')])2340 dependencies=[RDependency(2, 6, 0), RPackageDependency(u'ROCR')]) 2212 2341 2213 2342 AddArgumentMetadata(ModelEvaluation.PlotPerformanceOfBinaryClassificationModel, u'cls', … … 2552 2681 arcGISDisplayName=_(u'Plot ROC of Binary Classification Model'), 2553 2682 arcGISToolCategory=_(u'Statistics\\Model Data\\Evaluate Model Performance'), 2554 dependencies=[RDependency(2, 5, 0), RPackageDependency(u'ROCR')])2683 dependencies=[RDependency(2, 6, 0), RPackageDependency(u'ROCR')]) 2555 2684 2556 2685 CopyArgumentMetadata(ModelEvaluation.PlotPerformanceOfBinaryClassificationModel, u'cls', ModelEvaluation.PlotROCOfBinaryClassificationModel, u'cls') -
MGET/Branches/Jason/PythonPackage/src/GeoEco/Statistics/PredictLMForArcGISRasters.r
r317 r404 72 72 tryCatch( 73 73 { 74 if (any(rasterInfo2@grid@cells.dim != rasterInfo 2@grid@cells.dim))74 if (any(rasterInfo2@grid@cells.dim != rasterInfo@grid@cells.dim)) 75 75 stop("All of the predictor rasters must have the same number of rows and columns.", call.=FALSE) 76 77 if (any(rasterInfo2@bbox != rasterInfo2@bbox))78 stop("All of the predictor rasters must have the same geographic extent and cell size", call.=FALSE)79 76 }, finally=close(rasterInfo2)) 80 77 }
