O-D Matrix analysis does not work with ArcGIS Pro 2.8

840
2
Jump to solution
06-30-2021 02:41 PM
JasonBenedict
New Contributor II

Hi,

My code below was working with an older version of ArcGIS Pro (2.6) but I am getting errors when running it with version 2.8. Does anyone know why this would be happening?

import arcpy
import dirfind
from arcpy import env
import os
from pathlib import Path 
import time
import pandas as pd

# Set workspace environment
dropbox_dir = dirfind.guess_dropbox_dir()
input_gdb = dropbox_dir + 'Trase/Indonesia/palm/logistics/odmatrix2021.gdb'
env.workspace = dropbox_dir + 'Trase/Indonesia/palm/logistics/odmatrix2021.gdb'
env.overwriteOutput=True

# Specify island for create OD matrix analysis
# Options: kalimantan, sumatera, sulawesi, papua and jawa
island = "papua"

# Set inputs (mills, refineries or ports)
origins = os.path.join(input_gdb, "mills")
destinations = os.path.join(input_gdb, "kab_centroids")
network = os.path.join(input_gdb, island, island+"_ND")

# Get field names for origin and destination points
orig_field_names = [f.name for f in arcpy.ListFields(origins)]
print(orig_field_names)
dest_field_names = [f.name for f in arcpy.ListFields(destinations)]
print(dest_field_names)

def calcDistances(origins, network, destinations, outLoc):
    """
    Uses a transportation network and list of origins and destinations points to
    find the total distance from origins to destinations. Exports the names of
    origin-destination and distance in meters as a csv file
    
    Parameters
    ----------
    network: road network data converted to a network datasets

    origins: feature class of origins as points
    
    destinations: feature class of origins as points
             
    outLoc: location of output feature layer (in gdb)       
        
    Returns
    -------
    csv: CSV file with names of OD links and distances
    
    ODCostMatrix: feature layer of OD cost matrix with OD lines, origins
                  destinations, etc
        
    """    

    outNALayerName = "distMatrix"
    outLayerFile = outNALayerName       
  
    # Make OD Cost Matrix Layer
    stime = time.time()
    print ("Creating OD layer...")
    outNALayer = arcpy.MakeODCostMatrixLayer_na(network, outNALayerName, "Length",\
         "", "", "", "ALLOW_UTURNS", "", "NO_HIERARCHY", "", "STRAIGHT_LINES", "")
        
    outNALayer = outNALayer.getOutput(0)
    
    #Get the names of all the sublayers within the OD cost matrix layer.
    subLayerNames = arcpy.na.GetNAClassNames(outNALayer)
    
    #Stores the layer names that we will use later
    origLayerName = subLayerNames["Origins"]
    destLayerName = subLayerNames["Destinations"]
    linesLayerName = subLayerNames["ODLines"]
    
    #Adjust field names according to origin and destination codes
    oriField = "Name " + orig_field_names[2] + " #"
    destField = "Name " +dest_field_names[6] + " #"
    
    # Add origins
    print("Loading Origins...")
    arcpy.AddLocations_na(
        outNALayer,
        origLayerName,
        origins,
        oriField,
        "30 Kilometers",
        "",
        "",
        "MATCH_TO_CLOSEST",
        "APPEND",
        "NO_SNAP",
        "5 Meters",
        "INCLUDE",
        ""
    )

    # Add destinations
    print("Loading Destinations...")
    arcpy.AddLocations_na(
        outNALayer,
        destLayerName,
        destinations,
        destField,
        "30 Kilometers",
        "",
        "",
        "MATCH_TO_CLOSEST",
        "APPEND",
        "NO_SNAP",
        "5 Meters",
        "INCLUDE",
        ""
    )

    print("Solving...")
    # Solve od cost matrix
    arcpy.Solve_na(outNALayer, "SKIP", "TERMINATE", "")
    print ("Finished in %.0f" % (time.time() - stime))
    print("Solved! Saving...")
    arcpy.SaveToLayerFile_management(outNALayer, outLayerFile, "RELATIVE")
       
    # Extract lines layer, export to CSV
    fields = ["Name", "Total_Length"]
    for lyr in outNALayer.listLayers():
        if lyr.name == linesLayerName:
            print("Saving lines...")
            with open(outFile, 'w') as f:
                f.write(','.join(fields)+'\n') # csv headers
                with arcpy.da.SearchCursor(lyr, fields) as cursor:
                     for row in cursor:
                        f.write(','.join([str(r) for r in row])+'\n')
    
    df = pd.read_csv(outFile, index_col=None, header=0)
    df = df.drop_duplicates(keep='first')
    df.to_csv(outFile,index=False)
    
    print("Script completed successfully")
                        
    # Deleteing in memory outNAlayer
    arcpy.Delete_management(outNALayer)

outFile = (
    dropbox_dir
    + "Trase/Indonesia/palm/logistics/output/2021/"
    + island
    + "_"
    + Path(origins).name
    + "_"
    + Path(destinations).name
    + "_odmatrix.csv"
)  # csv file output and location
calcDistances(origins, network, destinations, input_gdb)

 

This is the error I get when I run the code:

['OBJECTID', 'Shape', 'trase_code']
['OBJECTID', 'Shape', 'type', 'prov', 'prov_code', 'kab', 'kab_code']
Creating OD layer...
Loading Origins...
Loading Destinations...
Solving...
Traceback (most recent call last):

File "<ipython-input-5-14840f252f73>", line 160, in <module>
calcDistances(origins, network, destinations, input_gdb)

File "<ipython-input-5-14840f252f73>", line 124, in calcDistances
arcpy.Solve_na(outNALayer, "SKIP", "TERMINATE", "")

File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\na.py", line 3182, in Solve
raise e

File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\na.py", line 3179, in Solve
retval = convertArcObjectToPythonObject(gp.Solve_na(*gp_fixargs((in_network_analysis_layer, ignore_invalids, terminate_on_solve_error, simplification_tolerance, overrides), True)))

File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\geoprocessing\_base.py", line 512, in <lambda>
return lambda *args: val(*gp_fixargs(args, True))

ExecuteError: ERROR 030212: Solve did not find a solution.
No solution found.
Failed to execute (Solve).

 

0 Kudos
1 Solution

Accepted Solutions
MelindaMorang
Esri Regular Contributor

Hello Jason. I think this is probably the result of a bug that was introduced in Pro 2.8. We have fixed it, and the fix will be released in the next 2.8 patch, which should be available in a few weeks.

So sorry for the inconvenience!

View solution in original post

2 Replies
MelindaMorang
Esri Regular Contributor

Hello Jason. I think this is probably the result of a bug that was introduced in Pro 2.8. We have fixed it, and the fix will be released in the next 2.8 patch, which should be available in a few weeks.

So sorry for the inconvenience!

JasonBenedict
New Contributor II

Thanks for the update @MelindaMorang !

0 Kudos