1

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.

  • What copy features statement are you receiving the error on (the first or second)? – artwork21 Dec 2 '16 at 13:34
2

You can't copy the OD matrix layer to a lines feature class directly. This OD matrix layer is a group layer, you need to retrieve the lines layer within the group. Try this:

arcpy.na.Solve(OD_Layer, "HALT")
lines = arcpy.mapping.ListLayers(OD_Layer, subLayerNames["ODLines"])[0]
arcpy.CopyFeatures_management(lines, "OD_Layer_{}".format(group))
  • Thank you! I had found the same solution yesterday on a geonet post :P – Below the Radar Dec 2 '16 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.