def ODLayer(): arcpy.Delete_management("ODMATRIX") arcpy.MakeODCostMatrixLayer_na(Network,"ODMATRIX",Costs,Max_Costs,to_find,cost_attr,"","","","","NO_LINES") p = arcpy.na.GetSolverProperties(arcpy.mapping.Layer("ODMATRIX")) Restriction_0 = list(p.restrictions) ##activate all restrictions p.restrictions = Restriction_0 if Barriers: arcpy.AddLocations_na("ODMATRIX","Line Barriers",Barriers,"","") if "Distance" in Modus: fm_A = checkfm(A_Shape,ID_A) arcpy.na.AddFieldToAnalysisLayer("ODMATRIX", "Origins","tfrom_park", "Integer") if fm_A is None: arcpy.AddLocations_na("ODMATRIX","Origins",A_Shape,"Name "+ID_A+\ " 0; tfrom_park # 1","","",[["MRH_Wege", "SHAPE"],["MRH_Luecken", "SHAPE"],["Ampeln", "NONE"],["Faehre_NMIV", "NONE"]],"","","","","EXCLUDE") else: fm_A = fm_A+"; tfrom_park tAb 1" arcpy.AddLocations_na("ODMATRIX","Origins",A_Shape,fm_A,"","","","","CLEAR","","","EXCLUDE") if "Potential" in Modus: arcpy.Delete_management("P_Shape") if Filter_P: arcpy.MakeFeatureLayer_management(P_Shape, "P_Shape",Filter_P+">0") else: arcpy.MakeFeatureLayer_management(P_Shape, "P_Shape") fm_P = checkfm("P_Shape",ID_P) if fm_P is None: arcpy.AddLocations_na("ODMATRIX","Destinations","P_Shape","Name "+ID_P+\ " 0; Attr_Minutes # #","","",[["MRH_Wege", "SHAPE"],["MRH_Luecken", "SHAPE"],["Ampeln", "NONE"],["Faehre_NMIV", "NONE"]],"","","","","EXCLUDE") else: arcpy.AddLocations_na("ODMATRIX","Destinations","P_Shape",fm_P,"","","","","CLEAR","","","EXCLUDE")
def ODRouting(FC,FC_ID,OID,row,fieldmap): arcpy.MakeFeatureLayer_management(FC, "places",OID+" >= "+str(row)+" and "+OID+" < "+str(row+5000)) if fieldmap == "": arcpy.AddLocations_na("ODLayer","Origins","places","Name "+FC_ID+\ " 0; Attr_Minutes # #","","",[["MRH_Wege_Split", "SHAPE"],["MRH_Luecken", "SHAPE"],["Ampeln", "NONE"],["Faehre_NMIV", "NONE"]],"","CLEAR","","","EXCLUDE") else: arcpy.AddLocations_na("ODLayer","Origins","places",fieldmap,"","","","","CLEAR","","","EXCLUDE") try: arcpy.Solve_na("ODLayer","SKIP","CONTINUE") ##SKIP:Not Located is skipped except: arcpy.AddMessage("> error "+str(row)+" bis "+str(row+5000)) arcpy.Delete_management("places") raise
def potential(origins,loop): global n, Column global Result, Column, e, routes, ID_A arcpy.AddMessage("> origins from "+str(origins)+" to "+str(origins+loop)+" from "+str(Origins)) arcpy.Delete_management("A_Shape") for field in arcpy.Describe(A_Shape).fields: if field.type == "OID": OID = str(field.name) arcpy.MakeFeatureLayer_management(A_Shape, "A_Shape",OID+" >= "+str(origins)+" and "+OID+" < "+str(origins+loop)) fm_A = checkfm("A_Shape",ID_A) if fm_A is None:arcpy.AddLocations_na("ODMATRIX","Origins","A_Shape","Name "+ID_A+\ " 0; Attr_Minutes # #","","",[["MRH_Wege", "SHAPE"],["MRH_Luecken", "SHAPE"],["Ampeln", "NONE"],["Faehre_NMIV", "NONE"]],"","","","","EXCLUDE") else: arcpy.AddLocations_na("ODMATRIX","Origins","A_Shape",fm_A,"","","","","CLEAR","","","EXCLUDE") arcpy.na.Solve("ODMATRIX") routes = pandas.DataFrame(arcpy.da.FeatureClassToNumPyArray("ODMATRIX\Lines",["Name"]+["Total_"+x for x in cost_attr])) routes[[ID_A,ID_P+"_P"]] = routes.Name.str.split(' - ',expand=True,).astype(int) routes.columns = [map(lambda a:a.replace("Total_",""),routes.columns)] routes.drop("Name", axis=1, inplace=True) StructData = pandas.DataFrame(dataP[[ID_P]+StructField]) StructData = StructData.rename(columns = {ID_P:ID_P+"_P"}) routes = pandas.merge(routes,StructData) Result = pandas.DataFrame(np.unique(routes[ID_A])) Result = Result.rename(columns = {0:ID_A}) for e in Measures: Column = e.split("__")[0] ##to get the name of places if e[-3:] == "Sum": for n in sumfak_t: Values = routes[routes[Costs]<=int(n)].groupby([ID_A])[Column].agg('sum').reset_index(drop=False) Result = pandas.merge(Result,Values,how="left",left_on=ID_A,right_on=ID_A) if sumfak_d: for n in sumfak_d: Values = routes[routes["Meter"]<=int(n)].groupby([ID_A])[Column].agg('sum').reset_index(drop=False) Result = pandas.merge(Result,Values,how="left",left_on=ID_A,right_on=ID_A) if e[-4:] == "Expo": for n in potfak: n = float(n) Values = routes.groupby([ID_A]).agg(exp_aggr).reset_index(drop=False)[[ID_A,Column]] Result = pandas.merge(Result,Values,how="left",left_on=ID_A,right_on=ID_A) Result = Result.fillna(0) Result = np.array(Result) for row in Result: row = [tuple(row)] oldsize = len(Results_T) Results_T.resize((oldsize+1,)) Results_T[oldsize:oldsize+1] = row file5.flush()
def ODLayer(mod,FC,FC_ID,fieldmap): arcpy.AddMessage("> starting with: "+mod[0]) costattr() if mod[0] == "bus": arcpy.MakeFeatureLayer_management(FC, "stops",BahnFeld+" = 0") else: arcpy.MakeFeatureLayer_management(FC, "stops",BahnFeld+" > 0") if mod[1] == 0: arcpy.AddMessage("> no stops in mode: "+mod[0]) arcpy.MakeODCostMatrixLayer_na(Network,"ODLayer",Costs,MaxCosts,mod[1],cost_attr,"","","","","NO_LINES") if fieldmap == "": arcpy.AddLocations_na("ODLayer","Destinations","stops","Name "+FC_ID+\ " 0; Attr_Minutes # #","","",[["MRH_Wege_Split", "SHAPE"],["MRH_Luecken", "SHAPE"],["Ampeln", "NONE"],["Faehre_NMIV", "NONE"]],"","","","","EXCLUDE") else: arcpy.AddLocations_na("ODLayer","Destinations","stops",fieldmap,"","","","","","","","EXCLUDE") arcpy.AddMessage("> "+mod[0]+"stops added \n") if Barrieren != "": arcpy.AddLocations_na("ODLayer","Line Barriers",Barrieren)
def distance(group, groups): arcpy.Delete_management("P_Shape") if Filter_Group_P: arcpy.MakeFeatureLayer_management(P_Shape, "P_Shape",Filter_Group_P+"= "+str(group)) arcpy.AddMessage("> group "+str(group)+"/"+str(len(groups))+" with "+str(len(dataP[dataP[Filter_Group_P]==group]))+" places") else: arcpy.MakeFeatureLayer_management(P_Shape, "P_Shape") arcpy.AddMessage("> distances to next place out of "+str(len(dataP))+" places") if Filter_P: arcpy.SelectLayerByAttribute_management("P_Shape", "ADD_TO_SELECTION", Filter_P+">0") fm_P = checkfm("P_Shape",ID_P) arcpy.na.AddFieldToAnalysisLayer("ODMATRIX", "Destinations","tto_park", "Integer") if fm_P is None:arcpy.AddLocations_na("ODMATRIX","Destinations","P_Shape","Name "+ID_P+\ " 0; tto_park # 2","","",[["MRH_Wege", "SHAPE"],["MRH_Luecken", "SHAPE"],["Ampeln", "NONE"],["Faehre_NMIV", "NONE"]],"","","","","EXCLUDE") else: fm_P = fm_P+"; tto_park tZu 2" arcpy.AddLocations_na("ODMATRIX","Destinations","P_Shape",fm_P,"","","","","CLEAR","","","EXCLUDE") arcpy.na.Solve("ODMATRIX") if PrT == "Motorized": arcpy.DeleteField_management("Lines",["tfrom_park","tto_park"]) arcpy.management.JoinField("Lines", "OriginID","Origins", "ObjectID", "tfrom_park") arcpy.management.JoinField("Lines", "DestinationID","Destinations", "ObjectID", "tto_park") routes = pandas.DataFrame(arcpy.da.FeatureClassToNumPyArray("ODMATRIX\Lines",["Name"]+["Total_"+x for x in cost_attr]+["DestinationRank","tfrom_park","tto_park"])) routes["Total_"+Costs] = routes["Total_"+Costs]+routes["tfrom_park"]+routes["tto_park"] else: routes = pandas.DataFrame(arcpy.da.FeatureClassToNumPyArray("ODMATRIX\Lines",["Name"]+["Total_"+x for x in cost_attr]+["DestinationRank"])) routes[[ID_A,ID_P+"_P"]] = routes.Name.str.split(' - ',expand=True,).astype(int) routes.columns = [map(lambda a:a.replace("Total_",""),routes.columns)] routes.drop("Name", axis=1, inplace=True) if Filter_Group_P: routes[Filter_Group_P] = group if PrT == "Motorized": Result = routes[[ID_A,ID_P+"_P"]+cost_attr+["tfrom_park","tto_park","DestinationRank"]+[Filter_Group_P]] else: Result = routes[[ID_A,ID_P+"_P"]+cost_attr+["DestinationRank"]+[Filter_Group_P]] else: if PrT == "Motorized": Result = routes[[ID_A,ID_P+"_P"]+cost_attr+["tfrom_park","tto_park","DestinationRank"]] else: Result = routes[[ID_A,ID_P+"_P"]+cost_attr+["DestinationRank"]] Result = np.array(Result) oldsize = len(Results_T) sizer = oldsize + len(Result) Results_T.resize((sizer,)) Result = list(map(tuple, Result)) Results_T[oldsize:sizer] = Result file5.flush()
def get_distance(points): point = arcpy.Point() pointGeometryList = [] for pt in points: point.X = pt[0] point.Y = pt[1] pointGeometry = arcpy.PointGeometry(point).projectAs( arcpy.SpatialReference(4326)) pointGeometryList.append(pointGeometry) arcpy.CopyFeatures_management(pointGeometryList, m) arcpy.AddLocations_na(B1_route, "Stops", m, "Name Name #", "0 Miles", "", "", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "0 Miles", "INCLUDE", "") # just in case try: arcpy.Solve_na(B1_route, "SKIP", "TERMINATE", "") arcpy.SelectData_management(B1_route, "Routes") arcpy.FeatureToLine_management(B1_route + "/Routes", feature, "", "ATTRIBUTES") except: return 999999 try: arcpy.Append_management(feature, empty_memory) except: arcpy.CopyFeatures_management(feature, empty_memory) return ([f[0] for f in arcpy.da.SearchCursor(feature, 'SHAPE@LENGTH')][0])
def get_dist(points, current_id, buffer_id): point = arcpy.Point() pointGeometryList = [] for pt in points: point.X = pt[0] point.Y = pt[1] pointGeometry = arcpy.PointGeometry(point).projectAs( arcpy.SpatialReference(4326)) pointGeometryList.append(pointGeometry) arcpy.CopyFeatures_management(pointGeometryList, m) arcpy.AddLocations_na(B1_route, "Stops", m, "Name Name #", "0 Miles", "", "", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "0 Miles", "INCLUDE", "") # just in case try: arcpy.Solve_na(B1_route, "SKIP", "TERMINATE", "") arcpy.SelectData_management(B1_route, "Routes") arcpy.FeatureToLine_management(B1_route + "/Routes", feature, "", "ATTRIBUTES") except: print "Cannot Solve" return [], 999999 arcpy.AddField_management(feature, "curr_id", "LONG") arcpy.AddField_management(feature, "buffer_id", "LONG") arcpy.CalculateField_management(feature, "curr_id", current_id, "PYTHON") arcpy.CalculateField_management(feature, "buffer_id", buffer_id, "PYTHON") arcpy.SelectLayerByLocation_management("newlf", "WITHIN", feature) _list_ = [f[0] for f in arcpy.da.SearchCursor("newlf", '_ID_')] return _list_, ([ f[0] for f in arcpy.da.SearchCursor(feature, 'SHAPE@LENGTH') ][0])
def update_incidents(mlayer): arcpy.DeleteRows_management('Closest Facility\Incidents') arcpy.AddLocations_na(network, 'Incidents', mlayer, 'Name {} #'.format(_HYBASID), _TOLERANCE, '#', 'tracks SHAPE;tracks_ND_Junctions NONE', 'MATCH_TO_CLOSEST', 'APPEND', 'NO_SNAP', '5 Meters', 'INCLUDE', 'tracks #;tracks_ND_Junctions #')
def add_route_to_layer(linkid, points, sumlayer): point = arcpy.Point() pointGeometryList = [] for pt in points: point.X = pt[0] point.Y = pt[1] pointGeometry = arcpy.PointGeometry(point).projectAs( arcpy.SpatialReference(4326)) pointGeometryList.append(pointGeometry) arcpy.CopyFeatures_management(pointGeometryList, m) arcpy.AddLocations_na(B1_route, "Stops", m, "Name Name #", "2 Meters", "", "", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "2 Meters", "INCLUDE", "") try: arcpy.Solve_na(B1_route, "SKIP", "TERMINATE", near_snap_dist) arcpy.SelectData_management(B1_route, "Routes") arcpy.FeatureToLine_management(B1_route + "/Routes", feature, "", "ATTRIBUTES") arcpy.CalculateField_management( feature, "FID_Routes", linkid, "PYTHON") # since ID field is not available except: print("Route not found. 999999 Returned") return 999999 arcpy.Merge_management([feature, sumlayer], temp2) arcpy.Copy_management(temp2, sumlayer) return 0
def get_length_route(points): point = arcpy.Point() pointGeometryList = [] for pt in points: point.X = pt[0] point.Y = pt[1] pointGeometry = arcpy.PointGeometry(point).projectAs(arcpy.SpatialReference(4326)) pointGeometryList.append(pointGeometry) arcpy.CopyFeatures_management(pointGeometryList, m) arcpy.AddLocations_na(route_f, "Stops", m, "Name Name #", "0.5 Miles", "", "", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "10 Meters", "INCLUDE", "") arcpy.Solve_na(route_f, "SKIP", "TERMINATE", "500 Kilometers") arcpy.SelectData_management(route_f, "Routes") arcpy.FeatureToLine_management(route_f + "\\Routes", f, "", "ATTRIBUTES") # corrected to "Total_Length" from "Total_Leng" leng = [row.getValue("Total_Length") for row in arcpy.SearchCursor(f)][0] / 1609.34 return leng
def get_dist_AB(fips_a, fips_b): arcpy.Select_analysis(snapped_dumm, m, 'FIPS = {0} OR FIPS = {1}'.format(fips_a, fips_b)) arcpy.AddLocations_na("Route", "Stops", m, "Name Name #", "5000 Kilometers", "", "B1 SHAPE;B1_ND_Junctions SHAPE", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "5 Meters", "INCLUDE", "B1 #;B1_ND_Junctions #") try: arcpy.Solve_na("Route", "SKIP", "TERMINATE", "5000 Kilometers") except: return [9999999, 9999999] arcpy.SelectData_management("Route", "Routes") #arcpy.CopyFeatures_management("Route/Routes", feature) arcpy.FeatureToLine_management("Route/Routes", feature) dummy = [[row[0], row[1] * 0.000621371] for row in arcpy.da.SearchCursor( feature, ['Total_resi', "SHAPE@LENGTH"], spatial_reference=sr)][0] return dummy
def get_shortest_path_link_ids(fips_a, fips_b): #print ("ArgGIS analyst: Job Received, OFIPS: {0}, DFIPS: {1} *".format(fips_a, fips_b)) arcpy.CheckOutExtension("Network") arcpy.Select_analysis(snapped_fips, o, 'FIPS = {0}'.format(fips_a)) arcpy.Select_analysis(snapped_fips, d, 'FIPS = {0}'.format(fips_b)) arcpy.Merge_management([o, d], m) arcpy.AddLocations_na("Route", "Stops", m, "Name Name #", "5000 Kilometers", "", "B1 SHAPE;B1_ND_Junctions SHAPE", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "5 Meters", "INCLUDE", "B1 #;B1_ND_Junctions #") try: arcpy.Solve_na("Route", "SKIP", "TERMINATE", "500 Kilometers") arcpy.SelectData_management("Route", "Routes") arcpy.FeatureToLine_management("Route/Routes", feature, "", "ATTRIBUTES") except: print ("Route between FIPS: {0} and {1} not found.".format(fips_a,fips_b)) unknown_routes_dict[fips_a]=fips_b return [] arcpy.SelectLayerByLocation_management(alllinks_f,"INTERSECT",feature, "", "NEW_SELECTION", "NOT_INVERT") dummy = [row.getValue("OBJECTID") for row in arcpy.SearchCursor(alllinks_f)] return dummy
def get_dist_AB(fips_a, fips_b): #print ("ArgGIS analyst: Job Received, ONODE: {0}, DNODE: {1} *".format(fips_a, fips_b)) arcpy.CheckOutExtension("Network") arcpy.Select_analysis(snapped_dumm, o, 'FIPS = {0}'.format(fips_a)) arcpy.Select_analysis(snapped_dumm, d, 'FIPS = {0}'.format(fips_b)) arcpy.Merge_management([o, d], m) arcpy.AddLocations_na("Route", "Stops", m, "Name Name #", "5000 Kilometers", "", "B1 SHAPE;B1_ND_Junctions SHAPE", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "5 Meters", "INCLUDE", "B1 #;B1_ND_Junctions #") try: arcpy.Solve_na("Route", "SKIP", "TERMINATE", "500 Kilometers") arcpy.SelectData_management("Route", "Routes") arcpy.FeatureToLine_management("Route/Routes", feature, "", "ATTRIBUTES") except: print("Route not found. 999999 Returned") return -99 dummy = [ row.getValue("Total_Leng") for row in arcpy.SearchCursor(feature) ][0] return dummy * 0.000621371
def add_route_to_layer(nodeA, nodeB, sumlayer): print("ArgGIS analyst: Job Received, ONODE: {0}, DNODE: {1} *".format( nodeA, nodeB)) # *these nodes are in different layers arcpy.CheckOutExtension("Network") arcpy.Select_analysis(SnappedNodes, o, 'ID = {0}'.format(nodeA)) arcpy.Select_analysis(SnappedNodes, d, 'ID = {0}'.format(nodeB)) arcpy.Merge_management([o, d], m) arcpy.AddLocations_na("Route", "Stops", m, "Name Name #", "5000 Kilometers", "", "B1 SHAPE;B1_ND_Junctions SHAPE", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "5 Meters", "INCLUDE", "B1 #;B1_ND_Junctions #") try: arcpy.Solve_na("Route", "SKIP", "TERMINATE", "500 Kilometers") arcpy.SelectData_management("Route", "Routes") arcpy.FeatureToLine_management("Route\\Routes", feature, "", "ATTRIBUTES") except: print("Route not found. 999999 Returned") return 0 arcpy.Merge_management([feature, sumlayer], templayer) arcpy.Copy_management(templayer, sumlayer) return 0
def get_dist(points, current_id, buffer_id): if points[0] == points[ 1]: # if both the snapped connecting node and the point being tested is the same return [], 0 arcpy.MakeFeatureLayer_management(new_l, "newlf") arcpy.MakeRouteLayer_na(B1_ND, B1_route, "Length") # print current_id # print buffer_id point = arcpy.Point() pointGeometryList = [] for pt in points: point.X = pt[0] point.Y = pt[1] pointGeometry = arcpy.PointGeometry(point).projectAs(sr_g) pointGeometryList.append(pointGeometry) arcpy.CopyFeatures_management(pointGeometryList, m) arcpy.AddLocations_na(B1_route, "Stops", m, "Name Name #", "", "", "", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "", "INCLUDE", "") # just in case try: arcpy.Solve_na(B1_route, "SKIP", "TERMINATE", "") except: return {}, 99999 #arcpy.Solve_na(B1_route, "SKIP", "TERMINATE", "") arcpy.SelectData_management(B1_route, "Routes") arcpy.FeatureToLine_management(B1_route + "/Routes", feature, "", "ATTRIBUTES") arcpy.AddField_management(feature, "curr_id", "LONG") arcpy.AddField_management(feature, "buffer_id", "LONG") arcpy.CalculateField_management(feature, "curr_id", current_id, "PYTHON") arcpy.CalculateField_management(feature, "buffer_id", buffer_id, "PYTHON") arcpy.SelectLayerByLocation_management("newlf", "WITHIN", feature) _list_ = [f[0] for f in arcpy.da.SearchCursor("newlf", '_ID_')] return _list_, ([ f[0] for f in arcpy.da.SearchCursor(feature, 'SHAPE@LENGTH', "", sr_p) ][0]) / 1604.34
def get_distance(nodeAlayer, nodeBlayer, nodeAColumnName, nodeBColumnName, nodeA, nodeB): #create a set of origin and destination FIPS to be loaded in the network analyst #print ("ArgGIS analyst: Job Received, ONODE: {0}, DNODE: {1} *".format(nodeA, nodeB)) # *these nodes are in different layers sys.stdout.write('.') arcpy.CheckOutExtension("Network") arcpy.Select_analysis(nodeAlayer + ".shp", o, '{0} = {1}'.format(nodeAColumnName, nodeA)) arcpy.Select_analysis(nodeBlayer + ".shp", d, '{0} = {1}'.format(nodeBColumnName, nodeB)) arcpy.Merge_management([o, d], m) arcpy.AddLocations_na("Route", "Stops", m, "Name Name #", "5000 Kilometers", "", "B1 SHAPE;B1_ND_Junctions SHAPE", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "5 Meters", "INCLUDE", "B1 #;B1_ND_Junctions #") try: arcpy.Solve_na("Route", "SKIP", "TERMINATE", "500 Kilometers") arcpy.SelectData_management("Route", "Routes") arcpy.FeatureToLine_management("Route\\Routes", feature, "", "ATTRIBUTES") except: return 999999 return ([f[0] for f in arcpy.da.SearchCursor(feature, 'SHAPE@LENGTH')][0])
LaskKohteet, Accumulation, "ALLOW_DEAD_ENDS_ONLY", "", Hierarkia, "", GrafOut) #Lisätään OD cost matrix Locationit ja määritetään parametrit: msg("Lisätään OD cost matrix Locationit") Aloitus() Lahtopaikat = Orig_lyr Kohdepaikat = Dest_lyr arcpy.SetProgressorLabel( "KOKONAISMATKAKETJUN LASKENTA...Lisätään OD-cost-matrix Lähtöpaikat...Tässä menee hetki..." ) arcpy.AddLocations_na(ODnimi, "Origins", Lahtopaikat, "Name NameO #", "5000 Meters", "", "", "MATCH_TO_CLOSEST", "APPEND", "NO_SNAP", "", "EXCLUDE", "") arcpy.SetProgressorPosition(55) arcpy.SetProgressorLabel( "KOKONAISMATKAKETJUN LASKENTA...Lisätään OD-cost-matrix Kohdepaikat...Tässä menee hetki..." ) arcpy.AddLocations_na(ODnimi, "Destinations", Kohdepaikat, "Name NameD #", "5000 Meters", "", "", "MATCH_TO_CLOSEST", "APPEND", "NO_SNAP", "", "EXCLUDE", "") arcpy.SetProgressorPosition(65) Valmis() msg("----------------------") #Suoritetaan OD cost matrix laskenta: msg("Suoritetaan OD-cost-matrix laskenta")
int(time.clock() - start_time)) arcpy.Delete_management("ODMATRIX") ODLayer = arcpy.MakeODCostMatrixLayer_na(Network, "ODMATRIX", Kosten, Max_Kosten[0], "", [Kosten, "t_miv"], "", "", "", "", "NO_LINES") #--add origins centroids--# arcpy.Delete_management("origi") arcpy.MakeFeatureLayer_management( 'R500_start', "origi", "OBJECTID >" + str(i * loop[0]) + " and OBJECTID <=" + str((i * loop[0]) + loop[0])) field_mappings = arcpy.na.NAClassFieldMappings( ODLayer.getOutput(0), "Origins", True, arcpy.ListFields("ODMATRIX\Origins")) arcpy.AddLocations_na(ODLayer, "Origins", "origi", field_mappings, "", "", "", "", "CLEAR") #--add destination centroids--# arcpy.Delete_management("desti") if i == ni: print "Select destinations: OBJECTID >" + str( ni * loop[0]) + " and OBJECTID <=" + str((ni * loop[0]) + 1000) arcpy.MakeFeatureLayer_management( 'R500_start', "ni_bezug", "OBJECTID >" + str(ni * loop[0]) + " and OBJECTID <=" + str((ni * loop[0]) + 1000)) arcpy.SelectLayerByLocation_management('R100_ziel', 'WITHIN_A_DISTANCE', 'ni_bezug', Max_Kosten[0]) ni = ni + ni_counter print "Next selection loop: " + str(ni) arcpy.Delete_management("ni_bezug")
def NAtoCSV(inSpace, inGdb, inNetworkDataset, impedanceAttribute, accumulateAttributeName, inOrigins, inDestinations, outNALayerName, outFile): try: #Check out the Network Analyst extension license if arcpy.CheckExtension("Network") == "Available": arcpy.CheckOutExtension("Network") else: # Raise a custom exception print "Network license unavailable, make sure you have network analyst extension installed." #Check out the Network Analyst extension license arcpy.CheckOutExtension("Network") #Set environment settings env.workspace = inSpace + inGdb env.overwriteOutput = True #Create a new OD Cost matrix layer. outNALayer = arcpy.na.MakeODCostMatrixLayer( inNetworkDataset, outNALayerName, impedanceAttribute, "#", "#", accumulateAttributeName, "ALLOW_UTURNS", "Oneway", "NO_HIERARCHY", "#", "NO_LINES", "#") #Get the layer object from the result object. The OD cost matrix layer can #now be referenced using the layer object. 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 originsLayerName = subLayerNames["Origins"] destinationsLayerName = subLayerNames["Destinations"] linesLayerName = subLayerNames["ODLines"] #Adjust field names #Exploit the fact that the detector feature is named hd_ML_snap, #change the field mapping of Name to id_stn oriField = "Name ID_TAZ12A #" oriSort = "ID_TAZ12A" destField = "Name ID_TAZ12A #" destSort = "ID_TAZ12A" if inOrigins[-4:] == "snap": oriField = "Name id_stn #" oriSort = "id_stn" if inDestinations[-4:] == "snap": destField = "Name id_stn #" destSort = "id_stn" #Add locations arcpy.AddLocations_na(outNALayer, originsLayerName, inOrigins, oriField, sort_field=oriSort, append="CLEAR") arcpy.AddLocations_na(outNALayer, destinationsLayerName, inDestinations, destField, sort_field=destSort, append="CLEAR") #Solve the OD cost matrix layer print "Begin Solving" arcpy.na.Solve(outNALayer) print "Done Solving" # Extract lines layer, export to CSV # SOMEHOW THIS WORKS, SO LETS KEEP IT THAT WAY fields = ["OriginID", "DestinationID", "Name", "Total_Cost"] for lyr in arcpy.mapping.ListLayers(outNALayer): if lyr.name == linesLayerName: with open(outFile, 'w') as f: #f.write(','.join(fields)+'\n') # csv headers with arcpy.da.SearchCursor(lyr, fields) as cursor: print "Successfully created lines searchCursor. Exporting to " + outFile for row in cursor: f.write(','.join([str(r) for r in row]) + '\n') # Deleteing using del outNALayer is not enough. Need to delete within arcpy to release arcpy.Delete_management(outNALayer) except Exception as e: # If an error occurred, print line number and error message import traceback, sys tb = sys.exc_info()[2] print "An error occurred in ModRealSolve line %i" % tb.tb_lineno print str(e) finally: #Check the network analyst extension license back in, regardless of errors. arcpy.CheckInExtension("Network")
file5.flush() #--Potenzial-Raster adden--# arcpy.Delete_management("Potenziale") arcpy.Delete_management("Raster") arcpy.MakeFeatureLayer_management(Potenzial_Raster_Layer, "Potenziale") arcpy.MakeFeatureLayer_management(Bezug[0], "Raster") if MIV == False: field_mappings = "Name " + Potenzial_ID + " 0; SourceID SourceID_NMIV 0;SourceOID SourceOID_NMIV 0;PosAlong PosAlong_NMIV 0;SideOfEdge SideOfEdge_NMIV 0" else: field_mappings = "Name " + Potenzial_ID + " 0; SourceID SourceID_MIV 0;SourceOID SourceOID_MIV 0;PosAlong PosAlong_MIV 0;SideOfEdge SideOfEdge_MIV 0; Attr_tAkt tAb 1" if MIV == False: arcpy.AddLocations_na(ODLayer, "Destinations", "Potenziale", field_mappings, "", "", "", "", "", "", "", "EXCLUDE") else: arcpy.AddLocations_na(ODLayer, "Destinations", "Potenziale", field_mappings, "", "", "", "", "", "", "", "EXCLUDE") Potenzial_Raster = arcpy.da.FeatureClassToNumPyArray( "Potenziale", [Potenzial_ID, "EW_Zensus", "AP", "Freizeit", "Versorgung"]) arcpy.Delete_management("Potenziale") Potenzial_Raster = pandas.DataFrame(Potenzial_Raster) #--Schleife über Rasterzellen--# Schleifen = (int(arcpy.GetCount_management("Raster").getOutput(0)) / loop) + 1
def main(OriginFile): # Tarkistetaan tarvittavat Lisenssit arcpy.CheckOutExtension("Network") # ------------------------------------------ # ArcGIS Serverille kovakoodatut parametrit # ------------------------------------------ #fileNumber = [x for x in range(286,294)] #for fileindex in fileNumber: ########################## #Määritetään tiedostopolut ########################## Origins = OriginFile #r"/home/MY_USERNAME/TTM/OD/Subsets/%s_Car_Matrix2015_Origs_KKJ2.shp" % fileindex Destinations = r"/home/MY_USERNAME/TTM/OD/Car_Matrix2015_Dest_KKJ2.shp" NetworkData = r"/home/MY_USERNAME/TTM/Digiroad/MetropAccess_Digiroad.gdb/MetropAccess_NetworkDataset/MetropAccess_NetworkDataset_ND" LiikenneElementit = r"/home/MY_USERNAME/TTM/Digiroad/MetropAccess_Digiroad.gdb/MetropAccess_NetworkDataset/METROPACCESS_DIGIROAD_LIIKENNE_ELEMENTTI" origin_fn = os.path.basename(Origins)[:-15] TulosNimi = "CarTT_Ruuhka_%s" % origin_fn Impedanssi = "Keskpva_aa" LaskKohteet = "ALL" Pysakointityyppi = "" Pysakointikentta = "" Kavelynopeus = 70.0 Grafiikka = "false" #Environment määritykset: temp = r"/mnt/TTM_Results" print("---------------\nProcessing file: %s\n---------------" % os.path.basename(Origins)) ElemKansio = os.path.dirname(NetworkData) OrigKansio = os.path.dirname(Origins) DestKansio = os.path.dirname(Destinations) arcpy.overwriteOutputs = True #Tsekataan onko temp geodatabase vai tavallinen kansio: if ".gdb" in temp or ".mdb" in temp: gdbCheck = True #Etsitään geodatabasen 'juuri' try: pos = temp.index('.gdb') except: pos = temp.index('.mdb') temp = temp[:pos+4] else: gdbCheck = False #Tsekataan sisältääkö TulosNimi välilyöntejä TulosNimi = TulosNimi.replace(" ", "_") ############## #METODIT ############## #Suoritusinfot: def Aloitus(): aika = time.asctime() teksti = "Aloitus: " + aika print(teksti) def Valmis(): aika = time.asctime() teksti = "Valmis: " + aika print(teksti) def msg(Message): print(Message) def virhe(Virheilmoitus): print(Virheilmoitus) sys.exit() def ExDel(haettava): if arcpy.Exists(haettava): arcpy.Delete_management(haettava) msg("------------------------------") msg("METROPACCESS-DIGIROAD") msg("MetropAccess-tutkimushanke") msg("HELSINGIN YLIOPISTO") msg("-------------------------------") msg("4. Kokonaismatkaketjun laskenta (sis. pysäköinti)") msg("-------------------------------") time.sleep(2.5) ################################################ #TARKISTUKSET ENNEN LASKENTAA ################################################ Aloitus() msg("TARKISTUKSET:") ##arcpy.SetProgressor("step", "KOKONAISMATKAKETJUN LASKENTA...Tarkistukset ennen laskentaa...", 0, 100, 5) #Luodaan suoritusinfopalkki #Tarkistetaan, että aineisto on joko EurefFinissä tai KKJ:ssa Desc = arcpy.Describe(NetworkData) NDProjektio = Desc.spatialReference.factoryCode msg("Tarkistetaan liikenneverkon projektio.") if NDProjektio == 3067 or NDProjektio == 2391 or NDProjektio == 2392 or NDProjektio == 2393 or NDProjektio == 2394 or NDProjektio == 104129: True else: virhe("Tieverkkoaineiston tulee olla projisoituna joko EUREF_FIN_TM35FIN:iin, GCS_EUREF_FIN:iin tai Finland_Zone_1, 2, 3 tai -4:ään (KKJ). Muuta Liikenne_elementti.shp projektio johonkin näistä Project -työkalulla, luo uusi Network Dataset perustuen tähän uuteen projisoituun LiikenneElementti -tiedostoon ja aja työkalu uudelleen.") #Tarkistetaan pysäköintikentän löytyminen: msg("Tarkistetaan pysäköintikentän löytyminen") if Pysakointityyppi == 5: fieldList = arcpy.ListFields(Destinations, Pysakointikentta) fieldCount = len(fieldList) if fieldCount == 1: teksti = "Käyttäjän määrittelemä pysäköintikenttä!" msg(teksti) elif Pysakointikentta == "": virhe("VIRHE! Pysäköintityypin määrittävää kenttää ei ole määritetty!") else: virhe("VIRHE! Pysäköintityypin määrittävää kenttää ei löydy taulusta! Tarkista, että pysäköintikenttä on luotu kohdetauluun ja että kirjoitusasu on oikein.") if Pysakointikentta == "": PysKenttaLog = "NONE" Valmis() #Tarkistetaan mitkä aikasakkolaskennan parametrit löytyvät NetworkDatasetistä: msg("Tarkistetaan kustannusparametrit") Aloitus() desc = arcpy.Describe(NetworkData) attributes = desc.attributes NDparams = [] for attribute in attributes: NDparams.append(attribute.name) Haettava = ["Digiroa_aa", "Kokopva_aa", "Keskpva_aa", "Ruuhka_aa", "Pituus"] Nro = 0 Accumulation = [] for x in range(5): if Haettava[Nro] in NDparams: Accumulation.append(Haettava[Nro]) Nro += 1 else: Nro += 1 Valmis() #Tarkistetaan löytyykö Impedanssi Accumulation taulusta, onko impedanssimuuttuja olemassa: msg("Tarkistetaan, että impedanssiatribuutti löytyy Network Datasetistä") Aloitus() if Impedanssi in NDparams: msg("Impedanssi määritetty!") else: virhe("VIRHE! Määriteltyä impedanssia ei ole määritelty Network Datasettiin. Tarkista, että muuttuja on todella olemassa\nja että Impedanssikentän kirjoitusasu täsmää käytettävän muuttujan kanssa. ") NDPath = desc.path NDsource = desc.edgeSources[0].name LE = os.path.join(NDPath, "%s.shp" % NDsource) #Parsitaan sourcedatan (Liikenne_Elementit) polku ja nimi del desc desc = arcpy.Describe(LiikenneElementit) basename = desc.baseName del desc if basename != NDsource: #Tarkistetaan onko inputiksi määritelty LiikenneElementti -tiedosto Network Datan todellinen source-layer: msg("LiikenneElementti -tiedosto ei ollut Network Datan source-layer. Vaihdettiin LiikenneElementti -tiedosto Network Datan Edge-sourceksi.") LiikenneElementit = LE if not Impedanssi in Accumulation: Accumulation.append(Impedanssi) msg("Käyttäjän määrittelemä impedanssi lisättiin Accumulation arvoihin!") #Tarkistetaan laskettavien kohteiden lukumäärä: LaskKohteet.replace(" ","") if LaskKohteet == "" or LaskKohteet == "ALL" or LaskKohteet == "all" or LaskKohteet == "All": LaskKohteet = "" LaskLogi = "ALL" elif LaskKohteet == "0": virhe("Laskettavia kohteita tulee olla vähintään yksi!") else: LaskKohteet = LaskKohteet Valmis() ##arcpy.SetProgressorPosition(5) msg("----------------------") ##################################################### #***************************************************# # LASKENTA *# #***************************************************# ##################################################### msg("ALOITETAAN LASKENTA") msg("Luodaan tarvittavat attribuutit") ##arcpy.SetProgressorLabel("KOKONAISMATKAKETJUN LASKENTA...Luodaan tarvittavat attribuutit...") Aloitus() ################################################ #Tehdään tiedostoihin tarvittavat attribuutit ################################################ #Origins: arcpy.AddField_management(Origins, "NameO", "TEXT") arcpy.AddField_management(Origins, "Kavely_O_T", "DOUBLE") #Kävelyaika lähtöpaikasta lähimpään tieverkkoon arcpy.AddField_management(Origins, "Kavely_T_P", "DOUBLE") #Kävelyaika tieverkosta parkkipaikalle #Ajoaika kentät: if "Digiroa_aa" in Accumulation: arcpy.AddField_management(Origins, "Digiroa_aa", "DOUBLE") if "Kokopva_aa" in Accumulation: arcpy.AddField_management(Origins, "Kokopva_aa", "DOUBLE") if "Keskpva_aa" in Accumulation: arcpy.AddField_management(Origins, "Keskpva_aa", "DOUBLE") if "Ruuhka_aa" in Accumulation: arcpy.AddField_management(Origins, "Ruuhka_aa", "DOUBLE") if Impedanssi in Accumulation: #Tehdään jos käyttäjä on haluaa käyttää jotain omaa impedanssiaan arcpy.AddField_management(Origins, Impedanssi, "DOUBLE") if "Pituus" in Accumulation: arcpy.AddField_management(Origins, "KavelMatkO", "DOUBLE") #Matka lähtöpaikasta parkkipaikalle kaupungin alueella/kaupungin ulkopuolella arcpy.AddField_management(Origins, "KavelDistO", "DOUBLE") #Kävelymatka lähtöpaikasta lähimpään tieverkkopisteeseen #Destinations: ##arcpy.AddField_management(Destinations, "NameD", "TEXT") ##arcpy.AddField_management(Destinations, "Parkkiaika", "DOUBLE") #Parkkipaikan etsintään kuluva aika ##arcpy.AddField_management(Destinations, "Kavely_P_T", "DOUBLE") #Kävelyaika parkkipaikalta lähimpään tieverkkoon ##arcpy.AddField_management(Destinations, "Kavely_T_D", "DOUBLE") #Kävelyaika lähimmästä tieverkkopisteestä kohteeseen ## ##if "Pituus" in Accumulation: ## arcpy.AddField_management(Destinations, "KavelMatkD", "DOUBLE") #Kävelymatka parkkipaikalta lähimpään tieverkkopisteeseen ## arcpy.AddField_management(Destinations, "KavelDistD", "DOUBLE") #Kävelymatka lähimmästä tieverkkopisteestä kohteeseen kantakaupungin alueella/kaupungin ulkopuolella Valmis() ##arcpy.SetProgressorPosition(10) msg("----------------------") #Tehdään id-kentät msg("Luodaan ID-kentät") ##arcpy.SetProgressorLabel("KOKONAISMATKAKETJUN LASKENTA...Luodaan ID-kentät...") Aloitus() #Rivi_id ei täsmää geodatabasessa ja shapefileessä!! Tsekataan onko tiedostot mdb:ssä tai gdb:ssä if ".mdb" in Origins or ".gdb" in Origins: OrigNameID = "'O' + str(!OBJECTID!)" else: OrigNameID = "'O' + str(!FID!)" if ".mdb" in Destinations or ".gdb" in Destinations: DestNameID = "'D' + str(!OBJECTID!)" else: DestNameID = "'D' + str(!FID!)" arcpy.CalculateField_management(Origins, "NameO", OrigNameID, "PYTHON", "") ##arcpy.CalculateField_management(Destinations, "NameD", DestNameID, "PYTHON", "") Valmis() ##arcpy.SetProgressorPosition(15) msg("----------------------") ############################################### #Lasketaan pisteiden etäisyydet tieverkostosta ############################################### msg("Lasketaan kävelyaika ja matka tieverkostosta") ##arcpy.SetProgressorLabel("KOKONAISMATKAKETJUN LASKENTA...Lasketaan kävelyaika ja matka tieverkostosta...") Aloitus() arcpy.Near_analysis(Origins, LiikenneElementit, "3000 Meters", "NO_LOCATION", "NO_ANGLE") ##arcpy.Near_analysis(Destinations, LiikenneElementit, "3000 Meters", "NO_LOCATION", "NO_ANGLE") #Lasketaan kävelyaika ja matka tieverkostosta: OrigReader = arcpy.UpdateCursor(Origins) ##DestReader = arcpy.UpdateCursor(Destinations) for row in OrigReader: row.Kavely_O_T = row.NEAR_DIST / Kavelynopeus row.KavelDistO = row.NEAR_DIST OrigReader.updateRow(row) del row ##for row in DestReader: ## row.Kavely_T_D = row.NEAR_DIST / Kavelynopeus ## row.KavelDistD = row.NEAR_DIST ## DestReader.updateRow(row) ## del row del OrigReader ##del DestReader Valmis() ##arcpy.SetProgressorPosition(20) msg("----------------------") #################################################################################### #Lasketaan parkkipaikan etsintään menevä aika perustuen käyttäjän parametreihin #################################################################################### # Pysäköintityypit - etsintäaika (minuuteissa): # 0: Ei oteta huomioon # 1: Keskiarvo - 0.42 (oletus) # 2: Kadunvarsipaikka - 0.73 # 3: Pysäköintitalo - 0.22 # 4: Erillisalueet - 0.16 # 5: Pysäköintityyppi löytyy käyttäjän määrittämästä kentästä # Pysakointikentta: <String> - Käyttäjän määrittämä kenttä, josta löytyy pysäköintityyppi #------------------------------------------------------------------------------------------ msg("Lasketaan pysäköintipaikan etsintään kuluva aika") ##arcpy.SetProgressorLabel("KOKONAISMATKAKETJUN LASKENTA...Lasketaan pysäköintipaikan etsintään kuluva aika...") Aloitus() if Pysakointityyppi == 0: arcpy.CalculateField_management(Destinations, "Parkkiaika", "0 ", "PYTHON") elif Pysakointityyppi == 1: arcpy.CalculateField_management(Destinations, "Parkkiaika", "0.42 ", "PYTHON") elif Pysakointityyppi == 2: arcpy.CalculateField_management(Destinations, "Parkkiaika", "0.73 ", "PYTHON") elif Pysakointityyppi == 3: arcpy.CalculateField_management(Destinations, "Parkkiaika", "0.22 ", "PYTHON") elif Pysakointityyppi == 4: arcpy.CalculateField_management(Destinations, "Parkkiaika", "0.16 ", "PYTHON") elif Pysakointityyppi == 5: #Käyttäjä määritellyt pysäköintityypin Kohdepiste-tiedostoon DestReader = arcpy.UpdateCursor(Destinations) for row in DestReader: if row.getValue(Pysakointikentta) == 0: row.Parkkiaika = 0 elif row.getValue(Pysakointikentta) == 1: row.Parkkiaika = 0.42 elif row.getValue(Pysakointikentta) == 2: row.Parkkiaika = 0.73 elif row.getValue(Pysakointikentta) == 3: row.Parkkiaika = 0.22 elif row.getValue(Pysakointikentta) == 4: row.Parkkiaika = 0.16 else: row.Parkkiaika = 0 msg("Kohteelle asetettu pysäköintityypin arvo on sallittujen arvojen (0-4) ulkopuolella! Kohteen pysäköintityyppiä ei oteta huomioon.") DestReader.updateRow(row) del row del DestReader Valmis() ##arcpy.SetProgressorPosition(25) msg("----------------------") ####################################################### #Kantakaupunki polygonin luominen laskentaa varten: ####################################################### msg("Luodaan kantakaupunkipolygoni") ##arcpy.SetProgressorLabel("KOKONAISMATKAKETJUN LASKENTA...Luodaan kantakaupunkipolygoni...") Aloitus() env.workspace = temp coordList = [[387678.024778,6675360.99039],[387891.53396,6670403.35286],[383453.380944,6670212.21613],[383239.871737,6675169.85373],[387678.024778,6675360.99039]] #Koordinaatit ovat EUREF_FIN_TM35FIN:issä point = arcpy.Point() array = arcpy.Array() #Lisätään koordinaatit Arrayhin: for coordPair in coordList: point.X = coordPair[0] point.Y = coordPair[1] array.add(point) Kantakaupunki = arcpy.Polygon(array) #Määritetään Spatial Reference: sr = arcpy.SpatialReference() sr.factoryCode = 3067 #EUREF_FIN_TM35FIN sr.create() #Luodaan kantakaupunki tiedosto: if gdbCheck == True: Kantis = os.path.join(temp,"Kantakaupunki") else: Kantis = os.path.join(temp,"Kantakaupunki.shp") ExDel(Kantis) arcpy.Select_analysis(Kantakaupunki, Kantis) #Määritetään kantakaupungille projektio: arcpy.DefineProjection_management(Kantis, sr) msg("Luotiin kantakaupunki") Valmis() ##arcpy.SetProgressorPosition(30) msg("----------------------") ################################################### #MÄÄRITETÄÄN TIEDOSTOT SAMAAN KOORDINAATISTOON ################################################### msg("Määritetään tiedostot samaan koordinaatistoon") ##arcpy.SetProgressorLabel("KOKONAISMATKAKETJUN LASKENTA...Määritetään tiedostot samaan koordinaatistoon...") Aloitus() #Destinations: DDesc = arcpy.Describe(Destinations) DestProjektio = DDesc.spatialReference.Name DFactCode = DDesc.spatialReference.factoryCode DProj = DestProjektio[:8] if gdbCheck == True: KohdePath = os.path.join(temp, "DestinationsProj") LahtoPath = os.path.join(temp, "OriginsProj") KantisPath = os.path.join(temp, "KantisProj") else: KohdePath = os.path.join(temp, "DestinationsProj.shp") LahtoPath = os.path.join(temp, "OriginsProj.shp") KantisPath = os.path.join(temp, "KantisProj.shp") ExDel(KohdePath) ExDel(LahtoPath) ExDel(KantisPath) #Origins: ODesc = arcpy.Describe(Origins) OrigProjektio = ODesc.spatialReference.Name OFactCode = ODesc.spatialReference.factoryCode OProj = OrigProjektio[:8] #Luodaan spatial reference perustuen NetworkDatan SR:een: del sr sr = arcpy.SpatialReference() if NDProjektio == 3067: #EurefFin sr.factoryCode = 3067 sr.create() elif NDProjektio == 104129: #GCS_EurefFIN sr.factoryCode = 104129 sr.create() elif NDProjektio == 2391: #KKJ1 sr.factoryCode = 2391 sr.create() elif NDProjektio == 2392: #KKJ2 sr.factoryCode = 2392 sr.create() elif NDProjektio == 2393: #KKJ3 sr.factoryCode = 2393 sr.create() elif NDProjektio == 2394: #KKJ4 sr.factoryCode = 2394 sr.create() #Määritetään Kohteille ja Lähtöpaikoille oikea projektio, jos NetworkData on EUREF_FIN_TM35FIN:issä tai GCS_EUREF_FIN:issä:: if NDProjektio == 3067 or NDProjektio == 104129: if NDProjektio == 104129: arcpy.Project_management(Kantis, KantisPath, sr, "") #Määritetään kantakaupunki samaan koordinaatistoon Kantakaupunki = KantisPath #Destinations: if NDProjektio != DFactCode: #Jos Network Data ja Destinationit ovat eri koordinaatistossa: if DFactCode >= 2391 and DFactCode <= 2394: Dtransform_method = "KKJ_To_EUREF_FIN" elif DFactCode == 3067: Dtransform_method = "" elif DProj == "WGS_1984" or DFactCode == 4326: #Projected WGS_1984 tai GCS_WGS_1984 Dtransform_method = "EUREF_FIN_To_WGS_1984" elif DProj == "ETRS_198": Dtransform_method = "EUREF_FIN_To_ETRS_1989" else: virhe("Kohdepisteet tulee olla projisoituna johonkin seuraavista koordinaatistoista:") virhe("KKJ, EUREF_FIN, WGS_1984, ETRS_1989") arcpy.Project_management(Destinations, KohdePath, sr, Dtransform_method) #Määritetään Destinationit samaan koordinaatistoon Destinations = KohdePath msg("Kohdepaikkojen projektio vaihdettiin samaksi kuin Network Datalla. Luotiin kopio tiedostosta.") #Origins: if NDProjektio != OFactCode: #Jos Network Data ja Originit ovat eri koordinaatistossa: if OFactCode >= 2391 and OFactCode <= 2394: Otransform_method = "KKJ_To_EUREF_FIN" elif OFactCode == 3067: Otransform_method = "" elif OProj == "WGS_1984" or OFactCode == 4326: #Projected WGS_1984 tai GCS_WGS_1984 Otransform_method = "EUREF_FIN_To_WGS_1984" elif OProj == "ETRS_198": Otransform_method = "EUREF_FIN_To_ETRS_1989" else: virhe("Lähtöpisteet tulee olla projisoituna johonkin seuraavista koordinaatistoista:") virhe("KKJ, EUREF_FIN, WGS_1984, ETRS_1989") arcpy.Project_management(Origins, LahtoPath, sr, Otransform_method) #Määritetään Destinationit samaan koordinaatistoon Origins = LahtoPath msg("Lähtöpaikkojen projektio vaihdettiin samaksi kuin Network Datalla. Luotiin kopio tiedostosta.") #Määritetään Kohteille ja Lähtöpaikoille oikea projektio, jos NetworkData on KKJ:ssa: elif NDProjektio == 2391 or NDProjektio == 2392 or NDProjektio == 2393 or NDProjektio == 2394: arcpy.Project_management(Kantis, KantisPath, sr, "KKJ_To_EUREF_FIN") #Määritetään kantakaupunki samaan koordinaatistoon Kantakaupunki = KantisPath if NDProjektio != DFactCode: #Jos NetworkData ja kohdepisteet ovat eri KKJ:ssa projisoidaan ne samaan. if DFactCode >= 2391 and DFactCode <= 2394: Dtransform_method = "" elif DProj == "WGS_1984" or DFactCode == 4326: #Projected WGS_1984 tai GCS_WGS_1984 Dtransform_method = "KKJ_To_WGS_1984_2_JHS153" elif DProj == "ETRS_198": Dtransform_method = "KKJ_To_ETRS_1989_2" else: virhe("Kohdepisteet tulee olla projisoituna johonkin seuraavista koordinaatistoista:") virhe("KKJ, EUREF_FIN, WGS_1984, ETRS_1989") arcpy.Project_management(Destinations, KohdePath, sr, Dtransform_method) #Määritetään Destinationit samaan koordinaatistoon Destinations = KohdePath msg("Kohdepaikkojen projektio vaihdettiin samaksi kuin Network Datalla. Luotiin kopio tiedostosta.") if NDProjektio != OFactCode: #Jos NetworkData ja kohdepisteet ovat eri KKJ:ssa projisoidaan ne samaan. if OFactCode >= 2391 and OFactCode <= 2394: Otransform_method = "" elif OProj == "WGS_1984" or OFactCode == 4326: #Projected WGS_1984 tai GCS_WGS_1984 Otransform_method = "KKJ_To_WGS_1984_2_JHS153" elif OProj == "ETRS_198": Otransform_method = "KKJ_To_ETRS_1989_2" else: virhe("Lähtöpisteet tulee olla projisoituna johonkin seuraavista koordinaatistoista:") virhe("KKJ, EUREF_FIN, WGS_1984, ETRS_1989") arcpy.Project_management(Origins, LahtoPath, sr, Otransform_method) #Määritetään Destinationit samaan koordinaatistoon Origins = LahtoPath msg("Lähtöpaikkojen projektio vaihdettiin samaksi kuin Network Datalla. Luotiin kopio tiedostosta.") Valmis() ##arcpy.SetProgressorPosition(35) msg("----------------------") ################################## #LASKETAAN KÄVELYYN KULUVA AIKA ################################## #Tehdään Feature Layerit spatiaalista valintaa varten: Orig_lyr = "Orig_lyr" Dest_lyr = "Dest_lyr" OrigPath = Orig_lyr + ".lyr" DestPath = Dest_lyr + ".lyr" env.workspace = OrigKansio ExDel(Orig_lyr) #Varmistetaan ettei FeatureLayeria ole jo olemassa env.workspace = DestKansio ExDel(Dest_lyr) #Varmistetaan ettei FeatureLayeria ole jo olemassa arcpy.MakeFeatureLayer_management(Origins, Orig_lyr, "", OrigKansio) arcpy.MakeFeatureLayer_management(Destinations, Dest_lyr, "", DestKansio) #Valitaan kohteet, jotka ovat kantakaupungin sisällä: arcpy.SelectLayerByLocation_management(Orig_lyr, "INTERSECT", Kantakaupunki, "", "NEW_SELECTION") ##arcpy.SelectLayerByLocation_management(Dest_lyr, "INTERSECT", Kantakaupunki, "", "NEW_SELECTION") #Lasketaan aika ja matka lähtöpaikasta parkkipaikalle/parkkipaikalta kohteeseen kantakaupungin alueella: #Kantakaupungissa matka autolle on 180 metriä msg("Lasketaan aika ja matka lähtöpaikasta parkkipaikalle/parkkipaikalta kohteeseen kantakaupungin alueella") ##arcpy.ResetProgressor() ##arcpy.SetProgressor("step", "KOKONAISMATKAKETJUN LASKENTA...Lasketaan aika ja matka lähtöpaikasta parkkipaikalle/parkkipaikalta kohteeseen kantakaupungin alueella...", 0, 100, 5) ##arcpy.SetProgressorPosition(40) Aloitus() # Calculate walking times with Field Calculator expression = "180.0 / %s" % Kavelynopeus arcpy.CalculateField_management(Orig_lyr, "Kavely_T_P", expression, "PYTHON", "") expression2 = "180.0" arcpy.CalculateField_management(Orig_lyr, "KavelMatkO", expression2, "PYTHON", "") ##OrigReader = arcpy.UpdateCursor(Orig_lyr) ##DestReader = arcpy.UpdateCursor(Dest_lyr) ##for row in OrigReader: ## row.Kavely_T_P = 180.0 / Kavelynopeus ## row.KavelMatkO = 180.0 ## OrigReader.updateRow(row) ## del row ##for row in DestReader: ## row.Kavely_P_T = 180.0 / Kavelynopeus ## row.KavelMatkD = 180.0 ## DestReader.updateRow(row) ## del row ##del OrigReader ##del DestReader Valmis() ##arcpy.SetProgressorPosition(40) msg("----------------------") #Vaihdetaan valinta kantakaupungin ulkopuolisille alueille: arcpy.SelectLayerByAttribute_management(Orig_lyr, "SWITCH_SELECTION", "") ##arcpy.SelectLayerByAttribute_management(Dest_lyr, "SWITCH_SELECTION", "") #Lasketaan aika ja matka lähtöpaikasta parkkipaikalle/parkkipaikalta kohteeseen kantakaupungin ulkopuolella: #Kantakaupungin ulkopuolella matka autolle on 135 metriä msg("Lasketaan aika ja matka lähtöpaikasta parkkipaikalle/parkkipaikalta kohteeseen kantakaupungin ulkopuolella") ##arcpy.SetProgressorLabel("KOKONAISMATKAKETJUN LASKENTA...Lasketaan aika ja matka lähtöpaikasta parkkipaikalle/parkkipaikalta kohteeseen kantakaupungin ulkopuolella...") Aloitus() # Calculate walking times with Field Calculator expression = "135.0 / %s" % Kavelynopeus arcpy.CalculateField_management(Orig_lyr, "Kavely_T_P", expression, "PYTHON", "") expression2 = "135.0" arcpy.CalculateField_management(Orig_lyr, "KavelMatkO", expression2, "PYTHON", "") ##OrigReader = arcpy.UpdateCursor(Orig_lyr) ##DestReader = arcpy.UpdateCursor(Dest_lyr) ##for row in OrigReader: ## row.Kavely_T_P = 135.0 / Kavelynopeus ## row.KavelMatkO = 135.0 ## OrigReader.updateRow(row) ## del row ##for row in DestReader: ## row.Kavely_P_T = 135.0 / Kavelynopeus ## row.KavelMatkD = 135.0 ## DestReader.updateRow(row) ## del row ##del OrigReader ##del DestReader #Poistetaan valinnat: arcpy.SelectLayerByAttribute_management(Orig_lyr, "CLEAR_SELECTION", "") ##arcpy.SelectLayerByAttribute_management(Dest_lyr, "CLEAR_SELECTION", "") ##################################### #REITITYS: OD-COST MATRIX LASKENTA ##################################### #Tarkistetaan onko aiempia OD-Cost-Matrixeja ja luodaan uniikki nimi: env.workspace = temp ODnimi = "Kokonaismatkaketju_ODC_MATRIX" ODPath = ODnimi + ".lyr" ExDel(ODnimi) Valmis() ##arcpy.SetProgressorPosition(45) msg("----------------------") #Tehdään OD Cost Matrix Layer: msg("Tehdään OD Cost Matrix Layer") ##arcpy.SetProgressorLabel("KOKONAISMATKAKETJUN LASKENTA...Tehdään OD-Cost-Matrix Layer...") Aloitus() if Grafiikka == "true" or "True": GrafOut = "STRAIGHT_LINES" else: GrafOut = "NO_LINES" if "Hierarkia" in NDparams: Hierarkia = "USE_HIERARCHY" else: Hierarkia = "NO_HIERARCHY" arcpy.MakeODCostMatrixLayer_na(NetworkData, ODnimi, Impedanssi, "", LaskKohteet, Accumulation, "ALLOW_DEAD_ENDS_ONLY", "", Hierarkia, "", GrafOut) #Lisätään OD cost matrix Locationit ja määritetään parametrit: msg("Lisätään OD cost matrix Locationit") Aloitus() Lahtopaikat = Orig_lyr Kohdepaikat = Dest_lyr ##arcpy.SetProgressorLabel("KOKONAISMATKAKETJUN LASKENTA...Lisätään OD-cost-matrix Lähtöpaikat...Tässä menee hetki...") arcpy.AddLocations_na(ODnimi, "Origins", Lahtopaikat, "Name NameO #", "5000 Meters", "", "", "MATCH_TO_CLOSEST", "APPEND", "NO_SNAP", "", "EXCLUDE", "") ##arcpy.SetProgressorPosition(55) ##arcpy.SetProgressorLabel("KOKONAISMATKAKETJUN LASKENTA...Lisätään OD-cost-matrix Kohdepaikat...Tässä menee hetki...") arcpy.AddLocations_na(ODnimi, "Destinations", Kohdepaikat, "Name NameD #", "5000 Meters", "", "", "MATCH_TO_CLOSEST", "APPEND", "NO_SNAP", "", "EXCLUDE", "") ##arcpy.SetProgressorPosition(65) Valmis() msg("----------------------") #Suoritetaan OD cost matrix laskenta: msg("Suoritetaan OD-cost-matrix laskenta") ##arcpy.SetProgressorLabel("KOKONAISMATKAKETJUN LASKENTA...Suoritetaan OD-cost-matrix laskenta...") Aloitus() arcpy.Solve_na(ODnimi, "SKIP", "TERMINATE") Valmis() ##arcpy.SetProgressorPosition(70) msg("----------------------") ################################################################################ #JOINATAAN KOKONAISMATKOIHIN TIEDOT KOHDE/LÄHTÖPISTEISTÄ (kävelyyn kuluva aika) ################################################################################ #Valitaan muokattavaksi OD C M:n Lines layer: arcpy.SelectData_management(ODnimi, "Lines") Lines = ODnimi + "/" + "Lines" #Lisätään Lines_lyr:iin tarvittavat kentät Joinin mahdollistamiseksi: arcpy.AddFieldToAnalysisLayer_na(ODnimi, "Lines", "LahtoNimi", "TEXT") arcpy.AddFieldToAnalysisLayer_na(ODnimi, "Lines", "KohdeNimi", "TEXT") #Muodostetaan Joinin id-kentät: arcpy.CalculateField_management(Lines, "LahtoNimi", "!Name!.split(\" -\")[0]", "PYTHON_9.3") arcpy.CalculateField_management(Lines, "KohdeNimi", "!Name!.split(\"- \")[1]", "PYTHON_9.3") #Eksportataan Line-feature shapeksi, jotta Join saadaan toimimaan: if gdbCheck == True: #Geodatabasessa tiedostonimessä ei saa olla tiedostomuodon päätettä (.shp) if ".shp" in TulosNimi: OutLineNimi = TulosNimi[:-4] else: OutLineNimi = TulosNimi else: if not ".shp" in TulosNimi: OutLineNimi = TulosNimi + ".shp" else: OutLineNimi = TulosNimi env.workspace = temp nameCheck = os.path.join(temp, OutLineNimi) if arcpy.Exists(nameCheck): unique = arcpy.CreateUniqueName(nameCheck) OutLines = unique Outnimi = string.split(unique, ".")[0] LogName = Outnimi else: OutLines = nameCheck Outnimi = nameCheck # Save Lines to disk msg("----------------------") Aloitus() msg("Save preliminary results to disk") arcpy.Select_analysis(Lines, OutLines) Valmis() msg("----------------------") #Poistetaan väliaikaistiedostot: env.workspace = temp ExDel(KohdePath) ExDel(LahtoPath) ExDel(KantisPath) ExDel(Kantis) # Return filepath to Shapefile return [OutLines, Origins, Destinations]
def Solve(Input_Layer_Location, ScenarioNames, Input_Dataset, Evacuation_Prefix, Safe_Zone_Prefix, Dynamics_Prefix, ThreadCount, msgLock, dbLock, ThreadNum): # Check out any necessary licenses if arcpy.CheckExtension("Network") == "Available": arcpy.CheckOutExtension("Network") else: arcpy.AddMessage("Network Analyst Extension Is Not Available") print "Network Analyst Is Not Available" sys.exit(0) # Load required toolboxes arcpy.env.overwriteOutput = True SolveCount = 0 try: # load layer file lyrFile = arcpy.mapping.Layer(Input_Layer_Location) messages = [] # loop over all scenarios, import them into each NA layer for ExpName in ScenarioNames: # arcpy.AddMessage("Importing scenario: " + ExpName[0]) EVC = Input_Dataset + '\\' + Evacuation_Prefix + ExpName[0] SAFE = Input_Dataset + '\\' + Safe_Zone_Prefix + ExpName[0] DYN = Input_Dataset + '\\' + Dynamics_Prefix + ExpName[0] # now loop over all NA layers and solve them one by one for lyr in arcpy.mapping.ListLayers(lyrFile): try: desc = arcpy.Describe(Input_Layer_Location + "\\" + lyr.longName) # only solve if the layer is a network analysis layer if desc.dataType == "NALayer": # We check if this setup and scenario is intended for this particular sub-process SolveCount += 1 if SolveCount % ThreadCount != ThreadNum: continue # load input locations del messages[:] try: messages.append( "Thread {}: loading input points to {} from scenario {}" .format(ThreadNum, lyr.name, ExpName[0])) arcpy.AddLocations_na( lyr, "Evacuees", EVC, "VehicleCount POPULATION #;Name UID #", "5000 Meters", "", "Streets NONE;SoCal_ND_Junctions SHAPE", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "5 Meters", "EXCLUDE", "Streets #;SoCal_ND_Junctions #") for msg in range(0, arcpy.GetMessageCount()): messages.append(arcpy.GetMessage(msg)) arcpy.AddLocations_na( lyr, "Zones", SAFE, "Name OBJECTID #;Capacity Capacity #", "5000 Meters", "", "Streets NONE;SoCal_ND_Junctions SHAPE", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "5 Meters", "EXCLUDE", "Streets #;SoCal_ND_Junctions #") for msg in range(0, arcpy.GetMessageCount()): messages.append(arcpy.GetMessage(msg)) arcpy.AddLocations_na( lyr, "DynamicChanges", DYN, "EdgeDirection Zones_EdgeDirection #;StartingCost Zones_StartingCost #;EndingCost Zones_EndingCost #;CostChangeRatio Zones_CostChangeRatio #;CapacityChangeRatio Zones_CapacityChangeRatio #", "5000 Meters", "", "Streets SHAPE;SoCal_ND_Junctions NONE", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "5 Meters", "INCLUDE", "Streets #;SoCal_ND_Junctions #") for msg in range(0, arcpy.GetMessageCount()): messages.append(arcpy.GetMessage(msg)) # solve the layer messages.append("Solving NALayer " + lyr.name + " with scenario " + ExpName[0]) arcpy.Solve_na(lyr, "SKIP", "TERMINATE") for msg in range(0, arcpy.GetMessageCount()): messages.append(arcpy.GetMessage(msg)) # going to export route and edge sub_layers solved_layers = arcpy.mapping.ListLayers(lyr) # lock and then write outputs to gdb try: dbLock.acquire() arcpy.CopyFeatures_management( solved_layers[4], Input_Dataset + "\\Routes_" + lyr.name + "_" + ExpName[0]) #Routes for msg in range(0, arcpy.GetMessageCount()): messages.append(arcpy.GetMessage(msg)) arcpy.CopyFeatures_management( solved_layers[5], Input_Dataset + "\\EdgeStat_" + lyr.name + "_" + ExpName[0]) #EdgeStat for msg in range(0, arcpy.GetMessageCount()): messages.append(arcpy.GetMessage(msg)) finally: dbLock.release() del solved_layers messages.append( "Combination {}: Solved {} with scenario {}{}". format(SolveCount, lyr.name, ExpName[0], os.linesep)) except BaseException as e: messages.append("Error: {}".format(e)) messages.append( "Combination {}: Errored {} with scenario {}{}" .format(SolveCount, lyr.name, ExpName[0], os.linesep)) # lock and then print messages try: msgLock.acquire() for msg in messages: arcpy.AddMessage(msg) finally: msgLock.release() except BaseException as e: arcpy.AddError(e) finally: del desc except BaseException as e: arcpy.AddError(e) finally: del lyrFile del messages arcpy.CheckInExtension("Network")
# Rebuild Network arcpy.BuildNetwork_na(inND) arcpy.AddMessage("ND Rebuild completed") time.sleep(loopTime) # Add lcoations inOrigins = fcTAZ inDestinations = fcTAZ ## arcpy.AddLocations_na(inOD, "Origins", inOrigins, ## "Name ID_TAZ12A #;SourceID SourceID #;SourceOID SourceOID #;PosAlong PosAlong #;SideOfEdge SideOfEdge #", append = "CLEAR") ## arcpy.AddLocations_na(inOD, "Destinations", inDestinations, ## "Name ID_TAZ12A #;SourceID SourceID #;SourceOID SourceOID #;PosAlong PosAlong #;SideOfEdge SideOfEdge #", append = "CLEAR") #Add using geometries instead. Should only add 2 min per iteration or 40 min overall arcpy.AddLocations_na(inOD, "Origins", inOrigins, "Name ID_TAZ12A #", append="CLEAR") arcpy.AddLocations_na(inOD, "Destinations", inDestinations, "Name ID_TAZ12A #", append="CLEAR") arcpy.AddMessage("Location Added, Proceed to solve.") # Solve arcpy.Solve_na(inOD, "SKIP", "CONTINUE", "#") arcpy.AddMessage("Solve Completed") time.sleep(loopTime) # Export to CSV
#destinationsList = [os.path.join(inter_dir,"stops79_EqDmode0.shp"),os.path.join(inter_dir,"stops79_EqDmode1.shp"),os.path.join(inter_dir,"stops79_EqDmode2.shp")] # Delete Duplicates from PCCF #arcpy.DeleteIdentical_management(origins, "field6;field7" , "", "0") od = 0 for destinations in allstopsList: if arcpy.management.GetCount(destinations)[0] != "0": outlayer800 = "outlayer800_" + str(od) output_layer_file = os.path.join(inter_dir, outlayer800 + ".lyrx") # Create a new OD Cost matrix layer. * Maximum walking distance to a bus stop is 800m. result_object = arcpy.MakeODCostMatrixLayer_na(network, outlayer800, "Length", "800", 1) # Get the layer object from the result object. outlayer800 = result_object.getOutput(0) arcpy.AddLocations_na(outlayer800, "origins", origins, "", '800 Meters') arcpy.AddLocations_na(outlayer800, "destinations", destinations, "", "800 Meters") # Solve the OD cost matrix layer arcpy.Solve_na(outlayer800) print('ODMatrix is solved for mode' + str(od)) arcpy.SaveToLayerFile_management(outlayer800, output_layer_file, "RELATIVE") # Extract OD Lines layer linesSublayer = arcpy.mapping.ListLayers(outlayer800, "Lines")[0] arcpy.CopyFeatures_management(linesSublayer, os.path.join(gdb, 'odLines_' + str(od))) odLines = os.path.join(gdb, 'odLines_' + str(od)) ###Calculate Walking Time arcpy.AddField_management(odLines, 'WalkingTime', "DOUBLE", 10)
StopCount = arcpy.GetCount_management(stops) intCount = int(StopCount.getOutput(0)) lastRow = intCount - 1 #This is used to get the last FID row in the stops shapefile. Query = """{0} = 0 or {0} = {1}""".format( arcpy.AddFieldDelimiters(stops, "FID"), lastRow ) #Equates to "FID" = 0 or "FID" = N-1, where N = # of rows. This query is used to select origin/destination points. stopsLayer = arcpy.MakeFeatureLayer_management(stops, "stops.lyr") selectedStops = arcpy.SelectLayerByAttribute_management( "stops.lyr", "NEW_SELECTION", Query) pointBarriers = outBarriersName Route = arcpy.MakeRouteLayer_na(NetworkDataset, RouteName, "Length", "USE_INPUT_ORDER", "PRESERVE_BOTH", "NO_TIMEWINDOWS", "Length", "ALLOW_UTURNS", "Oneway", "NO_HIERARCHY", "#", "TRUE_LINES_WITH_MEASURES") arcpy.AddLocations_na(Route, "Stops", selectedStops) arcpy.AddLocations_na(Route, "Point Barriers", pointBarriers) arcpy.Solve_na(Route, "SKIP") #Skip invalid locations. outRouteLayer = arcpy.SaveToLayerFile_management( Route, RouteName, "RELATIVE") #Save route as layer file to user-specified location. arcpy.AddMessage("Route layer created successfully. Route is located at:" + " " + RouteName) arcpy.CheckInExtension("Spatial")
origins = r"E:\jeff\RealTime\temp.gdb\Origin1" destinations = r"E:\Jeff\tor\points_for_street_dest_1.shp" out_folder = r"E:\Jeff\tor" # time to run the calc at what_time = datetime.datetime(2016, 5, 25, 5, 0, 0) # May 25, 2016 #Create OD Matrix for the time that is next in the time step arcpy.MakeODCostMatrixLayer_na(network, 'OD Cost Matrix', 'TravelTime_WithTransit', 99999, '#', '#', 'ALLOW_UTURNS', '#', 'NO_HIERARCHY', '#', 'STRAIGHT_LINES', what_time) #Add origin points arcpy.AddLocations_na( 'OD Cost Matrix', 'Origins', origins, 'Name DAuid #', '5000 Meters', '#', 'Connectors_Stops2Streets NONE;Streets_UseThisOne SHAPE;TransitLines NONE;Stops NONE;Stops_Snapped2Streets NONE;GTFS_FD_ND_Junctions NONE', 'MATCH_TO_CLOSEST', 'APPEND', 'SNAP', '0 Meters', 'EXCLUDE', 'Connectors_Stops2Streets #;Streets_UseThisOne #;TransitLines #;Stops #;Stops_Snapped2Streets #;GTFS_FD_ND_Junctions #' ) #Add destination points arcpy.AddLocations_na( 'OD Cost Matrix', 'Destinations', destinations, 'Name GEO_ID #', '5000 Meters', '#', 'Connectors_Stops2Streets NONE;Streets_UseThisOne SHAPE;TransitLines NONE;Stops NONE;Stops_Snapped2Streets NONE;GTFS_FD_ND_Junctions NONE', 'MATCH_TO_CLOSEST', 'APPEND', 'SNAP', '0 Meters', 'EXCLUDE', 'Connectors_Stops2Streets #;Streets_UseThisOne #;TransitLines #;Stops #;Stops_Snapped2Streets #;GTFS_FD_ND_Junctions #' ) #Solve OD Matrix for the time step arcpy.Solve_na('OD Cost Matrix', 'SKIP', 'TERMINATE', '#')
msg(teksti) infoCheck = True else: #Tehdään ServiceAreaLayer: arcpy.MakeServiceAreaLayer_na( NetworkData, BreakName, Impedanssi, Suunta, Break, Details, Overlap, RinDisk, Lines, "OVERLAP", "NO_SPLIT", "", Accumulation, "ALLOW_DEAD_ENDS_ONLY", "", Trim, TrimCut, "") #Lisätään yksitellen kohteet Facilityiksi: facility = temp + "\\" + facility + ".shp" desc = arcpy.Describe(facility) arcpy.AddLocations_na(BreakName, "Facilities", facility, "", "1000 Meters", "", "", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "5 Meters", "EXCLUDE", "") #Suoritetaan laskenta: arcpy.Solve_na(BreakName) #Lisätään kartalle: Poly = BreakName + "/" + "Polygons" Timesort = BreakNimi[i] + "min_" + Nimi + "_" + Kohde FacRename = arcpy.mapping.Layer( Poly).name = Timesort #Muutetaan nimi AddLyr = arcpy.mapping.Layer(FacRename) Group = "Sort_by_Time" AddLayerToGroup(AddLyr, Group)
arcpy.CheckOutExtension("Network") arcpy.env.overwriteOutput = True for i in range(0,115): env.workspace = "C:/Accessibility_data/gis_data/add_gtfs_model/gtfs_2018.gdb" arcpy.MakeFeatureLayer_management("bldgs_all_centroid", "build_lyr") # Process: Make OD Cost Matrix Layer arcpy.MakeODCostMatrixLayer_na("gtfs_2017_ND", "OD Cost Matrix" + str(i), "TravelTime_WithTransit", "", "", "", "ALLOW_UTURNS", "", "NO_HIERARCHY", "", "STRAIGHT_LINES", "31/12/1899 08:00:00") # Process: Select Layer By Attribute arcpy.SelectLayerByAttribute_management("build_lyr", "NEW_SELECTION", "(OBJECTID > " + str(i*200 ) + ") AND (OBJECTID <= " + str((i+1)*200)+")") # Process: Add Locations- Origins arcpy.AddLocations_na("OD Cost Matrix" + str(i), "Origins", "build_lyr", "Name Name #;TargetDestinationCount TargetDestinationCount #;CurbApproach CurbApproach 0;Cutoff_Length Cutoff_Length #;Cutoff_TravelTime_WithTransit Cutoff_TravelTime_WithTransit #", "5000 Meters", "", "Connectors_Stops2Streets SHAPE;Streets_UseThisOne SHAPE;TransitLines SHAPE;Stops SHAPE;Stops_Snapped2Streets SHAPE; NONE", "MATCH_TO_CLOSEST", "APPEND", "NO_SNAP", "5 Meters", "INCLUDE", "Connectors_Stops2Streets #;Streets_UseThisOne #;TransitLines #;Stops #;Stops_Snapped2Streets #;gtfs_2017_ND_Junctions #") # Process: Add Locations- Destinations arcpy.AddLocations_na("OD Cost Matrix" + str(i), "Destinations", "bldgs_all_centroid", "Name Name #;CurbApproach CurbApproach 0", "8000 Meters", "", "Connectors_Stops2Streets SHAPE;Streets_UseThisOne SHAPE;TransitLines SHAPE;Stops SHAPE;Stops_Snapped2Streets SHAPE;gtfs_2017_ND_Junctions NONE", "MATCH_TO_CLOSEST", "APPEND", "NO_SNAP", "5 Meters", "INCLUDE", "Connectors_Stops2Streets #;Streets_UseThisOne #;TransitLines #;Stops #;Stops_Snapped2Streets #;gtfs_2017_ND_Junctions #") #Omry: Check for add location (override) # Delete arcpy.Delete_management("build_lyr") try: # Process: Solve arcpy.Solve_na("OD Cost Matrix" + str(i), "SKIP", "TERMINATE", "") # Process: Select Data arcpy.SelectData_management("OD Cost Matrix" + str(i), "Lines")
def NAtoCSV_trans(inSpace, inGdb, inNetworkDataset, impedanceAttribute, accumulateAttributeName, inOrigins, inDestinations, outNALayerName, outFile, outField): ''' Same as NAtoCSV, but removed "oneway" since Transit network doesnot have this attribute Also changed the SNAP code to "ions" for all stations ''' fields = outField import arcpy from arcpy import env try: #Check out the Network Analyst extension license if arcpy.CheckExtension("Network") == "Available": arcpy.CheckOutExtension("Network") else: # Raise a custom exception print "Network license unavailable, make sure you have network analyst extension installed." #Check out the Network Analyst extension license arcpy.CheckOutExtension("Network") #Set environment settings env.workspace = inSpace + inGdb env.overwriteOutput = True #Create a new OD Cost matrix layer. outNALayer = arcpy.na.MakeODCostMatrixLayer(inNetworkDataset, outNALayerName, impedanceAttribute, "#", "#", accumulateAttributeName, "ALLOW_UTURNS","#","NO_HIERARCHY","#","NO_LINES","#") #Get the layer object from the result object. The OD cost matrix layer can #now be referenced using the layer object. 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 originsLayerName = subLayerNames["Origins"] destinationsLayerName = subLayerNames["Destinations"] linesLayerName = subLayerNames["ODLines"] #Adjust field names #Exploit the fact that the detector feature is named hd_ML_snap, (or AllStationsML) #change the field mapping of Name to id_stn oriField = "Name ID_TAZ12A #" oriSort = "ID_TAZ12A" destField = "Name ID_TAZ12A #" destSort = "ID_TAZ12A" searchMetro = "BlueLine_Split SHAPE;GoldLine_split SHAPE;GreenLine_split SHAPE;LABus_prj NONE;LABus_prj_conn NONE;Metro_Tiger_Conn SHAPE;Orange_Conn SHAPE;OrangeLine_split SHAPE;RedLine_split SHAPE;Silver_Conn SHAPE;SilverLine_split SHAPE;TAZ_Tiger_Conn NONE;tl_2012_LAC_prj NONE;BusStopsWLines_prj NONE;Metro_Tiger_Conn_pt SHAPE;Orange_Conn_pt SHAPE;Silver_Conn_pt SHAPE;PreBusDPS_ND_Junctions NONE" searchTAZ = "BlueLine_Split NONE;GoldLine_split NONE;GreenLine_split NONE;LABus_prj NONE;LABus_prj_conn NONE;Metro_Tiger_Conn NONE;Orange_Conn NONE;OrangeLine_split NONE;RedLine_split NONE;Silver_Conn NONE;SilverLine_split NONE;TAZ_Tiger_Conn SHAPE;tl_2012_LAC_prj NONE;BusStopsWLines_prj NONE;Metro_Tiger_Conn_pt NONE;Orange_Conn_pt NONE;Silver_Conn_pt NONE;PreBusDPS_ND_Junctions NONE" print "Origins: ", inOrigins, " Destinations: ", inDestinations if "Station" in inOrigins: oriField = "Name id_stn #" oriSort = "id_stn" arcpy.AddLocations_na(outNALayer, originsLayerName, inOrigins, oriField, sort_field = oriSort, append = "CLEAR", search_criteria = searchMetro) print "loaded stations onto transit network (search_criteria)" else: arcpy.AddLocations_na(outNALayer, originsLayerName, inOrigins, oriField, sort_field = oriSort, append = "CLEAR", search_criteria = searchTAZ) print "loaded stations onto network" if "Station" in inDestinations: destField = "Name id_stn #" destSort = "id_stn" arcpy.AddLocations_na(outNALayer, destinationsLayerName, inDestinations, destField, sort_field = destSort, append = "CLEAR", search_criteria = searchMetro) print "loaded stations onto transit network (search_criteria)" else: arcpy.AddLocations_na(outNALayer, destinationsLayerName, inDestinations, destField, sort_field = destSort, append = "CLEAR", search_criteria = searchTAZ) print "loaded stations onto network" #Solve the OD cost matrix layer print "Begin Solving" arcpy.na.Solve(outNALayer) print "Done Solving" # Extract lines layer, export to CSV for lyr in arcpy.mapping.ListLayers(outNALayer): if lyr.name == linesLayerName: with open(outFile, 'w') as f: #f.write(','.join(fields)+'\n') # csv headers with arcpy.da.SearchCursor(lyr, fields) as cursor: print "Successfully created lines searchCursor. Exporting to " + outFile for row in cursor: f.write(','.join([str(r) for r in row])+'\n') # Deleteing using del outNALayer is not enough. Need to delete within arcpy to release arcpy.Delete_management(outNALayer) except Exception as e: # If an error occurred, print line number and error message import sys tb = sys.exc_info()[2] print "An error occurred in NAtoCSV_Trans line %i" % tb.tb_lineno print str(e) finally: #Check the network analyst extension license back in, regardless of errors. arcpy.CheckInExtension("Network")
for ExpName in ScenarioNames: # arcpy.AddMessage("Importing scenario: " + ExpName[0]) EVC = Input_Dataset + '\\' + Evacuation_Feature_Class_Prefix + ExpName[0] SAFE = Input_Dataset + '\\' + Safe_Zone_Feature_Class_Prefix + ExpName[0] DYN = Input_Dataset + '\\' + Dynamics_Feature_Class_Prefix + ExpName[0] # now loop over all NA layers and solve them one by one for lyr in arcpy.mapping.ListLayers(lyrFile): desc = arcpy.Describe(Input_Layer_Location + "\\" + lyr.longName) # only solve if the layer is a network analysis layer if desc.dataType == "NALayer": arcpy.SetProgressorLabel("Solving " + lyr.name + " with scenario " + ExpName[0] + "...") # load input locations arcpy.AddMessage("loading input points to " + lyr.name + " from scenario " + ExpName[0]) arcpy.AddLocations_na(lyr, "Evacuees", EVC, "VehicleCount POPULATION #;Name UID #", "5000 Meters", "", "Streets NONE;SoCal_ND_Junctions SHAPE", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "5 Meters", "EXCLUDE", "Streets #;SoCal_ND_Junctions #") for msg in range(0, arcpy.GetMessageCount()): arcpy.AddReturnMessage(msg) arcpy.AddLocations_na(lyr, "Zones", SAFE, "Name OBJECTID #;Capacity Capacity #", "5000 Meters", "", "Streets NONE;SoCal_ND_Junctions SHAPE", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "5 Meters", "EXCLUDE", "Streets #;SoCal_ND_Junctions #") for msg in range(0, arcpy.GetMessageCount()): arcpy.AddReturnMessage(msg) arcpy.AddLocations_na(lyr, "DynamicChanges", DYN, "EdgeDirection Zones_EdgeDirection #;StartingCost Zones_StartingCost #;EndingCost Zones_EndingCost #;CostChangeRatio Zones_CostChangeRatio #;CapacityChangeRatio Zones_CapacityChangeRatio #", "5000 Meters", "", "Streets SHAPE;SoCal_ND_Junctions NONE", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "5 Meters", "INCLUDE", "Streets #;SoCal_ND_Junctions #") for msg in range(0, arcpy.GetMessageCount()): arcpy.AddReturnMessage(msg) # solve the layer arcpy.AddMessage("Solving NALayer " + lyr.name + " with scenario " + ExpName[0]) arcpy.Solve_na(lyr, "SKIP", "TERMINATE") for msg in range(0, arcpy.GetMessageCount()): arcpy.AddReturnMessage(msg)