My code takes 143.023 seconds for extracting nodes from a road network of city like Göteborg in Sweden. Please check it out if I can optimize it.
# -*- coding: utf-8 -*-
import arcpy
from Class import loading_layer
import time
def node_extraction(network_input):
time_start=time.time()
nodes_list = []
list_of_existing_nodes = []
for feature in network_input:
coordinates_list = list()
feature_startX = feature["Shape"].firstPoint.X
feature_startY = feature["Shape"].firstPoint.Y
start_list =[]
start_list.append(feature_startX)
start_list.append(feature_startY)
feature_endX = feature["Shape"].lastPoint.X
feature_endY = feature["Shape"].lastPoint.Y
end_list =[]
end_list.append(feature_endX)
end_list.append(feature_endY)
if nodes_list.__len__() is not 0:
if start_list in list_of_existing_nodes:
point_index=list_of_existing_nodes.index(start_list)
nodes_list[point_index][1].append(feature["FID"])
else:
nodes_list.append((feature["Shape"].firstPoint, [feature["FID"]]))
list_of_existing_nodes.append(start_list)
if end_list in list_of_existing_nodes:
point_index=list_of_existing_nodes.index(end_list)
nodes_list[point_index][1].append(feature["FID"])
else:
nodes_list.append((feature["Shape"].lastPoint, [feature["FID"]]))
list_of_existing_nodes.append(end_list)
else:
nodes_list.append((feature["Shape"].firstPoint, [feature["FID"]]))
nodes_list.append((feature["Shape"].lastPoint, [feature["FID"]]))
list_of_existing_nodes.append(start_list)
list_of_existing_nodes.append(end_list)
time_end=time.time()
print time_end-time_start
layer1 = loading_layer("D:/path/to/your/road/data.shp")
layer1.create_new_dict()
node_extraction(layer1.new_features_dict)
Load_layer
class is as follows:
import arcpy
from arcpy.sa import *
from arcpy import env
import re
from _collections import defaultdict
class loading_layer(object):
def __init__(self, input_data):
self.features_dict = defaultdict(list)
self.new_features_dict = []
self.Address = input_data
self.file_name = re.search(r'\w+.shp',input_data).group()
self.coord_sys = arcpy.Describe(self.Address).spatialReference
self.coord_sys_name = arcpy.Describe(self.Address).spatialReference.name
self.fieldList = [f.name for f in arcpy.ListFields(self.Address)]
if "matched_to".upper() not in self.fieldList:
arcpy.AddField_management(input_data, u"Matched_to", "TEXT")
self.fieldList.append(u"Matched_to")
print "field is added"
print str(self.fieldList)
def iterate_features(self):
feature_set = arcpy.SearchCursor(self.Address)
for feature in feature_set:
yield feature
def create_new_dict(self):
iterator = self.iterate_features()
for item in iterator:
feature = dict()
for f in self.fieldList:
feature[f] = item.getValue(f)
self.new_features_dict.append(feature)