Performing a spatial analysis operation using objects (ArcObjects .NET 10.6 SDK)
ArcObjects Help for .NET developers > Developing with ArcGIS > Learning ArcObjects > ArcGIS extensions > Spatial Analyst > Performing a spatial analysis operation using objects (ArcObjects .NET 10.6 SDK)

Performing a spatial analysis operation using objects


Summary
This topic discusses the steps to perform a spatial analysis operation using Spatial Analyst objects. Code examples are also provided.

In this topic


About spatial analysis operations using objects

There are many objects in the Spatial Analyst object libraries and hundreds of methods to perform spatial analysis. Even though there are many objects and methods, you only need to follow five main steps to perform any spatial analysis operation. The following discusses these steps and provides code examples.

Check out a Spatial Analyst license

The first step to execute a Spatial Analyst operation is to check out a Spatial Analyst license. Check out a license before executing each Spatial Analyst method and check it in when you are done, or you can check out a license once at the beginning and keep it checked out until you are done executing all spatial analysis operations. However, keeping the license checked out while performing a lot of pre- and post-processing work that does not require a license, might not be efficient in an environment where licenses are shared between users.
If an object is available with 3D and Spatial Analyst extensions, you can use Spatial Analyst or 3D Analyst licenses for execution. Objects available with the core ArcGIS Engine product do not require any license.
The following code example shows how to check out a Spatial Analyst license:
[VB.NET]
Public Function GetSpatialAnalystLicense() As esriLicenseStatus
    'Check out a Spatial Analyst license with the ArcView product.
    Dim productCode As esriLicenseProductCode=esriLicenseProductCode.esriLicenseProductCodeArcEngine
    Dim pAoInitialize As IAoInitialize=New AoInitializeClass()
    Dim licenseStatus As esriLicenseStatus=esriLicenseStatus.esriLicenseUnavailable
    'Check the productCode.
    licenseStatus=pAoInitialize.IsProductCodeAvailable(productCode)
    If licenseStatus=esriLicenseStatus.esriLicenseAvailable Then
        'Check the extensionCode.
        licenseStatus=pAoInitialize.IsExtensionCodeAvailable(productCode, esriLicenseExtensionCode.esriLicenseExtensionCodeSpatialAnalyst)
        If licenseStatus=esriLicenseStatus.esriLicenseAvailable Then
            'Initialize the license.
            licenseStatus=pAoInitialize.Initialize(productCode)
            If (licenseStatus=esriLicenseStatus.esriLicenseCheckedOut) Then
                'Check out the Spatial Analyst extension.
                licenseStatus=pAoInitialize.CheckOutExtension(esriLicenseExtensionCode.esriLicenseExtensionCodeSpatialAnalyst)
            End If
        End If
    End If
    Return licenseStatus
End Function
[C#]
public esriLicenseStatus GetSpatialAnalystLicense()
{
    //Check out a Spatial Analyst license with the ArcView product. 
    esriLicenseProductCode productCode =
        esriLicenseProductCode.esriLicenseProductCodeArcEngine;
    IAoInitialize pAoInitialize=new AoInitializeClass();
    esriLicenseStatus licenseStatus=esriLicenseStatus.esriLicenseUnavailable;
    //Check the productCode. 
    licenseStatus=pAoInitialize.IsProductCodeAvailable(productCode);
    if (licenseStatus == esriLicenseStatus.esriLicenseAvailable)
    {
        //Check the extensionCode. 
        licenseStatus=pAoInitialize.IsExtensionCodeAvailable(productCode,
            esriLicenseExtensionCode.esriLicenseExtensionCodeSpatialAnalyst);
        if (licenseStatus == esriLicenseStatus.esriLicenseAvailable)
        {
            //Initialize the license. 
            licenseStatus=pAoInitialize.Initialize(productCode);
            if ((licenseStatus == esriLicenseStatus.esriLicenseCheckedOut))
            {
                //Check out the Spatial Analyst extension. 
                licenseStatus=pAoInitialize.CheckOutExtension
                    (esriLicenseExtensionCode.esriLicenseExtensionCodeSpatialAnalyst)
                    ;
            }
        }
    }

    return licenseStatus;
}

Set the analysis environment

Certain operators, such as the RasterDensityOp and the RasterInterpolationOp, require that some properties of the analysis output be specified. Two properties of particular importance to set are the output cell size and the extent of the analysis.
The analysis environment (through the RasterAnalysis object) controls the following four primary properties when performing analysis:
  • Cell size
  • Extent
  • Mask
  • Spatial reference
Even though these settings do nothing to the original data, the extent and mask do affect the locations where the operation occurs. The extent defines the area on which the operation will be performed. The mask defines the cell locations in the extent on which to perform the operation and the specified cell size controls the resolution of the output. The spatial reference sets the spatial reference of the output and projects input data to the output coordinate systems if necessary, before performing analysis.
Each operator object can have its own analysis environment settings. You can set the environment parameters individually for each operator object. For more information, see Working with the analysis environment.
When created, the new operator object inherits its analysis environment settings from the RasterAnalysis object. Setting the analysis environment is optional in most cases. If nothing is specified, a method executes with the default settings. However, there are cases when you must specify an environment setting explicitly. For example, to execute inverse distance weighted (IDW), you must specify a cell size.
The following code example shows how to the set cell size for an operator:
[VB.NET]
' Create an Op (RasterInterpolation operator).
Dim interpOp As IInterpolationOp=New RasterInterpolationOpClass()
' Query Op for IRasterAnalysisEnvironment.
Dim rasterAnalysisEnvironment As IRasterAnalysisEnvironment=CType(interpOp, IRasterAnalysisEnvironment)
Dim object_cellSize As Object=CType(2, Object)
rasterAnalysisEnvironment.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, object_cellSize)
[C#]
// Create an Op (RasterInterpolation operator).
IInterpolationOp interpOp=new RasterInterpolationOpClass();
// Query Op for IRasterAnalysisEnvironment.
IRasterAnalysisEnvironment rasterAnalysisEnvironment=(IRasterAnalysisEnvironment)
    interpOp;
object object_cellSize=(object)2;
rasterAnalysisEnvironment.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue,
    ref object_cellSize);

Specify inputs

Once you have a license and have optionally set the analysis environment, identify the input data you want to use for the Spatial Analyst operation. You can specify the input as RasterDataset, RasterBand, Raster, or RasterDescriptor object inputs into a Spatial Analyst operation that requires a raster input.
A RasterDataset represents an existing dataset stored on disk or in a database in a particular raster format (for example, Tagged Image File Format [TIFF]). RasterBand is the individual band of a RasterDataset. Some RasterDatasets have multiple bands like a satellite image while others contain a single band, such as an ESRI grid.
A Raster is a virtual representation of raster data derived from a data source on disk. A Raster can be a subset of the original RasterDataset, be projected into a different projection, and composed of bands from different RasterDatasets.
A RasterDescriptor is used to present a subset of the original Raster (for example, through an attribute selection) and uses an alternative value for each cell defined in a field in the data's attribute table, or uses an alternative value for each cell defined in a field in the data's attribute table.
For more information about the raster data object model, see the DataSourcesRaster and DataSourcesRasterUI libraries.
The following code example shows how to access a raster on disk:
[VB.NET]
Public Function OpenRasterDataset(ByVal sPath As String, ByVal sFileName As String) As IRasterDataset
    ' Returns RasterDataset object given a file name and its directory.
    ' sPath—Path of the input raster dataset.
    ' sFileName—Name of the input raster dataset.
    Dim rasterDataset As IRasterDataset=Nothing
    Try
    Dim workspaceFactory As IWorkspaceFactory=New RasterWorkspaceFactoryClass
    Dim rasterWorkspace As IRasterWorkspace
    If workspaceFactory.IsWorkspace(sPath) Then
        rasterWorkspace=CType(workspaceFactory.OpenFromFile(sPath, 0), IRasterWorkspace)
        rasterDataset=rasterWorkspace.OpenRasterDataset(sFileName)
    End If
    Catch ex As Exception
    Console.WriteLine("Failed in Opening RasterDataset. " & ex.InnerException.ToString)
    End Try
    Return rasterDataset
End Function
[C#]
public IRasterDataset OpenRasterDataset(string sPath, string sFileName)
{
    // Returns RasterDataset object given a file name and its directory.
    // sPath—Path of the input raster dataset.
    // sFileName—Name of the input raster dataset.
    IRasterDataset rasterDataset=null;
    try
    {
        IWorkspaceFactory workspaceFactory=new RasterWorkspaceFactoryClass();
        IRasterWorkspace rasterWorkspace=null;
        if (workspaceFactory.IsWorkspace(sPath))
        {
            rasterWorkspace=(IRasterWorkspace)workspaceFactory.OpenFromFile(sPath,
                0);
            rasterDataset=rasterWorkspace.OpenRasterDataset(sFileName);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed in Opening RasterDataset. " +
            ex.InnerException.ToString());
    }
    return rasterDataset;
}
Some Spatial Analyst operations, such as PointDensity, IDW, and so on, require features as an input. The following are valid feature data objects that can be used in a Spatial Analyst operation:
  • FeatureClass
  • FeatureClassDescriptor
A FeatureClass represents the entire dataset, whereas a FeatureClassDescriptor, like a RasterDescriptor, is used to represent a subset through selection and uses an alternative field from the feature attribute table, or uses an alternative field from the feature attribute table.
In most operations, input features are converted to a raster using the analysis environment settings.
The following code example shows how to accesses a feature dataset on disk:
[VB.NET]
Public Function OpenFeatureClassFromShapefile(ByVal sPath As String, ByVal sShapeName As String) As IFeatureClass
    ' Returns a FeatureClass object given a shapefile's name and its path.
    Dim featureClass As IFeatureClass=Nothing
    Try
    Dim workspaceFactory As IWorkspaceFactory=New ShapefileWorkspaceFactoryClass
    Dim featureWorkspace As IFeatureWorkspace
    If workspaceFactory.IsWorkspace(sPath) Then
        Dim workspace As IWorkspace=workspaceFactory.OpenFromFile(sPath, 0)
        featureWorkspace=CType(workspace, IFeatureWorkspace)
        featureClass=featureWorkspace.OpenFeatureClass(sShapeName)
    End If
    Catch ex As Exception
    featureClass=Nothing
    Console.WriteLine("Failed in creating FeatureClass " + ex.InnerException.ToString)
    End Try
    Return featureClass
End Function
[C#]
public IFeatureClass OpenFeatureClassFromShapefile(string sPath, string sShapeName)
{
    // Returns a FeatureClass object given a shapefile's name and its path.
    IFeatureClass featureClass=null;
    try
    {
        IWorkspaceFactory workspaceFactory=new ShapefileWorkspaceFactoryClass();
        IFeatureWorkspace featureWorkspace=null;
        if (workspaceFactory.IsWorkspace(sPath))
        {
            IWorkspace workspace=workspaceFactory.OpenFromFile(sPath, 0);
            featureWorkspace=(IFeatureWorkspace)workspace;
            featureClass=featureWorkspace.OpenFeatureClass(sShapeName);
        }
    }
    catch (Exception ex)
    {
        featureClass=null;
        Console.WriteLine("Failed in creating FeatureClass " +
            ex.InnerException.ToString());
    }
    return featureClass;
}
For more information on RasterDescriptor and FeatureDescriptor, see Working with field and selection.

Execute the operation

The majority of the objects in the Spatial Analyst object libraries are operator objects that contain the methods for spatial analysis. Executing an operation involves, creating an operator object, optionally setting analysis environment, and calling the method with the appropriate input dataset and other parameters. 
The following code example creates the RasterSurfaceOp and executes the Slope method on an input elevation raster (the OpenRasterDataset function previously described is called):
[VB.NET]
Public Sub RunSlope()
    ' Gets an elevation raster from disk.
    ' Note: The OpenRasterDataset method was previously created in this topic.
    ' It is not a standard ArcObject's function.
    Dim elev1 As IRasterDataset=OpenRasterDataset("C:\Spatial", "elevation")
    ' Queries the RasterSurfaceOp.
    Dim surfaceOp As ISurfaceOp=New RasterSurfaceOpClass()
    ' Creates a geodataset to store the results and runs the operation.
    Dim geoDataset_Elevation As IGeoDataset=CType(elev1, IGeoDataset)
    Dim zFactor As System.Object=Type.Missing
    Dim outSlope As IGeoDataset
    outSlope=surfaceOp.Slope(geoDataset_Elevation, esriGeoAnalysisSlopeEnum.esriGeoAnalysisSlopeDegrees, zFactor)
End Sub
[C#]
public void RunSlope()
{
    // Gets an elevation raster from disk.
    // Note: The OpenRasterDataset method was previously created in this topic.
    // It is not a standard ArcObject's function.
    IRasterDataset elev1=OpenRasterDataset("C:\\Spatial", "elevation");
    // Queries the RasterSurfaceOp.
    ISurfaceOp surfaceOp=new RasterSurfaceOpClass();
    // Creates a geodataset to store the results and runs the operation.
    IGeoDataset geoDataset_Elevation=(IGeoDataset)elev1;
    System.Object zFactor=Type.Missing;
    IGeoDataset outSlope;
    outSlope=surfaceOp.Slope(geoDataset_Elevation,
        esriGeoAnalysisSlopeEnum.esriGeoAnalysisSlopeDegrees, ref zFactor);
}
Even though there are many operator objects with hundreds of methods, you can execute all of them using the same pattern as previously described. The only things that change in this example are the operator object, the method, and specified parameters.

Use the output

The raster output from a method points to a temporary raster dataset. This temporary dataset is created in the OutWorkspace and is deleted as soon as it is not referenced by any objects. It can be used as input into another operator or saved as a permanent raster dataset. Starting with ArcGIS Engine 10, it is possible to create a permanent output dataset during execution of the method.
For information on how to make the output permanent, see Data processing in spatial analysis operations.
The following code example shows how to turn a temporary output into a permanent dataset:
[VB.NET]
Public Sub MakePermanent(ByVal raster As IRaster)
    ' Query the output (a Raster object) for IRasterBandCollection.
    Dim rasterBandCollection As IRasterBandCollection=CType(raster, IRasterBandCollection)
    ' Get the dataset from the first band.
    Dim rasterBand As IRasterBand=rasterBandCollection.Item(0)
    Dim rasterDataset As IRasterDataset=rasterBand.RasterDataset
    ' Query the dataset for ITemporaryDataset.
    Dim temporaryDataset As ITemporaryDataset=CType(rasterDataset, ITemporaryDataset)
    Dim workspaceFactory As IWorkspaceFactory=New RasterWorkspaceFactoryClass
    Dim workspace As IWorkspace=workspaceFactory.OpenFromFile("c:\temp", 0)
    ' Format can be "GRID," "TIFF," or "IMAGINE Image."
    ' Note: Format string is case sensitive.
    temporaryDataset.MakePermanentAs("Result2.img", workspace, "IMAGINE Image")
End Sub
[C#]
public void MakePermanent(IRaster raster)
{
    // Save temporary raster.
    // Query the output (a Raster object) for IRasterBandCollection.
    IRasterBandCollection rasterBandCollection=(IRasterBandCollection)raster;
    // Get the dataset from the first band.
    IRasterBand rasterBand=rasterBandCollection.Item(0);
    IRasterDataset rasterDataset=rasterBand.RasterDataset;
    // Query the dataset for ITemporaryDataset.
    ITemporaryDataset temporaryDataset=(ITemporaryDataset)rasterDataset;
    IWorkspaceFactory workspaceFactory=new RasterWorkspaceFactoryClass();
    IWorkspace workspace=workspaceFactory.OpenFromFile("c:\\temp", 0);
    // Format can be "GRID," "TIFF," or "IMAGINE Image."
    // Note: Format string is case sensitive.
    temporaryDataset.MakePermanentAs("Result2.img", workspace, "IMAGINE Image");
}
Even though there are many ways to specify the input data, perform operations, use the output, and many possible sequences to perform the necessary analysis, the pattern you follow to use any Spatial Analyst operator are the same five steps described in this topic. The only things that change in any analysis are the input datasets, operator, method, its parameters, and how the output is used.






To use the code in this topic, reference the following assemblies in your Visual Studio project. In the code files, you will need using (C#) or Imports (VB .NET) directives for the corresponding namespaces (given in parenthesis below if different from the assembly name):

Development licensing Deployment licensing
ArcGIS Desktop Basic: Spatial Analyst ArcGIS Desktop Basic: Spatial Analyst
ArcGIS Desktop Standard: Spatial Analyst ArcGIS Desktop Standard: Spatial Analyst
ArcGIS Desktop Advanced: Spatial Analyst ArcGIS Desktop Advanced: Spatial Analyst