Select to view content in your preferred language

Python Toolbox Script Problem -Cannot get output raster layer to display or save in project

788
2
11-17-2023 11:02 AM
JannaBighouse
New Contributor

I am new to Python and am in the process of creating a Python Toolbox in ArcGIS Pro (version 3.1.3) to conduct a trend analysis on a multidimensional Raster layer. When I run the tool, it states that it ran successfully, but it is not adding the trend analysis raster layer to the project. My code is below (things that I have tried are commented out). I am obviously missing something simple. Any help to correct this would be greatly appreciated! 

# -*- coding: utf-8 -*-

import arcpy
import os

# Define a class named Toolbox
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the .pyt file)."""
self.label = "Coral Reef Assessment Tools"
self.alias = "toolbox"

# List of tool classes associated with this toolbox
self.tools = [SeaSurfaceTemp_Trend_Analysis]

# Define the tool class named SeaSurfaceTemp_Trend_Analysis
class SeaSurfaceTemp_Trend_Analysis(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Bighouse_Temperature_Trend_Analysis"
self.description = "Performs a multidimensional trend analysis on a raster layer"
self.canRunInBackground = False

# Assign parameters
def getParameterInfo(self):
"""Define parameter definitions"""
params = [
arcpy.Parameter(displayName="Input Multidimensional Raster Layer",
name="input_Multidimensional_Raster_layer",
datatype="GPRasterLayer",
parameterType="Required",
direction="Input"),

arcpy.Parameter(displayName="Output Raster",
name="output_raster_name",
datatype="DERasterDataset",
parameterType="Required",
direction="Output"),
]
return params

# Other methods ...

def execute(self, parameters, messages):
"""The source code of the tool."""
try:
multidimensional_raster = parameters[0].valueAsText
output_raster_name = parameters[1].valueAsText

# Hardcoded extent and spatial reference
xmin, ymin, xmax, ymax = -177.540046, 21.549769, -159.090139, 28.420046
spatial_reference = arcpy.SpatialReference(4326) # WGS 1984

# Set the environment with extent and spatial reference
with arcpy.EnvManager(extent=arcpy.Extent(xmin, ymin, xmax, ymax),
outputCoordinateSystem=spatial_reference):

# Perform the trend analysis
out_multidimensional_raster = arcpy.ia.GenerateTrendRaster(
in_multidimensional_raster=multidimensional_raster,
dimension="StdTime",
variables="cfsrsst",
line_type="HARMONIC",
frequency=1,
ignore_nodata="DATA",
cycle_length=1,
cycle_unit="YEARS",
rmse="RMSE",
r2="NO_R2",
slope_p_value="NO_SLOPEPVALUE",
seasonal_period=""
)

# Save the output raster to a file test lines added
#output_path = os.path.join(arcpy.env.scratchFolder, output_raster_name + ".tif")
#out_multidimensional_raster.save(output_path)

# Make raster layer from saved output raster and add to map
arcpy.management.MakeRasterLayer(multidimensional_raster, output_raster_name)

return
# Make a raster layer from the saved output raster and add it to the map
#result = arcpy.management.MakeRasterLayer(output_path, output_raster_name)
#output_raster_layer = result.getOutput(0)

# Set the derived output parameter
arcpy.SetParameter(1, output_raster_layer)
except Exception as e:
arcpy.AddError(f"An error occurred: {str(e)}")
raise

return

 

 

 

0 Kudos
2 Replies
Yuhash
by
Frequent Contributor

Hi Janna, 

I think you need to first identify the ArcGIS project and the active map, then add the layer in order to view the output.

aprx = arcpy.mp.ArcGISProject("current")
mp = aprx.listMaps()[0]
mp.addLayer(output_raster_layer)

 

0 Kudos
JannaBighouse
New Contributor

Thanks for the quick response. I added the lines you mentioned, but it still isn't adding the layer to view. Below is what my script looks like now. Again, it stated that the tool ran successfully, but no layer can be found. Did I add the lines in the wrong place? Any other suggestions would be greatly appreciated!

Thanks again! 

# -*- coding: utf-8 -*-

import arcpy
import os

# Define a class named Toolbox
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the .pyt file)."""
self.label = "Coral Reef Assessment Tools"
self.alias = "toolbox"

# List of tool classes associated with this toolbox
self.tools = [SeaSurfaceTemp_Trend_Analysis]

# Define the tool class named SeaSurfaceTemp_Trend_Analysis
class SeaSurfaceTemp_Trend_Analysis(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Bighouse_Temperature_Trend_Analysis"
self.description = "Performs a multidimensional trend analysis on a raster layer"
self.canRunInBackground = False

# Assign parameters
def getParameterInfo(self):
"""Define parameter definitions"""
params = [
arcpy.Parameter(displayName="Input Multidimensional Raster Layer",
name="input_Multidimensional_Raster_layer",
datatype="GPRasterLayer",
parameterType="Required",
direction="Input"),

arcpy.Parameter(displayName="Output Raster",
name="output_raster_name",
datatype="DERasterDataset",
parameterType="Required",
direction="Output"),
]
return params

# Other methods ...

def execute(self, parameters, messages):
"""The source code of the tool."""
try:
multidimensional_raster = parameters[0].valueAsText
output_raster_name = parameters[1].valueAsText

# Hardcoded extent and spatial reference
xmin, ymin, xmax, ymax = -177.540046, 21.549769, -159.090139, 28.420046
spatial_reference = arcpy.SpatialReference(4326) # WGS 1984

# Set the environment with extent and spatial reference
with arcpy.EnvManager(extent=arcpy.Extent(xmin, ymin, xmax, ymax),
outputCoordinateSystem=spatial_reference):

# Perform the trend analysis
out_multidimensional_raster = arcpy.ia.GenerateTrendRaster(
in_multidimensional_raster=multidimensional_raster,
dimension="StdTime",
variables="cfsrsst",
line_type="HARMONIC",
frequency=1,
ignore_nodata="DATA",
cycle_length=1,
cycle_unit="YEARS",
rmse="RMSE",
r2="NO_R2",
slope_p_value="NO_SLOPEPVALUE",
seasonal_period=""
)

# Save the output raster to a file test lines added
#output_path = os.path.join(arcpy.env.scratchFolder, output_raster_name + ".tif")
#out_multidimensional_raster.save(output_path)

# Make raster layer from saved output raster and add to map
arcpy.management.MakeRasterLayer(multidimensional_raster, output_raster_name)

return
# Set the derived output parameter first three lines are test code
aprx = arcpy.mp.ArcGISProject("current")
mp = aprx.listMaps()[0]
mp.addLayer(output_raster_layer)

arcpy.SetParameter(0, output_raster_layer)

# Make a raster layer from the saved output raster and add it to the map
#result = arcpy.management.MakeRasterLayer(output_path, output_raster_name)
#output_raster_layer = result.getOutput(0)

except Exception as e:
arcpy.AddError(f"An error occurred: {str(e)}")
raise

return



0 Kudos