Changeset 404

Show
Ignore:
Timestamp:
06/08/09 13:48:16 (4 years ago)
Author:
jjr8
Message:

This and the previous few revisions fix and implement:

* #264: Predict GAM and Predict GLM tools should check the left and bottom extents and the number of rows and columns rather than all four extents
* #265: The Raster Type search option does not work for batch processing tools that find rasters
* #284: Tools that do not have "Run Python script in process" checked run extremely slowly under ArcGIS 9.3
* #357: Add support for ArcGIS 9.3.1
* #358: When provided with raster layers, Predict GAM and Predict GLM tools fail with GDAL Error 4: `<raster>' does not exist in the file system, and is not recognised as a supported dataset name.
* #359: With ArcGIS 9.3.1, Predict GAM and Predict GLM tools fail with RPy_RException: Error: GDAL Error 5: Access window out of range in RasterIO()
* #360: All tools that invoke R leak memory
* #361: Python's logging package causes large memory leaks in "in process" MGET tools under ArcGIS 9.3

The ArcGIS 9.3 toolbox still needs to rebuilt and more testing needs to happen, but this revision represents a large amount of the total work required for MGET 0.7b1.

Location:
MGET/Branches/Jason/PythonPackage/src/GeoEco
Files:
2 added
8 removed
33 modified

Legend:

Unmodified
Added
Removed
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/ArcGIS.py

    r380 r404  
    933933        # turn on debug logging.) 
    934934 
    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) 
    936938            raise 
    937939        else: 
     
    940942    if caughtException: 
    941943        Logger.Debug(_(u'Python script %s exiting with return value 1, indicating failure.') % sys.argv[0]) 
     944        GeoprocessorManager.SetGeoprocessor(None) 
    942945        sys.exit(1) 
    943946 
     
    945948 
    946949    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 
     955def _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 
    947973 
    948974 
     
    13861412                geoprocessor = GeoprocessorManager.GetGeoprocessor() 
    13871413                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 
    13971426            except: 
    13981427                pass 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/AssimilatedModules/rpy/src-rpy-1.0.3/BUILDING_FOR_GEOECO.txt

    r389 r404  
    575714. For each version of Python supported by GeoEco (assume version number is XY, e.g. 25): 
    5858 
    59     a. Run: \pythonXY\python.exe setup.py build 
     59    a. Run: C:\pythonXY\python.exe setup.py build 
    6060    b. Run: copy build\lib.win32-X.Y\_rpy2081.pyd ..\lib\win32\PythonXY 
    6161    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  
    192192 
    193193  argformat = (char *)PyMem_Malloc((strlen(name)+3)*sizeof(char)); 
     194  if (!argformat) 
     195    return PyErr_NoMemory(); 
    194196  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); 
    198205  Py_INCREF(func); 
    199206  *var = func; 
     
    224231{ 
    225232  if (o) { 
     233    Py_INCREF(o); 
    226234    return o; 
    227235  } else { 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/AssimilatedModules/rpy/src-rpy-1.0.3/src/rpymodule.c

    r320 r404  
    17791779    R_RunExitFinalizers();   
    17801780    CleanEd();               
    1781 #if (R_VERSION >= R_Version(2,7,0)) 
     1781#if (R_VERSION >= R_Version(2,5,0)) 
    17821782    Rf_KillAllDevices(); 
    17831783#else 
     
    18421842  use_numeric = i; 
    18431843 
     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; 
    18441849#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; 
    18601857} 
    18611858 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/DataManagement/ArcGISRasters.py

    r398 r404  
    7474        finally: 
    7575            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) 
    7685 
    7786    @classmethod 
     
    11671176 
    11681177AddArgumentMetadata(ArcGISRaster.Copy, u'sourceRaster', 
    1169     typeMetadata=ArcGISRasterTypeMetadata(mustExist=True), 
     1178    typeMetadata=ArcGISRasterLayerTypeMetadata(mustExist=True), 
    11701179    description=_(u'Raster to copy.'), 
    11711180    arcGISDisplayName=_(u'Source raster')) 
     
    11881197exists."""), 
    11891198    initializeToArcGISGeoprocessorVariable=u'OverwriteOutput') 
     1199 
     1200# Public method: ArcGISRaster.CopySilent 
     1201 
     1202AddMethodMetadata(ArcGISRaster.CopySilent, 
     1203    shortDescription=_(u'Copies an ArcGIS raster and logs a debug message rather than an informational message.'), 
     1204    longDescription=_( 
     1205u"""This method does the same thing as the Copy method, except it logs 
     1206a debug message rather than an informational message. It is intended 
     1207for use when the raster-copy operation is not imporant enough to 
     1208warrent notifying the user (for example, when an output raster is 
     1209extracted from a temporary directory to the final location)."""), 
     1210    isExposedToPythonCallers=True, 
     1211    isExposedByCOM=True, 
     1212    dependencies=[ArcGISDependency(9, 1)]) 
     1213 
     1214CopyArgumentMetadata(ArcGISRaster.Copy, u'cls', ArcGISRaster.CopySilent, u'cls') 
     1215CopyArgumentMetadata(ArcGISRaster.Copy, u'sourceRaster', ArcGISRaster.CopySilent, u'sourceRaster') 
     1216CopyArgumentMetadata(ArcGISRaster.Copy, u'destinationRaster', ArcGISRaster.CopySilent, u'destinationRaster') 
     1217CopyArgumentMetadata(ArcGISRaster.Copy, u'overwriteExisting', ArcGISRaster.CopySilent, u'overwriteExisting') 
    11901218 
    11911219# Public method: ArcGISRaster.CreateTemporaryRastersToPreventArcGISCrash 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/DataManagement/Directories.py

    r131 r404  
    151151 
    152152                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): 
    154154                    parentDirectory = os.path.join(gp.ScratchWorkspace, u'GeoEcoTemp') 
    155155 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/DataProducts/Aviso.py

    r350 r404  
    2121import datetime 
    2222import os 
     23import time 
    2324 
    2425from GeoEco.DataManagement.ArcGISRasters import ArcGISRaster 
     
    153154            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]]" 
    154155 
    155         # Look up the minimum longitude and latitude and the step 
    156         # 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). 
    157158 
    158159        if not ds.has_key('LatLonMin'): 
     
    163164        minLon = ds['LatLonMin'][1] 
    164165        minLat = ds['LatLonMin'][0] 
     166        maxLat = max(ds['NbLatitudes'][:]) 
    165167        step = ds['LatLonStep'][0] 
    166168 
    167169        Logger.Debug(_(u'Minimum longitude = %s (on 0-to-360 coordinate system)') % str(minLon)) 
    168170        Logger.Debug(_(u'Minimum latitude = %s') % str(minLat)) 
     171        Logger.Debug(_(u'Maximum latitude = %s') % str(maxLat)) 
    169172        Logger.Debug(_(u'Cell size = %s degrees') % str(step)) 
    170173 
     
    393396                # Download the image as a numpy array. 
    394397 
    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 
    396415 
    397416                # Transpose and flip the image, so it is in the 
     
    423442                # expected map extent. If so, strip it too. 
    424443 
    425                 if isGlobal and max(ds['NbLatitudes'][:]) == 90.: 
     444                if isGlobal and maxLat == 90.: 
    426445                    image = image[1:, :] 
    427446 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/DataProducts/NOAA/CoastWatchAVHRR.py

    r350 r404  
    8181         
    8282        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.'))) 
    8484 
    8585        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.'))) 
    8787 
    8888        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"?> 
    22 
    33<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
     
    456456      consult an ArcGIS expert for more information.</li> 
    457457 
    458       <li style="margin-top: 1em;"><a href="http://www.r-project.org/"><b>R statistics program</b></a>, version 2.5.1 to 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 - 
    459459      this is required by GeoEco tools that perform statistical calculations. You 
    460460      must have a version in the range indicated. Newer or older versions will not 
     
    468468      do not have MATLAB, download the MATLAB Component Runtime from the link above.</li> 
    469469 
    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 - 
    471471      these are required if you want to use any of the GeoEco tools that process 
    472472      CoastWatch data. In the CoastWatch Utilities setup, be sure to you enable the 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/R.py

    r402 r404  
    106106 
    107107        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, load 
    116         # 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) 
    126108        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: 
    128143                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. 
    136149             
    137150        return result 
     
    418431         
    419432        if major is None: 
    420             Logger.RaiseException(SoftwareNotInstalledError(_(u'This function 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))) 
     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))) 
    421434             
    422435        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))) 
    424442 
    425443        # If we haven't import the rpy module yet, import it. rpy 
     
    522540 
    523541            rpy.set_default_mode(rpy.PROC_CONVERSION) 
     542            rpy.proc_table.clear() 
    524543            rpy.proc_table[lambda o: True] = RDependency._ConvertRObjectToPythonObject 
    525544 
     
    559578 
    560579                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) 
    561621 
    562622    _RMajorVersion = None 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/Statistics/Exploratory.py

    r400 r404  
    6161                r('%s <- NULL' % transformsName) 
    6262 
    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) 
    6464            if outputFile is None: 
    6565                r('ScatterplotMatrix(%s, transforms=%s, .diag="%s", lower="%s", upper="%s")' % (dataFrameName, transformsName, str(diagonal), str(lower), str(upper))) 
     
    9999                    Logger.RaiseException(ValueError(_(u'The table %(table)s is empty.') % {u'table': table})) 
    100100             
    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) 
    102102 
    103103            if transform is None: 
     
    175175                    Logger.RaiseException(ValueError(_(u'The table %(table)s is empty.') % {u'table': table})) 
    176176             
    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) 
    178178 
    179179            if transform is None: 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/Statistics/Modeling.py

    r400 r404  
    5757         
    5858        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) 
    6161 
    6262            tempDir = TemporaryDirectory() 
     
    134134         
    135135        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) 
    138138 
    139139            tempDir = TemporaryDirectory() 
     
    207207            # Log a summery of the model, to remind the user what it is. 
    208208 
    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) 
    210210 
    211211            r('writeLines("")') 
     
    233233            # no way to suppress these messages from within R. 
    234234 
    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) 
    236236 
    237237            oldLoggingLevel = r.LogInfoAsDebug 
     
    260260                    gp.BuildPyramids_Management(tempOutputRaster) 
    261261 
    262             # Move the output rasters to the requested destinations. 
     262            # Copy the output rasters to the requested destinations. 
    263263 
    264264            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) 
    266266 
    267267        # Delete R variables assigned by this function. 
     
    315315            # Create the plot. 
    316316         
    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) 
    318318 
    319319            if measure2 is None: 
     
    398398            # Create the plot. 
    399399         
    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) 
    401401 
    402402            if cutoffValue is None: 
     
    832832        # Log a summery of the model, to remind the user what it is. 
    833833 
    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) 
    835835 
    836836        r('writeLines("")') 
     
    885885            Logger.Info(_(u'Predicting...')) 
    886886 
    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) 
    888888 
    889889            oldLoggingLevel = r.LogInfoAsDebug 
     
    926926        # Move the output rasters to the requested destinations. 
    927927 
    928         ArcGISRaster.MoveSilent(tempResponseRaster, outputResponseRaster, overwriteExisting=overwriteExisting) 
     928        ArcGISRaster.CopySilent(tempResponseRaster, outputResponseRaster, overwriteExisting=overwriteExisting) 
    929929         
    930930        if outputErrorRaster is not None: 
    931             ArcGISRaster.MoveSilent(tempErrorRaster, outputErrorRaster, overwriteExisting=overwriteExisting) 
     931            ArcGISRaster.CopySilent(tempErrorRaster, outputErrorRaster, overwriteExisting=overwriteExisting) 
    932932             
    933933        if outputBinaryResponseRaster is not None: 
    934             ArcGISRaster.MoveSilent(tempBinaryRaster, outputBinaryResponseRaster, overwriteExisting=overwriteExisting) 
     934            ArcGISRaster.CopySilent(tempBinaryRaster, outputBinaryResponseRaster, overwriteExisting=overwriteExisting) 
    935935 
    936936    # Delete R variables assigned by this function. 
     
    995995        rastersForPredictors[r['yVar']] = yRaster 
    996996 
    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...')) 
    10061001 
    10071002    from GeoEco.Types import EnvelopeTypeMetadata 
     
    10101005    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. 
    10111006    rasters = copy.deepcopy(rastersForPredictors.values()) 
    1012     arc93SnapRaster = None 
    10131007 
    10141008    for i in range(len(vars)): 
    1015         if rasters[i] == templateRaster: 
    1016             continue 
    1017          
     1009        needToCopy = False 
    10181010        needToProject = False 
    10191011        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         
    10201017        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 
    10401031            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)}) 
    10431033                needToProject = True 
    10441034 
    10451035            else: 
     1036                [rasterLeft, rasterBottom, rasterRight, rasterTop] = EnvelopeTypeMetadata.ParseCoordinatesFromString(d.Extent) 
     1037                     
    10461038                deltaLeft = (float(extent.split()[0]) - float(d.Extent.split()[0])) / cellSize     # Difference, in cells, between the left edge of the template and this raster 
    10471039                deltaBottom = (float(extent.split()[1]) - float(d.Extent.split()[1])) / cellSize   # Difference, in cells, between the bottom edge of the template and this raster 
     
    10501042 
    10511043                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]}) 
    10581054 
    10591055                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]}) 
    10621057                    needToClip = True 
    10631058 
    10641059                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]}) 
    10671061                    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. 
    10751071 
    10761072        if needToProject: 
    10771073 
    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. 
    10801077             
    1081             resamplingTechnique = u'BILINEAR' 
    10821078            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' 
    11061084 
    11071085            # Set the geoprocessor's Extent environment 
     
    11171095            try: 
    11181096                # If this is ArcGIS 9.3, set the SnapRaster 
    1119                 # environment variable as well. 
     1097                # environment variable to the template raster. 
    11201098                 
    11211099                if GeoprocessorManager.GetArcGISMajorVersion() > 9 or GeoprocessorManager.GetArcGISMajorVersion() == 9 and GeoprocessorManager.GetArcGISMinorVersion() >= 3: 
     
    11231101                    if oldSnapRaster is None: 
    11241102                        oldSnapRaster = u'' 
    1125                     gp.SnapRaster = arc93SnapRaster 
     1103                    gp.SnapRaster = templateRaster 
    11261104 
    11271105                # Project the raster. If this is ArcGIS 9.3 or later, 
     
    11391117                    else: 
    11401118                        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})) 
    11411159 
    11421160                # If this is ArcGIS 9.3, reset the SnapRaster ArcGIS 
     
    11591177                    pass 
    11601178 
    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. 
    11651247 
    11661248    r['rastersForPredictors'] = rastersForPredictors 
     1249 
     1250def _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 
    11671296 
    11681297 
     
    11991328    arcGISDisplayName=_(u'Fit GLM'), 
    12001329    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)]) 
    12021331 
    12031332AddArgumentMetadata(GLM.FitToArcGISTable, u'cls', 
     
    16231752    arcGISDisplayName=_(u'Predict GLM From Rasters'), 
    16241753    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')]) 
    16261755 
    16271756CopyArgumentMetadata(GLM.FitToArcGISTable, u'cls', GLM.PredictFromArcGISRasters, u'cls') 
     
    17191848 
    17201849AddArgumentMetadata(GLM.PredictFromArcGISRasters, u'templateRaster', 
    1721     typeMetadata=ArcGISRasterTypeMetadata(mustExist=True, mustBeDifferentThanArguments=[u'inputModelFile', u'outputResponseRaster'], canBeNone=True), 
     1850    typeMetadata=ArcGISRasterLayerTypeMetadata(mustExist=True, mustBeDifferentThanArguments=[u'inputModelFile', u'outputResponseRaster'], canBeNone=True), 
    17221851    description=_( 
    17231852u"""Template raster that defines the coordinate system, extent, and 
     
    18772006    arcGISDisplayName=_(u'Fit GAM'), 
    18782007    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)]) 
    18802009 
    18812010AddArgumentMetadata(GAM.FitToArcGISTable, u'cls', 
     
    20592188    arcGISDisplayName=_(u'Predict GAM From Rasters'), 
    20602189    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')]) 
    20622191 
    20632192CopyArgumentMetadata(GAM.FitToArcGISTable, u'cls', GAM.PredictFromArcGISRasters, u'cls') 
     
    20912220    arcGISDisplayName=_(u'Predict Bayesian Probabilities for GAM From Rasters'), 
    20922221    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')]) 
    20942223 
    20952224CopyArgumentMetadata(GAM.FitToArcGISTable, u'cls', GAM.BayesPredictFromArcGISRasters, u'cls') 
     
    22092338    arcGISDisplayName=_(u'Plot Performance of Binary Classification Model'), 
    22102339    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')]) 
    22122341 
    22132342AddArgumentMetadata(ModelEvaluation.PlotPerformanceOfBinaryClassificationModel, u'cls', 
     
    25522681    arcGISDisplayName=_(u'Plot ROC of Binary Classification Model'), 
    25532682    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')]) 
    25552684 
    25562685CopyArgumentMetadata(ModelEvaluation.PlotPerformanceOfBinaryClassificationModel, u'cls', ModelEvaluation.PlotROCOfBinaryClassificationModel, u'cls') 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/Statistics/PredictLMForArcGISRasters.r

    r317 r404  
    7272                tryCatch( 
    7373                { 
    74                     if (any(rasterInfo2@grid@cells.dim != rasterInfo2@grid@cells.dim)) 
     74                    if (any(rasterInfo2@grid@cells.dim != rasterInfo@grid@cells.dim)) 
    7575                        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) 
    7976                }, finally=close(rasterInfo2)) 
    8077            }