def CopyDomainsBetweenTables(inputTable, outputTable): inGDB = os.path.split(inputTable)[0] outGDB = os.path.split(outputTable)[0] arcpy.env.overwriteOutput = True dscOutWorkspace = arcpy.Describe(outGDB) domainList = [] domainDict = dict() fieldList = arcpy.ListFields(inputTable) for field in fieldList: if field.domain: print("{0} has domain {1}".format(field.name, field.domain)) if not (field.domain in dscOutWorkspace.domains): arcpy.DomainToTable_management(inGDB, field.domain, "IN_MEMORY/DomainTab", "Code", "Description") arcpy.TableToDomain_management("IN_MEMORY/DomainTab", "Code", "Description", outGDB, field.domain) arcpy.AddMessage("Added " + field.domain + " to " + outGDB) domainDict[field.name] = field.domain domainList += [field.domain] fieldList = arcpy.ListFields(outputTable) for field in fieldList: if not field.domain and domainDict.has_key(field.name): arcpy.AssignDomainToField_management(outputTable, field.name, domainDict[field.name]) arcpy.AddMessage("Assigned " + field.domain + " to " + outputTable) arcpy.SetParameterAsText(2, outputTable)
def add_domain(): # 挂阈值 domain_flag = '' tb_flag = "" tbfld_flag = "" for k in range(nrows): if table.cell(k, 0).value == '': continue # print table.row_values(k) alst = table.row_values(k) if '' in alst: alst = list(set(alst)) alst.remove('') if len(alst) == 1: tb_flag = table.cell(k, 0).value elif len(alst) > 2: domain_flag = table.cell(k, 0).value tbfld_flag = table.cell(k, 3).value # print tb_flag # print "\t",domain_flag,tbfld_flag try: if tbfld_flag == "ENGINEETYPE": arcpy.AlterField_management(tb_flag, tbfld_flag, new_field_alias="工程类型", field_type="SHORT") elif tbfld_flag == "SYSDATAFROM": arcpy.AlterField_management(tb_flag, tbfld_flag, field_type="SHORT") arcpy.AssignDomainToField_management(tb_flag, tbfld_flag, domain_flag) except RuntimeError: print arcpy.GetMessages()
def AssignDomain(self, FC, FieldClass): for field in arcpy.ListFields(FC): if hasattr(FieldClass, field.name): attr = getattr(FieldClass, field.name) if attr['domain'] <> None: arcpy.AssignDomainToField_management( FC, attr['name'], attr['domain']['name'])
def add_additive_specification_range_domain_to_gdb(in_gdb, in_features, fields, domain_name, field_type="DOUBLE", range_min=0, range_max=25): """This function will add additive shared-row specification domains for categorical fields based on a CSV. Uses Pandas. :param - in_gdb - input geodatabase to add domains to :param - in_features - optional input that is used to assign domains to feature class is chosen. :param - domain_name - name of new range domain :param - field_type - field type used by domains :param - fields - fields to assign domains too :param - range_min - the minimum value allowed by the range domain :param - range_max - the maximum value allowed by the range domain """ try: domain_description = str(domain_name) + "_Range_Domain" try: srl.arc_print("Adding range domain for numeric values...") arcpy.CreateDomain_management(in_gdb, domain_name, domain_description, field_type, "RANGE") except: arcpy.AddWarning("Could not create domain. Either it already exists or some other error...") srl.arc_print("Set min and max values of domains...") arcpy.SetValueForRangeDomain_management(in_gdb, domain_name, range_min, range_max) srl.arc_print("Attempting to assign numeric fields ...") for field in fields: try: if len(arcpy.ListFields(in_features, field)) > 0: arcpy.AssignDomainToField_management(in_features, field, domain_name) except: arcpy.AddWarning("Could not assign domain to field {0}...".format(field)) except Exception as e: srl.arc_print("Tool Script Error!") import traceback, sys tb = sys.exc_info()[2] srl.arc_print("An error occurred on line %i" % tb.tb_lineno) arcpy.AddError("The error occurred on line {0}...".format(tb.tb_lineno))
def _bind_domain(out_gdb, x): for f in x['fields']: if f['domain']: logger.info(f['domain']) arcpy.AssignDomainToField_management(in_table=out_gdb + '/' + x['name'], field_name=f['name'], domain_name=f['domain'])
def AssignDomainToField(in_table, field_name, domain_name): try: arcpy.AssignDomainToField_management(in_table, field_name, domain_name) print u"Campo {}.{} associado ao dominio {} com sucesso.".format( in_table, field_name, domain_name) except Exception as ex: print u"ERRO ao adicionar dominio ao campo {}.{}:".format( in_table, field_name), ex.message
def assignDomain(self): arcpy.env.workspace = self.pathGdb for j in jsonFiles: name = j.split(".")[-2] field_names = [f.name for f in arcpy.ListFields(name)] for x in listFieldsDomain: if x[0] in field_names: arcpy.AssignDomainToField_management(name, x[0], x[1]) print name
def aaaa(self): # listaFT = Lista de feature y tablas de la gdb # listnamesField = Lista de nombre de los campos # listFieldsDomain = Lista [nombre dominio, campo al que pertenece] for m in listaFT: listnamesField = [x.name for x in arcpy.ListFields(m)] for y in listFieldsDomain: for z in listnamesField: if y[1] == z: arcpy.AssignDomainToField_management(m, y[1], y[0])
def CreateClassDomain(): domDict = {"AI":"Apartment Improved","C":"Commercial","CA":"Commercial Auxiliary","CI":"Commercial Improved","CV":"Commercial Vacant","I":"Industrial",\ "IA":"Industrial Auxiliary","II":"Industrial Improved","IV":"Industrial Vacant","R":"Residential","RA":"Residential Auxiliary","RI":"Residential Improved",\ "RV":"Residential Vacant","UI":"Utility Improved","XA":"Exempt Auxiliary","XI":"Exempt Improved","XV":"Exempt Vacant"} arcpy.CreateDomain_management(workspace, "Parcels_Class", "Class Code", "TEXT", "CODED", "DEFAULT", "DEFAULT") for code in domDict: arcpy.AddCodedValueToDomain_management(workspace, "Parcels_Class", code, domDict[code]) arcpy.AssignDomainToField_management(inFeature, "Class", "Parcels_Class")
def recoverFields(itemfields, mdpath): try: # Get field names from image service isfieldsName = [field["name"].lower() for field in itemfields] # Get field names from mosaic dataset mdfields = arcpy.ListFields(mdpath) mdfieldsName = [field.name.lower() for field in mdfields] mdfieldsName.remove("raster") missingfieldsName = [x for x in isfieldsName if x not in mdfieldsName] if len(missingfieldsName) > 0: for fieldname in missingfieldsName: arcpy.AddMessage( "Adding missing field %s to the output mosaic dataset..." % fieldname) mfield = filter( lambda mfield: mfield["name"].lower() == fieldname, itemfields)[0] ftype = getfieldTypeKey(mfield["type"]) fprecision = "" fscale = "" flength = mfield["length"] if mfield.has_key("length") else "" falias = mfield["alias"] if mfield.has_key("alias") else "" fnullable = "" frequire = "" fdomain = mfield["domain"] if mfield.has_key("domain") else "" # Add missing field to the mosaic dataset arcpy.AddField_management(mdpath, fieldname, ftype, fprecision, fscale, flength, falias, fnullable, frequire) # Add domain if exist if fdomain != "" and fdomain != None: domainDict = fdomain["codedValues"] for code in domainDict: arcpy.AddCodedValueToDomain_management( os.path.dirname(mdpath), fdomain["name"], code["code"], code["name"]) arcpy.AssignDomainToField_management( mdpath, fieldname, fdomain["name"]) # Optional: add an extra OID field to save ids in the original image service arcpy.AddField_management(mdpath, "OOID", "LONG") except: arcpy.AddError("ERROR: Failure in the recoverFields function")
def create_domen_EVA_in_DateBase(self): """ Create domains streets in DateBase from tables streets and delete table streets :return: domain streets """ for domen_table_EVA in self.list_domen_tables_EVA: #Create domen EVA from domen_table arcpy.TableToDomain_management(domen_table_EVA, "ID_EVA", "Name_EVA", self.nameDataBase, domen_table_EVA.split("""\\""")[-1], "EVA", "APPEND") #Delete domen_table in DateBase arcpy.Delete_management(domen_table_EVA, "Table") if self.name_district != "Минск": arcpy.AssignDomainToField_management( self.nameStreets, 'Name_EVA', domen_table_EVA.split("""\\""")[-1], self.new_dict_syptypes[domen_table_EVA.split("""\\""") [-1].split('_')[0]][0]) else: arcpy.AssignDomainToField_management( self.nameStreets, 'Name_EVA', domen_table_EVA.split("""\\""")[-1], 17030)
def AddSubtypeDomains(feature_list, workspace, Parameter_Values): """ Applies the subtypes listed in the Anthro_Attribute_Table as a domain to the Subtype field in the anthro feature classes. :param feature_list: a list of anthro features :param workspace: the project's unique gdb :param Parameter_Values: the Parameter_Values table :return: None """ arcpy.TableToDomain_management(Parameter_Values, "Subtype", "Subtype", workspace, "Subtype", "Valid anthropogenic subtypes", "REPLACE") for feature in feature_list: arcpy.AssignDomainToField_management(feature, "Subtype", "Subtype")
def create_player_domain(gdb, fc, line_fc, player_dict): domName = "Players" inField = "PLAYER_ID" # Process: Create the coded value domain arcpy.CreateDomain_management(gdb, domName, "Player Names", "TEXT", "CODED") # Process: Add valid material types to the domain #use a for loop to cycle through all the domain codes in the dictionary for code in player_dict: arcpy.AddCodedValueToDomain_management(gdb, domName, code, player_dict[code]) # Process: Constrain the material value of distribution mains arcpy.AssignDomainToField_management(fc, inField, domName)
def create_domen_ATE_in_DateBase(self): """ Create domain ATE, which containes list of settlements in chosen district :return: domain ATE in DateBase """ for domen_table_ATE in self.list_domen_tables_ATE: #Create domen EVA from domen_table arcpy.TableToDomain_management(domen_table_ATE, "ID_ATE", "Name_ATE", self.nameDataBase, domen_table_ATE.split("""\\""")[-1], "ATE", "APPEND") #Delete domen_table in DateBase arcpy.Delete_management(domen_table_ATE, "Table") arcpy.AssignDomainToField_management( self.nameStreets, 'Name', domen_table_ATE.split("""\\""")[-1], self.new_dict_syptypes[ domen_table_ATE.split("""\\""")[-1].split('_')[0]][0])
def CreateLUCDomain(): domDict = {"10":"Residential Condo","11":"Single Family","12":"Two Family","13":"Three Family","14":"Four Family","15":"5-10 Family",\ "16":"11-20 Family","17":"21+ Family","18":"Seasonal","19":"Garage & Sheds","20":"Commercial Condos",\ "21":"Retail","22":"Office","23":"Hotel & Motel","24":"Wholesale","25":"Parking Lots","26":"Private Clubs","27":"Multi Use Commercial",\ "31":"Manufacturing","32":"Warehouse & Storage","33":"Transportation","34":"Communication","35":"Extraction","36":"Multi Use Industrial",\ "04":"Bed & Breakfast","40":"Vacant Land","41":"Parking Space Condo","42":"Boat Slips","05":"Parking Condos","53":"Exempt Religious",\ "54":"Exempt Benevolent & Charitable","55":"Exempt Literary & Scientific","56":"Exempt Governmental","57":"Exempt by Law",\ "58":"Land Bank","06":"Multi Use Residential","07":"Residential Hotels","08":"Apartment & Rooms","09":"Rooming Houses"} arcpy.CreateDomain_management(workspace, "Parcels_LUC", "Land Use Code", "TEXT", "CODED", "DEFAULT", "DEFAULT") for code in domDict: arcpy.AddCodedValueToDomain_management(workspace, "Parcels_LUC", code, domDict[code]) arcpy.AssignDomainToField_management(inFeature, "LUC", "Parcels_LUC")
def UniqueValueToDomain(Workspace, Table, Field_Name, Domain_Name): arcpy.env.overwriteOutput = True tempFRQTable = 'IN_MEMORY/FRQ' tempFRQView = "frq_View" InputField = FindField(Table, str(Field_Name)) #arcpy.AddMessage(InputField.type) if (InputField.type in [ u'SmallInteger', u'Double', u'Long', u'OID', u'Single', u'Integer' ]): notEmptySQL = """"Code" IS NULL""" else: notEmptySQL = """"Code" IS NULL OR "Code" = ''""" # Process: Frequency arcpy.Frequency_analysis(Table, tempFRQTable, Field_Name) # Process: AddField arcpy.AddField_management(tempFRQTable, "Description", "TEXT") arcpy.AddField_management(tempFRQTable, "Code", InputField.type, InputField.precision, InputField.scale, InputField.length) # Process: CalculateField arcpy.CalculateField_management(tempFRQTable, "Description", "[" + Field_Name + "]", "VB", "") arcpy.CalculateField_management(tempFRQTable, "Code", "[" + Field_Name + "]", "VB", "") #Delete empty codes arcpy.MakeTableView_management(tempFRQTable, tempFRQView) arcpy.SelectLayerByAttribute_management(tempFRQView, "NEW_SELECTION", notEmptySQL) arcpy.DeleteRows_management(tempFRQView) # Process: TableToDomain arcpy.TableToDomain_management(tempFRQView, "Code", "Description", Workspace, Domain_Name, "Description", "REPLACE") # Process: AssignDomainToField arcpy.AssignDomainToField_management(Table, Field_Name, Domain_Name)
def push_to_gdb(final_lyr, gis, webgis_config, gis_env_config, services_list): """ Copies the finalized layer to a geodatabase. The feature class will be reprojected, if specified in the config file. If a feature service is referencing the feature class, it will be stopped prior to copying features and restarted afterwards. """ # Output final_lyr to target geodatabase feature class print('Copying features to target geodatabase...') arcpy.CopyFeatures_management(final_lyr, gis_env_config['out_fc_name']) # Assign domains to fields print('Assigning domains to fields...') field_domain_lst = [['classcode', 'taxClassDESCR'], ['schooltaxcode', 'taxSchoolDESCR']] for domain in field_domain_lst: arcpy.AssignDomainToField_management(gis_env_config['out_fc_name'], domain[0], domain[1]) print('Altering ObjectID alias...') arcpy.AlterField_management(gis_env_config['out_fc_name'], 'OBJECTID', new_field_alias='OBJECTID') # Clear environment workspace cache arcpy.ClearWorkspaceCache_management() # Restart feature services print('Starting feature services...') for serv in services_list: print('Starting {} feature service'.format( serv.properties.serviceName)) serv.start() # Update the Portal item summary print('Updating feature service summary...') update_summary(gis, webgis_config['portal_item'])
def recover_fld_domain(): arcpy.env.workspace = r"D:\全生命周期" for ds in list_feature_batch('Pipe.gdb'): #print ds blst = save_defaultvalue_domain() for ds_item, fc_dic_item in blst[0].items(): if ds_item == os.path.basename(ds): print ds arcpy.env.workspace = ds for fc_item,fld_dic in fc_dic_item.items(): print "正在执行主程序" for fc in arcpy.ListFeatureClasses(): # 为要素类是使用 if fc == fc_item: print fc + '\n' for fld in arcpy.ListFields(fc): for fld_item,domain_dflt_lst in fld_dic.items(): if fld_item == fld.name: #fld.domain = domain_dflt_lst[1] try: arcpy.AssignDomainToField_management(fc,fld.name,domain_dflt_lst[1]) except arcpy.ExecuteError: print arcpy.GetMessages() print 10 * '#' print "图层:" + fc + ' ' + '字段:' + fld.name + ' ' + "名称为" + domain_dflt_lst[1] +'的阈值不存在' #fld.defaultValue = domain_dflt_lst[0] if domain_dflt_lst[0] is not None: try: arcpy.AssignDefaultToField_management(fc,fld.name,int(domain_dflt_lst[0]),"","false") except arcpy.ExecuteError: print arcpy.GetMessages() print 10*"%" print fc,fld.name,domain_dflt_lst[0] print 10 * "%"
def createUN(jsonFile, outGDB): cfgStr = open(jsonFile, 'r', encoding='gbk').read() unObj = json.loads(cfgStr) unName = unObj["unName"] # 创建un和结构网络 arcpy.env.preserveGlobalIds = True arcpy.env.overwriteOutput = True arcpy.CreateFileGDB_management(os.path.dirname(outGDB), os.path.basename(outGDB)) arcpy.pt.StageUtilityNetwork(outGDB, unObj["territoryFeaCls"], unObj["feaDS"], unName) # Tips:尽量使用相对路径,如有工具不支持再改用绝对路径 arcpy.env.workspace = os.path.join(outGDB, unObj["feaDS"]) # 导入fieldDomains,domain是面向GDB级的物理设置 for domain in unObj["fieldDomains"]: dName = domain["name"] if domain.get("dtype") == "RANGE": arcpy.CreateDomain_management(outGDB, dName, domain.get("desc", dName), domain.get("ftype", "SHORT"), "RANGE") arcpy.SetValueForRangeDomain_management(outGDB, dName, domain['min'], domain['max']) continue table = arcpy.management.CreateTable('in_memory', dName)[0] # ?[0] arcpy.AddField_management(table, 'code', domain.get("ftype", "SHORT")) arcpy.AddField_management(table, 'name', 'TEXT', field_length=254) with arcpy.da.InsertCursor(table, ('code', 'name')) as cur: for v in domain["values"]: cur.insertRow((v["code"], v["name"])) arcpy.TableToDomain_management(table, 'code', 'name', outGDB, dName, domain.get("desc", dName), update_option='REPLACE') arcpy.Delete_management(table) # 创建除了structure以外的域网络 for dnObj in unObj["domainNetworks"]: if dnObj["name"].lower() != "structure": arcpy.AddDomainNetwork_un(unName, dnObj["name"], dnObj["tierDef"], dnObj["controllerType"], dnObj.get("alias")) # 添加TerminalConfiguration,categories,netAttributes,这些是面向整个UN级的逻辑设置 # Tips:需要先创建至少一个域网络,才能添加TerminalConfiguration terminalConfigs = unObj.get("terminalConfigs") if terminalConfigs: for terminalCfg in terminalConfigs: if terminalCfg["dir"] == "DIRECTIONAL": arcpy.AddTerminalConfiguration_un( unName, terminalCfg["name"], "DIRECTIONAL", terminals_directional=terminalCfg["terminals"], valid_paths=terminalCfg["paths"], default_path=terminalCfg.get("default")) else: arcpy.AddTerminalConfiguration_un( unName, terminalCfg["name"], "BIDIRECTIONAL", terminals_bidirectional=terminalCfg["terminals"], valid_paths=terminalCfg["paths"], default_path=terminalCfg.get("default")) # TODO: 网络分组与分层的区别? categories = unObj.get("categories") if categories: ## 为什么加这种判断 for category in categories: arcpy.AddNetworkCategory_un(unName, category) # TODO:网络属性的可选设置有什么作用? netAttributes = unObj.get("netAttributes") if netAttributes: for attrib in netAttributes: arcpy.AddNetworkAttribute_un(unName, attrib["name"], attrib["type"], attrib.get("inline"), attrib.get("apportionable"), attrib.get("domain"), attrib.get("overridable"), attrib.get("nullable"), attrib.get("substitution"), attrib.get("attrToSubstitution")) # 添加子类,创建新字段,指定属性域,指定网络属性,这些是面向Table级的物理设置 for dnObj in unObj["domainNetworks"]: # 子类已经自动设置为ASSETGROUP字段,添加自定义值 subtypes = dnObj.get("subtypes") if subtypes: for subtype in subtypes: for v in subtype["values"]: arcpy.AddSubtype_management(subtype["feaCls"], v["code"], v["name"]) if subtype.get("default"): arcpy.SetDefaultSubtype_management(subtype["feaCls"], subtype.get("default")) # 添加自定义字段 newFields = dnObj.get("newFields") if newFields: for field in newFields: length = field.get( "length") if field["type"].upper() == "TEXT" else None arcpy.AddField_management(field["feaCls"], field["name"], field["type"], field_length=length, field_alias=field.get("alias")) # 为字段指定属性域 fDomains = dnObj.get("fieldDomains") if fDomains: for fd in fDomains: arcpy.AssignDomainToField_management(fd["feaCls"], fd["fieldName"], fd["domainName"], fd.get("subtypeCodes")) if fd.get("default"): arcpy.AssignDefaultToField_management( fd["feaCls"], fd["fieldName"], fd["default"], fd.get("subtypeCodes")) # 为字段指定网络属性 netAttributes = dnObj.get("netAttributes") if netAttributes: for attribute in netAttributes: for field in attribute["fields"]: fc, fName = field.split("/") fObj = arcpy.ListFields(fc, fName) if fObj: arcpy.SetNetworkAttribute_un(unName, attribute["name"], dnObj["name"], fc, fName) # 为资产指定多项配置:端子配置、分组、边连通性、角色,这些是面向资产级的逻辑设置 with open(unObj.get("assetsCSV", "not exist"), 'r', encoding='gbk') as fp: reader = csv.reader(fp) # 读取列为列表 header = next( reader ) # ['domainNet', 'feaCls', 'assetName', 'categories', 'terminalCfg', 'edgeConnectivity', 'roleType', 'deletionType', 'viewScale', 'splitType'] assetCfg = namedtuple('assetCfg', header) for row in reader: row = assetCfg(*row) asset = row.assetName.split('/') if row.terminalCfg: arcpy.SetTerminalConfiguration_un(unName, row.domainNet, row.feaCls, *asset, row.terminalCfg) if row.categories: arcpy.SetNetworkCategory_un(unName, row.domainNet, row.feaCls, *asset, row.categories) if row.edgeConnectivity: # 边联通非空 arcpy.SetEdgeConnectivity_un(unName, row.domainNet, row.feaCls, *asset, row.edgeConnectivity) if row.roleType: arcpy.SetAssociationRole_un(unName, row.domainNet, row.feaCls, *asset, row.roleType, row.deletionType, row.viewScale, row.splitType) # 创建tier,并设置子网定义,这些是面向子网级的逻辑设置 # TODO: subnetwork_field_name有什么作用?subnetDef还有很多可选设置 for dnObj in unObj["domainNetworks"]: dnName = dnObj["name"] if dnName.lower() != "structure": # tierGroups tierGroups = dnObj.get("tierGroups") if tierGroups and dnObj["tierDef"] == "HIERARCHICAL": for groupName in tierGroups: arcpy.AddTierGroup_un(unName, dnName, groupName) tiers = dnObj.get("tiers") if tiers: for tier in tiers: if dnObj["tierDef"] == "HIERARCHICAL": arcpy.AddTier_un( unName, dnName, tier["name"], tier["rank"], topology_type="MESH", tier_group_name=tier.get("groupName"), subnetwork_field_name=tier["subnetField"]) else: arcpy.AddTier_un(unName, dnName, tier["name"], tier["rank"], topology_type=tier["topo"]) arcpy.SetSubnetworkDefinition_un( unName, dnName, tier["name"], tier["disjoint"], tier["devices"], tier["controllers"], tier.get("lines"), tier.get("aggregated"), tier.get("diagrams"), include_barriers=tier.get("barriers"), traversability_scope=tier.get("traverse")) # TODO: 导入rule arcpy.ImportRules_un(unName, "All", "E:/ArcGIS/unnet/rules.csv") # TODO: 导入数据 # 数据导入是基于子类的,把要素类路径写入到子类中,修改了demoUN域网络的子类型值 for dnObj in unObj["domainNetworks"]: subtypes = dnObj.get("subtypes") if subtypes: for subtype in subtypes: for v in subtype["values"]: arcpy.Append_management(subtype["path"], subtype["feaCls"], "NO_TEST", subtype=v["name"])
def wet_weather(feature_layer): """ This adds specific fields required for wet weather inspections This will report errors if: 1) Any of the fields already exist 2) The input layer is not a point layer 3) The layer is not found 4) The layer is a shapefile Example: add_gps_fields(r"C:/temp/test.shp") :param feature_layer: (string) The feature layer (shapefile, feature class, etc) to add the fields to :return: """ try: # need to know dataType of input desc = arcpy.Describe(feature_layer) dataType = desc.dataType.lower() if dataType == "featurelayer": dataType = arcpy.Describe( feature_layer).dataElement.dataType.lower() # catch invalid inputs if dataType == "shapefile": arcpy.AddIDMessage("ERROR this is not a valid type") return if dataType != "featureclass" or desc.shapeType.lower() != "point": arcpy.AddIDMessage("ERROR this is not a valid type") return # check if it's a service or feature class in db # Check the domains to see if they exist and are valid # will update if necessary if r'/rest/services' not in arcpy.Describe(feature_layer).catalogPath: geodatabase = get_geodatabase_path(feature_layer) check_and_create_domains(geodatabase) # Add the fields # Add Wet Weather metadata fields existingFields = [ field.name for field in arcpy.ListFields(feature_layer) ] if 'Inspected_By1' not in existingFields: arcpy.AddField_management(feature_layer, 'Inspected_By1', field_type="TEXT", field_alias='Inspector-1:', field_is_nullable="NULLABLE", field_domain="Inspector") if 'Inspected_By2' not in existingFields: arcpy.AddField_management(feature_layer, 'Inspected_By2', field_type="TEXT", field_alias='Inspector-2:', field_is_nullable="NULLABLE", field_domain="Inspector") if 'Inspec_Num' not in existingFields: arcpy.AddField_management( feature_layer, 'Inspec_Num', field_type="DOUBLE", field_alias='Wet Weather Inspection #:', field_is_nullable="NULLABLE", ) if 'Clear_Flow' not in existingFields: arcpy.AddField_management(feature_layer, 'Clear_Flow', field_type="TEXT", field_alias='Clear Flow In Manhole:', field_is_nullable="NULLABLE", field_domain="Yes_No") if 'ESRISNSR_AZIMUTH' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRISNSR_AZIMUTH', field_type="DOUBLE", field_alias='Compass reading (°)', field_is_nullable="NULLABLE") # Update fields with Domains # Update GNSS metadata fields with Domains domainFields = [ field for field in arcpy.ListFields(feature_layer) if field.name == 'ESRIGNSS_FIXTYPE' or field.name == 'ESRIGNSS_STATIONID' or field.name == 'ESRIGNSS_NUMSATS' or field.name == 'ESRIGNSS_POSITIONSOURCETYPE' ] for field in domainFields: if field.name == 'ESRIGNSS_FIXTYPE' and not field.domain: arcpy.AssignDomainToField_management(feature_layer, field, 'ESRI_FIX_TYPE_DOMAIN') continue if field.name == 'ESRIGNSS_STATIONID' and not field.domain: arcpy.AssignDomainToField_management(feature_layer, field, 'ESRI_STATION_ID_DOMAIN') continue if field.name == 'ESRIGNSS_NUMSATS' and not field.domain: arcpy.AssignDomainToField_management(feature_layer, field, 'ESRI_NUM_SATS_DOMAIN') continue if field.name == 'ESRIGNSS_POSITIONSOURCETYPE' and not field.domain: arcpy.AssignDomainToField_management( feature_layer, field, 'ESRI_POSITIONSOURCETYPE_DOMAIN') continue except Exception as e: arcpy.AddError("{}\n".format(e)) return
def main(): """ The main routine which processes stuff """ arcpy.AddMessage("Setting up workspace and parameters.") arcpy.env.overwriteOutput = True workspace = r"in_memory" arcpy.env.workspace = workspace output_date = datetime.datetime.now().strftime("%Y%m%d") output = arcpy.GetParameterAsText(0) if output == "#" or not output: output = r"D:\Projects\TreeProject\TreeProject.gdb\treecrops_{}".format( output_date) # Set more variables output_fc = output.split("\\")[-1] output_workspace = output.split(output_fc)[0][:-1] print(output_fc) print(output_workspace) # Create output FC if it doesn't exist if arcpy.Exists(output): pass else: print("Creating output feature class") arcpy.CreateFeatureclass_management(output_workspace, output_fc, "POLYGON", spatial_reference=4283) # For feature service connection # noinspection SpellCheckingInspection gis = GIS("http://arcgis.com", "jmckechn_une", "Leoj270592") print("Credentials verified: {}".format(gis)) rest_url = "https://services5.arcgis.com/3foZbDxfCo9kcPwP/arcgis/rest/services/" \ "TreeCrops_Editing/FeatureServer/0" # Try copying editing service to local gdb trees = output_workspace + "\\fs_download_{}".format(output_date) if arcpy.Exists(trees): arcpy.Delete_management(trees) print("Removing existing {}".format(trees)) else: print("Copying from service: {}".format(rest_url)) arcpy.CopyFeatures_management(rest_url, trees) print("Copy successful: {}".format(trees)) # Copy data to memory and set up feature layer trees_memory = r"in_memory/trees" trees_lyr = "trees_lyr" query = "(commodity IS NOT NULL AND commodity <> 'other') AND (stage IS NULL OR stage = '1' OR stage = '2')" print("Copying data to memory") arcpy.CopyFeatures_management(trees, trees_memory) arcpy.MakeFeatureLayer_management(trees_memory, trees_lyr, where_clause=query) # Remove ag_ features if they exist rem_list = arcpy.ListFeatureClasses("ag_*") for i in rem_list: print("Deleting {}".format(i)) arcpy.Delete_management(workspace + r"/" + i) # Get unique values print("Getting unique attributes from fields") field_list = ["commodity", "source", "year"] com_list = [] for i in field_list: if i == "commodity": u_list = unique_values(trees_lyr, i) for j in u_list: com_list.append(j) else: pass # # Remove banana for speed :) (testing) # print("Remove banana for speed :) (testing)") # com_list.remove("banana") print(com_list) update_list = [] print("Looping through selecting unique features to aggregate") for c in com_list: print(" Working on {} features".format(c)) print(" selecting") selection_query = "commodity = '{}'".format(c) arcpy.SelectLayerByAttribute_management(trees_lyr, "NEW_SELECTION", selection_query) ag_output = "ag_{}".format(c) print(" aggregating") arcpy.AggregatePolygons_cartography(trees_lyr, ag_output, "25 METERS", "1 HECTARES", "1 HECTARES", "ORTHOGONAL") print(" Adding and calculating field") arcpy.AddField_management(ag_output, "commodity", "TEXT") arcpy.CalculateField_management(ag_output, "commodity", "'{}'".format(c), "ARCADE") print(" created {}".format(ag_output)) # Copy aggregated features to output location print(" copying to output location") arcpy.CopyFeatures_management(ag_output, output + "_{}".format(c)) update_list.append(output + "_{}".format(c)) # make a list of ag_... feature classes and loop update analysis tool print("Joining features back together with update tool") loop_no = len(com_list) update_no = 0 update_output = output + "_update{}".format(update_no) print("update_list: {}".format(update_list)) print("loop_no: {}".format(loop_no)) print("update_no: {}".format(update_no)) print("update_output: {}".format(update_output)) arcpy.CopyFeatures_management(update_list[0], update_output) while update_no + 1 <= loop_no: loop_name = update_list[update_no].split("{}_".format(output_fc))[-1] print(" {} loop ({}/{})".format(loop_name, update_no + 1, loop_no)) if update_no == 0: arcpy.Update_analysis(update_output, update_list[update_no], output + "_update{}".format(update_no + 1)) print(" variables: {}, {}, {}".format( update_output, update_list[update_no], output + "_update{}".format(update_no + 1))) else: arcpy.Update_analysis(output + "_update{}".format(update_no), update_list[update_no], output + "_update{}".format(update_no + 1)) print(" variables: {}, {}, {}".format( output + "_update{}".format(update_no), update_list[update_no], output + "_update{}".format(update_no + 1))) update_no += 1 arcpy.CopyFeatures_management(output + "_update{}".format(loop_no), output) # join attributes back to output print("Trying spatial join") arcpy.SpatialJoin_analysis(output, trees_memory, output + "_join", "JOIN_ONE_TO_ONE") # Add hectare field arcpy.AddField_management(output + "_join", "hectares", "DOUBLE") arcpy.CalculateGeometryAttributes_management( output + "_join", [["hectares", "AREA_GEODESIC"]], area_unit="HECTARES", coordinate_system=4283) # Overwrite output print("Explode, and overwriting output") arcpy.MultipartToSinglepart_management(output + "_join", output) # Clean up fields join_field_del_list = [ "Join_Count", "TARGET_FID", "comment", "other", "stage", "edit", "Shape__Area", "Shape__Length", "commodity_1", "ORIG_FID", "field", "review", "imagery", "industry", "uncertain" ] print("Deleting the following fields:") print(join_field_del_list) for i in join_field_del_list: arcpy.DeleteField_management(output, i) # Assign domains print("Assigning domains") arcpy.AssignDomainToField_management(output, "source", "source_domain") arcpy.AssignDomainToField_management(output, "commodity", "commodity_domain") arcpy.AssignDomainToField_management(output, "year", "year_domain") arcpy.env.workspace = output_workspace # Delete all working features except actual output, topology and original tree data. print("Trying to delete unnecessary data") del_fc_list = arcpy.ListFeatureClasses("{}_*".format(output_fc)) print(del_fc_list) for i in del_fc_list: print("Deleting {}".format(i)) arcpy.Delete_management(output_workspace + "\\{}".format(i)) # Derive points print("Creating points") arcpy.FeatureToPoint_management(output_fc, output + "_point", "INSIDE")
def add_gnss_fields(feature_layer): """ This adds specific fields required for GPS units to auto-populate in collector application This will report errors if: 1) Any of the fields already exist 2) The input layer is not a point layer 3) The layer is not found 4) The layer is a shapefile Example: add_gps_fields(r"C:/temp/test.shp") :param feature_layer: (string) The feature layer (shapefile, feature class, etc) to add the fields to :return: """ try: if not arcpy.Exists(feature_layer): arcpy.AddError( "Feature layer: {} not found!".format(feature_layer)) return if arcpy.Describe(feature_layer).shapeType != "Point": arcpy.AddError( "Feature layer: {} is not a point layer".format(feature_layer)) return if arcpy.Describe(feature_layer).dataType == "Feature Layer": if arcpy.Describe( feature_layer).dataElement.dataType == "ShapeFile": arcpy.AddError("ShapeFiles are not supported.") return elif arcpy.Describe(feature_layer).dataType == "ShapeFile": arcpy.AddError("ShapeFiles are not supported.") return # check if it's a service or feature class in db # Check the domains to see if they exist and are valid # will update if necessary if r'/rest/services' not in arcpy.Describe(feature_layer).catalogPath: arcpy.AddMessage('Checking domains...') geodatabase = get_geodatabase_path(feature_layer) check_and_create_domains(geodatabase) # Add the fields arcpy.AddMessage('Adding Required Fields...') # Add GNSS metadata fields existingFields = [ field.name for field in arcpy.ListFields(feature_layer) ] if 'ESRIGNSS_POSITIONSOURCETYPE' not in existingFields: arcpy.AddField_management( feature_layer, 'ESRIGNSS_POSITIONSOURCETYPE', field_type="SHORT", field_alias='Position source type', field_is_nullable="NULLABLE", field_domain="ESRI_POSITIONSOURCETYPE_DOMAIN") if 'ESRIGNSS_RECEIVER' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_RECEIVER', field_type="STRING", field_length=50, field_alias='Receiver Name', field_is_nullable="NULLABLE") if 'ESRIGNSS_LATITUDE' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_LATITUDE', field_type="DOUBLE", field_alias='Latitude', field_is_nullable="NULLABLE") if 'ESRIGNSS_LONGITUDE' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_LONGITUDE', field_type="DOUBLE", field_alias='Longitude', field_is_nullable="NULLABLE") if 'ESRIGNSS_ALTITUDE' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_ALTITUDE', field_type="DOUBLE", field_alias='Altitude', field_is_nullable="NULLABLE") if 'ESRIGNSS_H_RMS' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_H_RMS', field_type="DOUBLE", field_alias='Horizontal Accuracy (m)', field_is_nullable="NULLABLE") if 'ESRIGNSS_V_RMS' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_V_RMS', field_type="DOUBLE", field_alias='Vertical Accuracy (m)', field_is_nullable="NULLABLE") if 'ESRIGNSS_FIXDATETIME' not in existingFields: arcpy.AddField_management( feature_layer, 'ESRIGNSS_FIXDATETIME', field_type="Date", field_alias='Fix Time', field_is_nullable="NULLABLE", ) if 'ESRIGNSS_FIXTYPE' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_FIXTYPE', field_type="SHORT", field_alias='Fix Type', field_is_nullable="NULLABLE", field_domain="ESRI_FIX_TYPE_DOMAIN") if 'ESRIGNSS_CORRECTIONAGE' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_CORRECTIONAGE', field_type="DOUBLE", field_alias='Correction Age', field_is_nullable="NULLABLE") if 'ESRIGNSS_STATIONID' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_STATIONID', field_type="SHORT", field_alias='Station ID', field_is_nullable="NULLABLE") if 'ESRIGNSS_NUMSATS' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_NUMSATS', field_type="SHORT", field_alias='Number of Satellites', field_is_nullable="NULLABLE", field_domain="ESRI_NUM_SATS_DOMAIN") if 'ESRIGNSS_PDOP' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_PDOP', field_type="DOUBLE", field_alias='PDOP', field_is_nullable="NULLABLE") if 'ESRIGNSS_HDOP' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_HDOP', field_type="DOUBLE", field_alias='HDOP', field_is_nullable="NULLABLE") if 'ESRIGNSS_VDOP' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_VDOP', field_type="DOUBLE", field_alias='VDOP', field_is_nullable="NULLABLE") if 'ESRIGNSS_DIRECTION' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_DIRECTION', field_type="DOUBLE", field_alias='Direction of travel (°)', field_is_nullable="NULLABLE") if 'ESRIGNSS_SPEED' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRIGNSS_SPEED', field_type="DOUBLE", field_alias='Speed (km/h)', field_is_nullable="NULLABLE") if 'ESRISNSR_AZIMUTH' not in existingFields: arcpy.AddField_management(feature_layer, 'ESRISNSR_AZIMUTH', field_type="DOUBLE", field_alias='Compass reading (°)', field_is_nullable="NULLABLE") if 'ESRIGNSS_AVG_H_RMS' not in existingFields: arcpy.AddField_management( feature_layer, 'ESRIGNSS_AVG_H_RMS', field_type="DOUBLE", field_alias='Average Horizontal Accuracy (m)', field_is_nullable="NULLABLE", ) if 'ESRIGNSS_AVG_V_RMS' not in existingFields: arcpy.AddField_management( feature_layer, 'ESRIGNSS_AVG_V_RMS', field_type="DOUBLE", field_alias='Average Vertical Accuracy (m)', field_is_nullable="NULLABLE", ) if 'ESRIGNSS_AVG_POSITIONS' not in existingFields: arcpy.AddField_management( feature_layer, 'ESRIGNSS_AVG_POSITIONS', field_type="SHORT", field_alias='Averaged Positions', field_is_nullable="NULLABLE", ) if 'ESRIGNSS_H_STDDEV' not in existingFields: arcpy.AddField_management( feature_layer, 'ESRIGNSS_H_STDDEV', field_type="DOUBLE", field_alias='Standard Deviation (m)', field_is_nullable="NULLABLE", ) arcpy.AddMessage("Successfully added GPS Metadata fields.\n") # Update fields with Domains arcpy.AddMessage('Updating Fields with Domains...') # Update GNSS metadata fields with Domains domainFields = [field for field in arcpy.ListFields(feature_layer) if field.name == 'ESRIGNSS_FIXTYPE' or \ field.name == 'ESRIGNSS_STATIONID' or field.name == 'ESRIGNSS_NUMSATS' or field.name == 'ESRIGNSS_POSITIONSOURCETYPE'] for field in domainFields: if field.name == 'ESRIGNSS_FIXTYPE' and not field.domain: arcpy.AssignDomainToField_management(feature_layer, field, 'ESRI_FIX_TYPE_DOMAIN') continue if field.name == 'ESRIGNSS_NUMSATS' and not field.domain: arcpy.AssignDomainToField_management(feature_layer, field, 'ESRI_NUM_SATS_DOMAIN') continue if field.name == 'ESRIGNSS_POSITIONSOURCETYPE' and not field.domain: arcpy.AssignDomainToField_management( feature_layer, field, 'ESRI_POSITIONSOURCETYPE_DOMAIN') continue arcpy.AddMessage( "Successfully updated GPS Metadata fields with domains.\n") except Exception as e: arcpy.AddError("{}\n".format(e)) return
fgdb_name = 'DataCollection.gdb' workspace_path = current_dir + '\\' + fgdb_name arcpy.env.workspace = r'D:\vs2015 项目练习\610EX3\610EX3\DataCollection.gdb' arcpy.CreateFeatureclass_management(fgdb_name, "test", "POINT") #add field arcpy.AddField_management("test", "rateScore", "TEXT") # Set local parameters domName = "Rate" gdb = "DataCollection.gdb" inField = "rateScore" # Process: Create the coded value domain arcpy.CreateDomain_management("DataCollection.gdb", domName, "score", "TEXT", "CODED") # Store all the domain values in a dictionary with the domain code as the "key" # and the domain description as the "value" (domDict[code]) domDict = {"A": "111", "B": "222", "C": "333", "D": "444", "E": "555"} # Process: Add valid material types to the domain # use a for loop to cycle through all the domain codes in the dictionary for code in domDict: arcpy.AddCodedValueToDomain_management(gdb, domName, code, domDict[code]) # Process: Constrain the material value of distribution mains arcpy.AssignDomainToField_management('test', inField, domName)
arcpy.AddField_management(FC, "EXPEDIENTE", "TEXT", field_precision=20) arcpy.AddField_management(FC, "OPERADOR", "TEXT", field_precision=100) arcpy.AddField_management(FC, "PROYECTO", "TEXT", field_precision=100) arcpy.AddField_management(FC, "VEREDA", "TEXT", field_precision=255) arcpy.AddField_management(FC, "MUNICIPIO", "TEXT", field_precision=5) arcpy.AddField_management(FC, "DEPARTAMENTO", "TEXT", field_precision=2) arcpy.AddField_management(FC, "ID_VEDA", "TEXT", field_precision=10) arcpy.AddField_management(FC, "N_COBERTURA", "TEXT", field_precision=255) arcpy.AddField_management(FC, "NOMENCLATURA", "TEXT", field_precision=255) arcpy.AddField_management(FC, "DESCRIPCION", "TEXT", field_precision=255) arcpy.AddField_management(FC, "FECHA_MUESTRA", "DATE") arcpy.AddField_management(FC, "OBSERVACIONES", "TEXT", field_precision=255) arcpy.AddField_management(FC, "ESTE", "DOUBLE") arcpy.AddField_management(FC, "NORTE", "DOUBLE") arcpy.AssignDomainToField_management(FC, "MUNICIPIO", "Dom_Departamento") arcpy.AssignDomainToField_management(FC, "DEPARTAMENTO", "Dom_Municipio") # Creating MedidaVeda arcpy.CreateFeatureclass_management(dataSet, "MedidaVeda", "POLYGON") FC = dataSet + '\\MedidaVeda' arcpy.AddField_management(FC, "EXPEDIENTE", "TEXT", field_precision=20) arcpy.AddField_management(FC, "OPERADOR", "TEXT", field_precision=100) arcpy.AddField_management(FC, "PROYECTO", "TEXT", field_precision=100) arcpy.AddField_management(FC, "VEREDA", "TEXT", field_precision=255) arcpy.AddField_management(FC, "MUNICIPIO", "TEXT", field_precision=5) arcpy.AddField_management(FC, "DEPARTAMENTO", "TEXT", field_precision=2) arcpy.AddField_management(FC, "MEDIDA_MANEJO", "TEXT", field_precision=3) arcpy.AddField_management(FC, "COBERTURA", "TEXT", field_precision=255) arcpy.AddField_management(FC, "NOMENCLATURA", "TEXT", field_precision=255)
#arcpy.CreateDomain_management(in_workspace, doname, "No or Yes", "TEXT", "CODED") arcpy.CreateDomain_management(workspace, doname, "No or Yes", "TEXT", "CODED") # Add Coded Value to Domain #arcpy.AddCodedValueToDomain_management (in_workspace, doname, "Yes", "Yes") arcpy.AddCodedValueToDomain_management(workspace, doname, "Yes", "Yes") #arcpy.AddCodedValueToDomain_management (in_workspace, doname, "No", "No") arcpy.AddCodedValueToDomain_management(workspace, doname, "No", "No") #Assign Domain To Field #arcpy.AssignDomainToField_management (inFC, "RECERT_NEEDED", doname) arcpy.AssignDomainToField_management(workspace + '\\' "Project_Record", "RECERT_NEEDED", doname) arcpy.EnableEditorTracking_management(workspace + '\\' "MUPOLYGON", "Creator_Field", "Creation_Date_Field", "Editor_Field", "Last_Edit_Date_Field", "ADD_FIELDS", "UTC") arcpy.EnableEditorTracking_management(workspace + '\\' "FEATPOINT", "Creator_Field", "Creation_Date_Field", "Editor_Field", "Last_Edit_Date_Field", "ADD_FIELDS", "UTC") arcpy.EnableEditorTracking_management(workspace + '\\' "FEATLINE", "Creator_Field", "Creation_Date_Field", "Editor_Field", "Last_Edit_Date_Field", "ADD_FIELDS",
print(i + "Collector_Field.gdb") # For each geodatabase create the Photo_Direction domain domName = "PhotoDirection" for i in GDBPathsList: arcpy.CreateDomain_management(i, domName, "Cardinal Direction of the Photo", "TEXT", "CODED") domDict = {"N": "N", "E": "E", "S": "S", "W": "W"} for code in domDict: arcpy.AddCodedValueToDomain_management(i, domName, code, domDict[code]) print(i) # For each Geodatabase create a line, point, and polygon layer LineTemplate = r"E:\Dropbox (RES)\@RES GIS\projects\CA\Domain\GDB\PajaroCollector_Field.gdb\Line" PolygonTemplate = r"E:\Dropbox (RES)\@RES GIS\projects\CA\Domain\GDB\PajaroCollector_Field.gdb\Polygon" PointTemplate = r"C:\Users\jtouzel\Documents\ArcGIS\Templates.gdb\Point" has_m = "DISABLED" has_z = "DISABLED" for i in GDBPathsList: arcpy.CreateFeatureclass_management(i, "Point", "POINT", PointTemplate, has_m, has_z, prj10) pointPath = os.path.join(i, "Point") arcpy.AssignDomainToField_management(pointPath, "PHOTO_DIRECTION", domName) arcpy.CreateFeatureclass_management(i, "Line", "POLYLINE", LineTemplate, has_m, has_z, prj10) arcpy.CreateFeatureclass_management(i, "Polygon", "POLYGON", PolygonTemplate, has_m, has_z, prj10) print(i)
if not "Hydro_Domain" in listOfDomains: arcpy.TableToDomain_management(Hydro_Groups_Lookup, "HydrolGRP", "HydrolGRP", watershedGDB_path, "Hydro_Domain", "Hydro_Domain", "REPLACE") if not "Condition_Domain" in listOfDomains: arcpy.TableToDomain_management(Condition_Lookup, "CONDITION", "CONDITION", watershedGDB_path, "Condition_Domain", "Condition_Domain", "REPLACE") del listOfDomains # Assign Domain To Landuse Fields for User Edits... arcpy.AssignDomainToField_management(landuse, "LANDUSE", "LandUse_Domain", "") arcpy.AssignDomainToField_management(landuse, "CONDITION", "Condition_Domain", "") AddMsgAndPrint( "\tSuccessfully added \"LANDUSE\" and \"CONDITION\" fields to Landuse Layer and associated Domains", 0) # ---------------------------------------------------------------------------------------------------------------------------------- Work with soils # --------------------------------------------------------------------------------------- Clip Soils # Clip the soils to the dissolved (and possibly unioned) watershed arcpy.Clip_analysis(inSoils, landuse, wsSoils) AddMsgAndPrint( "\nSuccessfully clipped soils layer to Landuse layer and removed unnecessary fields",
def main(): # GET PARAMETER VALUES Analysis_Area = arcpy.GetParameterAsText(0) Current_Anthro_Features_Provided = arcpy.GetParameterAsText(1) # optional Dist_Lek = arcpy.GetParameterAsText(2) # DEFINE DIRECTORIES # Get the pathname to this script scriptPath = sys.path[0] arcpy.AddMessage("Script folder: " + scriptPath) # Construct pathname to workspace workspace = arcpy.Describe(Analysis_Area).path arcpy.AddMessage("Project geodatabase: " + workspace) # Instantiate a ccsStandard object ccsStandard = ccslib.ccsStandard(workspace, scriptPath) # ENVIRONMENT SETTINGS # Set workspaces arcpy.env.workspace = workspace scratch_folder = os.path.join(arcpy.Describe(workspace).path, 'scratch') if arcpy.Exists(scratch_folder): pass else: arcpy.CreateFolder_management( arcpy.Describe(workspace).path, 'scratch') arcpy.env.scratchWorkspace = scratch_folder # Overwrite outputs arcpy.env.overwriteOutput = True # DEFINE VARIABLES FOR INPUT DATA AnthroAttributeTable = ccsStandard.AnthroAttributeTable emptyRaster = ccsStandard.EmptyRaster inputDataPath = ccsStandard.InputDataPath # Filenames for feature classes and raster used by this script ELIGIBLE_PROPOSED_FEATURES = "Proposed_Surface_Disturbance_Eligible" DEBIT_PROJECT_AREA = "Debit_Project_Area" # Filenames for feature classes and rasters created by this script CURRENT_ANTHRO_FEATURES = "Current_Anthro_Features" PROJECTED_ANTHRO_FEATURES = "Projected_Anthro_Features" PERMANENT_ANTHRO_FEATURES = "Permanent_Anthro_Features" CURRENT_ANTHRO_DISTURBANCE = "Current_Anthro_Disturbance" PROJECTED_ANTHRO_DISTURBANCE = "Projected_Anthro_Disturbance" PERMANENT_ANTHRO_DISTURBANCE = "Permanent_Anthro_Disturbance" MAP_UNITS = "Map_Units" # ------------------------------------------------------------------------ # FUNCTION CALLS # Check tool version ccslib.CheckToolVersion() # Check out Spatial Analyst extension ccslib.CheckOutSpatialAnalyst() # Check Analysis_Area expected_fcs = [ELIGIBLE_PROPOSED_FEATURES, DEBIT_PROJECT_AREA] ccslib.CheckPolygonInput(Analysis_Area, expected_fcs=expected_fcs) # Create Current_Anthro_Features layer, or copy provided into geodatabase if Current_Anthro_Features_Provided: # Clear selection, if present ccslib.ClearSelectedFeatures(Current_Anthro_Features_Provided) # Check Current_Anthro_Features required_fields = [ "Type", "Subtype", "Overlap_Status", "Returned", "Subtype_As_Modified" ] no_null_fields = None expected_fcs = None ccslib.CheckPolygonInput(Current_Anthro_Features_Provided, required_fields, expected_fcs, no_null_fields) # Update message arcpy.AddMessage("Copying Current_Anthro_Features to project " "geodatabase") # Copy Current_Anthro_Features to geodatabase provided_input = Current_Anthro_Features_Provided parameter_name = CURRENT_ANTHRO_FEATURES Current_Anthro_Features = ccslib.AdoptParameter(provided_input, parameter_name, preserve_existing=True) else: # Update message arcpy.AddMessage("Merging all clipped anthropogenic features to " "create the Current_Anthro_Features layer") # Merge features (selecting only polygon features) fileList = arcpy.ListFeatureClasses("Anthro*Clip", feature_type="Polygon") out_name = CURRENT_ANTHRO_FEATURES Current_Anthro_Features = ccslib.MergeFeatures(fileList, out_name) # Simplify fields. critical to remove any fields named # 'Surface_Disturbance' in Current_Anthro_Features before joining # Proposed_Surface_Disturbance to create Projected_Anthro_Features allowable_fields = [ "Type", "Subtype", "SubtypeID", "Subtype_As_Modified", "Overlap_Status", "Returned" ] ccslib.SimplifyFields(Current_Anthro_Features, allowable_fields) # Remove subtypes from Current_Anthro_Features feature = Current_Anthro_Features subtypes = arcpy.da.ListSubtypes(feature) try: if len(subtypes) == 1 and subtypes[0]['SubtypeField'] == '': pass else: for subtype in subtypes: arcpy.RemoveSubtype_management(feature, subtype) arcpy.AddMessage("Subtype removed") except arcpy.ExecuteError: arcpy.AddMessage("Could not remove Subtype Domain from " "Current_Anthro_Features") # Add Domains for Type and Subtype try: arcpy.RemoveDomainFromField_management(feature, "Type") arcpy.AssignDomainToField_management(feature, "Type", "Type") except arcpy.ExecuteError: arcpy.AddMessage("Could not update Type Domain for " "Current_Anthro_Features") try: arcpy.RemoveDomainFromField_management(feature, "Subtype") arcpy.AssignDomainToField_management(feature, "Subtype", "Subtype") except arcpy.ExecuteError: arcpy.AddMessage("Could not update Subtype Domain for " "Current_Anthro_Features") try: arcpy.RemoveDomainFromField_management(feature, "Subtype_As_Modified") arcpy.AssignDomainToField_management(feature, "Subtype", "Subtype") except arcpy.ExecuteError: arcpy.AddMessage("Could not update Type Domain for " "Current_Anthro_Features") # Calculate Current_Anthro_Disturbance extent_fc = Analysis_Area anthro_features = Current_Anthro_Features term = ccsStandard.DebitTerms[0] Current_Anthro_Disturbance = ccslib.CalcAnthroDist(extent_fc, anthro_features, emptyRaster, AnthroAttributeTable, term) Current_Anthro_Disturbance.save(CURRENT_ANTHRO_DISTURBANCE) # Update message arcpy.AddMessage("Current_Anthro_Disturbance Calculated") arcpy.AddMessage("Removing any anthropogenic features from the " "Current_Anthro_Features layer that will be " "replaced or upgraded from one subtype to another " "by the debit project") # Calculate post-project anthropogenic disturbance mod_field = "Overlap_Status" removed_code = "Removed" subtype_mod_field = "Subtype_As_Modified" out_name = PROJECTED_ANTHRO_FEATURES Projected_Anthro_Features = ccslib.SelectProposed( Current_Anthro_Features, ELIGIBLE_PROPOSED_FEATURES, mod_field, removed_code, subtype_mod_field, out_name) # Simplify fields (do not remove Surface Disturbance or Reclassified # Subtype field for use in SelectPermanent()) allowable_fields = [ "Type", "Subtype", "SubtypeID", "Overlap_Status", "Returned", "Subtype_As_Modified" "Surface_Disturbance", "Reclassified_Subtype" ] ccslib.SimplifyFields(Projected_Anthro_Features, allowable_fields) # Calculate Projected_Anthro_Disturbance extent_fc = Analysis_Area anthro_features = Projected_Anthro_Features term = ccsStandard.DebitTerms[1] Projected_Anthro_Disturbance = ccslib.CalcAnthroDist( extent_fc, anthro_features, emptyRaster, AnthroAttributeTable, term) Projected_Anthro_Disturbance.save(PROJECTED_ANTHRO_DISTURBANCE) # Update message arcpy.AddMessage("Projected_Anthro_Disturbance Calculated") arcpy.AddMessage("Creating Permanent Anthro Features and calculating " "disturbance") # Calculate permanent anthropogenic disturbance # Select permanent anthropogenic features from Projected Anthro Features mod_field = "Overlap_Status" returned_field = "Returned" subtype_mod_field = "Subtype_As_Modified" duration_field = "Surface_Disturbance" permanent_codes = ["Term_Reclassified", "Permanent"] reclass_code = "Term_Reclassified" reclass_subtype_field = "Reclassified_Subtype" out_name = PERMANENT_ANTHRO_FEATURES Permanent_Anthro_Features = ccslib.SelectPermanent( Current_Anthro_Features, ELIGIBLE_PROPOSED_FEATURES, mod_field, returned_field, subtype_mod_field, duration_field, permanent_codes, reclass_code, reclass_subtype_field, out_name) # Simplify fields allowable_fields = [ "Type", "Subtype", "SubtypeID", "Overlap_Status", "Returned", "Subtype_As_Modified" "Surface_Disturbance", "Reclassified_Subtype" ] ccslib.SimplifyFields(Permanent_Anthro_Features, allowable_fields) # Calculate Permanent Anthro Disturbance extent_fc = Analysis_Area anthro_features = Permanent_Anthro_Features term = ccsStandard.DebitTerms[2] Permanent_Anthro_Disturbance = ccslib.CalcAnthroDist( extent_fc, anthro_features, emptyRaster, AnthroAttributeTable, term) Permanent_Anthro_Disturbance.save(PERMANENT_ANTHRO_DISTURBANCE) # Update message arcpy.AddMessage("Permanent_Anthro_Disturbance Calculated") # Calculate local scale modifiers for Current, Projected, and # Permanent condition extent_fc = Analysis_Area terms = ccsStandard.DebitTerms for term in terms: anthro_disturbance = term + "_Anthro_Disturbance" ccslib.CalcModifiers(extent_fc, inputDataPath, Dist_Lek, anthro_disturbance, term) # Calculate impact intensity for debit project try: ccslib.calcDebitImpact(inputDataPath) # Add debit project impact to map layerFile = ccsStandard.getLayerFile("Debit_Project_Impact.lyr") ccslib.AddToMap("Debit_Project_Impact", layerFile, zoom_to=True) except: pass # Update message arcpy.AddMessage("Creating Map Units layer") # Create Map_Units layer Project_Area = DEBIT_PROJECT_AREA out_name = MAP_UNITS Map_Units = ccslib.CreateMapUnits(Project_Area, out_name) # Update message arcpy.AddMessage("Creating pre-defined map units of Wet Meadows") # Intersect the Map_Units layer with the NV Wet Meadows layer in_feature = ccsStandard.Wet_Meadows field_name = "Meadow" na_value = "No Meadow" ccslib.CreatePreDefinedMapUnits(Map_Units, in_feature, field_name, na_value) # Update message arcpy.AddMessage("Creating pre-defined map units of PJ") # Intersect the Map_Units layer with the Phase III PJ layer in_feature = ccsStandard.PJ_Phase_III field_name = "Conifer_Phase" ccslib.CreatePreDefinedMapUnits(Map_Units, in_feature, field_name) # Update message arcpy.AddMessage("Creating pre-defined map units of proposed surface " "disturbance") # Intersect the Map_Units layer with the proposed surface disturbance in_features = ELIGIBLE_PROPOSED_FEATURES ccslib.CreatePreDefinedMapUnits(Map_Units, in_features, field_name) # Remove unwanted fields from Map Units feature class allowable_fields = [ "Disturbance_Type", "BROTEC", "Conifer_Phase", "Meadow" ] ccslib.SimplifyFields(Map_Units, allowable_fields) # Populate empty attributes with Indirect feature = Map_Units fieldName = "Disturbance_Type" where_clause = "{} = ''".format( arcpy.AddFieldDelimiters(feature, fieldName)) with arcpy.da.UpdateCursor(feature, fieldName, where_clause) as cursor: for row in cursor: row[0] = "Indirect" cursor.updateRow(row) # Add Map_Units to map layerFile = ccsStandard.getLayerFile("Map_Units.lyr") ccslib.AddToMap(Map_Units, layerFile) # Add fields Map_Unit_ID, Map_Unit_Name, and Precip to map unit input_feature = Map_Units fields = ["Map_Unit_ID", "Map_Unit_Name", "Notes"] fieldTypes = ["SHORT", "TEXT", "TEXT"] ccslib.AddFields(input_feature, fields, fieldTypes, copy_existing=True) # Add Domains to Map_Units layer # Create Domain for Map_Unit_ID attributes input_feature = Map_Units domainName = "Map_Unit_ID" range_low = 0 range_high = 10000 ccslib.AddRangeDomain(input_feature, workspace, domainName, range_low, range_high) # Create Domain for Meadow attributes featureList = [Map_Units] domainName = "Meadow" codeList = ["Altered", "Unaltered", "No Meadow"] ccslib.AddCodedTextDomain(featureList, workspace, domainName, codeList) # Clean up arcpy.Delete_management("in_memory") # Save map document and exit if arcpy.ListInstallations()[0] == 'arcgispro': p = arcpy.mp.ArcGISProject("CURRENT") p.save() else: mxd = arcpy.mapping.MapDocument("CURRENT") mxd.save()
def main(thisDB, coordSystem, nCrossSections): # create feature dataset GeologicMap addMsgAndPrint(' Creating feature dataset GeologicMap...') try: arcpy.CreateFeatureDataset_management(thisDB, 'GeologicMap', coordSystem) except: addMsgAndPrint(arcpy.GetMessages(2)) # create feature classes in GeologicMap # poly feature classes featureClasses = ['MapUnitPolys'] for fc in ['DataSourcePolys', 'MapUnitOverlayPolys', 'OverlayPolys']: if fc in OptionalElements: featureClasses.append(fc) for featureClass in featureClasses: fieldDefs = tableDict[featureClass] if addLTYPE and fc <> 'DataSourcePolys': fieldDefs.append(['PTYPE', 'String', 'NullsOK', 50]) createFeatureClass(thisDB, 'GeologicMap', featureClass, 'POLYGON', fieldDefs) # line feature classes featureClasses = ['ContactsAndFaults'] for fc in ['GeologicLines', 'CartographicLines', 'IsoValueLines']: if fc in OptionalElements: featureClasses.append(fc) if debug: addMsgAndPrint('Feature classes = ' + str(featureClasses)) for featureClass in featureClasses: fieldDefs = tableDict[featureClass] if featureClass in ['ContactsAndFaults', 'GeologicLines'] and addLTYPE: fieldDefs.append(['LTYPE', 'String', 'NullsOK', 50]) createFeatureClass(thisDB, 'GeologicMap', featureClass, 'POLYLINE', fieldDefs) # point feature classes featureClasses = [] for fc in [ 'OrientationPoints', 'GeochronPoints', 'FossilPoints', 'Stations', 'GenericSamples', 'GenericPoints' ]: if fc in OptionalElements: featureClasses.append(fc) for featureClass in featureClasses: fieldDefs = tableDict[featureClass] if addLTYPE: fieldDefs.append(['PTTYPE', 'String', 'NullsOK', 50]) createFeatureClass(thisDB, 'GeologicMap', featureClass, 'POINT', fieldDefs) # create feature dataset CorrelationOfMapUnits if 'CorrelationOfMapUnits' in OptionalElements: addMsgAndPrint(' Creating feature dataset CorrelationOfMapUnits...') arcpy.CreateFeatureDataset_management(thisDB, 'CorrelationOfMapUnits') fieldDefs = tableDict['CMUMapUnitPolys'] createFeatureClass(thisDB, 'CorrelationOfMapUnits', 'CMUMapUnitPolys', 'POLYGON', fieldDefs) fieldDefs = tableDict['CMULines'] createFeatureClass(thisDB, 'CorrelationOfMapUnits', 'CMULines', 'POLYLINE', fieldDefs) fieldDefs = tableDict['CMUPoints'] createFeatureClass(thisDB, 'CorrelationOfMapUnits', 'CMUPoints', 'POINT', fieldDefs) # create CrossSections if nCrossSections > 26: nCrossSections = 26 if nCrossSections < 0: nCrossSections = 0 # note space in position 0 alphabet = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ' for n in range(1, nCrossSections + 1): xsLetter = alphabet[n] xsName = 'CrossSection' + xsLetter xsN = 'CS' + xsLetter #create feature dataset CrossSectionA addMsgAndPrint(' Creating feature data set CrossSection' + xsLetter + '...') arcpy.CreateFeatureDataset_management(thisDB, xsName) fieldDefs = tableDict['MapUnitPolys'] if addLTYPE: fieldDefs.append(['PTYPE', 'String', 'NullsOK', 100]) fieldDefs[0][0] = xsN + 'MapUnitPolys_ID' createFeatureClass(thisDB, xsName, xsN + 'MapUnitPolys', 'POLYGON', fieldDefs) fieldDefs = tableDict['ContactsAndFaults'] if addLTYPE: fieldDefs.append(['LTYPE', 'String', 'NullsOK', 100]) fieldDefs[0][0] = xsN + 'ContactsAndFaults_ID' createFeatureClass(thisDB, xsName, xsN + 'ContactsAndFaults', 'POLYLINE', fieldDefs) fieldDefs = tableDict['OrientationPoints'] if addLTYPE: fieldDefs.append(['PTTYPE', 'String', 'NullsOK', 100]) fieldDefs[0][0] = xsN + 'OrientationPoints_ID' createFeatureClass(thisDB, xsName, xsN + 'OrientationPoints', 'POINT', fieldDefs) # create tables tables = ['DescriptionOfMapUnits', 'DataSources', 'Glossary'] for tb in [ 'RepurposedSymbols', 'StandardLithology', 'GeologicEvents', 'MiscellaneousMapInformation' ]: if tb in OptionalElements: tables.append(tb) for table in tables: addMsgAndPrint(' Creating table ' + table + '...') try: arcpy.CreateTable_management(thisDB, table) fieldDefs = tableDict[table] for fDef in fieldDefs: try: if fDef[1] == 'String': arcpy.AddField_management(thisDB + '/' + table, fDef[0], transDict[fDef[1]], '#', '#', fDef[3], '#', transDict[fDef[2]]) else: arcpy.AddField_management(thisDB + '/' + table, fDef[0], transDict[fDef[1]], '#', '#', '#', '#', transDict[fDef[2]]) except: addMsgAndPrint('Failed to add field ' + fDef[0] + ' to table ' + table) addMsgAndPrint(arcpy.GetMessages(2)) except: addMsgAndPrint(arcpy.GetMessages()) ### GeoMaterials addMsgAndPrint(' Setting up GeoMaterials table and domains...') # Copy GeoMaterials table arcpy.Copy_management( os.path.dirname(sys.argv[0]) + '/../Resources/GeMS_lib.gdb/GeoMaterialDict', thisDB + '/GeoMaterialDict') # make GeoMaterials domain arcpy.TableToDomain_management(thisDB + '/GeoMaterialDict', 'GeoMaterial', 'IndentedName', thisDB, 'GeoMaterials') # attach it to DMU field GeoMaterial arcpy.AssignDomainToField_management(thisDB + '/DescriptionOfMapUnits', 'GeoMaterial', 'GeoMaterials') # Make GeoMaterialConfs domain, attach it to DMU field GeoMaterialConf arcpy.CreateDomain_management(thisDB, 'GeoMaterialConfidenceValues', '', 'TEXT', 'CODED') for val in GeoMaterialConfidenceValues: arcpy.AddCodedValueToDomain_management(thisDB, 'GeoMaterialConfidenceValues', val, val) arcpy.AssignDomainToField_management(thisDB + '/DescriptionOfMapUnits', 'GeoMaterialConfidence', 'GeoMaterialConfidenceValues') #Confidence domains, Glossary entries, and DataSources entry if addConfs: addMsgAndPrint( ' Adding standard ExistenceConfidence and IdentityConfidence domains' ) # create domain, add domain values, and link domain to appropriate fields addMsgAndPrint( ' Creating domain, linking domain to appropriate fields') arcpy.CreateDomain_management(thisDB, 'ExIDConfidenceValues', '', 'TEXT', 'CODED') for item in DefaultExIDConfidenceValues: # items are [term, definition, source] code = item[0] arcpy.AddCodedValueToDomain_management(thisDB, 'ExIDConfidenceValues', code, code) arcpy.env.workspace = thisDB dataSets = arcpy.ListDatasets() for ds in dataSets: arcpy.env.workspace = thisDB + '/' + ds fcs = arcpy.ListFeatureClasses() for fc in fcs: fieldNames = fieldNameList(fc) for fn in fieldNames: if fn in ('ExistenceConfidence', 'IdentityConfidence', 'ScientificConfidence'): #addMsgAndPrint(' '+ds+'/'+fc+':'+fn) arcpy.AssignDomainToField_management( thisDB + '/' + ds + '/' + fc, fn, 'ExIDConfidenceValues') # add definitions of domain values to Glossary addMsgAndPrint(' Adding domain values to Glossary') ## create insert cursor on Glossary cursor = arcpy.da.InsertCursor( thisDB + '/Glossary', ['Term', 'Definition', 'DefinitionSourceID']) for item in DefaultExIDConfidenceValues: cursor.insertRow((item[0], item[1], item[2])) del cursor # add definitionsource to DataSources addMsgAndPrint(' Adding definition source to DataSources') ## create insert cursor on DataSources cursor = arcpy.da.InsertCursor(thisDB + '/DataSources', ['DataSources_ID', 'Source', 'URL']) cursor.insertRow(( 'FGDC-STD-013-2006', 'Federal Geographic Data Committee [prepared for the Federal Geographic Data Committee by the U.S. Geological Survey], 2006, FGDC Digital Cartographic Standard for Geologic Map Symbolization: Reston, Va., Federal Geographic Data Committee Document Number FGDC-STD-013-2006, 290 p., 2 plates.', 'https://ngmdb.usgs.gov/fgdc_gds/geolsymstd.php')) del cursor # if cartoReps, add cartographic representations to all feature classes # trackEdits, add editor tracking to all feature classes and tables if cartoReps or trackEdits: arcpy.env.workspace = thisDB tables = arcpy.ListTables() datasets = arcpy.ListDatasets() for dataset in datasets: addMsgAndPrint(' Dataset ' + dataset) arcpy.env.workspace = thisDB + '/' + dataset fcs = arcpy.ListFeatureClasses() for fc in fcs: hasReps, repLyr = cartoRepsExistAndLayer(fc) if cartoReps and hasReps: addMsgAndPrint( ' Adding cartographic representations to ' + fc) try: arcpy.AddRepresentation_cartography( fc, fc + '_rep1', 'RuleID1', 'Override1', default, repLyr, 'NO_ASSIGN') """ Note the 1 suffix on the representation name (fc+'_rep1') and the RuleID1 and Override1 fields. If at some later time we wish to add additional representations to a feature class, each will require it's own RuleID and Override fields which may be identified, and tied to the appropriate representation, by suffixes 2, 3, ... Naming representations fc+'_rep'+str(n) should be sufficient to identify each representation in a geodatabase uniquely, and allow for multiple representations within a single feature class. It appears that ArcGIS provides no means of scripting an inventory of representations within feature class or geodatabase. So, the convenience of establishing a coded-value domain that ties representation rule IDs (consecutive integers) to some sort of useful text identifier becomes a necessity for flagging the presence of a representation: One CAN script the inventory of domains in a geodatabase. Run arcpy.da.ListDomains. Check the result for names of the form <featureClassName>_rep??_Rule and voila, you've got a list of representations (and their associated feature classes) in the geodatabase. Moral: If you add a representation, be sure to add an associated coded-value domain and name it appropriately! """ except: addMsgAndPrint(arcpy.GetMessages(2)) if trackEdits: addTracking(fc) if trackEdits: addMsgAndPrint(' Tables ') arcpy.env.workspace = thisDB for aTable in tables: if aTable <> 'GeoMaterialDict': addTracking(aTable)
field_type = 'text' arcpy.AddField_management(inFeatures, fieldname, "TEXT") featureClass = r'C:\gisclass\classHW.gdb\NewFC' print('field created') domName = "NewDomain" gdb = current_workspace inFeatures = featureClass inField = fieldname arcpy.CreateDomain_management(gdb, domName, "This is the stuff", "TEXT", "CODED") domDict = { "1": "stuff", "2": "stuff2", "3": "stuff3", "4": "stuff4", "5": "Boom!" } for code in domDict: arcpy.AddCodedValueToDomain_management(gdb, domName, code, domDict[code]) arcpy.AssignDomainToField_management(inFeatures, inField, domName) print('Success')