I can't force Python raster calculator to sum the rasters

5943
7
Jump to solution
05-08-2016 07:37 AM
StanislawPolanski
New Contributor II

Hi, Im newbie two Python scripting at all, anyway.

I'm trying to sum two rasters in Python toolbox, but it doesn't work the way I want it to. Here's the code:

import arcpy
from arcpy import env
from arcpy.sa import *


class Toolbox(object):
    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the
        .pyt file)."""
        self.label = "Toolbox"
        self.alias = ""
        # List of tool classes associated with this toolbox
        self.tools = [Tool]


class Tool(object):
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "Tool"
        self.description = ""
        self.canRunInBackground = False

    def getParameterInfo(self):
        """Define parameter definitions"""
        param0 = arcpy.Parameter(displayName="Input Features", name="in_features", datatype="DERasterDataset",  parameterType="Required", direction="Input", multiValue = True)
        params = [param0]
        return params

    def isLicensed(self):
        """Set whether tool is licensed to execute."""
        return True

    def updateParameters(self, parameters):
        """Modify the values and properties of parameters before internal
        validation is performed.  This method is called whenever a parameter
        has been changed."""
        return

    def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        return

    def execute(self, parameters, messages):
        # Set environment settings
        env.workspace = "C:/temp"

        #Set local variables
        inRaster = parameters[0].valueAsText
        rasters = inRaster.split(';')

        # Check out the ArcGIS Spatial Analyst extension license
        arcpy.CheckOutExtension("Spatial")

        #Execute sum
        output = Raster(rasters[0]) + Raster(rasters[1])

        #Save the output
        output.save("C:/temp/result/output02")

        return

I have two different 0-1 rasters in the same region created from different buffers. I expected it sums for each pixels it values, when on the same pixels i need it to give two when both pixels are black, one when when one of them is black and 0 when both are 0. But it just gives me nearly the same raster as the first. What do I do wrong? I expect it to work this way:

n9rAV.png

Here're the results I get, at first look the result's streams are not continous, but due to the image it should be:

Dokument1.jpg

0 Kudos
1 Solution

Accepted Solutions
PeterBecker
Esri Regular Contributor

I'm not 100% sure of what you are trying to achieve. If you are looking to get a raster that is the sum of overlapping rasters consider adding the rasters to a mosaic dataset and then setting the Mosaic Operator to Sum. This will dynamically return you a raster that is the sum of the overlapping rasters. You can use directly (without needing export and create a new raster) or export as a new raster.  One word of caution: The Mosaic Dataset has a parameters call 'Max Number of Rasters per mosaic'. This defined the maximum number of raster that can participate in a single export. If you are trying to summarize larger numbers of rasters then consider increasing this value to the maximum number of raster that you can expect in an export extent.

View solution in original post

7 Replies
DanPatterson_Retired
MVP Emeritus

picture and script are confusing.  Are you adding 2 rasters (as in the script) or 3 (as in the image)

Why go to such trouble when you can simply use built in tools?  What capability does the tool add?  Your script doesn't check extents, cell size, snap raster etc.  Is it only designed to work with rasters in a particular area and/or construct? What are the results when you go throught the addition process using arctoolbox SA tools?

StanislawPolanski
New Contributor II

Thanks for your response. I'm adding two rasters and getting the third as a result. I need this tool as a part of a slightly bigger project. I haven't thought about all the things you written about because there's nothing like that in ArcGIS docs, I mean:

ArcGIS Help (10.2, 10.2.1, and 10.2.2)

When I go through the arctoolbox "Raster Calculator" it also gives me such result. It prints out only sum of mutual parts of both rasters (within boundaries of both rasters it makes "NoData") instead of a sum. Later on I just need mathematical weighted sum of values for each pixel which somehow (btw weighted sum function also gives me such result).

0 Kudos
DanPatterson_Retired
MVP Emeritus

Stanislaw...

I rarely use the raster calculator, I use the tools in the spatial analyst toolset in arctoolbox.

For example, Plus—Help | ArcGIS for Desktop

lists towards the bottom the Environments that need to be considered when using the tool.  The list is extensive.  Don't assume that some global default is indeed global, it takes a second to check using the Environments button on the bottom right of every dialog...while you are there, expand the help topic, they are good, but generally not expanded for some unknown reason.

The main link to all of SA's tools is here An overview of the Spatial Analyst Toolbox—Help | ArcGIS for Desktop

You will even discover little gems that are often missed like Cell Statistics—Help | ArcGIS for Desktop

which has an option to get the sum with/or without accounting for nodata cells, whereas the Plus tool assigns a nodata value to a cell if a cell in the stack contains no data.

So examine the tools there and I recommend to all to avoid the raster calculator unless you have accounted for all the things that can go wrong when working with raster data.

Hope this helps

PeterBecker
Esri Regular Contributor

I'm not 100% sure of what you are trying to achieve. If you are looking to get a raster that is the sum of overlapping rasters consider adding the rasters to a mosaic dataset and then setting the Mosaic Operator to Sum. This will dynamically return you a raster that is the sum of the overlapping rasters. You can use directly (without needing export and create a new raster) or export as a new raster.  One word of caution: The Mosaic Dataset has a parameters call 'Max Number of Rasters per mosaic'. This defined the maximum number of raster that can participate in a single export. If you are trying to summarize larger numbers of rasters then consider increasing this value to the maximum number of raster that you can expect in an export extent.

NeilAyres
MVP Alum

Stan,

as you describe yourself as a "newbie" to python, I am a little surprised that you start by making a whole tool class.

I hardly ever use classes, but then I'm not a "proper" programmer (as some developer has said to me), but I do use python extensively, day-to-day, to suck data in, do something with it, and, hopefully, spit out something useful.

So, as Dan and others say - Start with the basics, use the tools provided, do it manually first, if you get the workflow right, then you can automate it (if needed) using python / arcpy scripting.

StanislawPolanski
New Contributor II

Thank you! It seems to me like there's everything ok with the script, but I can't understand how the raster tools work itself. Ima dig in and probably post another question later. I really appreciate your responses, because it tells me i just asked the question in a wrong way.

0 Kudos
curtvprice
MVP Esteemed Contributor

The Cell Statistics tool is probably the better operator to use in the context of your example. It has a nice feature in that you can tell it to ignore NoData in the cell-by-cell sum. Another key thing about the Spatial Analyst tools is you want your two inputs to be created so that they line up exactly (cell size and snap) so the cell-by-cell operations will work as expected.

Neil, the reason he's using a tool class is because this is a python toolbox .pyt and this is the programming style normally used for those.

Stan, if you are new To Python you may want to stay away from Python toolboxes until you are more experienced, they are a lot of extra work, even if you are very skilled with Python. (That extra work may be worth it, but it is more work than a script attached to a .tbx.)

0 Kudos