I want to perform OD Matrix Cost in loop for each locations group inside a feature class.
As output, I want a lines feature class per group.
import arcpy
arcpy.env.overwriteOutput = True
def execute():
network_dataset = arcpy.GetParameter(0)
impedenace_attribute = arcpy.GetParameter(1)
locations_fc = arcpy.GetParameter(2)
sort_field = arcpy.GetParameter(3)
group_by_field = arcpy.GetParameter(4)
output_workspace = arcpy.GetParameter(5)
arcpy.env.workspace = output_workspace
calculate_OD(network_dataset, impedenace_attribute, locations_fc, group_by_field, sort_field, output_workspace)
def calculate_OD(network_dataset, impedenace_attribute, locations_fc, group_by_field, sort_field, output_workspace):
group_by_list = sorted(set((row[0] for row in arcpy.da.SearchCursor(locations_fc, group_by_field))))
OD_Layer = arcpy.MakeODCostMatrixLayer_na(network_dataset, "OD_Matrix_Layer", impedenace_attribute)
OD_Layer = OD_Layer.getOutput(0)
for group in group_by_list:
expression = u"{} = '{}'".format(group_by_field, group)
group_layer = arcpy.MakeFeatureLayer_management(locations_fc, "locations_{}".format(group), where_clause=expression)
group_fc = arcpy.CopyFeatures_management(group_layer, "OD_locations_{}".format(group))
subLayerNames = arcpy.na.GetNAClassNames(OD_Layer)
originsLayerName = subLayerNames["Origins"]
arcpy.na.AddLocations(OD_Layer, originsLayerName, group_fc, sort_field=sort_field, append="CLEAR")
destinationLayerName = subLayerNames["Destinations"]
arcpy.na.AddLocations(OD_Layer, destinationLayerName, group_fc, sort_field=sort_field, append="CLEAR")
arcpy.na.Solve(OD_Layer,"HALT")
#save output in feature class (this generate the error below)
arcpy.CopyFeatures_management(OD_Layer, "OD_output_{}".format(group))
execute()
However, I have a problem when copying the ODLines sublayer to a new feature class.
ExecuteError: Failed to execute. Parameters are not valid. ERROR 000840: The value is not a Feature Layer. ERROR 000840: The value is not a Raster Catalog Layer.