def Custom_Erase(inFeature1, inFeature2, outFeature): # Instead of erase, might try a union, then selection for only the features # that do not have their centers within the 2nd feature class, # or that are not entirely within the 2nd feature class, # then output the selected features. # MakeFeatureLayer, Union, SelectByLocation, CopyFeatures. tempUnionFeatureClass = r'in_memory\UnionTemp' unionList = list() unionList.append(inFeature1) unionList.append(inFeature2) Union_analysis(unionList, tempUnionFeatureClass, "ALL") tempUnionLayer = MakeFeatureLayer_management(tempUnionFeatureClass, "UnionLayer") tempFeature2 = MakeFeatureLayer_management(inFeature2, "Feature2") SelectLayerByLocation_management(tempUnionLayer, "HAVE_THEIR_CENTER_IN", tempFeature2) SelectLayerByLocation_management(tempUnionLayer, "WITHIN", tempFeature2, "0 Feet", "ADD_TO_SELECTION") CopyFeatures_management( tempUnionLayer, r'\\gisdata\ArcGIS\GISdata\GDB\CCL_Scratch_Boundary.gdb\TempUnionSelection' ) SelectLayerByAttribute_management(tempUnionLayer, "SWITCH_SELECTION") CopyFeatures_management( tempUnionLayer, r'\\gisdata\ArcGIS\GISdata\GDB\CCL_Scratch_Boundary.gdb\TempUnionSelectionSwitch' ) CopyFeatures_management(tempUnionLayer, outFeature)
def DirectionalUrbanClass(): #do the same as for State Sys but for Non State Urban Classified Highways (Nusys) FeatureVerticesToPoints_management("RoadCenterlinesC", "in_memory/UrbanPoints", "MID") FeatureClassToFeatureClass_conversion( NSND, "in_memory", "NSND_NPD", where_clause="NETWORK_DIRECTION IN ( 'SB' , 'WB' )") LocateFeaturesAlongRoutes_lr("UrbanPoints", "NSND_NPD", "NE_UNIQUE", "200 Feet", "in_memory/UrbanPointsMeasures", "RID POINT MEAS", "ALL", "DISTANCE", "ZERO", "FIELDS", "M_DIRECTON") Delete_management("UrbanPoints") #is the query stil valid for non state system? Explore hte NE Unique. State System did not use the county number prefix SelectLayerByAttribute_management( "UrbanPointsMeasures", "NEW_SELECTION", """SUBSTRING( "RID", 4, 7) NOT LIKE SUBSTRING("NON_State_System_LRSKey" ,4, 7)""" ) DeleteRows_management(in_rows="UrbanPointsMeasures") MakeRouteEventLayer_lr("NSND_NPD", "NE_UNIQUE", "UrbanPointsMeasures", "rid POINT MEAS", "UrbanPointEvents", offset_field="Distance", add_error_field="ERROR_FIELD", add_angle_field="ANGLE_FIELD", angle_type="NORMAL", complement_angle="ANGLE", offset_direction="RIGHT", point_event_type="POINT") MakeFeatureLayer_management("UrbanPointEvents", "UNPD_ID", """"Distance">=0""") SelectLayerByLocation_management("UNPD_ID", "INTERSECT", "RoadCenterlinesC", "1 Feet", "NEW_SELECTION") #at this point, there are a lot of false positives, places with single carriagway roads and nusys divided #we need to incorporate the check overlap process to identify where their are single and dual carriagways here #starting with the technique to find sausages or dual carraigeways #SpatialJoin_analysis("UNPD_ID", "RoadCenterlinesC", "in_memory/ValidateSausages120", "JOIN_ONE_TO_ONE", "KEEP_ALL", '#', "INTERSECT", "120 Feet", "Distance") #this Spatial Join step is improving the results, removing most false positives. It still shows overlapping segments #it would be improved even more, potentially, by testing the non-primary direction against dissolve somehow. #except, the calculate method is by segment to the source, a dissolve would complicate the process of calculating back to the source data #we are looking for count grater than 0 of the offset point to hte segment, so a dissolved segment should work import EliminateOverlaps from EliminateOverlaps import CollectorDissolve #set the roadcenterline input and dissolve output for RoadCenterline dissolve for this subroutine roadcenterlines = "RoadCenterlinesC" ClassOutput = r"in_memory/RMC2" CollectorDissolve() SpatialJoin_analysis("UNPD_ID", "RMC2dissolve", "in_memory/ValidateSausages120", "JOIN_ONE_TO_ONE", "KEEP_ALL", '#', "INTERSECT", "120 Feet", "Distance")
def ConflateKDOTrestart(gdb, DOTRoads): """Conflation restart for selecting KDOT roads to conflate to the NG911 Network""" from arcpy import SelectLayerByLocation_management, FeatureClassToFeatureClass_conversion from arcpy import env env.overwriteOutput = 1 checkfile = gdb MakeFeatureLayer_management(DOTRoads+"/KDOT_HPMS_2012","KDOT_Roads","#","#","#") MakeFeatureLayer_management(checkfile+"/RoadCenterline","RoadCenterline","#","#","#") SelectLayerByLocation_management("KDOT_Roads","INTERSECT","RoadCenterline","60 Feet","NEW_SELECTION") FeatureClassToFeatureClass_conversion("KDOT_Roads",checkfile+r"/NG911","KDOT_Roads_Review","#","#","#")
def ConflateKDOTrestart(): """Conflation restart for selecting KDOT roads to conflate to the NG911 Network""" MakeFeatureLayer_management(DOTRoads + "/KDOT_HPMS_2012", "KDOT_Roads", "#", "#", "#") MakeFeatureLayer_management(gdb + "/RoadCenterline", "RoadCenterline", "#", "#", "#") SelectLayerByLocation_management("KDOT_Roads", "INTERSECT", "RoadCenterline", "60 Feet", "NEW_SELECTION") FeatureClassToFeatureClass_conversion("KDOT_Roads", gdb + r"/NG911", "KDOT_Roads_Review", "#", "#", "#")
def restrictDomain(self, object, operation): """ Restricts current instance's domain based on object's domain @param object: extent to which the object is restricted @param operation: valid options: "inside", "outside" """ name = "restDom_" + str(self.sObj) outputLocation = "in_memory\\" + name if operation == 'inside': # select by location select = SelectLayerByLocation_management(self.filepath, "INTERSECT", object.filepath) CopyFeatures_management(select, outputLocation) restDom = utils.makeObject(outputLocation) elif operation == 'outside': # select by location sel = SelectLayerByLocation_management(self.filepath, "INTERSECT", object.filepath) select = SelectLayerByLocation_management(sel, "INTERSECT", object.filepath, "", "SWITCH_SELECTION") CopyFeatures_management(select, outputLocation) restDom = utils.makeObject(outputLocation) else: raise NotImplementedError(operation) # update cc instance's attributes desc = Describe(outputLocation) restDom.domain = desc.extent restDom.filepath = outputLocation restDom.filename = os.path.basename(outputLocation) return restDom
def checkFeatureLocations(gdb): userMessage("Checking feature locations...") from os import path from arcpy import MakeFeatureLayer_management, SelectLayerByAttribute_management, SelectLayerByLocation_management, GetCount_management, Delete_management, da values = [] #make sure feature are all inside authoritative boundary #get authoritative boundary authBound = path.join(gdb, "NG911", "AuthoritativeBoundary") ab = "ab" MakeFeatureLayer_management(authBound, ab) for dirpath, dirnames, filenames in da.Walk(gdb, True, '', False, ["FeatureClass"]): for filename in filenames: if filename != "AuthoritativeBoundary": #get full path name & create a feature layer fullPath = path.join(gdb, filename) fl = "fl" MakeFeatureLayer_management(fullPath, fl) #select by location to get count of features outside the authoritative boundary SelectLayerByLocation_management(fl, "INTERSECT", ab) SelectLayerByAttribute_management(fl, "SWITCH_SELECTION", "") #get count of selected records result = GetCount_management(fl) count = int(result.getOutput(0)) #report results if count > 0: fields = ("OBJECTID") with da.SearchCursor(fl, fields) as rows: for row in rows: val = (today, "Feature not inside authoritative boundary", filename, "", row[0]) values.append(val) else: userMessage(filename + ": all records inside authoritative boundary") #clean up Delete_management(fl) userMessage("Completed check on feature locations") if values != []: RecordResults("fieldValues", values, gdb)
def ConflateKDOT(): """detects road centerline changes and transfers the HPMS key field from the KDOT roads via ESRI conflation tools""" from arcpy import TransferAttributes_edit, DetectFeatureChanges_management, GenerateRubbersheetLinks_edit, RubbersheetFeatures_edit spatialtolerance = "20 feet" MakeFeatureLayer_management(DOTRoads + "/KDOT_HPMS_2012", "KDOT_Roads", "#", "#", "#") MakeFeatureLayer_management( gdb + "/RoadCenterline", "RoadCenterline", "#", "#", "#") #this may already exist so check, and use FD if Exists(gdb + r"/NG911/KDOT_Roads_Review"): print "selection of KDOT roads for conflation already exists" else: SelectLayerByLocation_management("KDOT_Roads", "INTERSECT", "RoadCenterline", "60 Feet", "NEW_SELECTION") FeatureClassToFeatureClass_conversion("KDOT_Roads", gdb + r"/NG911", "KDOT_Roads_Review", "#", "#", "#") MakeFeatureLayer_management(gdb + "/KDOT_Roads_Review", "KDOT_Roads_Review", "#", "#", "#") GenerateRubbersheetLinks_edit("KDOT_Roads_Review", "RoadCenterline", gdb + r"/NG911/RoadLinks", spatialtolerance, "ROUTE_ID LRSKEY", gdb + r"/RoadMatchTbl") MakeFeatureLayer_management(gdb + "/NG911/RoadLinks", "RoadLinks", "#", "#", "#") MakeFeatureLayer_management(gdb + "/NG911/RoadLinks_pnt", "RoadLinks_pnt", "#", "#", "#") RubbersheetFeatures_edit("KDOT_Roads_Review", "RoadLinks", "RoadLinks_pnt", "LINEAR") DetectFeatureChanges_management("KDOT_Roads_Review", "RoadCenterline", gdb + r"/NG911/RoadDifference", spatialtolerance, "#", gdb + r"/RoadDifTbl", spatialtolerance, "#") MakeFeatureLayer_management(gdb + "/NG911/RoadDifference", "RoadDifference", "#", "#", "#") TransferAttributes_edit("KDOT_Roads_Review", "RoadCenterline", "YEAR_RECORD;ROUTE_ID", spatialtolerance, "#", gdb + r"/LRS_MATCH")
def ConflateKDOT(gdb, DOTRoads): """detects road centerline changes and transfers the HPMS key field from the KDOT roads via ESRI conflation tools""" from arcpy import MakeFeatureLayer_management, Exists, TransferAttributes_edit, DetectFeatureChanges_management, RubbersheetFeatures_edit, SelectLayerByLocation_management, FeatureClassToFeatureClass_conversion, GenerateRubbersheetLinks_edit, RubbersheetFeatures_edit from arcpy import env env.overwriteOutput = 1 checkfile = gdb spatialtolerance = "20 feet" #MakeFeatureLayer_management(checkfile+"/AuthoritativeBoundary","AuthoritativeBoundary_Layer","#","#","#") #MakeFeatureLayer_management(checkfile+"/CountyBoundary","CountyBoundary_Layer","#","#","#") MakeFeatureLayer_management(DOTRoads+"/KDOT_HPMS_2012","KDOT_Roads","#","#","#") MakeFeatureLayer_management(checkfile+"/RoadCenterline","RoadCenterline","#","#","#") if Exists(checkfile+r"/NG911/KDOT_Roads_Review"): print "selection of KDOT roads for conflation already exists" else: SelectLayerByLocation_management("KDOT_Roads","INTERSECT","RoadCenterline","60 Feet","NEW_SELECTION") FeatureClassToFeatureClass_conversion("KDOT_Roads",checkfile+r"/NG911","KDOT_Roads_Review","#","#","#") MakeFeatureLayer_management(checkfile+"/KDOT_Roads_Review","KDOT_Roads_Review","#","#","#") GenerateRubbersheetLinks_edit("KDOT_Roads_Review","RoadCenterline",checkfile+r"/NG911/RoadLinks",spatialtolerance,"ROUTE_ID LRSKEY",checkfile+r"/RoadMatchTbl") MakeFeatureLayer_management(checkfile+"/NG911/RoadLinks","RoadLinks","#","#","#") MakeFeatureLayer_management(checkfile+"/NG911/RoadLinks_pnt","RoadLinks_pnt","#","#","#") RubbersheetFeatures_edit("KDOT_Roads_Review","RoadLinks","RoadLinks_pnt","LINEAR") DetectFeatureChanges_management("KDOT_Roads_Review","RoadCenterline",checkfile+r"/NG911/RoadDifference",spatialtolerance,"#",checkfile+r"/RoadDifTbl",spatialtolerance,"#") MakeFeatureLayer_management(checkfile+"/NG911/RoadDifference","RoadDifference","#","#","#") TransferAttributes_edit("KDOT_Roads_Review","RoadCenterline","YEAR_RECORD;ROUTE_ID",spatialtolerance,"#",checkfile+r"/LRS_MATCH")
def SecondaryDirectionFinder(): #make a point at the center of each line segment for a highway #No way currently to do this for RML highways, NUSYS provides the directional layer for C highwyas #FeatureToPoint_management("State Highways", "in_memory/HighwayPoints", "INSIDE") #maybe two ways to do this, this time, I'm using midpoint from feature to point - catch FeatureVerticesToPoints_management( "RoadCenterlines", out_feature_class="in_memory/HighwayPoints", point_location="MID") #FeatureToPoint_management(Roads, "in_memory/HighwayPoints", "INSIDE") FeatureClassToFeatureClass_conversion( SRND, "in_memory", "SRND_NPD", where_clause="NETWORK_DIRECTION IN ( 'SB' , 'WB' )") #CRND Secondary Direction is the CRND layer where "NETWORK_DIRECTION IN ( 'SB' , 'WB' )" #Locate Features Along Routes will calculate a +/- offset distance of the dual carriageway points from the CRND centerline LocateFeaturesAlongRoutes_lr("HighwayPoints", "SRND_NPD", "NE_UNIQUE", "500 Feet", "in_memory/HighwayPointsMeasures", "RID POINT MEAS", "ALL", "DISTANCE", "ZERO", "FIELDS", "M_DIRECTON") #All the Highway Points are no longer needed and can be freed from memory Delete_management("HighwayPoints") #since we located along all routes instead of the nearest routes, we need to select the rows that have the correct LRS key #SelectLayerByAttribute_management("in_memory/HighwayPointsMeasures", "NEW_SELECTION", """SUBSTRING( "RID", 1, 7) NOT LIKE SUBSTRING("StateKey1", 4, 7)""") #Using State_System_LRSKey from Conflation just in case the StateKey1 has not yet been added or calculated. SelectLayerByAttribute_management( "HighwayPointsMeasures", "NEW_SELECTION", """SUBSTRING( "RID", 1, 7) NOT LIKE SUBSTRING("State_System_LRSKey" ,4, 7)""" ) DeleteRows_management(in_rows="HighwayPointsMeasures") # point events are located along the routes that KDOT says are divided on the dual carriageway MakeRouteEventLayer_lr("SRND_NPD", "NE_UNIQUE", "HighwayPointsMeasures", "rid POINT MEAS", "HighwayPointEvents", offset_field="Distance", add_error_field="ERROR_FIELD", add_angle_field="ANGLE_FIELD", angle_type="NORMAL", complement_angle="ANGLE", offset_direction="RIGHT", point_event_type="POINT") #select the secondary direction points based on the offset direction MakeFeatureLayer_management("HighwayPointEvents", "NPD_ID", """"Distance">=0""") # some random points, due to the 500 ft buffer I think, are getting included. Select the event points that do not intersect a state highway road centerline feature # SelectLayerByLocation_management("NPD_ID", "INTERSECT", "RoadCenterlines", "1 Feet", "NEW_SELECTION") #sometimes (center turn lanes, left turn lanes, painted medians, median terminus locations) #there is a difference between what KDOT says is Divided and the dual carriagway geometry. #Consider this and determine how to handle divided highways in the route Keys/route structures. #this next step will only factor in the FeatureClassToFeatureClass_conversion( "NPD_ID", ConflationDatabase + "\\" + GeodatabaseName + ".SDE.KANSAS_DOT", "Non_Primary_Divided_Highway", '"Distance">=0')
env.overwriteOutput = True CheckOutExtension("Spatial") # load input data area = 'C:/area.shp' dem = 'C:/dem.tif' waterPoint = 'C:/waterPoints.shp' building = 'C:/buildings.shp' # set parameters distance = 50 elevation = 3 # select water points within area waterPoint_inArea = SelectLayerByLocation_management(waterPoint, 'INTERSECT', area) # select buildings within area building_inArea = SelectLayerByLocation_management(building, 'INTERSECT', area) # elevation of waterPoints waterPoint_elev = ExtractValuesToPoints(waterPoint_inArea, dem, 'in_memory/wp_elev') # calculate elevation of buildings (using centroid) building_point = FeatureToPoint_management(building_inArea, 'in_memory/building_point', 'CENTROID') building_pt_elev = ExtractValuesToPoints(building_point, dem, 'in_memory/building_pt_elev') building_elevation = CopyFeatures_management(building_inArea,
# Try selects all the park and ride facilities in a given city and saves them out to a new feature class try: # SQL to select only one city queryString = '"' + nameField + '" = ' + "'" + nameCity + "'" # It means the same that: " nameField + " = ' nameCity ' # Name of new layer of city nameCityLayer = nameCity.replace(" ", "_") + '_lyr' # Make a feature layers MakeFeatureLayer_management(parkAndRide, "parkAndRide_lry") MakeFeatureLayer_management(cityBoundaries, nameCityLayer, queryString) # Select all park and ride into of only city SelectLayerByLocation_management("parkAndRide_lry", "CONTAINED_BY", nameCityLayer) # Name of new feature class nameFeatureOut = nameCity + '_ParkAndRide' # Create a new feature class only with park and ride into of city CopyFeatures_management("parkAndRide_lry", nameOut) # Detele feature layers Delete_management("parkAndRide_lry") Delete_management(nameCityLayer) # If happen some error except: # Show the message
def transferBasedOnLocalRouteKeys(): # Build a list of the unique route keys that match the given criteria: # Then, use that list to select the features in the source with those # keys. # Next, spatially select features in the target layer with the # selected features from the source layer. # If there are more than 0 features selected, delete the selected # target features. # Then, cursor in the selected source features. subsetSelectionQuery = """ KDOT_LRS_KEY LIKE '%L%' AND NOT KDOT_LRS_KEY LIKE '%W%' """ fcAsFeatureLayerForTransferring = 'FCAsFeatureLayer_Transferring' if Exists(fcAsFeatureLayerForTransferring): Delete_management(fcAsFeatureLayerForTransferring) else: pass MakeFeatureLayer_management(fcWithroutesToTransferFrom, fcAsFeatureLayerForTransferring) MakeFeatureLayer_management(targetFC1, targetFC1asFeatureLayer) lrsKeyFieldList = [str(lrsKeyToUse)] newCursor = daSearchCursor(fcWithroutesToTransferFrom, lrsKeyFieldList, subsetSelectionQuery) uniqueLRSKeysDict = dict() for cursorRow in newCursor: uniqueLRSKeysDict[str(cursorRow[0])] = 1 try: del newCursor except: pass uniqueLRSKeysList = uniqueLRSKeysDict.keys() try: uniqueLRSKeysList.remove('None') except: print( "Could not remove 'None' from the list of uniqueLRSKeys since it was not a part of the list." ) print("LRSKey list creation successful.") print('Found ' + str(len(uniqueLRSKeysList)) + ' unique LRS Keys in the centerline data for this query:') print(str(subsetSelectionQuery)) #Use multiSelection multiSelectionQueryBase = str( str(subsetSelectionQuery) + ''' AND ''' + ''' "''' + str(lrsKeyToUse) + '''" IS NOT NULL AND "''' + str(lrsKeyToUse) + '''" IN (''') multiSelectionQuery = multiSelectionQueryBase multiCounter = 0 ##multiDissolveFields = [str(lrsKeyToUse), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX', 'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT', ## 'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R'] ##multiDissolveFields = str(lrsKeyToUse) + ';LRS_COUNTY_PRE;LRS_ROUTE_PREFIX;LRS_ROUTE_NUM;LRS_ROUTE_SUFFIX;LRS_UNIQUE_IDENT;LRS_UNIQUE_IDENT1' ##multiStatsFields = str(n1FromMeas) + " MIN;" + str(n1ToMeas) + " MAX" ##multiStatsFields = "" ##singlePart = "SINGLE_PART" ##unsplitLines = "UNSPLIT_LINES" # 3.) Loop through the list of unique LRS Keys for uniqueKeyItem in uniqueLRSKeysList: # Make a selection list that includes 50 keys, then select the keys and dissolve to make a new # feature class. # After the selection is dissolved, use a spatial select on the original feature class and # an attribute selection on the original feature class to see which original features should # be deleted. # Then, delete the selected features (if at least 1 selected). # Basically, doing it piece by piece is a problem since I'm not including LRS KEY # selections to prevent the spatial selection from deleting pieces that overlap, but # that should have different LRS Keys. Need to do all of the features # at once to make sure that I'm not deleting pieces that should actually be there. # Seems like it shouldn't be a problem, but the numbers say it is. # 4.) For groups of 200000 LRS Keys, select all the features with those LRS Keys. if multiCounter <= 199999: multiSelectionQuery += """'""" + str( uniqueKeyItem) + """'""" + """, """ multiCounter += 1 else: # Add the current item, then multiSelectionQuery += """'""" + str( uniqueKeyItem) + """'""" + """, """ # Remove the trailing ", " and add a closing parenthesis. multiSelectionQuery = multiSelectionQuery[:-2] + """) """ SelectLayerByAttribute_management(fcAsFeatureLayerForTransferring, "NEW_SELECTION", multiSelectionQuery) # Have to do from step 5 on here also. ### -shouldbeafunctionblock#1- ### # 5.) Count selected features. countResult0 = GetCount_management(fcAsFeatureLayerForTransferring) intCount0 = int(countResult0.getOutput(0)) if intCount0 >= 1: print( "Spatially selecting with the fcAsFeatureLayerForTransferring features, of which there are " + str(intCount0) + " selected.") ##print("Selected by this query:") ##print(str(multiSelectionQuery)) # 9.) Else, spatially select features in the original feature class with 'SHARE_A_LINE_SEGMENT_WITH'. SelectLayerByLocation_management( targetFC1asFeatureLayer, "SHARE_A_LINE_SEGMENT_WITH", fcAsFeatureLayerForTransferring, 0, "NEW_SELECTION") # Added to prevent the Selection from taking over '%W%' routes at this time. SelectLayerByAttribute_management(targetFC1asFeatureLayer, "SUBSET_SELECTION", subsetSelectionQuery) # 10.) Count to make sure that at least one feature is selected. countResult2 = GetCount_management(targetFC1asFeatureLayer) intCount2 = int(countResult2.getOutput(0)) print( 'There were ' + str(intCount2) + ' features selected for replacement in the targetFC1asFeatureLayer layer.' ) if intCount2 >= 1: # 11.) If so, cursor the features out of the dissolve layer. featureList = list() searchCursorFields = [ str(lrsKeyToUse), str(startMeasure), str(endMeasure), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX', 'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT', 'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R', 'LABEL', 'SHAPE@' ] newCursor = daSearchCursor(fcAsFeatureLayerForTransferring, searchCursorFields) for cursorItem in newCursor: featureList.append(list(cursorItem)) try: del newCursor except: pass # 12.) Delete the selected features in the input layer. try: DeleteFeatures_management(targetFC1asFeatureLayer) except: print("Could not delete features for the selection " + str(multiSelectionQuery) + ".") # 13.) Insert the features from the dissolve layer into the copy of the centerlines. insertCursorFields = [ str(lrsKeyToUse), str(startMeasure), str(endMeasure), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX', 'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT', 'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R', 'LABEL', 'SHAPE@' ] newCursor = daInsertCursor(targetFC1asFeatureLayer, insertCursorFields) for featureItem in featureList: newCursor.insertRow(featureItem) try: del newCursor except: pass try: del featureList except: pass else: pass ### -shouldbeafunctionblock#1- ### multiSelectionQuery = ''' "''' + str( lrsKeyToUse) + '''" IS NOT NULL AND "''' + str( lrsKeyToUse) + '''" IN (''' multiCounter = 0 # After the for loop, if there is still anything remaining which was unselected in the # the previous multiSelectionQuery steps. # Remove the trailing ", " and add a closing parenthesis. if multiSelectionQuery != multiSelectionQueryBase: multiSelectionQuery = multiSelectionQuery[:-2] + """) """ else: # The selection query would not select anything. return SelectLayerByAttribute_management(fcAsFeatureLayerForTransferring, "NEW_SELECTION", multiSelectionQuery) # Then redo from step 5 on at the end of the loop IF there is anything left to select # which was not selected... so if selectionCounter != 0. ### -shouldbeafunctionblock#2- ### # 5.) Count selected features. countResult0 = GetCount_management(fcAsFeatureLayerForTransferring) intCount0 = int(countResult0.getOutput(0)) if intCount0 >= 1: print( "Spatially selecting with the fcAsFeatureLayerForTransferring features, of which there are " + str(intCount0) + " selected.") ##print("Selected by this query:") ##print(str(multiSelectionQuery)) # 9.) Else, spatially select features in the original feature class with 'SHARE_A_LINE_SEGMENT_WITH'. SelectLayerByLocation_management(targetFC1asFeatureLayer, "SHARE_A_LINE_SEGMENT_WITH", fcAsFeatureLayerForTransferring, 0, "NEW_SELECTION") # Added to prevent the Selection from taking over '%W%' routes at this time. SelectLayerByAttribute_management(targetFC1asFeatureLayer, "SUBSET_SELECTION", subsetSelectionQuery) # 10.) Count to make sure that at least one feature is selected. countResult2 = GetCount_management(targetFC1asFeatureLayer) intCount2 = int(countResult2.getOutput(0)) print( 'There were ' + str(intCount2) + ' features selected for replacement in the targetFC1asFeatureLayer layer.' ) if intCount2 >= 1: # 11.) If so, cursor the features out of the dissolve layer. featureList = list() searchCursorFields = [ str(lrsKeyToUse), str(startMeasure), str(endMeasure), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX', 'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT', 'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R', 'LABEL', 'SHAPE@' ] newCursor = daSearchCursor(fcAsFeatureLayerForTransferring, searchCursorFields) for cursorItem in newCursor: featureList.append(list(cursorItem)) try: del newCursor except: pass # 12.) Delete the selected features in the input layer. try: DeleteFeatures_management(targetFC1asFeatureLayer) except: print("Could not delete features for the selection " + str(multiSelectionQuery) + ".") # 13.) Insert the features from the dissolve layer into the copy of the centerlines. insertCursorFields = [ str(lrsKeyToUse), str(startMeasure), str(endMeasure), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX', 'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT', 'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R', 'LABEL', 'SHAPE@' ] newCursor = daInsertCursor(targetFC1asFeatureLayer, insertCursorFields) for featureItem in featureList: newCursor.insertRow(featureItem) try: del newCursor except: pass try: del featureList except: pass else: pass
def featureReplacement(sourceFL, targetFL, featuresToSelect): # 1c.) Get the common fields so that you can search and insert correctly. targetFeatureDesc = Describe(targetFL) targetFeatureFields = targetFeatureDesc.fields targetFeatureOIDField = targetFeatureDesc.OIDFieldName targetFeatureShapeField = targetFeatureDesc.shapeFieldName targetFeatureFieldNames = [x.name for x in targetFeatureFields] sourceFeatureDesc = Describe(sourceFL) sourceFeatureFields = sourceFeatureDesc.fields sourceFeatureOIDField = sourceFeatureDesc.OIDFieldName sourceFeatureShapeField = sourceFeatureDesc.shapeFieldName sourceFeatureFieldNames = [x.name for x in sourceFeatureFields] excludeFieldNames = [targetFeatureOIDField, targetFeatureShapeField, sourceFeatureOIDField, sourceFeatureShapeField] searchCursorFields = [x for x in targetFeatureFieldNames if x in sourceFeatureFieldNames and x not in excludeFieldNames] searchCursorFields.append('SHAPE@') # Remove and then re-add the uniqueKeyField so that it is the last column and can be easily referenced. searchCursorFields.remove(str(uniqueKeyFieldToUse)) searchCursorFields.append(str(uniqueKeyFieldToUse)) insertCursorFields = searchCursorFields # Select the features in the source layer SelectLayerByAttribute_management(sourceFL, "NEW_SELECTION", featuresToSelect) # Repeat the selection in the target layer SelectLayerByAttribute_management(targetFL, "NEW_SELECTION", featuresToSelect) # Then select the common segments spatially, with some room for possible movement. SelectLayerByLocation_management(targetFL, 'WITHIN_A_DISTANCE', sourceFL, 50, 'SUBSET_SELECTION') # 5.) Count selected features in the target and delete them if there is at least 1. countResult0 = GetCount_management(targetFL) intCount0 = int(countResult0.getOutput(0)) if intCount0 >= 1: # 12.) Delete the selected features in the input layer, if any. try: DeleteFeatures_management(targetFL) except: print("Could not delete features for the selection " + str(featuresToSelect) + ".") else: pass # 10.) Count to make sure that at least one feature is selected. countResult1 = GetCount_management(sourceFL) intCount1 = int(countResult1.getOutput(0)) if intCount1 >= 1: # If so, cursor the features out featureList = list() newCursor = daSearchCursor(sourceFL, searchCursorFields) for cursorItem in newCursor: featureList.append(list(cursorItem)) try: del newCursor except: pass # 11.) Insert the selected source features into the copy of the centerlines. newCursor = daInsertCursor(targetFL, insertCursorFields) for featureItem in featureList: newCursor.insertRow(featureItem) try: del newCursor except: pass try: del featureList except: pass
# For each feature of city in cityBoundaries geography data for row in cityRows: # Get the name of each city nameCity = row[0] # queryString = '"' + nameField + '" = ' + "'" + nameCity + "'" # Make a feature layer of just the current city polygon # The queryString is reponsible for select only the feature of city MakeFeatureLayer_management(cityBoundaries, "CurrentCityLayer", queryString) MakeFeatureLayer_management(parkAndRide, "ParkAndRide_lry") # Selecty by location all feature of park and ride that contain in current city SelectLayerByLocation_management("ParkAndRide_lry", "CONTAINED_BY", "CurrentCityLayer") # Get the total value of park and ride for each city countPark = GetCount_management("ParkAndRide_lry") totalPark = int(countPark.getOutput(0)) # Count of city in cityBoundaries totalCity += 1 # If the total park and rise is bigger then 1 if totalPark > 1: # The row in field HasTwoParkAndRides update to "True" row[1] = "True" # Count each city has than more that two park and ride in your limits
queryStringCountry) for typeAmenities in amenities: # SQL pick up the type amenities queryStringAmenities = '"' + nameFieldAmenity + '" = ' + "'" + typeAmenities + "'" # The name of new feature layer nameAmenitiesLayer = typeAmenities + "lyr" # Mame a feature layer of type amenities MakeFeatureLayer_management(osmPoints, nameAmenitiesLayer, queryStringAmenities) # Select only amanities into the country El Salvador SelectLayerByLocation_management(nameAmenitiesLayer, "CONTAINED_BY", nameCountryLayer) # Makes a separate shapefile for each types of amenities CopyFeatures_management(nameAmenitiesLayer, typeAmenities) # Get the new separete shapefile amenitiesTable = typeAmenities + '.dbf' # Name of new field for amenities newField = "source" # Add new field called 'source' AddField_management(amenitiesTable, newField, "TEXT", 100) with UpdateCursor(typeAmenities + ".shp", newField) as amenitiesRows:
def SecondaryDirectionFinder(): #make a point at the center of each line segment for a highway #No way currently to do this for RML highways, NUSYS provides the directional layer for C highwyas #FeatureToPoint_management("State Highways", "in_memory/HighwayPoints", "INSIDE") #maybe two ways to do this, this time, I'm using midpoint from feature to point - catch FeatureVerticesToPoints_management( in_features="RoadCenterlines", out_feature_class="in_memory/HighwayPoints", point_location="MID") FeatureClassToFeatureClass_conversion( SRND, "in_memory", "SRND_NPD", where_clause="NETWORK_DIRECTION IN ( 'SB' , 'WB' )") #CRND SEcondary Direction is the CRND layer where "NETWORK_DIRECTION IN ( 'SB' , 'WB' )" #Locate Features Along Routes will calculate a +/- offset distance of the dual carriageway points from the CRND centerline LocateFeaturesAlongRoutes_lr("HighwayPoints", "SRND_NPD", "NE_UNIQUE", "500 Feet", "in_memory/HighwayPointsMeasures", "RID POINT MEAS", "ALL", "DISTANCE", "ZERO", "FIELDS", "M_DIRECTON") # Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script # The following inputs are layers or table views: "HighwayPointsMeasures" SelectLayerByAttribute_management( in_layer_or_view="HighwayPointsMeasures", selection_type="NEW_SELECTION", where_clause= """SUBSTRING( "RID", 1, 7) NOT LIKE SUBSTRING("StateKey1", 1, 7)""") DeleteRows_management(in_rows="HighwayPointsMeasures") MakeRouteEventLayer_lr("SRND_NPD", "NE_UNIQUE", "HighwayPointsMeasures", "rid POINT MEAS", "HighwayPointEvents", offset_field="Distance", add_error_field="ERROR_FIELD", add_angle_field="ANGLE_FIELD", angle_type="NORMAL", complement_angle="ANGLE", offset_direction="RIGHT", point_event_type="POINT") #select the secondary direction points MakeFeatureLayer_management("HighwayPointEvents", "NPD_ID", """"Distance">=0""") # some random points, due to the 500 ft buffer I think, are getting included. Select the event points that do not intersect a state highway road centerline feature # SelectLayerByLocation_management(in_layer="NPD_ID", overlap_type="INTERSECT", select_features="RoadCenterlines", search_distance="1 Feet", selection_type="NEW_SELECTION", invert_spatial_relationship="INVERT") FeatureClassToFeatureClass_conversion( "NPD_ID", "Database Connections/Conflation2012_sde.sde/Conflation.SDE.KANSAS_DOT", "Non_Primary_Divided_Highway", '"Distance">=0')
AddWarning(strErrorMsg) SetParameterAsText(6, strErrorMsg) sys.exit() # Make a dictionary of layer name and layer variable for iteration purposes dictLayers = {"zip": flZCTA, "lepc": flLEPC, "county": flCounty} dictNames = {} # Iterate through layers in dictionary and run SelectLayerByLocation for key in dictLayers: lyrLayer = dictLayers.get(key) try: SelectLayerByLocation_management( in_layer=lyrLayer, overlap_type="CONTAINS", select_features=ptGeometry, search_distance="", selection_type="NEW_SELECTION", invert_spatial_relationship="NOT_INVERT") except: strErrorMsg = "Error with SelectLayerByLocation_management." AddWarning(strErrorMsg) SetParameterAsText(6, strErrorMsg) sys.exit() intSelectionCount = 0 resultSelectionCount = GetCount_management( lyrLayer) # Result Object, not an actual number intSelectionCount = int(GetCount_management(lyrLayer).getOutput( 0)) # Cast to int because returns as unicode '''' During development, a point was used that fell on more than one polygon. The process returned two counties selected and two lepc's selected. But, they were not in the same order so they weren't written to the
def dissolveBasedOnLocalRouteKeys(routesToDissolve, subsetSelectionQuery): # Moved out the selection building code to the other function where # it makes more sense. # Use similar code here to what is found in the main dissolve loop. # Just need to do multiselection on all of the possible routes that # match the subsetSelectionQuery and for each multiselection, create # a dissolve feature set, then use the same reintroduction tests # that are used in the main dissolve to reintroduce the dissolved # lines without removing any that weren't dissolved or adding # any new overlaps. fcAsFeatureLayerForDissolves = 'FCAsFeatureLayer_Dissolves' if Exists(fcAsFeatureLayerForDissolves): Delete_management(fcAsFeatureLayerForDissolves) else: pass MakeFeatureLayer_management(routesToDissolve, fcAsFeatureLayerForDissolves) lrsKeyFieldList = [str(lrsKeyToUse)] newCursor = daSearchCursor(routesToDissolve, lrsKeyFieldList, subsetSelectionQuery) uniqueLRSKeysDict = dict() for cursorRow in newCursor: uniqueLRSKeysDict[str(cursorRow[0])] = 1 try: del newCursor except: pass uniqueLRSKeysList = uniqueLRSKeysDict.keys() try: uniqueLRSKeysList.remove('None') except: print( "Could not remove 'None' from the list of uniqueLRSKeys since it was not a part of the list." ) print("LRSKey list creation successful.") print('Found ' + str(len(uniqueLRSKeysList)) + ' unique LRS Keys in the centerline data for this query:') print(str(subsetSelectionQuery)) #Use multiSelection multiSelectionQueryBase = str( str(subsetSelectionQuery) + ''' AND ''' + ''' "''' + str(lrsKeyToUse) + '''" IS NOT NULL AND "''' + str(lrsKeyToUse) + '''" IN (''') multiSelectionQuery = multiSelectionQueryBase multiCounter = 0 multiDissolveFields = [ str(lrsKeyToUse), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX', 'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT', 'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R' ] ##multiDissolveFields = str(lrsKeyToUse) + ';LRS_COUNTY_PRE;LRS_ROUTE_PREFIX;LRS_ROUTE_NUM;LRS_ROUTE_SUFFIX;LRS_UNIQUE_IDENT;LRS_UNIQUE_IDENT1' ##multiStatsFields = str(n1FromMeas) + " MIN;" + str(n1ToMeas) + " MAX" multiStatsFields = "" singlePart = "SINGLE_PART" unsplitLines = "UNSPLIT_LINES" # 3.) Loop through the list of unique LRS Keys for uniqueKeyItem in uniqueLRSKeysList: # Make a selection list that includes 50 keys, then select the keys and dissolve to make a new # feature class. # After the selection is dissolved, use a spatial select on the original feature class and # an attribute selection on the original feature class to see which original features should # be deleted. # Then, delete the selected features (if at least 1 selected). # try: Delete_management(dissolveOutFC) except: print("Could not delete the dissolveOutFC layer.") # 4.) For groups of 2000 LRS Keys, select all the features with those LRS Keys. if multiCounter <= 1999: multiSelectionQuery += """'""" + str( uniqueKeyItem) + """'""" + """, """ multiCounter += 1 else: # Add the current item, then multiSelectionQuery += """'""" + str( uniqueKeyItem) + """'""" + """, """ # Remove the trailing ", " and add a closing parenthesis. multiSelectionQuery = multiSelectionQuery[:-2] + """) """ SelectLayerByAttribute_management(fcAsFeatureLayerForDissolves, "NEW_SELECTION", multiSelectionQuery) # Have to do from step 5 on here also. ### -shouldbeafunctionblock#1- ### # 5.) Count selected features. countResult0 = GetCount_management(fcAsFeatureLayerForDissolves) intCount0 = int(countResult0.getOutput(0)) if intCount0 >= 1: # 6.) Make a new layer or dissolved layer from this selection. Dissolve_management(fcAsFeatureLayerForDissolves, dissolveOutFC, multiDissolveFields, multiStatsFields, singlePart, unsplitLines) # 7.) Count the number of dissolved features. countResult1 = GetCount_management(dissolveOutFC) intCount1 = int(countResult1.getOutput(0)) print('Counted ' + str(intCount1) + ' features returned for that dissolve.') # 8a.) If the number of dissolved features is 0, then append the error to the error file # and go on to the next LRS Key in the loop. if intCount1 == 0: with open(dissolveErrorsFile, 'a') as errorFile: errorFile.write(str(multiSelectionQuery)) # 8b.) From the spatial select, select the subset of features that also have a matching LRS Key. else: SelectLayerByAttribute_management( fcAsFeatureLayerForDissolves, 'NEW_SELECTION', multiSelectionQuery) # 9.) Else, spatially select features in the original feature class with 'SHARE_A_LINE_SEGMENT_WITH'. SelectLayerByLocation_management( fcAsFeatureLayerForDissolves, 'SHARE_A_LINE_SEGMENT_WITH', dissolveOutFC, 0, 'SUBSET_SELECTION') # 10.) Count to make sure that at least one feature is selected. countResult2 = GetCount_management( fcAsFeatureLayerForDissolves) intCount2 = int(countResult2.getOutput(0)) print( 'There were ' + str(intCount2) + ' features selected for replacement in the fcAsFeatureLayerForDissolves layer.' ) if intCount2 >= 1: # 11.) If so, cursor the features out of the dissolve layer. featureList = list() searchCursorFields = [ str(lrsKeyToUse), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX', 'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT', 'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R', 'SHAPE@' ] newCursor = daSearchCursor(dissolveOutFC, searchCursorFields) for cursorItem in newCursor: featureList.append(list(cursorItem)) try: del newCursor except: pass # 12.) Delete the selected features in the input layer. try: DeleteFeatures_management( fcAsFeatureLayerForDissolves) except: print( "Could not delete features for the selection " + str(multiSelectionQuery) + ".") # 13.) Insert the features from the dissolve layer into the copy of the centerlines. insertCursorFields = [ str(lrsKeyToUse), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX', 'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT', 'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R', 'SHAPE@' ] newCursor = daInsertCursor( fcAsFeatureLayerForDissolves, insertCursorFields) for featureItem in featureList: newCursor.insertRow(featureItem) try: del newCursor except: pass try: del featureList except: pass else: pass multiSelectionQuery = ''' "''' + str( lrsKeyToUse) + '''" IS NOT NULL AND "''' + str( lrsKeyToUse) + '''" IN (''' multiCounter = 0 ### -shouldbeafunctionblock#1- ### # After the for loop, if there is still anything remaining which was unselected in the # the previous multiSelectionQuery steps. # Remove the trailing ", " and add a closing parenthesis. if multiSelectionQuery != multiSelectionQueryBase: multiSelectionQuery = multiSelectionQuery[:-2] + """) """ else: # The selection query would not select anything. return SelectLayerByAttribute_management(fcAsFeatureLayerForDissolves, "NEW_SELECTION", multiSelectionQuery) # Then redo from step 5 on at the end of the loop IF there is anything left to select # which was not selected... so if selectionCounter != 0. ### -shouldbeafunctionblock#2- ### # 5.) Count selected features. countResult0 = GetCount_management(fcAsFeatureLayerForDissolves) intCount0 = int(countResult0.getOutput(0)) if intCount0 >= 1: # 6.) Make a new layer or dissolved layer from this selection. -- Question about fields. Dissolve_management(fcAsFeatureLayerForDissolves, dissolveOutFC, multiDissolveFields, multiStatsFields, singlePart, unsplitLines) # 7.) Count the number of dissolved features. countResult1 = GetCount_management(dissolveOutFC) intCount1 = int(countResult1.getOutput(0)) print('Counted ' + str(intCount1) + ' features returned for that dissolve.') # 8a.) If the number of dissolved features is 0, then append the error to the error file # and go on to the next LRS Key in the loop. if intCount1 == 0: with open(dissolveErrorsFile, 'a') as errorFile: errorFile.write(str(multiSelectionQuery)) # 8b.) From the spatial select, select the subset of features that also have a matching LRS Key. else: SelectLayerByAttribute_management(fcAsFeatureLayerForDissolves, 'NEW_SELECTION', multiSelectionQuery) # 9.) Else, spatially select features in the original feature class with 'SHARE_A_LINE_SEGMENT_WITH'. SelectLayerByLocation_management(fcAsFeatureLayerForDissolves, 'SHARE_A_LINE_SEGMENT_WITH', dissolveOutFC, 0, 'SUBSET_SELECTION') # 10.) Count to make sure that at least one feature is selected. countResult2 = GetCount_management(fcAsFeatureLayerForDissolves) intCount2 = int(countResult2.getOutput(0)) print( 'There were ' + str(intCount2) + ' features selected in the fcAsFeatureLayerForDissolves layer.' ) if intCount2 >= 1: # 11.) If so, cursor the features out of the dissolve layer. featureList = list() searchCursorFields = [ str(lrsKeyToUse), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX', 'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT', 'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R', 'SHAPE@' ] newCursor = daSearchCursor(dissolveOutFC, searchCursorFields) for cursorItem in newCursor: featureList.append(list(cursorItem)) try: del newCursor except: pass # 12.) Delete the selected features in the input layer. try: DeleteFeatures_management(fcAsFeatureLayerForDissolves) except: print("Could not delete features for the selection " + str(multiSelectionQuery) + ".") # 13.) Insert the features from the dissolve layer into the copy of the centerlines. insertCursorFields = [ str(lrsKeyToUse), 'LRS_COUNTY_PRE', 'LRS_ROUTE_PREFIX', 'LRS_ROUTE_NUM', 'LRS_ROUTE_SUFFIX', 'LRS_UNIQUE_IDENT', 'LRS_UNIQUE_IDENT1', 'KDOT_COUNTY_L', 'KDOT_COUNTY_R', 'SHAPE@' ] newCursor = daInsertCursor(fcAsFeatureLayerForDissolves, insertCursorFields) for featureItem in featureList: newCursor.insertRow(featureItem) try: del newCursor except: pass try: del featureList except: pass else: pass
def compute_adjacency_list(input_points, input_network, id_attribute, impedance_attribute, accumulator_attributes, search_radius, output_location, adj_dbf_name): """ |input_points|: point shape file marking entity (e.g. building) locations |input_network|: street network in which |input_points| is located |id_attribute|: the name of attribute that distinguishes between input points |impedance_attribute|: distance between neighboring nodes will be based on this attribute |accumulator_attributes|: distance between neighboring nodes will also be recorded for these attributes |search_radius|: the maximum extent for centrality computation |output_location|: adjacency list dbf will be saved here |adj_dbf_name|: the name of the adjacency list dbf """ # Number of points in |input_points| input_point_count = int(GetCount_management(input_points).getOutput(0)) # Make a directory to store all auxiliary files auxiliary_dir = join(output_location, AUXILIARY_DIR_NAME) if not Exists(auxiliary_dir): mkdir(auxiliary_dir) # Record the edge and junction source names of |input_network| junction_feature, edge_feature = network_features(input_network) # Calculate network locations if not already calculated test_input_point = UpdateCursor(input_points).next() locations_calculated = all( row_has_field(test_input_point, field) for field in NETWORK_LOCATION_FIELDS) if not locations_calculated: calculate_network_locations(input_points, input_network) # Calculate barrier cost per input point if not already calculated barrier_costs_calculated = row_has_field(test_input_point, trim(BARRIER_COST_FIELD)) if not barrier_costs_calculated: AddMessage(BARRIER_COST_COMPUTATION_STARTED) # Add |BARRIER_COST_FIELD| column in |input_points| AddField_management(in_table=input_points, field_name=trim(BARRIER_COST_FIELD), field_type="DOUBLE", field_is_nullable="NON_NULLABLE") # Initialize a dictionary to store the frequencies of (SnapX, SnapY) values xy_count = {} # A method to retrieve a (SnapX, SnapY) pair for a row in |input_points| get_xy = lambda row: (row.getValue(trim("SnapX")), row.getValue(trim("SnapY"))) barrier_pre_progress = Progress_Bar(input_point_count, 1, BARRIER_COST_PRE_PROCESSING) rows = UpdateCursor(input_points) for row in rows: snap_xy = get_xy(row) if snap_xy in xy_count: xy_count[snap_xy] += 1 else: xy_count[snap_xy] = 1 barrier_pre_progress.step() # Populate |BARRIER_COST_FIELD|, this will be used in OD matrix computation barrier_progress = Progress_Bar(input_point_count, 1, BARRIER_COST_COMPUTATION) rows = UpdateCursor(input_points) for row in rows: barrier_cost = BARRIER_COST / xy_count[get_xy(row)] row.setValue(trim(BARRIER_COST_FIELD), barrier_cost) rows.updateRow(row) barrier_progress.step() AddMessage(BARRIER_COST_COMPUTATION_FINISHED) # Necessary files od_cost_matrix_layer = join(auxiliary_dir, OD_COST_MATRIX_LAYER_NAME) od_cost_matrix_lines = join(od_cost_matrix_layer, OD_COST_MATRIX_LINES) temp_adj_dbf_name = TEMP_ADJACENCY_DBF_NAME(adj_dbf_name) temp_adj_dbf = join(output_location, temp_adj_dbf_name) adj_dbf = join(output_location, adj_dbf_name) partial_adj_dbf = join(auxiliary_dir, PARTIAL_ADJACENCY_LIST_NAME) polygons = join(auxiliary_dir, POLYGONS_SHAPEFILE_NAME) raster = join(auxiliary_dir, RASTER_NAME) polygons_layer = join(auxiliary_dir, POLYGONS_LAYER_NAME) input_points_layer = join(auxiliary_dir, INPUT_POINTS_LAYER_NAME) # Make sure none of these files already exists for path in [ od_cost_matrix_layer, temp_adj_dbf, adj_dbf, partial_adj_dbf, polygons, raster, polygons_layer, input_points_layer, od_cost_matrix_lines ]: delete(path) # Cutoff radius for OD matrix computation cutoff_radius = 2 * BARRIER_COST + min(search_radius, BARRIER_COST / 2) # Compute OD matrix MakeODCostMatrixLayer_na(in_network_dataset=input_network, out_network_analysis_layer=od_cost_matrix_layer, impedance_attribute=impedance_attribute, default_cutoff=str(cutoff_radius), accumulate_attribute_name=accumulator_attributes, UTurn_policy="ALLOW_UTURNS", hierarchy="NO_HIERARCHY", output_path_shape="NO_LINES") # Determine raster cell size points_per_raster_cell = OD_MATRIX_ENTRIES / input_point_count raster_cell_count = max(1, input_point_count / points_per_raster_cell) input_points_extent = Describe(input_points).Extent raster_cell_area = (input_points_extent.width * input_points_extent.height / raster_cell_count) raster_cell_size = int(sqrt(raster_cell_area)) # Construct |raster| from |input_points| PointToRaster_conversion(in_features=input_points, value_field=id_attribute, out_rasterdataset=raster, cell_assignment="MOST_FREQUENT", priority_field="NONE", cellsize=str(raster_cell_size)) # Construct |polygons| from |raster| RasterToPolygon_conversion(in_raster=raster, out_polygon_features=polygons, simplify="NO_SIMPLIFY", raster_field="VALUE") # Export empty |od_cost_matrix_lines| to |temp_dbf| to start adjacency list TableToTable_conversion(in_rows=od_cost_matrix_lines, out_path=output_location, out_name=temp_adj_dbf_name) # Construct |polygons_layer| and |input_points_layer| for (feature, layer) in [(polygons, polygons_layer), (input_points, input_points_layer)]: MakeFeatureLayer_management(in_features=feature, out_layer=layer) def add_locations(sub_layer, field_mappings=""): """ |sub_layer|: one of "Origins", "Destinations", "Barrier Points" |field_mappings|: field mappings in addition to those for "Name" and "CurbApproach" """ AddLocations_na(in_network_analysis_layer=od_cost_matrix_layer, sub_layer=sub_layer, in_table=input_points_layer, field_mappings=("Name %s #; CurbApproach # 0; %s" % (id_attribute, field_mappings)), search_tolerance=SEARCH_TOLERANCE, search_criteria=("%s SHAPE; %s SHAPE;" % (junction_feature, edge_feature)), append="CLEAR", snap_to_position_along_network="SNAP", snap_offset=SNAP_OFFSET) # OD cost matrix destinations AddMessage(ADDING_DESTINATIONS_STARTED) SelectLayerByLocation_management(in_layer=input_points_layer) add_locations("Destinations") AddMessage(ADDING_DESTINATIONS_FINISHED) # OD cost matrix point barriers AddMessage(ADDING_BARRIERS_STARTED) add_locations("Point Barriers", ("FullEdge # 0; BarrierType # 2;" "Attr_%s %s #;" % (impedance_attribute, trim(BARRIER_COST_FIELD)))) AddMessage(ADDING_BARRIERS_FINISHED) # Compute adjacency list, one raster cell at a time progress = Progress_Bar(raster_cell_count, 1, STEP_1) rows = UpdateCursor(polygons) for row in rows: # Select the current polygon SelectLayerByAttribute_management(in_layer_or_view=polygons_layer, selection_type="NEW_SELECTION", where_clause="FID = %s" % str(row.FID)) # Origins SelectLayerByLocation_management(in_layer=input_points_layer, select_features=polygons_layer) add_locations("Origins") # Solve OD Cost matrix Solve_na(in_network_analysis_layer=od_cost_matrix_layer, ignore_invalids="SKIP") # Add origin and destination fields to the adjacency list dbf for (index, field) in [(0, ORIGIN_ID_FIELD_NAME), (1, DESTINATION_ID_FIELD_NAME)]: CalculateField_management(in_table=od_cost_matrix_lines, field=field, expression="!Name!.split(' - ')[%d]" % index, expression_type="PYTHON") # Record actual distance between neighboring nodes distance_field = "Total_%s" % impedance_attribute CalculateField_management(in_table=od_cost_matrix_lines, field=distance_field, expression="!%s! - 2 * %d" % (distance_field, BARRIER_COST), expression_type="PYTHON") # Append result to |temp_adj_dbf| TableToTable_conversion(in_rows=od_cost_matrix_lines, out_path=auxiliary_dir, out_name=PARTIAL_ADJACENCY_LIST_NAME) Append_management(inputs=partial_adj_dbf, target=temp_adj_dbf, schema_type="TEST") progress.step() # Copy data from |temp_adj_dbf| to |adj_dbf| Rename_management(in_data=temp_adj_dbf, out_data=adj_dbf) # Clean up for path in [ od_cost_matrix_layer, partial_adj_dbf, polygons, raster, polygons_layer, input_points_layer, auxiliary_dir ]: delete(path)
# Name and field of city geography data cities = "CityBoundaries" nameField = "HasParkAndRide" # Name of park/ride geography data parkAndRide = "ParkAndRide" # Try make layers try: # Make a city layer and park/ride layer MakeFeatureLayer_management(cities,"CityBoundaries_lyr") MakeFeatureLayer_management(parkAndRide,"ParkAndRide_lry") # Select only the cities that contain point of park and ride SelectLayerByLocation_management("CityBoundaries_lyr", "CONTAINS", "ParkAndRide_lry") # If happen some error except: # Show the massage print 'It not possible to make a layer' # Try update field try: # Select the field HasParkAndRide of CityBoundaries layer with UpdateCursor("CityBoundaries_lyr", (nameField,)) as cursor: # For each row in field for row in cursor: