def create_team_subtype(gdb, fc, subtype_dict): # Process: Set Subtype Field... arcpy.SetSubtypeField_management(os.path.join(gdb, fc), "TEAM_ID") # use a for loop to cycle through the dictionary for code in subtype_dict: arcpy.AddSubtype_management(os.path.join(gdb, fc), code, subtype_dict[code])
def addSubtypes(schemasFolder, schema, featureClass, fieldName): # Sets the field used to determine the subtype of each feature # Populates the subtypes for the specified feature class try: arcpy.AddMessage("Starting: AddSubtypes") # Initialize a dict subTypes = {} # Set the subtype field arcpy.SetSubtypeField_management(featureClass, fieldName) # Populate the subtypes from the provided subtype schema file subtypesSchemaFile = os.path.join(schemasFolder, "Subtypes_" + schema + ".csv") if os.path.exists(subtypesSchemaFile): with open(subtypesSchemaFile, 'r') as csvFile: reader = csv.reader(csvFile, dialect='excel') # Skip the headers header = next(reader) defaultSubtype = 0 isFirst = True # Read the lines and add them as subtypes for line in reader: arcpy.AddSubtype_management(featureClass, int(line[0]), line[1]) subTypes[line[0]] = line[1] if isFirst == True: # Set the default subtype value arcpy.SetDefaultSubtype_management( featureClass, int(line[0])) isFirst = False except Exception as err: arcpy.AddError( traceback.format_exception_only(type(err), err)[0].rstrip()) else: arcpy.AddMessage("Success! - Completed: AddSubtypes") finally: arcpy.AddMessage("Exiting: AddSubtypes") return subTypes
def set_gsi_subtype(input_feature_class, field): arcpy.SetSubtypeField_management(input_feature_class, field) # Store all the subtype values in a dictionary with the subtype code as the "key" and the # subtype description as the "value" (subtypeDict[code]) gsi_subtype_dict = {"1": "TRENCH", "2": "BUMPOUT", "3": "RAIN GARDEN", "4": "WETLAND", \ "5": "BASIN", "6": "TREE TRENCH", "7": "PLANTER", "8": "PERVIOUS PLANTER", \ "9": "SWALE", "10": "GREEN ROOF", "11": "CISTERN"} for code in gsi_subtype_dict: arcpy.AddSubtype_management(input_feature_class, code, gsi_subtype_dict[code]) # Set Default Subtype... arcpy.SetDefaultSubtype_management(input_feature_class, "1")
def create_mdb_DateBase(self): """ Create *mdb DataBase with DateSet, and polyline layer with fields ("Name_ATE", "Name", "Name_EVA", "ID_ATE", "ID_EVA"). Set sybtype for field "Name_ATE" and add sybtypes. :return: DateBase """ # create mdb arcpy.CreatePersonalGDB_management( self.work_path, '{0}_streets.mdb'.format(self.name_district)) # create dataset Streets arcpy.CreateFeatureDataset_management(self.nameDataBase, "Streets", wgs84) # create shp Streets arcpy.CreateFeatureclass_management(self.nameDataSet, "Streets", "POLYLINE", "", "DISABLED", "DISABLED", wgs84, "", "0", "0", "0") # create fields in shp Streets arcpy.AddField_management(self.nameStreets, "Name_ATE", "LONG", "", "", "", "", "NULLABLE", "REQUIRED", "") arcpy.AddField_management(self.nameStreets, "Name", "LONG", "", "", "", "", "NULLABLE", "REQUIRED", "") arcpy.AddField_management(self.nameStreets, "Name_EVA", "LONG", "", "", "", "", "NULLABLE", "REQUIRED", "") arcpy.AddField_management(self.nameStreets, "ID_ATE", "LONG", "", "", "", "", "NULLABLE", "REQUIRED", "") arcpy.AddField_management(self.nameStreets, "ID_EVA", "LONG", "", "", "", "", "NULLABLE", "REQUIRED", "") # set Sybtypefield - Name_ATE arcpy.SetSubtypeField_management(self.nameStreets, "Name_ATE") # create sybtypes in DateBase if self.name_district != "Минск": for element in self.new_dict_syptypes.items(): arcpy.AddSubtype_management(self.nameStreets, element[1][0], element[0]) else: arcpy.AddSubtype_management(self.nameStreets, 17030, 'Минск')
def detruireDomaineAttribut(self, workspace, classe): #------------------------------------------------------------------------------------- """ Permet de détruire tous les domaines existants dans la Géodatabase. Paramètres: ----------- workspace : Nom de la géodatabase ou les domaines seront détruits. classe : Liste des noms de classe contenus dans la géodatabase utilisés pour créer les domaines. """ #Définir le workspace par défaut arcpy.env.workspace = workspace #Extraire les FeatureClass de la Géodatabase for fc in arcpy.ListFeatureClasses(): #Vérifier si la classe est présente dans la liste des classes if fc.upper() in classe: #Afficher le message pour détruire les domaines de la classe traité arcpy.AddMessage(" ") arcpy.AddMessage(u"- Détruire les subtypes de la classe : " + fc) #Définir tous les Subtypes subtypes = arcpy.da.ListSubtypes(fc) #Vérifier si un Subtype est présent if subtypes.values()[0]['SubtypeField'] <> "": #Afficher le message arcpy.AddMessage("SetSubtypeField_management('" + fc + "', #, True)") #Enlever les subtypes d'une classe arcpy.SetSubtypeField_management(fc, "#", True) #Afficher les subtypes #for stcode, stdict in list(subtypes.items()): #Afficher le message #arcpy.AddMessage(" RemoveSubtype_management('" + fc + "', '" + str(stcode) + "')") #Détruire un subtype d'une classe #arcpy.RemoveSubtype_management(fc, stcode) #Afficher le message pour détruire les domaines de la classe traité arcpy.AddMessage(u"- Détruire le domaine et la valeur par défaut pour chaque attribut de la classe : " + fc) #Traiter tous les fields for field in arcpy.ListFields(fc): #Vérifier la présence d'un domaine if field.domain <> "": #Afficher le message arcpy.AddMessage("RemoveDomainFromField_management('" + fc + "', '" + field.name + "')") #Détruire un domaine dans un attribut d'une classe arcpy.RemoveDomainFromField_management(fc, field.name) #Vérifier si une valeur par défaut est présente if field.defaultValue <> None: #Afficher le message arcpy.AddMessage("AssignDefaultToField_management('" + fc + "', '" + field.name + "' # # True)") #Détruire la valeur par défaut de l'attribut d'une classe arcpy.AssignDefaultToField_management(fc, field.name, "#", "#", True) #Extraire les tables de la Géodatabase for tbl in arcpy.ListTables(): #Vérifier si la table est présente dans la liste des classes if tbl.upper() in classe: #Afficher le message pour détruire les domaines de la classe traité arcpy.AddMessage(" ") arcpy.AddMessage(u"- Détruire les subtypes de la table : " + tbl) #Définir tous les Subtypes subtypes = arcpy.da.ListSubtypes(tbl) #Vérifier si un Subtype est présent if subtypes.values()[0]['SubtypeField'] <> "": #Afficher le message arcpy.AddMessage("SetSubtypeField_management('" + tbl + "', #, True)") #Enlever les subtypes d'une classe arcpy.SetSubtypeField_management(tbl, "#", True) #Afficher les subtypes #for stcode, stdict in list(subtypes.items()): #Afficher le message #arcpy.AddMessage(" RemoveSubtype_management('" + tbl + "', '" + str(stcode) + "')") #Détruire un subtype d'une table #arcpy.RemoveSubtype_management(tbl, stcode) #Afficher le message pour détruire les domaines de la classe traité arcpy.AddMessage(u"- Détruire le domaine et la valeur par défaut pour chaque attribut de la table : " + tbl) #Traiter tous les fields for field in arcpy.ListFields(tbl): #Vérifier la présence d'un domaine if field.domain <> "": #Afficher le message arcpy.AddMessage("RemoveDomainFromField_management('" + tbl + "', '" + field.name + "')") #Détruire un domaine dans un attribut d'une classe arcpy.RemoveDomainFromField_management(tbl, field.name) #Vérifier si une valeur par défaut est présente if field.defaultValue <> None: #Afficher le message arcpy.AddMessage("AssignDefaultToField_management('" + tbl + "', '" + field.name + "' # # True)") #Détruire la valeur par défaut de l'attribut d'une table arcpy.AssignDefaultToField_management(tbl, field.name, "#", "#", True) #Envoyer un message arcpy.AddMessage(" ") arcpy.AddMessage(u"- Détruire les domaines non-utilisés dans la Géodatabase") #Extraire la description de la Géodatabase desc = arcpy.Describe(workspace) #Extraire tous les domaines existants de la Géodatabase domains = desc.domains #Traiter tous les domaines for domain in domains: try: #Détruire un domaine arcpy.DeleteDomain_management(workspace, domain) #Afficher le message arcpy.AddMessage("DeleteDomain_management('" + workspace + "', '" + domain + "')") #Gestion des erreurs except Exception, err: #Afficher l'erreur arcpy.AddWarning(u"Le domaine est encore utilisé et ne peut être détruit : " + domain)
def main(): #### Create a folder based on the date (ie: Year_Month_Day = 2018_4_16) now = datetime.datetime.now() year = now.year month = now.month day = now.day folder_name = str(year) + "_" + str(month) + "_" + str(day) # create the folder print "Creating Directory..." directory = "C:\\Users\\gbunce\\Documents\\projects\\NetworkDataset\\RecentBuilds\\" + folder_name if not os.path.exists(directory): print "Creating Directory: " + str(directory) + " ..." os.makedirs(directory) else: print "Directory: " + str(directory) + " exists." # create new fgdb print "Creating File Geodatabase..." network_fgdb = arcpy.CreateFileGDB_management(directory, 'UtahRoadsNetworkAnalysis.gdb') # create dataset in the fgdb print "Creating Feature Dataset..." arcpy.CreateFeatureDataset_management(network_fgdb, 'NetworkDataset', sgid_roads) # import the sgid roads fc print "Importing SGID Roads ..." #expression = "ZIPCODE_L in ('84108', '84106', '84105')" ##TESTING STUFF## expression = "" network_roads = arcpy.FeatureClassToFeatureClass_conversion(sgid_roads, str(network_fgdb) + r'/NetworkDataset', 'Roads', expression) ## add the needed fields ## print "Add needed network fields to fgdb road data" arcpy.AddField_management(network_roads,"NETSUBTYPE", "SHORT", "","","") arcpy.AddField_management(network_roads,"USEEXIST", "TEXT", "","","1") arcpy.AddField_management(network_roads,"URBTRAFFIC", "TEXT", "","","1") arcpy.AddField_management(network_roads,"EXCL_WALK", "TEXT", "","","1") arcpy.AddField_management(network_roads,"IMPED_MIN","DOUBLE","6","2") arcpy.AddField_management(network_roads,"F_T_IMP_MIN","DOUBLE","6","2") arcpy.AddField_management(network_roads,"T_F_IMP_MIN","DOUBLE","6","2") arcpy.AddField_management(network_roads,"IMPED_PED","DOUBLE","6","2") #arcpy.AddField_management(network_roads,"STARTX","DOUBLE","7","1") # add geometry attributes below, instead #arcpy.AddField_management(network_roads,"ENDX","DOUBLE","7","1") # add geometry attributes below, instead #arcpy.AddField_management(network_roads,"STARTY","DOUBLE","7","1") # add geometry attributes below, instead #arcpy.AddField_management(network_roads,"ENDY","DOUBLE","7","1") # add geometry attributes below, instead #arcpy.CalculateGeometryAttributes_management(network_roads, [["STARTX", "LINE_START_X"], ["ENDX", "LINE_END_X"]]) # add geometry attributes below, instead ## Add geometry fields with start and end XY values ## # but, do this for only limited access roads arcpy.MakeFeatureLayer_management(network_roads, 'network_roads_lyr', "DOT_HWYNAM <> ''") arcpy.AddGeometryAttributes_management('network_roads_lyr', "LINE_START_MID_END") arcpy.Delete_management('network_roads_lyr') ## create the needed scratch data (ie: the urban areas) and assign the segments that intersect the urban bounaries with an URBTRAFFIC = Yes or No ## urban_areas = generate_scratch_data(directory) #arcpy.MakeFeatureLayer_management(urban_areas, 'urban_areas_lyr') arcpy.MakeFeatureLayer_management(network_roads, 'network_roads_lyr') urban_roads_selected = arcpy.SelectLayerByLocation_management('network_roads_lyr', 'intersect', urban_areas) # 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 arcpy.CalculateField_management(urban_roads_selected, field="URBTRAFFIC", expression='"Y"', expression_type='VB', code_block='') # calculte the segments that were not in an urban area to "N" urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "URBTRAFFIC is NULL") arcpy.CalculateField_management(urban_roads_selected, field="URBTRAFFIC", expression='"N"', expression_type='VB', code_block='') ## begin calculating the field values ## ## USEEXIST ## print "Calculate USEEXIST fields..." # Yes urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "not (SPEED_LMT is null) and ( SPEED_LMT >= 5 and SPEED_LMT <= 80)") arcpy.CalculateField_management(urban_roads_selected, field="USEEXIST", expression='"Y"', expression_type='VB', code_block='') # No - also set SPEED_LMT to 25 for these records as well urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "USEEXIST is null or USEEXIST <> '1'") arcpy.CalculateField_management(urban_roads_selected, field="USEEXIST", expression='"N"', expression_type='VB', code_block='') arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='25', expression_type='VB', code_block='') ## SPEED_LMT ## print "Calculate speed limits..." # 70 mph - UDOT limited access highway and freeways urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "CARTOCODE = '1' OR ((DOT_RTNAME = '0201P' OR DOT_RTNAME = '0201N') and CARTOCODE = '4') OR CARTOCODE = '2'") arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='70', expression_type='VB', code_block='') # 65 mph - major state and US highways urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(CARTOCODE = '2' OR CARTOCODE = '3' OR CARTOCODE = '4' OR CARTOCODE = '5') AND USEEXIST = 'N'") arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='65', expression_type='VB', code_block='') # 55 mph - UDOT freeway collectors/feeders urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "DOT_RTNAME like '%C%' and (USEEXIST is null or USEEXIST <> 'Y')") arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='55', expression_type='VB', code_block='') # 40 mph - UDOT ramps urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "DOT_RTNAME like '%R%' and (USEEXIST is null or USEEXIST <> 'Y')") arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='40', expression_type='VB', code_block='') # 50 mph - invalid speeds on major local roads urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(USEEXIST is null or USEEXIST <> 'Y') AND ( CARTOCODE = '8')") arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='55', expression_type='VB', code_block='') # 45 mph - unpaved major roads urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(USEEXIST is null or USEEXIST <> 'Y') AND ( CARTOCODE = '9')") arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='45', expression_type='VB', code_block='') # downgrade speeds all non-divided major local and major highways in the urban buffer to 40 mph. However, exclude Timp Highway, MountainView, Legacy, Bangerter Highway and fast portion of US 89 in Davis County urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(CARTOCODE = '2' OR CARTOCODE = '3' OR CARTOCODE = '4' OR CARTOCODE = '5' OR CARTOCODE = '8' OR CARTOCODE = '9') AND URBTRAFFIC = 'Y' AND NOT (DOT_RTNAME = '0201P' OR DOT_RTNAME = '0201N' OR DOT_RTNAME = '0154P' or DOT_RTNAME = '0154N' OR DOT_RTNAME = '0085P' or DOT_RTNAME = '0085N' or (DOT_RTNAME Like '0%' and (CARTOCODE = '2' or CARTOCODE = '4')) or DOT_RTNAME LIKE '0092PC%' or DOT_RTNAME LIKE '0092NC%' or (DOT_RTNAME LIKE '0089%' and DOT_RTPART = '10'))") arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='40', expression_type='VB', code_block='') # downgrade the speeds on all freeways in settled areas to 65 urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(CARTOCODE = '1' OR ((DOT_RTNAME = '0201P' OR DOT_RTNAME = '0201N') and CARTOCODE = '4') OR CARTOCODE = '2') and URBTRAFFIC = 'Y'") arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='65', expression_type='VB', code_block='') ## Fix roads with a speed limit of zero # apply manual corrections - US89 , Timp Highway collector urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "DOT_RTNAME like '0092%' and DOT_RTNAME like '%C%'") arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='65', expression_type='VB', code_block='') urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "DOT_RTNAME like '0085%'") arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='55', expression_type='VB', code_block='') urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "DOT_RTNAME like '0154%'") arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='55', expression_type='VB', code_block='') #### PART 2: Calculate Travel Cost Impedance #### print "Calculate Travel Cost Impedance..." # calculate impedance (in minutes) for all ramp-accessed roads (freeways) urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "CARTOCODE = '1' or CARTOCODE = '2' or CARTOCODE = '4' or DOT_RTNAME like '%R%' or DOT_RTNAME like '%C%' or URBTRAFFIC = 'N'") arcpy.CalculateField_management(urban_roads_selected, field="IMPED_MIN", expression='([SHAPE_Length]/1609 * 60) / [SPEED_LMT]', expression_type='VB', code_block='') # switch selection and calculate the impedance (in minutes) for all traffic controlled roads by increasing the travel time by a factor of 1.5 to account for stop signs, signals, and turns urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','SWITCH_SELECTION') arcpy.CalculateField_management(urban_roads_selected, field="IMPED_MIN", expression='([SHAPE_Length]/1609 * 60) / [SPEED_LMT] * 1.5', expression_type='VB', code_block='') arcpy.CalculateField_management(urban_roads_selected, field="IMPED_PED", expression='[SHAPE_Length] / 84', expression_type='VB', code_block='') # select limited access roadways (ie: freeways/ramps) and multiply by 1.2 urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "CARTOCODE = '1' OR ((DOT_RTNAME = '0201P' OR DOT_RTNAME = '0201N') and CARTOCODE = '4') OR CARTOCODE = '2' or CARTOCODE = '7'") arcpy.CalculateField_management(urban_roads_selected, field="IMPED_MIN", expression='([SHAPE_Length]/1609 * 60) / [SPEED_LMT] * 1.2', expression_type='VB', code_block='') ## impedance needed to be be set differently for each direction on one way streets and routes. Check to see if ONE_WAY attributes for limited access freeways/highways need to be fixed print "Calculate one ways..." # for both directions of travel on I-215 (semi-looping), set the ONE_WAY attribute using manual selection so that all features oriented in the true direction of travel are set to 1 and the others to 2 # oneway codes [0 = Two way travel; 1 = One way travel in direction of arc; 2 = One way travel in opposite direction of arc] # set oneway to '1' urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0215N' and DOT_F_MILE > DOT_T_MILE) or (DOT_RTNAME = '0215P' and DOT_F_MILE < DOT_T_MILE)") arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='1', expression_type='VB', code_block='') # set oneway to '2' urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0215N' and DOT_F_MILE < DOT_T_MILE) or (DOT_RTNAME = '0215P' and DOT_F_MILE > DOT_T_MILE)") arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='2', expression_type='VB', code_block='') ## For the positive (eastbound) travel direction for x (E-W) trending routes # query the coordinate values for these selected records (using two temporary fields populated by the calculate geometry field tool), to set the ONE_WAY attribute for these selected records as follows: # where x coordinate at start point is < then x coordinate at end point: set oneway = 1 urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0080P' or DOT_RTNAME = '0084P' or DOT_RTNAME = '0070P' or (DOT_RTNAME = '0201P' and DOT_RTPART = '2' ) or (DOT_RTNAME = '0007P' and DOT_RTPART = '2')) and START_X < END_X") arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='1', expression_type='VB', code_block='') # where x coordinate at start point is > then x coordinate at end point: set oneway = 2 urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0080P' or DOT_RTNAME = '0084P' or DOT_RTNAME = '0070P' or (DOT_RTNAME = '0201P' and DOT_RTPART = '2' ) or (DOT_RTNAME = '0007P' and DOT_RTPART = '2')) and START_X > END_X") arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='2', expression_type='VB', code_block='') ## For the negative (westbound) travel direction for X Trending (E-W) routes # Query the coordinate values for these selected records (using two temporary fields populated by the calculate geometry field tool), to set the ONE_WAY attribute for these selected records as follows: # where x coordinate at start point is > then x coordinate at end point: set oneway = 1 urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0080N' or DOT_RTNAME = '0084N' or DOT_RTNAME = '0070N' or DOT_RTNAME = '0201N' or DOT_RTNAME = '0007N') and START_X > END_X") arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='1', expression_type='VB', code_block='') # where x coordinate at start point is < then x coordinate at end point: set oneway = 2 urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0080N' or DOT_RTNAME = '0084N' or DOT_RTNAME = '0070N' or DOT_RTNAME = '0201N' or DOT_RTNAME = '0007N') and START_X < END_X") arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='2', expression_type='VB', code_block='') ## For the positive (northbound) travel direction for Y Trending (N-S) routes # Query the coordinate values for these selected records (using two temporary fields populated by the calculate geometry field tool), to set the ONE_WAY attribute for these selected records as follows: # where y coordinate at start point is < then y coordinate at end point: set oneway = 1 urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0015P' or (DOT_RTNAME = '0152P' and DOT_RTPART ='2') or (DOT_RTNAME = '0154P' and DOT_RTPART ='2') or DOT_RTNAME = '0067P' or (DOT_RTNAME = '0189P' and DOT_RTPART ='2') or (DOT_RTNAME = '0191P' and DOT_RTPART ='2') or (DOT_RTNAME = '0089P' and (DOT_RTPART ='4' or DOT_RTPART ='7' or DOT_RTPART ='9' or DOT_RTPART ='11'))) and START_Y < END_Y") arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='1', expression_type='VB', code_block='') # where y coordinate at start point is > then y coordinate at end point: set oneway = 2 urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0015P' or (DOT_RTNAME = '0152P' and DOT_RTPART ='2') or (DOT_RTNAME = '0154P' and DOT_RTPART ='2') or DOT_RTNAME = '0067P' or (DOT_RTNAME = '0189P' and DOT_RTPART ='2') or (DOT_RTNAME = '0191P' and DOT_RTPART ='2') or (DOT_RTNAME = '0089P' and (DOT_RTPART ='4' or DOT_RTPART ='7' or DOT_RTPART ='9' or DOT_RTPART ='11'))) and START_Y > END_Y") arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='2', expression_type='VB', code_block='') ## For the negative (southbound) travel direction for south north (y) trending routes and exception for a couple sections of us40 and us6 # Query the coordinate values for these selected records (using two temporary fields populated by the calculate geometry field tool), to set the ONE_WAY attribute for these selected records as follows: # where y coordinate at start point is > then y coordinate at end point: set oneway = 1 urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0015N' or DOT_RTNAME = '0152N' or DOT_RTNAME = '0154N' or DOT_RTNAME = '0067N' or DOT_RTNAME = '0189N' or DOT_RTNAME = '0191N ' or DOT_RTNAME = '0040N' or DOT_RTNAME = '0006N' or DOT_RTNAME = '0089N' or (DOT_RTNAME = '0040P' and DOT_RTPART ='2') or (DOT_RTNAME = '0006P' and DOT_RTPART ='3')) and START_Y > END_Y") arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='1', expression_type='VB', code_block='') # where y coordinate at start point is < then y coordinate at end point: set oneway = 2 urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0015N' or DOT_RTNAME = '0152N' or DOT_RTNAME = '0154N' or DOT_RTNAME = '0067N' or DOT_RTNAME = '0189N' or DOT_RTNAME = '0191N ' or DOT_RTNAME = '0040N' or DOT_RTNAME = '0006N' or DOT_RTNAME = '0089N' or (DOT_RTNAME = '0040P' and DOT_RTPART ='2') or (DOT_RTNAME = '0006P' and DOT_RTPART ='3')) and START_Y < END_Y") arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='2', expression_type='VB', code_block='') ## Calculate the travel cost fields and then inflate the travel cost for the wrong direction of travel on one way segments by a large factor (100 x current impedance is currently used) print "Calculate T_F_IMP_MIN and F_T_IMP_MIN values..." # Transfer over all IMPED_MIN values to both T_F_IMP_MIN and F_T_IMP_MIN fields. # clear selection urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','CLEAR_SELECTION') arcpy.CalculateField_management(urban_roads_selected, field="T_F_IMP_MIN", expression='[IMPED_MIN]', expression_type='VB', code_block='') arcpy.CalculateField_management(urban_roads_selected, field="F_T_IMP_MIN", expression='[IMPED_MIN]', expression_type='VB', code_block='') # Now, inflate the travel time on one ways... # Select all roads where the ONEWAY attribute = 1 urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "ONEWAY = '1'") arcpy.CalculateField_management(urban_roads_selected, field="T_F_IMP_MIN", expression='[IMPED_MIN] * 100', expression_type='VB', code_block='') # Select all roads where the ONEWAY attribute = 2 urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "ONEWAY = '2'") arcpy.CalculateField_management(urban_roads_selected, field="F_T_IMP_MIN", expression='[IMPED_MIN] * 100', expression_type='VB', code_block='') ## Part 3 - Build the network dataset # Create 2 different values for the NETSUBTYPE field so connectivity can be modeled at endpoints for limited access highways and ramps and at any vertex for other, surface streets: # Query for limited access features and set NETSUBTYPE = 1 and set EXCL_WALK = Y print "Calculate NETSUBTYPE values..." urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "CARTOCODE = '1' or CARTOCODE = '2' or CARTOCODE = '4' or DOT_RTNAME like '%R%' or DOT_RTNAME like '%C%'") arcpy.CalculateField_management(urban_roads_selected, field="NETSUBTYPE", expression='1', expression_type='VB', code_block='') arcpy.CalculateField_management(urban_roads_selected, field="EXCL_WALK", expression='Y', expression_type='VB', code_block='') # Switch selection and set remaining records NETSUBTYPE = 2 and set EXCL_WALK = N urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','SWITCH_SELECTION') arcpy.CalculateField_management(urban_roads_selected, field="NETSUBTYPE", expression='2', expression_type='VB', code_block='') arcpy.CalculateField_management(urban_roads_selected, field="EXCL_WALK", expression='N', expression_type='VB', code_block='') # clean up resources and memory arcpy.Delete_management('network_roads_lyr') # create Subtypes to define the two geodatabase subtypes using the NETSUBTYPE field # Code: "1" || Description "Limited Access & Ramps" # Code: "2" || Description "Other" print "Create SUBTYPES for Limited Access & Ramps and Other..." arcpy.SetSubtypeField_management(network_roads, field="NETSUBTYPE", clear_value="false") arcpy.AddSubtype_management(network_roads, subtype_code="1", subtype_description="Limited Access & Ramps") arcpy.AddSubtype_management(network_roads, subtype_code="2", subtype_description="Other") # build the netork based on an existing network .xml file template ## this is done in a seperate script b/c it needs to be run in Desktop 10.6 (or higher) or Pro ## use this script: "agrc_roadnetwork_create_and_build_network_run2nd.py" print "Done!"
#turn the contacts and boundary into unit polygons inFeatures = [contactsFCPath, boundaryFCPath] arcpy.FeatureToPolygon_management( inFeatures, os.path.join(digitisingFDPath, unitsTempFCName), "", "NO_ATTRIBUTES", "") ##Get the attributes for Unit polygons V2 from the original Unitsl Feature Class using a Spatial Join arcpy.SpatialJoin_analysis(os.path.join(digitisingFDPath, unitsTempFCName), inputUnitsFCPath, unitsUpdatedFCPath, "", "", "", "HAVE_THEIR_CENTER_IN", "", "") ##Add the unit code sub_type to the output polygon feature class #Create empty sub type for the Unit Code field arcpy.SetSubtypeField_management(unitsUpdatedFCPath, unitCodeFieldName) #create a new numpy array from the Unit polygon attributes we just created. This array is a 1d array of tuples fields = ['OID@', unitCodeFieldName] UnitCodeSubTypeArray = arcpy.da.TableToNumPyArray(validUnitTableName, fields) #loop through the unit code sub-type array and add each value to the sub-types for the unit code field #the array is a 1d array of tuples, so we need to use "array[][]" to access individual values for i in range(UnitCodeSubTypeArray.shape[0]): arcpy.AddSubtype_management(unitsUpdatedFCPath, UnitCodeSubTypeArray[i][0], UnitCodeSubTypeArray[i][1]) ##Delete the temp units layer arcpy.Delete_management(os.path.join(digitisingFDPath, unitsTempFCName))
elif row[0] == 'T6': row[1] = 6 elif row[0] == 'T7': row[1] = 7 elif row[0] == 'T8': row[1] = 8 else: row[1] = 9 calcursor.updateRow(row) arcpy.AddMessage("Region codes updated for {0}.".format(fc)) try: for fc in fcList: # Set subtype on Planning Region Code field arcpy.SetSubtypeField_management(fc, "PlanningRegionCode") arcpy.AddMessage("Subtype set for {0}.".format(fc)) # Add subtypes for code in subtypeDict: arcpy.AddSubtype_management(fc, code, subtypeDict[code]) arcpy.AddMessage("Subtypes added {0}.".format(fc)) except: arcpy.AddMessage("Subtype could not created for {0}.".format(fc)) try: # Create T1 Communities domain arcpy.CreateDomain_management(inGDB, "T1Communities",
##Create the unit polygons #turn the contacts and boundary into unit polygons inFeatures = [contactsFCPath, boundaryFCPath] arcpy.FeatureToPolygon_management( inFeatures, os.path.join(digitisingFDPath, unitsFCName), "", "NO_ATTRIBUTES", "") ##Add the unit code sub_type to the unit polygon feature class #Add the Unit code Field arcpy.AddField_management(os.path.join(digitisingFDPath, unitsFCName), unitCodeFieldName, "LONG") #Create empty sub type for the Unit Code field arcpy.SetSubtypeField_management( os.path.join(digitisingFDPath, unitsFCName), unitCodeFieldName) #create a new numpy array from the Unit polygon attributes we just created. This array is a 1d array of tuples fields = ['OID@', unitCodeFieldName] UnitCodeSubTypeArray = arcpy.da.TableToNumPyArray(validUnitTableName, fields) #loop through the unit code sub-type array and add each value to the sub-types for the unit code field #the array is a 1d array of tuples, so we need to use "array[][]" to access individual values for i in range(UnitCodeSubTypeArray.shape[0]): arcpy.AddSubtype_management( os.path.join(digitisingFDPath, unitsFCName), UnitCodeSubTypeArray[i][0], UnitCodeSubTypeArray[i][1]) ##Script Finished
def main(): # GET PARAMETER VALUES New_Anthro_Features = arcpy.GetParameterAsText(0) Existing_Anthro_Features = arcpy.GetParameterAsText(1) replace_subtypes = arcpy.GetParameterAsText(2) # Overwrite outputs arcpy.env.overwriteOutput = True # Helper functions (from ccslib) def Str2Bool(string): """ Converts a string to Python boolean. If not 'true' in lowercase, returns False. :param string: a string of True or False, not cap sensitive :return: Boolean """ if string == 'True' or string == 'true': return True else: return False def AddFields(input_feature, field_to_add, field_types, copy_existing=False): """ Adds provided fields to the input_feature, removes or copies existing of the same name. :param input_feature: a feature class :param field_to_add: a list of field names as strings :param field_types: a list of field types as strings, in order of fields_ to_add :param copy_existing: True to create a copy of any existing field with same name as field to add :return: None """ # Create dictionary of field types mapped to fields to add fieldTypesDict = dict(zip(field_to_add, field_types)) # Copy fields if they exist and delete original existingFields = arcpy.ListFields(input_feature) fieldNames = [each.name.lower() for each in existingFields] for field in field_to_add: if field.lower() in fieldNames: arcpy.AddMessage(field + " field exists.") if copy_existing: arcpy.AddMessage("Copying to new field named " + field + "_copy.") fieldIndex = fieldNames.index(field.lower()) if field.lower() + "_copy" in fieldNames: arcpy.AddMessage("Deleting field " + field + "_copy") arcpy.DeleteField_management(input_feature, field + "_copy") arcpy.AddField_management(input_feature, field + "_copy", existingFields[fieldIndex].type) with arcpy.da.UpdateCursor( input_feature, [field, field + "_copy"]) as cursor: try: for row in cursor: row[1] = row[0] cursor.updateRow(row) except arcpy.ExecuteError: arcpy.AddMessage("Unable to copy from " + field + " to " + field + "_copy.") arcpy.AddMessage("Deleting original field.") arcpy.DeleteField_management(input_feature, field) # Add fields for field in field_to_add: # arcpy.AddMessage("Adding " + field + " field") arcpy.AddField_management(input_feature, field, fieldTypesDict[field], field_length=50) # Main script # Get path to existing anthro features desc = arcpy.Describe(Existing_Anthro_Features) anthro_feature_path = desc.catalogPath # List subtypes from the existing anthro features subtypes = arcpy.da.ListSubtypes(Existing_Anthro_Features) # Add new field "Feature" AddFields(New_Anthro_Features, ['Feature'], ['SHORT']) # Copy new features over existing feature = arcpy.CopyFeatures_management(New_Anthro_Features, anthro_feature_path) replace_subtypes = Str2Bool(replace_subtypes) if replace_subtypes: # Set Feature field to Subtype field arcpy.SetSubtypeField_management(feature, "Feature") # Create subtypes for stcode, stdict in list(subtypes.items()): arcpy.AddSubtype_management(feature, stcode, stdict['Name']) # Iterate through subtypes and update feature code def get_feature_code(subtype_name): for stcode, stdict in list(subtypes.items()): if stdict['Name'] == subtype_name: return stcode with arcpy.da.UpdateCursor(feature, ["Feature", "Subtype"]) as cursor: for row in cursor: row[0] = get_feature_code(row[1]) cursor.updateRow(row) # Apply domains feature_basename = desc.baseName domain_name = feature_basename + "_Subtypes" arcpy.AssignDomainToField_management(feature, "Subtype", domain_name) if len(subtypes) == 1 and subtypes[0]['SubtypeField'] == '': pass else: st_codes = [ str(stcode) for stcode, stdict in list(subtypes.items()) ] arcpy.AssignDomainToField_management(feature, "Subtype", domain_name, st_codes) # Apply defaults for st_code, st_dict in list(subtypes.items()): default = subtypes[st_code]['Name'] arcpy.AssignDefaultToField_management(feature, "Subtype", default, st_code) default_type = feature_basename st_codes = [str(stcode) for stcode, stdict in list(subtypes.items())] arcpy.AssignDefaultToField_management(feature, "Type", default_type, st_codes)
def creerSubtype(self, catalogue, workspace, classe, subtype='CODE_SPEC'): #------------------------------------------------------------------------------------- """ Permet de créer les SubTypes dans les classes de la Géodatabase. Paramètres: ----------- catalogue : Numéro du catalogue. workspace : Nom de la géodatabase ou les domaines seront créés. classe : Liste des noms de classe contenus dans la géodatabase utilisés pour créer les domaines. subtype : Nom de l'attribut contenant les subtypes. """ #Envoyer un message arcpy.AddMessage(" ") arcpy.AddMessage("- Créer les SubTypes dans les classes de la Géodatabase") #Définir le workspace par défaut arcpy.env.workspace = workspace #Extraire la description de la Géodatabase for fc in classe.split(","): #Afficher le message arcpy.AddMessage(" SetSubtypeField_management('" + fc + "', '" + subtype + "')") #Définir l'attribut qui contient le Subtype arcpy.SetSubtypeField_management(fc, subtype) #Définir aucun propriétaire de la classe par défaut prop = "" #Vérifier si le propriétaire est présent dans le nom de la classe if "." in fc: #Définir le propriétaire de la classe prop = fc.split(".")[0] + "." #Créer la SQL pour extraire les subtypes sql = ("select distinct B.feat_type_code_bd, B.feat_type_name_fr" " from feat_catalogue A, feat_type B" " where A.feat_catal_type=" + catalogue.split(":")[0] + " and A.feat_catal_id=B.feat_catal_fk" " and B.feat_type_name_database='" + fc.replace(prop,"") + "'" " order by B.feat_type_code_bd") #arcpy.AddMessage(sql) #Exécuter la SQL resultat = self.BDG.query(sql) #Vérifier le résultat if resultat: #Traiter tous les résultats for valeur in resultat: #Afficher le message arcpy.AddMessage(" AddSubtype_management('" + fc + "', " + str(valeur[0]) + ", '" + str(valeur[0]) + ":" + valeur[1] + "')") #Ajouter un subtype à la classe arcpy.AddSubtype_management(fc, valeur[0], str(valeur[0]) + ":" + valeur[1]) #Afficher le message arcpy.AddMessage(" SetDefaultSubtype_management('" + fc + "', " + str(resultat[0][0]) + ")") #Définir le Subtype par défaut arcpy.SetDefaultSubtype_management(fc, resultat[0][0]) #Sortir return
def create_structures_fc(gdb): """ Create Historic Structures feature class """ arcpy.env.workspace = gdb fc = "HistoricStructures" spatref = arcpy.SpatialReference( "WGS 1984 Web Mercator (auxiliary sphere)") if arcpy.Exists(fc): arcpy.Delete_management(os.path.join(gdb, fc)) has_m = "DISABLED" has_z = "DISABLED" # Execute CreateFeatureclass arcpy.CreateFeatureclass_management(gdb, fc, "POINT", "", has_m, has_z, spatref) arcpy.AddField_management(fc, "ResourceID", "LONG", "", "", "", "Resource ID", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "PropName", "TEXT", "", "", 100, "Resource Name", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "StrucType", "LONG", "", "", "", "Structure Type", "NON_NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "BldType", "TEXT", "", "", 3, "Building Type", "NON_NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "StyleType", "TEXT", "", "", 3, "Architectural Style", "NON_NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "Eligibility", "TEXT", "", "", 3, "Eligibility Status", "NON_NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "ConstYr", "LONG", "", "", "", "Construction Year", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "Address", "TEXT", "", "", 200, "Address", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(fc, "Notes", "TEXT", "", "", 200, "Notes", "NULLABLE", "NON_REQUIRED", "") arcpy.AddGlobalIDs_management(fc) arcpy.AddField_management(fc, "EPProject", "TEXT", "", "", 20, "EPEI Project ID", "NULLABLE", "NON_REQUIRED", "") arcpy.SetSubtypeField_management(fc, "StrucType") for item in subtypes.items(): arcpy.AddSubtype_management(fc, item[0], item[1]) arcpy.SetDefaultSubtype_management(fc, 5) for item in subtypes.items(): arcpy.AssignDomainToField_management(fc, "BldType", item[1], item[0]) arcpy.AssignDomainToField_management( fc, "StyleType", "Styles", ['0', '1', '2', '3', '4', '5', '6', '7', '8']) arcpy.AssignDomainToField_management( fc, "Eligibility", "Eligibility", ['0', '1', '2', '3', '4', '5', '6', '7', '8']) arcpy.AssignDefaultToField_management( fc, "Eligibility", "U", ['0', '1', '2', '3', '4', '5', '6', '7', '8']) arcpy.AssignDefaultToField_management( fc, "StyleType", "NS", ['0', '1', '2', '3', '4', '5', '6', '7', '8']) arcpy.AssignDefaultToField_management( fc, "BldType", "OT", ['0', '1', '2', '3', '4', '6', '7', '8']) arcpy.AssignDefaultToField_management(fc, "BldType", "NAT", '5') return os.path.join(gdb, fc)
domain_s_poly) print('...Assigned all universal domains to fields') GWRutils.logMessage(log, '...Assigned all universal domains to fields') except Exception as e: print('Failed to assign universal domains to fields! Exiting...') print(e) GWRutils.logMessage( log, 'Failed to assign universal domains to fields! ' + 'Exiting...') GWRutils.logMessage(log, str(e)) sys.exit() # Create subtypes in Activity and Chemical tables based on propertyOID try: arcpy.SetSubtypeField_management(activity_fc, 'PropertyOID') arcpy.SetSubtypeField_management(chem_app_table, 'PropertyOID') for prop in props_dict: arcpy.AddSubtype_management(activity_fc, prop, props_dict[prop]) arcpy.AddSubtype_management(chem_app_table, prop, props_dict[prop]) print('...Created propertyOID subtypes in Activity and Chemical datasets') GWRutils.logMessage( log, '...Created propertyOID subtypes in Activity ' + 'and Chemical datasets') except Exception as e: print('Failed to create propertyOID subtypes in Activity and Chemical ' + 'datasets! Exiting...') print(e) GWRutils.logMessage( log, 'Failed to create propertyOID subtypes in ' +
arcpy.CreateTable_management(workingGDBPath, validUnitTableName) #add the Unit Code field to the Valid Units Table arcpy.AddField_management(validUnitTableName,unitCodeFieldName,"TEXT","") #add the Unit Name field to the Valid Units Table arcpy.AddField_management(validUnitTableName,unitNameFieldName,"TEXT","") ##Create accuracy field in the contacts feature class and add sub type containing valid accuracy types #add the accuracy field arcpy.AddField_management(os.path.join(digitisingFDName,contactsFCName),accuracyFieldName,"LONG","") #Create empty sub type to go in the Accuracy Field arcpy.SetSubtypeField_management(os.path.join(digitisingFDName,contactsFCName),accuracyFieldName) #define a sub-type(ST) array for accuracy fields as tuples accuracySTArray = [(1,"Accurate"),(2,"Approximate"),(3,"Inferred")] #loop through the unit code sub-type array and add each value to the sub-types for the unit code field #the array is a 1d array of tuples, so we need to use "array[][]" to access individual values for i in range(len(accuracySTArray)): arcpy.AddSubtype_management(os.path.join(digitisingFDName,contactsFCName),accuracySTArray[i][0],accuracySTArray[i][1]) ##Script Finished #code to provide error messages. From SURV319 2017 Tutorial 4 instructions except arcpy.ExecuteError: # Get the tool error messages #
for sub in subtype_list: dict = {} with arcpy.da.SearchCursor(jobs_table, fields) as cursor: for row in cursor: ACC_WORK_GROUP = row[3] if ACC_WORK_GROUP == sub: JOB_ID = int(row[0]) JOB_NAME = row[1] dict[JOB_ID] = JOB_NAME domains_dict[sub] = dict # print(domains_dict) #### SUBTYPES: ### try: # Process: Set Subtype Field... arcpy.SetSubtypeField_management(featureClass, "subtype") # Process: Add Subtypes... # Store all the suptype values in a dictionary with the subtype code as the "key" and the # subtype description as the "value" (stypeDict[code]) # stypeDict = {"0": "'ODF-ი'","1": "P2P ინსტალაცია","2": "არხის მშენებლობა","3": "ბოძის მონტაჟი","4": "კაბელის მონტაჟი","5": "კარადის მონტაჟი","6": "სპლიტერი","7":"ქურო","8": "ჭის მონტაჟი",} #Create dict from list!!! subtypeDict = {} for i in range(len(subtype_list)): subtypeDict[str(i)] = subtype_list[i] print(subtypeDict) # use a for loop to cycle through the dictionary for code in subtypeDict: arcpy.AddSubtype_management(featureClass, code, subtypeDict[code])