CreateEdgeList

# CreateEdgeList.py
#
# Description:
#  Loops through each patch in a raster dataset and creates a cost surface
#  to determine the minimum distance to each other patch in the raster and
#  writes these minimum distances out to an edge file, in CSV format

# Inputs: patch raster, cost surface raster, maxDist
#
# Outputs: edge list CSV file

# Import modules
import sys, os, arcpy
import arcpy.sa as sa
arcpy.env.overwriteOutput = 1

# Inputs
patchRaster = sys.argv[1]   #r'C:WorkSpaceGBAT2012GHAT_V01CellBasedScratchSubnetPatches'
arcpy.env.extent = patchRaster
costRaster = sys.argv[2]    #r'C:WorkSpaceGBAT2012GHAT_V01CellBasedScratchSubnetCost'
maxDist = sys.argv[3]       #7500

# Outputs
edgeList = sys.argv[4]      #r'C:WorkSpaceGBAT2012GHAT_V01CellBasedScratchCPEdgelist.csv'


# Check out the spatial analyst extension; send error if unavailable
if arcpy.CheckExtension("spatial") == 'Avalailable':
    arcpy.CheckOutExtension("spatial")


# Get a list of patch IDs
patchIDs = []
rows = arcpy.SearchCursor(patchRaster)
row = rows.next()
while row:
    patchIDs.append(row.Value)
    row = rows.next()
del row, rows

# Initiate the output edge list
outFile = open(edgeList,'w')
outFile.write("FromID,ToID,Costn")

# Initiate status variables
total = float(len(patchIDs))
interval = total/20 #<-- 20.0 reports status at 5% completion intervals
interval2 = interval
iter = 0
arcpy.AddMessage("Initiating edge list creation...")

# Loop through each patchID in the PatchIDList
for patchID in patchIDs:
    iter = iter + 1
    if iter > interval:
        arcpy.AddMessage(" %d%% complete." %(float(iter/total)*100.0))
        interval = interval + interval2
    # - Isolate the patch
    selectedPatch = sa.SetNull(patchRaster, patchRaster, "Value <> %s" %patchID)
    # - Calculate a cost distance and cost back link raster from the selected patch
    costDist = sa.CostDistance(selectedPatch, costRaster, maxDist)
    # - Tabulate zonal stats for the other patches on the cost distance
    zStatTable = sa.ZonalStatisticsAsTable(patchRaster,"Value",costDist,"in_memoryzstattbl","DATA","MINIMUM")
    # - Write out to an edge list
    recs = arcpy.SearchCursor("in_memoryzstattbl","VALUE > %d" %patchID)
    rec = recs.next()
    while rec:
        outFile.write("%d,%d,%sn" %(patchID, rec.VALUE, rec.MIN))
        rec = recs.next()
    del rec, recs
    
# Close the edge list file object
outFile.close()

# Clean up and exit
#arcpy.Delete_management("zstattbl")
arcpy.AddMessage("Edges successfully written to %s" %edgeList)