raster-functions icon indicating copy to clipboard operation
raster-functions copied to clipboard

error running Clip raster function using Foreach loop

Open DavidAnderson-USFS opened this issue 1 year ago • 2 comments

I'm writing a script that needs to clip a multidimensional raster (Gridmet temperature data) to a smaller area. Poking around the documentation this is the workflow that I came up with temp_max_file = r"D:\r3_analyst_work\Climate_Change_Modeling\climate_envelope\GridMetData_2020\tmmx_2020.nc" max_temp_rast = arcpy.Raster(temp_max_file,True) clip_frame= r"D:\r3_analyst_work\GIS_work\test_working_netcdf_climate_data\Default.gdb\small_area" max_temp_clip_raster = arcpy.sa.Foreach(max_temp_rast,"Clip",{"ClippingGeometry":clip_frame, "ClippingType":1}) When I run this I get **RuntimeError Traceback (most recent call last) In [39]: Line 1: max_temp_clip_raster = arcpy.sa.Foreach(max_temp_rast,"Clip",{"ClippingGeometry":clip_frame, "ClippingType":1})

File C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\ia_ia.py, in Foreach: Line 114: return arcgisscripting._ia.Foreach(in_raster=in_raster,

RuntimeError: Failed to apply Raster Function: 'Clip' (The parameter is incorrect. )**

There is no indication what parameter is incorrect. I had to extract the parameter name by exporting the Clip raster function and then reading the XML document.

Using the ArcPro interface the raster function works correctly on those data sets.

From what I can tell, my code is exactly the same as the NDVI example provided in the Foreach documentation.

DavidAnderson-USFS avatar Mar 15 '23 17:03 DavidAnderson-USFS

@DavidAnderson-USFS The clip tool internally converts a feature to a geometry JSON and use that as ClippingGeometry. For some reason we are investigating, the conversion is not done when used in Foreach. Please try this snippet as workaround:

import json

temp_max_file = r"D:\r3_analyst_work\Climate_Change_Modeling\climate_envelope\GridMetData_2020\tmmx_2020.nc"
max_temp_rast = arcpy.Raster(temp_max_file,True)
clip_frame= r"D:\r3_analyst_work\GIS_work\test_working_netcdf_climate_data\Default.gdb\small_area"

geo_list =[]
for row in arcpy.da.SearchCursor(clip_frame, ["OID@", "SHAPE@"]):
    geo_list.append(row[1])
geo_union = geo_list[0]
for i in range(1, len(geo_list)):
    geo_union = geo_union.union(geo_list[i])
geometry_inp = json.loads(geo_union.JSON)

max_temp_clip_raster = arcpy.sa.Foreach(max_temp_rast,"Clip",{"ClippingGeometry":geometry_inp, "ClippingType":1}) 

shenganzhan avatar Mar 16 '23 18:03 shenganzhan

@shenganzhan I was able successfully implement this workaround. Thank you for rapid response in providing a solution.

@DavidAnderson-USFS The clip tool internally converts a feature to a geometry JSON and use that as ClippingGeometry. For some reason we are investigating, the conversion is not done when used in Foreach. Please try this snippet as workaround:

DavidAnderson-USFS avatar Mar 17 '23 14:03 DavidAnderson-USFS