def build_domains(fgdb, domains): """Create the esri domains (picklists) for track logs and features.""" arcpy.CreateDomain_management( fgdb, "YesNoBoolean", "Yes/No values", "SHORT", "CODED" ) arcpy.AddCodedValueToDomain_management(fgdb, "YesNoBoolean", 0, "No") arcpy.AddCodedValueToDomain_management(fgdb, "YesNoBoolean", 1, "Yes") for domain in domains: name = "{0}Codes".format(domain) description = "Valid values for {0}".format(domain) arcpy.CreateDomain_management(fgdb, name, description, "SHORT", "CODED") items = domains[domain] for i, item in enumerate(items): arcpy.AddCodedValueToDomain_management(fgdb, name, i, item)
def updateDomains(domainsFolder, targetGDB): try: arcpy.AddMessage("Starting: UpdateDomains") # Update all coded (list) domains path = os.path.normpath( os.path.join(domainsFolder, "Coded_Domain_*.csv")) for fname in glob.glob(path): # Find the domain's name and description and then add it to the gdb domainName, domainDescription = findNameAndDescription( fname, "Coded_Domain_") arcpy.AddMessage("Updating domain " + domainName + "...") arcpy.TableToDomain_management(fname, "Value", "Name", targetGDB, domainName, domainDescription, "REPLACE") # Update all range domains path = os.path.normpath( os.path.join(domainsFolder, "Range_Domain_*.csv")) for fname in glob.glob(path): # Find the domain's name and description and then add it to the gdb domainName, domainDescription = findNameAndDescription( fname, "Range_Domain_") arcpy.AddMessage("Updating domain " + domainName + "...") # Set the range domain's min and max values with open(fname, 'r') as csvFile: reader = csv.reader(csvFile, dialect='excel') # Skip the header, use the second line header = next(reader) line = next(reader) arcpy.CreateDomain_management(targetGDB, domainName, domainDescription, Utility.fieldTypeLookup(line[0]), "RANGE") arcpy.SetValueForRangeDomain_management( targetGDB, domainName, int(line[1]), int(line[2])) except Exception as err: arcpy.AddError( traceback.format_exception_only(type(err), err)[0].rstrip()) else: arcpy.AddMessage("Success! - Completed: UpdateDomains") finally: arcpy.AddMessage("Exiting: UpdateDomains")
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 create_temp_domain(workspace,old_domain_obj): arcpy.CreateDomain_management( in_workspace = workspace, domain_name = 'TEMP_DOMAIN', domain_description = 'Temporary domain used in domain update script', field_type = old_domain_obj.type, domain_type = "CODED")
def createCodedValuesDomain(cls, name, description, field_type, values): """Add a coded values domain, and populate it with coded values.""" arcpy.CreateDomain_management(cls.fixture_path, name, description, field_type, 'CODED') for (code, desc) in values.items(): arcpy.AddCodedValueToDomain_management(cls.fixture_path, name, code, desc)
def create_gdb_domain(gdb, name, description, ftype, dtype, c_values): new_domain = arcpy.CreateDomain_management(in_workspace=gdb, domain_name=name, domain_description=description, field_type=ftype, domain_type=dtype) for coded_value in c_values: arcpy.AddCodedValueToDomain_management(gdb, name, coded_value, c_values[coded_value]) print("Field Domain {} added to FGDB".format(name))
def addJson2Gdb(self): listJsons = [os.path.join(self.path, x) for x in os.listdir(self.path)] for jsonFile in listJsons: with open(jsonFile, "r") as f: jx=f.read().decode("Windows-1252") df = pd.read_json(jx) domain = arcpy.CreateDomain_management(self.gdb, df["name"][0], '', 'TEXT') for dom in df['codedValues']: val = [v for k,v in dom.items()] arcpy.AddCodedValueToDomain_management(self.gdb, df['name'][0], val[0], val[1])
def makeDomain(jsonFile): with open(jsonFile, "r") as f: jx = f.read().decode("Windows-1252") df = pd.read_json(jx) domain = arcpy.CreateDomain_management(gdb, df["name"][0], '', 'TEXT') for dom in df['codedValues']: val = [v for k, v in dom.items()] print val arcpy.AddCodedValueToDomain_management(gdb, df['name'][0], val[0], val[1])
def addToWorkspace(self, workspace): """Add this domain to the GDB workspace.""" arcpy.CreateDomain_management(workspace, self.domainName, self.description, self.fieldType, self.domainType, self.splitPolicy, self.mergePolicy) for code in self.codedValues: print code arcpy.AddCodedValueToDomain_management(workspace, self.domainName, code, self.codedValues[code])
def makeDomain(self, jsonFile): with open(jsonFile, "r") as f: jx = f.read().decode("Windows-1252") data = json.loads(jx) df = pd.DataFrame.from_dict(data) domain = arcpy.CreateDomain_management(self.pathGdb, df['name'][0], "", "TEXT") print df['name'][0] for dom in df['codedValues']: val = [v for k, v in dom.items()] arcpy.AddCodedValueToDomain_management(self.pathGdb, df['name'][0], val[0], val[1])
def AddValueToDomain(workspace, domain, code, description): arcpy.env.workspace = workspace if not arcpy.Exists(domain): arcpy.CreateDomain_management(in_workspace=workspace, domain_name=domain, domain_description=domain, field_type="TEXT", domain_type="CODED", split_policy="DEFAULT", merge_policy="DEFAULT") arcpy.AddCodedValueToDomain_management(workspace, domain, code, description)
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 create_domins(): _in_workspace = get_workspace() for _key in createDomainDict: _domain_dict = createDomainDict[_key] arcpy.CreateDomain_management( in_workspace=_in_workspace, domain_name=_domain_dict[0], domain_description=_domain_dict[1], field_type=_domain_dict[2], domain_type=_domain_dict[3], split_policy=_domain_dict[4], ) print("Domain created: {}".format(_key))
def CreateDomain(workspace, nome, desc, field_type, domain_type, split_policy, merge_policy): try: domain_names = [d.name for d in arcpy.da.ListDomains(workspace)] if nome in domain_names: print u"Dominio {} já existe.".format(nome) else: arcpy.CreateDomain_management(workspace, nome, desc, field_type, domain_type, split_policy, merge_policy) print u"Dominio {} foi criado com sucesso.".format(nome) except Exception as ex: print u"ERRO ao criar dominio:", nome, ex.message
def AddDomains(self): ListDomains = [ getattr(fields.domains, domain) for domain in dir(fields.domains) if not domain[0:2] == '__' ] for domain in ListDomains: print(domain['name']) arcpy.CreateDomain_management(self.gdb, domain['name'], domain['alias'], domain['type'], "CODED") for code in domain['codes'].keys(): arcpy.AddCodedValueToDomain_management(self.gdb, domain['name'], code, domain['codes'][code])
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 alter_domain_name(): soucedomain = domain_dictionary('SPDM2_201803.gdb','Short') for dmname, alias_codesc in soucedomain.items(): new_dmname = dmname[0:2]+'_' + dmname[2:] #if del_nm == dmname: if dmname[2] != '_': arcpy.CreateDomain_management(outdataset, new_dmname, alias_codesc[0], 'Short', 'CODED') print "创建域值" for cod, desc in alias_codesc[1].items(): try: arcpy.AddCodedValueToDomain_management(outdataset, new_dmname, int(cod), desc) except arcpy.ExecuteError: print arcpy.GetMessages() print cod, desc print type(cod) arcpy.DeleteDomain_management(outdataset,dmname)
def _json_to_domain(output_target, out_gdb, x): if output_target == OUTPUT_GDB: # Process: Create the coded value domain arcpy.CreateDomain_management( out_gdb, x['name'], field_type=_json_type_to_gdb_type(x['fieldType']), domain_type='CODED' if x['subType'] == 'CodedValue' else 'RANGE', domain_description=x['description']) for kv in x['values']: arcpy.AddCodedValueToDomain_management(out_gdb, x['name'], kv['k'], kv['v']) elif output_target == OUTPUT_XML: template = """<Domain xsi:type='esri:CodedValueDomain'> <DomainName>%(name)s</DomainName> <FieldType>%(type)s</FieldType> <MergePolicy>esriMPTDefaultValue</MergePolicy> <SplitPolicy>esriSPTDefaultValue</SplitPolicy> <Description></Description> <Owner></Owner> <CodedValues xsi:type='esri:ArrayOfCodedValue'> %(domains)s </CodedValues> </Domain>""" domains = list( map( lambda kv: """<CodedValue xsi:type='esri:CodedValue'> <Name>%(v)s</Name> <Code xsi:type='xs:%(type)s'>%(k)s</Code> </CodedValue>""" % { 'type': _json_type_to_xml_attr_type(x['fieldType']), 'k': kv['k'], 'v': kv['v'] }, x['values'])) return template % { 'name': x['name'], 'type': _json_type_to_xml_type(x['fieldType']), 'domains': "\n".join(domains) }
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 alter_domiantype_single(): outdataset = r'D:\智能化管线项目\新气\新气数据处理\新气数据入库_0916\新库0910.gdb' save_domain = domain_dictionary(outdataset, 'LONG') # print save_domain arcpy.DeleteDomain_management(outdataset, "gn_Reportstatus") for dmname, alias_codesc in save_domain.items(): # if del_nm == dmname: arcpy.CreateDomain_management(outdataset, "gn_Reportstatus", alias_codesc[0], 'Short', 'CODED') print "创建域值" for cod, desc in alias_codesc[1].items(): try: arcpy.AddCodedValueToDomain_management(outdataset, "gn_Reportstatus", int(cod), desc) except arcpy.ExecuteError: print arcpy.GetMessages() print cod, desc print type(cod)
def addJson2Gdb(self): """ Agregar Dominios a Geodatabase :return: """ listJsons = [ os.path.join(pathDomain, x) for x in os.listdir(pathDomain) ] print listJsons for jsonFile in listJsons: with open(jsonFile, "r") as f: jx = f.read().decode("Windows-1252") df = pd.read_json(jx) print df arcpy.CreateDomain_management(self.gdb, df["name"][0], '', 'TEXT') for dom in df['codedValues']: val = [v for k, v in dom.items()] arcpy.AddCodedValueToDomain_management(self.gdb, df['name'][0], val[0], val[1])
def create_domains(gdb): domain_definitions = [[ 'Status', 'STATUS_DOMAIN', ['Poor', 'Fair', 'Good', 'Very good', 'Excellent'] ], ['Color', 'COLOR_DOMAIN', ['Red', 'Green', 'Yellow', 'Blue']]] for domain_definition in domain_definitions: arcpy.CreateDomain_management(in_workspace=gdb, domain_name=domain_definition[1], domain_description=domain_definition[0], field_type="TEXT", domain_type="CODED", split_policy="DEFAULT", merge_policy="DEFAULT") for value in domain_definition[2]: arcpy.AddCodedValueToDomain_management( in_workspace=gdb, domain_name=domain_definition[1], code=value, code_description=value)
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)
"FL_INDEX", "UNIQUE", "ASCENDING") #arcpy.AddIndex_management(workspace+'\\'"FEATLINE", "AREASYMBOL", "AREASYMBOL", "UNIQUE", "ASCENDING") #arcpy.AddIndex_management(workspace+'\\'"FEATLINE", "FEATSYM", "FEATSYM", "UNIQUE", "ASCENDING") #arcpy.AddIndex_management(workspace+'\\'"FEATLINE", "FEATKEY", "FEATKEY", "UNIQUE", "ASCENDING") arcpy.AddIndex_management(workspace + '\\' "SAPOLYGON", ["AREASYMBOL"], "SA_INDEX", "UNIQUE", "ASCENDING") #arcpy.AddIndex_management(workspace+'\\'"SAPOLYGON", "AREASYMBOL", "AREASYMBOL", "UNIQUE", "ASCENDING") doname = "RECERT_NEEDED" #Domain Name #Create Domain #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)
def create_domain(nrows): # global flg flg = '' flg_bk = '' item_flg = '' for k in range(nrows): domains = arcpy.da.ListDomains(arcpy.env.workspace) domname_lst = [domain.name for domain in domains] 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('') # print alst if len(alst) > 2: # 注意截取的字符串 # item_flg = table.cell(k, 2).value # print flg+"1" try: if table.cell(k, 0).value not in domname_lst: arcpy.CreateDomain_management( arcpy.env.workspace, table.cell(k, 0).value, table.cell(k, 1).value, table.cell(k, 2).value.upper(), "CODED") flg = table.cell(k, 0).value # print flg item_flg = table.cell(k, 2).value.upper() # print item_flg flg_bk = '' else: print "{} 该阈值名称已经存在!".format(table.cell(k, 0).value) flg_bk = table.cell(k, 0).value flg = '' except RuntimeError, arcpy.ExecuteError: print arcpy.GetMessages() # except arcpy.ExecuteError as err: # print err elif len(alst) == 2: # print 10*"#" # print flg # print flg_bk # print 10 * "#" if flg_bk: # print flg_bk # print "因为阈值{}已存在,无需再为其添加阈值项!".format(flg_bk) continue elif flg: # print 222 try: # print 112 # print item_flg # print 113 if item_flg == 'SHORT': arcpy.AddCodedValueToDomain_management( arcpy.env.workspace, flg, int(table.cell(k, 0).value), table.cell(k, 1).value) print int(table.cell(k, 0).value) print type(int(table.cell(k, 0).value)), table.cell( k, 1).value else: arcpy.AddCodedValueToDomain_management( arcpy.env.workspace, flg, table.cell(k, 0).value, table.cell(k, 1).value) except RuntimeError: print arcpy.GetMessages()
arcpy.env.workspace = workspace # Feature Dataset aanmaken voor de FC's per vak oDS = workspace + "/SRFLINE_SDATA" arcpy.AddMessage("Uitvoer Dataset: " + oDS + "\n") if not arcpy.Exists(oDS): arcpy.CreateFeatureDataset_management(workspace, "SRFLINE_SDATA") arcpy.AddMessage("Uitvoer Dataset: SRFLINE_SDATA aangemaakt!") else: arcpy.AddMessage("Bestaande uitvoer Dataset: SRFLINE_SDATA gebruiken!") #--------------------------------------------------------- # Om de mogelijkheid te hebben om na het genereren van de dwarsprofielen per vak verkeerder profielen uit te kunnen # zetten wordt er een kolom aan het basis profiellijnen en punten bestand(PWK_DWARSPROFIEL_POINT en PWK_DWARSPROFIEL_LINE) # toegevoegd incl een domein met ja/nee try: arcpy.AddMessage("Domein aanmaken: ") arcpy.CreateDomain_management(workspace, 'Meenemen', 'Meenemen', "TEXT", "CODED") arcpy.AddCodedValueToDomain_management(workspace, 'Meenemen', 'ja', 'ja') arcpy.AddCodedValueToDomain_management(workspace, 'Meenemen', 'nee', 'nee') except: arcpy.AddWarning("Domein al toegevoegd!") # Kolom toevoegen incl. domein try: arcpy.AddField_management(ppFC, "meenemen", "TEXT", "", "", 3, "", "NULLABLE", "NON_REQUIRED", "Meenemen") #arcpy.AssignDefaultToField_management(in_table=ppFC, field_name="meenemen", default_value="ja", subtype_code="", clear_value="false") arcpy.AddField_management(plFC, "meenemen", "TEXT", "", "", 3, "", "NULLABLE", "NON_REQUIRED", "Meenemen") #arcpy.AssignDefaultToField_management(in_table=plFC, field_name="meenemen", default_value="ja", subtype_code="", clear_value="false") # ff alles op ja zetten arcpy.CalculateField_management(in_table=ppFC, field="meenemen",
def check_and_create_domains(geodatabase): """ Checks if the domains already exist, if they do then it checks the values and ranges If the domains do not exist, they are created :param geodatabase: (string) the path to the geodatabase to check :return: """ domains = arcpy.da.ListDomains(geodatabase) domain_names = [domain.name for domain in domains] if 'Yes_No' in domain_names: for domain in domains: if domain.name == 'Yes_No': # check if cvs 0,1,2,4,5 are in the codedValues values = [cv for cv in domain.codedValues] if not set(set([0, 1, 2, 4, 5])).issubset(values): arcpy.AddIDMessage("ERROR This domain already exists") return else: # Add the domain and values arcpy.CreateDomain_management(in_workspace=geodatabase, domain_name="Yes_No", domain_description="Yes or No", field_type="TEXT", domain_type="CODED", split_policy="DEFAULT", merge_policy="DEFAULT") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Yes_No", code="Yes", code_description="Yes") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Yes_No", code="No", code_description="No") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Yes_No", code="N/A", code_description="N/A") # Check if 'Inspector" is a domain, if so check the range if 'Inspector' in domain_names: for domain in domains: if domain.name == 'Inspector': # check if cvs 0,1,2,4,5 are in the codedValues values = [cv for cv in domain.codedValues] if not set(set([0, 1, 2, 4, 5])).issubset(values): arcpy.AddIDMessage("ERROR This domain already exists") return else: # Add the domain and set the range arcpy.CreateDomain_management(in_workspace=geodatabase, domain_name="Inspector", domain_description="Inspector", field_type="TEXT", domain_type="CODED", split_policy="DEFAULT", merge_policy="DEFAULT") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Inspector", code="ALA", code_description="ALA") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Inspector", code="BAR", code_description="BAR") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Inspector", code="BUR", code_description="BUR") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Inspector", code="CAS", code_description="CAS") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Inspector", code="JJH", code_description="JJH") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Inspector", code="JLK", code_description="JLK") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Inspector", code="JWN", code_description="JWN") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Inspector", code="MJT", code_description="MJT") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Inspector", code="REM", code_description="REM") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Inspector", code="RWG", code_description="RWG") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Inspector", code="SAB", code_description="SAB") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Inspector", code="SJS", code_description="SJS") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Inspector", code="SUB", code_description="SUB") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Inspector", code="WBH", code_description="WBH") # Check if Flow Percentage is a domain if 'Flow_Percent' in domain_names: for domain in domains: if domain.name == 'Flow_Percent': # check if cvs 0,1,2,4,5 are in the codedValues values = [cv for cv in domain.codedValues] if not set(set([0, 1, 2, 4, 5])).issubset(values): arcpy.AddIDMessage("ERROR This domain already exists") return else: # Add the domain and set the range arcpy.CreateDomain_management(in_workspace=geodatabase, domain_name="Flow_Percent", domain_description="Flow Percentage", field_type="TEXT", domain_type="CODED", split_policy="DEFAULT", merge_policy="DEFAULT") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Flow_Percent", code="0", code_description="0% (No Flow)") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Flow_Percent", code="25", code_description="25%") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Flow_Percent", code="50", code_description="50%") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Flow_Percent", code="75", code_description="75%") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Flow_Percent", code="100", code_description="100%") # Check if Clock Position is a domain if 'Clock_Pos' in domain_names: for domain in domains: if domain.name == 'Clock_Pos': # check if cvs 0,1,2,4,5 are in the codedValues values = [cv for cv in domain.codedValues] if not set(set([0, 1, 2, 4, 5])).issubset(values): arcpy.AddIDMessage("ERROR This domain already exists") return else: # Add the domain and set the range arcpy.CreateDomain_management(in_workspace=geodatabase, domain_name="Clock_Pos", domain_description="Clock Position", field_type="TEXT", domain_type="CODED", split_policy="DEFAULT", merge_policy="DEFAULT") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Clock_Pos", code="1", code_description="1 o'clock") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Clock_Pos", code="10", code_description="10 o'clock") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Clock_Pos", code="11", code_description="11 o'clock") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Clock_Pos", code="12", code_description="12 o'clock") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Clock_Pos", code="2", code_description="2 o'clock") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Clock_Pos", code="3", code_description="3 o'clock") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Clock_Pos", code="4", code_description="4 o'clock") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Clock_Pos", code="5", code_description="5 o'clock") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Clock_Pos", code="6", code_description="6 o'clock") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Clock_Pos", code="7", code_description="7 o'clock") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Clock_Pos", code="8", code_description="8 o'clock") arcpy.AddCodedValueToDomain_management(in_workspace=geodatabase, domain_name="Clock_Pos", code="9", code_description="9 o'clock")
def check_and_create_domains(geodatabase): """ Checks if the domains already exist, if they do then it checks the values and ranges If the domains do not exist, they are created :param geodatabase: (string) the path to the geodatabase to check :return: """ domains = arcpy.da.ListDomains(geodatabase) domain_names = [domain.name for domain in domains] if 'ESRI_FIX_TYPE_DOMAIN' in domain_names: for domain in domains: if domain.name == 'ESRI_FIX_TYPE_DOMAIN': # check if cvs 0,1,2,4,5 are in the codedValues values = [cv for cv in domain.codedValues] if not set(set([0, 1, 2, 4, 5])).issubset(values): arcpy.AddError( "ESRI_FIX_TYPE_DOMAIN is missing a coded value pair.") return else: # Add the domain and values arcpy.AddMessage( 'Adding ESRI_FIX_TYPE_DOMAIN domain to parent geodatabase...') arcpy.CreateDomain_management(in_workspace=geodatabase, domain_name="ESRI_FIX_TYPE_DOMAIN", domain_description="Fix Type", field_type="SHORT", domain_type="CODED", split_policy="DEFAULT", merge_policy="DEFAULT") arcpy.AddCodedValueToDomain_management( in_workspace=geodatabase, domain_name="ESRI_FIX_TYPE_DOMAIN", code="0", code_description="Fix not valid") arcpy.AddCodedValueToDomain_management( in_workspace=geodatabase, domain_name="ESRI_FIX_TYPE_DOMAIN", code="1", code_description="GPS") arcpy.AddCodedValueToDomain_management( in_workspace=geodatabase, domain_name="ESRI_FIX_TYPE_DOMAIN", code="2", code_description="Differential GPS") arcpy.AddCodedValueToDomain_management( in_workspace=geodatabase, domain_name="ESRI_FIX_TYPE_DOMAIN", code="4", code_description="RTK Fixed") arcpy.AddCodedValueToDomain_management( in_workspace=geodatabase, domain_name="ESRI_FIX_TYPE_DOMAIN", code="5", code_description="RTK Float") # Check if 'NumSats" is a domain, if so check the range if 'ESRI_NUM_SATS_DOMAIN' in domain_names: if domain.name == "ESRI_NUM_SATS_DOMAIN": if domain.range[0] != 0 or domain.range[1] != 99: arcpy.AddError("ESRI_NUM_SATS_DOMAIN domain has invalid range") return else: # Add the domain and set the range arcpy.AddMessage("Adding ESRI_NUM_SATS_DOMAIN to parent database...") arcpy.CreateDomain_management( in_workspace=geodatabase, domain_name="ESRI_NUM_SATS_DOMAIN", domain_description="Number of Satellites", field_type="SHORT", domain_type="RANGE", split_policy="DEFAULT", merge_policy="DEFAULT") arcpy.SetValueForRangeDomain_management(geodatabase, "ESRI_NUM_SATS_DOMAIN", 0, 99) if 'ESRI_POSITIONSOURCETYPE_DOMAIN' in domain_names: for domain in domains: if domain.name == 'ESRI_POSITIONSOURCETYPE_DOMAIN': # check if cvs 0,1,2,3,4 are in the codedValues values = [cv for cv in domain.codedValues] if not set(set([0, 1, 2, 3, 4])).issubset(values): arcpy.AddError( "ESRI_POSITIONSOURCETYPE_DOMAIN is missing a coded value pair." ) return else: # Add the domain and values arcpy.AddMessage( 'Adding ESRI_POSITIONSOURCETYPE_DOMAIN domain to parent geodatabase...' ) arcpy.CreateDomain_management( in_workspace=geodatabase, domain_name="ESRI_POSITIONSOURCETYPE_DOMAIN", domain_description="Position Source Type", field_type="SHORT", domain_type="CODED", split_policy="DEFAULT", merge_policy="DEFAULT") arcpy.AddCodedValueToDomain_management( in_workspace=geodatabase, domain_name="ESRI_POSITIONSOURCETYPE_DOMAIN", code="0", code_description="Unknown") arcpy.AddCodedValueToDomain_management( in_workspace=geodatabase, domain_name="ESRI_POSITIONSOURCETYPE_DOMAIN", code="1", code_description="User defined") arcpy.AddCodedValueToDomain_management( in_workspace=geodatabase, domain_name="ESRI_POSITIONSOURCETYPE_DOMAIN", code="2", code_description="Integrated (System) Location Provider") arcpy.AddCodedValueToDomain_management( in_workspace=geodatabase, domain_name="ESRI_POSITIONSOURCETYPE_DOMAIN", code="3", code_description="External GNSS Receiver") arcpy.AddCodedValueToDomain_management( in_workspace=geodatabase, domain_name="ESRI_POSITIONSOURCETYPE_DOMAIN", code="4", code_description="Network Location Provider")
logger.logGPMsg() print "creating geodatabase" arcpy.CreateFileGDB_management(out_folder, dbName) logger.logGPMsg() print "creating coded value domains" for d in domains: print d arcpy.TableToDomain_management(domainsXLS + "\\" + d + "$", "CODE", "CODE", gdb, "roadkill_" + d, "roadkill_" + d) logger.logGPMsg() print "creating xyphoid range domain" arcpy.CreateDomain_management(gdb, xyphoidDomainName, xyphoidDomainName, "SHORT", "RANGE") logger.logGPMsg() arcpy.SetValueForRangeDomain_management(gdb, xyphoidDomainName, xyphoidMin, xyphoidMax) logger.logGPMsg() print "creating Reports fc" srPath = os.path.join( arcpy.GetInstallInfo()["InstallDir"], r"Coordinate Systems\Projected Coordinate Systems\UTM\NAD 1983\NAD 1983 UTM Zone 12N.prj" ) spatial_reference = arcpy.SpatialReference(srPath) arcpy.CreateFeatureclass_management(gdb, reports, "POINT", None, None, None, spatial_reference) logger.logGPMsg()
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.AddField_management(FC, "OBSERVACIONES", "TEXT", field_precision=255) arcpy.AddField_management(FC, "AREA_ha", "Double") arcpy.AssignDomainToField_management(FC, "MUNICIPIO", "Dom_Departamento") arcpy.AssignDomainToField_management(FC, "DEPARTAMENTO", "Dom_Municipio") # Creating Med_Manejo domName = "Med_Manejo" inField = "MEDIDA_MANEJO" # Process: Create the coded value domain arcpy.CreateDomain_management(gdb, domName, "Tipo de medida de manejo;", "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 = { "100": "Reubicación", "200": "Rescate", "300": "Traslado", "400": "Compensación", "500": "Otro" } # 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_1, domName, code, domDict[code])