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)
Example #2
0
def export_all_domains(geodatabase, workspace=None):
    """Output all the domains in a geodatabase
    to tables in a workspace.
    :param geodatabase {String}:
        Path or reference to a geodatabase.
    :param output_folder {String}
        optional path to output folder. If not supplied defaults to gdb
    """
    try:
        if not workspace:
            workspace = geodatabase
        domains = arcpy.da.ListDomains(geodatabase)
        for domain in domains:
            dname = arcpy.ValidateTableName(domain.name + '_domain', workspace)
            output = os.path.join(workspace, dname)
            output_msg('Exporting {0} domain to {1}'.format(
                domain.name, dname))
            arcpy.DomainToTable_management(geodatabase, domain.name, output,
                                           "codedValues", 'description')

    except Exception as e:
        output_msg(str(e.args[0]))
        output_msg(arcpy.GetMessages())
    finally:
        output_msg("Completed")
Example #3
0
    def initializeRulesByMilitaryFeatures(self, featureClass):
        # Military Feature use several different possible fields to store this Rule ID
        desc = arcpy.Describe(featureClass)
        CODE_FIELD_NAME = "code"
        DESCRIPTION_FIELD_NAME = "description"
        ruleFieldName = None
        ruleDomainName = None
        for field in desc.Fields:
            if (field.name in DictionaryConstants.RuleFieldsList):
                if (field.domain is not None and field.domain != ""):
                    # Note Bene: only works with FGDBs (assumes MilFeature only stored in these)
                    dataPath = desc.path
                    gdbPath = dataPath.split(".gdb")[0]
                    gdbPath += ".gdb"
                    ruleFieldName = field.name
                    ruleDomainName = field.domain
                    arcpy.DomainToTable_management(
                        gdbPath, field.domain, "in_memory/" + ruleDomainName,
                        CODE_FIELD_NAME, DESCRIPTION_FIELD_NAME)
                    break

        # map both ways for performance/simplicty of use
        ruleID2Name = self.getRuleID2NameDictionary()
        name2RuleID = self.getName2RuleIDDictionary()

        symbolCount = 0
        if (ruleFieldName is None) or (ruleDomainName is None):
            arcpy.AddError("Layer RuleId not found, can't continue")
        else:
            print "Symbol RuleId found & exporting: " + ruleFieldName
            domainRows = arcpy.SearchCursor("in_memory/" + ruleDomainName)
            for domainRow in domainRows:
                ruleid = domainRow.getValue(CODE_FIELD_NAME)
                symbolname = domainRow.getValue(DESCRIPTION_FIELD_NAME)

                if self.endsInPAA(symbolname):
                    symbolname = symbolname[0:-6]

                symbolCount = symbolCount + 1
                print str(ruleid) + " --> " + symbolname
                ruleID2Name[ruleid] = symbolname
                name2RuleID[symbolname] = ruleid

        if symbolCount == 0:
            arcpy.AddError("No Layer RepRules found, can't continue")
            ruleFieldName = None
        elif symbolCount < 50:
            arcpy.AddWarning("Only " + str(symbolCount) +
                             " RepRules found, may not work as expected")

        return ruleFieldName
Example #4
0
def export_domains(domains):
    for domain in domains:
        arcpy.AddMessage('Exporting %s CV to table in %s' % (domain.name, gdb))
        table = os.path.join(gdb, domain.name)
        arcpy.DomainToTable_management(gdb, domain.name, table, 'field',
                                       'descript', '#')
        if xls:
            os.chdir(gdb)
            os.chdir('..')
            xlsfile = '%s_%s.xls' % (os.path.join(
                os.path.basename(gdb)), domain.name)
            arcpy.AddMessage('Exporting %s CV to table in %s' %
                             (domain.name, xlsfile))
            arcpy.TableToExcel_conversion(table, xlsfile)
Example #5
0
    def create_domain_table(self, domain):
        domain_name = slugify(domain.name, separator='_', lowercase=False)
        domain_table = "{}_lut".format(domain_name)

        domain_field = "Code"
        domain_field_desc = "Description"

        print(" {}".format(domain_table))

        if not arcpy.Exists(domain_table):
            arcpy.DomainToTable_management(
                self.workspace, domain.name, domain_table, domain_field, domain_field_desc)

        # create index
        self.create_index(domain_table, domain_field)
        self.split_schemas(domain_table, "lookup_tables")
Example #6
0
def DomainToTableIamuw(DomainLocation, NameFilter, TableDatabase):
    '''
        This function takes a database that contains ESRI domains (string) that
        the user wants to export to tables.  A filter to query out some of the
        domains if necessary (string) and finally a secondary database where the
        new tables will be created (string).
        '''
    arcpy.env.workspace = TableDatabase
    arcpy.env.overwriteOutput = True
    Description = arcpy.Describe(DomainLocation)
    Domains = Description.domains
    for Domain in Domains:
        print Domain
        if NameFilter in Domain:
            Table = os.path.join(TableDatabase, Domain)
            arcpy.DomainToTable_management(DomainLocation, Domain, Table,
                                           'Code', 'Description')
Example #7
0
    def create_domain_table(self, domain):
        domain_name = domain.name.replace(" ", "")
        domain_table = "%s_lut" % domain_name

        domain_field = "Code"
        domain_field_desc = "Description"

        print " %s" % domain_table

        if not arcpy.Exists(domain_table):
            arcpy.DomainToTable_management(self.workspace, domain.name,
                                           domain_table, domain_field,
                                           domain_field_desc)

        # create index
        self.create_index(domain_table, domain_field)
        self.split_schemas(domain_table, "lookup_tables")
Example #8
0
 def __init__(self):
     global bike_lanes_cv
     self.items = []
     self.bike_lanes_dict = {}
     arcpy.DomainToTable_management(
         r'X:\Trans\Bicycle and Pedestrian\Data\BikeFacilities\2020_GDB_Update\OSM_Sockeye.sde',
         'BikeLanes2', 'in_memory/bike_lanes_cv', 'codeField',
         'descriptionField')
     with arcpy.da.SearchCursor(
             'in_memory/bike_lanes_cv',
         ['codeField', 'descriptionField']) as cursor:
         for row in cursor:
             self.bike_lanes_dict[row[1]] = row[0]
             self.items.append(row[1])
     #arcpy.Delete_management("in_memory/bike_lanes_cv")
     bike_lanes_cv = self.bike_lanes_dict['Yes']
     #self.cvd_dict = self.getCVDDict()
     #self.items = ["item1", "item2"]
     self.editable = True
     self.enabled = True
     self.dropdownWidth = 'WWW'
     self.width = 'WWW'
     self.value = "Yes"
Example #9
0
    def create_domain_table(self, domain):
        domain_name = domain.name.replace(" ", "")
        logging.debug("create_domain_table: {} ".format(domain_name))
        domain_table = "{}{}".format(self.lookup_prefix, domain_name.lower())

        domain_field = "Code"
        domain_field_desc = "Description"

        logging.debug(" %s" % domain_table)

        if not arcpy.Exists(domain_table):
            arcpy.DomainToTable_management(self.workspace, domain.name,
                                           domain_table, domain_field,
                                           domain_field_desc)

        # create index
        dom = {
            "feature": domain_table,
            "type": "table",
            "schema": self.lookup_tables_schema
        }
        self.domain_tables.append(dom)
        self.create_index(domain_table, domain_field,
                          self.lookup_tables_schema)
import os
import arcpy
from arcpy.sa import *

arcpy.env.overwriteOutput = True

geodatabase_name = r"Vancouver.gdb"
geodatabase_location = r"G:\CART3032\projects\Vancouver"
geodatabase = os.path.join(geodatabase_location, geodatabase_name)

target_location = r"C:\Temp"

code_field = "Key"
value_field = "Value"

domains = [
    "road_class_cl",
    "building_function_cl",
]
# domains = arcpy.Describe(geodatabase).domains

for domain in domains:
    dbf = os.path.join(target_location, domain + ".dbf")
    arcpy.DomainToTable_management(geodatabase, str(domain), dbf, code_field,
                                   value_field)
    with arcpy.da.UpdateCursor(dbf, [value_field]) as cursor:
        for row in cursor:
            row[0] = row[0].split(": ")[1].split(" / ")[0]
            cursor.updateRow(row)
Example #11
0
import os, arcpy
# Set workspace environment to geodatabase
arcpy.env.workspace = r"C:\Users\jamatney\AppData\Roaming\Esri\Desktop10.2\ArcCatalog\rtca user connected to rtca_new database.sde"

arcpy.overwriteOutput = True

gdb = r"C:\Users\jamatney\AppData\Roaming\ESRI\Desktop10.4\ArcCatalog\Connection to CASCADES.cnr.ncsu.edu.sde"
gdb_domains = r"C:\Users\jamatney\Desktop\Domains\domains.gdb"

desc = arcpy.Describe(gdb)
domains = desc.domains

for domain in domains:
    print 'Exporting %s CV to table in %s' % (domain, gdb)
    out_table = os.path.join(gdb_domains, domain)
    arcpy.DomainToTable_management(gdb, domain, out_table, 'field','description', '#')
Example #12
0
def createTables(surveyGDB, outWorkspace, prefix):
    '''Creates the doamins, tables and relationships of the survey in the target workspace'''
    arcpy.AddMessage('\t-Creating Tables')
    arcpy.env.workspace = surveyGDB
    allTables = getSurveyTables(surveyGDB)

    dscW = arcpy.Describe(arcpy.env.workspace)
    #migrate the domains
    arcpy.AddMessage('\t\t-Creating Domains')
    for domainName in dscW.domains:
        if domainName[0:3] == 'cvd':
            arcpy.AddMessage('\t\t\t-'.format(domainName))
            tempTable = 'in_memory\{0}'.format(domainName)
            domainTable = arcpy.DomainToTable_management(surveyGDB, domainName, tempTable,'CODE', 'DESC')
            newDomain = arcpy.TableToDomain_management(tempTable, 'CODE', 'DESC', outWorkspace, domainName, update_option='REPLACE')
            arcpy.Delete_management(tempTable)

    arcpy.AddMessage("\t\t-Creating Feature Classes & Tables")
    for table in allTables:
        dsc = arcpy.Describe(table)
        newTableName = "{0}_{1}".format(prefix, table)
        templateTable = template=os.path.join(surveyGDB, table)

        if dsc.datatype == u'FeatureClass':
            newTable = arcpy.CreateFeatureclass_management(outWorkspace, newTableName, "POINT", template=templateTable, spatial_reference=dsc.spatialReference)
        else:
            newTable = arcpy.CreateTable_management(outWorkspace, newTableName, template=templateTable)
        arcpy.AddMessage("\t\t\t-Created {0}".format(newTableName))

        #Attach domains to fields
        tableFields = arcpy.ListFields(table)
        for field in tableFields:
            if field.domain != '':
                arcpy.AssignDomainToField_management(newTable, field.name, field.domain)
        if dscW.workspaceType == "RemoteDatabase":
            arcpy.RegisterAsVersioned_management(newTable)

    arcpy.AddMessage('\t\t-Creating Relationships')
    #Reconnect Relationship classes, checking for attachments
    CARDINALITIES = {
    'OneToOne': "ONE_TO_ONE",
    'OneToMany': "ONE_TO_MANY",
    'ManyToMany': "MANY_TO_MANY"
    }

    for child in [(c.name, c.datatype) for c in dscW.children if c.datatype == u'RelationshipClass']:
        dscRC = arcpy.Describe(child[0])
        RCOriginTable = dscRC.originClassNames[0]
        RCDestTable = dscRC.destinationClassNames[0]
        newOriginTable = "{0}_{1}".format(prefix, RCOriginTable)
        newOriginPath = os.path.join(outWorkspace, newOriginTable)
        if dscRC.isAttachmentRelationship:
            #Simple case - attachments have a dedicated tool
            arcpy.EnableAttachments_management(newOriginPath)
        else:
            newDestTable = "{0}_{1}".format(prefix, RCDestTable)
            newDestPath = os.path.join(outWorkspace, newDestTable)
            newRC = os.path.join(outWorkspace, "{0}_{1}".format(prefix, child[0]))
            relationshipType = "COMPOSITE" if dscRC.isComposite else "SIMPLE"
            fwd_label = dscRC.forwardPathLabel if dscRC.forwardPathLabel != '' else 'Repeat'
            bck_label = dscRC.backwardPathLabel if dscRC.backwardPathLabel != '' else 'MainForm'
            msg_dir = dscRC.notification.upper()
            cardinality = CARDINALITIES[dscRC.cardinality]
            attributed = "ATTRIBUTED" if dscRC.isAttributed else "NONE"
            originclassKeys = dscRC.originClassKeys
            originclassKeys_dict = {}
            for key in originclassKeys:
                originclassKeys_dict[key[1]] = key[0]
            originPrimaryKey = originclassKeys_dict[u'OriginPrimary']
            originForiegnKey = originclassKeys_dict[u'OriginForeign']
            arcpy.CreateRelationshipClass_management(newOriginPath, newDestPath, newRC, relationshipType, fwd_label, bck_label, msg_dir, cardinality, attributed, originPrimaryKey, originForiegnKey)
Example #13
0
# encoding=utf8
import json
import os
import arcpy
import pandas as pd

arcpy.env.overwriteOutput  = True

gdb = r'D:\APPS\SURVEY\BDG_YACMIN\GPT_YM_YACIM_1.gdb'
path = r'D:\APPS\SURVEY\BDG_YACMIN\tb'

lDom = [x.name for x in arcpy.da.ListDomains(gdb)]

for x in lDom:
    print x
    tbtemp = arcpy.DomainToTable_management(gdb, x, os.path.join(gdb, "tb_%s" % x), "Code", "Desc")
    with arcpy.da.SearchCursor(tbtemp, ["Code", "Desc"]) as cursor:
        for i in cursor:

    # data = arcpy.da.TableToNumPyArray(tbtemp, ["Code", "Desc"])
    # print data
    # df = pd.DataFrame(data)
    # print df
    with open(path + "{}.json".format(x), 'wb') as outfile:
        json.dump(df, outfile)
Example #14
0
                                    #Start exporting Domains to tables
                                    logger.log(
                                        10, '4 ; Processing domains in ' +
                                        desc.DataType + ' ' +
                                        desc.CatalogPath + ' ' + ' (' +
                                        desc.ShapeType + ' type)')
                                    cursor.execute('SELECT * FROM Domains')
                                    rows = cursor.fetchall()
                                    for fld in desc.Fields:
                                        for row in rows:
                                            if fld.domain != '' and fld.domain == row[
                                                    0]:
                                                arcpy.DomainToTable_management(
                                                    database, fld.domain,
                                                    gdb_target + '\\' +
                                                    fld.domain, "Code",
                                                    "Description")
                                                logger.log(
                                                    10, '4 ; Exported ' +
                                                    fld.domain +
                                                    ' domain table to ' +
                                                    gdb_target + '\\' +
                                                    fld.domain)
                                    logger.log(
                                        10,
                                        '4 ; Finished processing domains for Feature class '
                                        + database + '\\' + fds + '\\' + fc)

                                    # inserting columns
                                    logger.log(
Example #15
0
def writeMessageFile():

    global DEBUG_GEOMETRY_CONVERSION, appendFile, foundEmptySIDC, FORCE_UNIQUE_IDs

    try:
        arcpy.AddMessage("Starting: Write/Append Message File")

        # Get input feature class
        inputFC = arcpy.GetParameter(0)
        if (inputFC == "") or (inputFC is None):
            inputFC = os.path.join(
                MilitaryUtilities.dataPath,
                r"/test_inputs.gdb/FriendlyOperations/FriendlyUnits")
        desc = arcpy.Describe(inputFC)
        if desc is None:
            arcpy.AddError("Bad Input Feature Class")
            return

        shapeType = desc.shapeType

        # Get output filename
        outputFile = arcpy.GetParameterAsText(1)

        # Get standard
        standard = arcpy.GetParameterAsText(2)

        # Message Type Field
        messageTypeField = arcpy.GetParameterAsText(3)

        # Sort Order
        orderBy = arcpy.GetParameterAsText(4)

        # Disable Geo Transformation and use default SIDC
        disableGeoTransform = arcpy.GetParameterAsText(5)
        if not ((disableGeoTransform == "") or (disableGeoTransform is None)):
            DEBUG_GEOMETRY_CONVERSION = (disableGeoTransform.upper() == "TRUE")

        arcpy.AddMessage("Running with Parameters:")
        arcpy.AddMessage("0 - Input FC: " + str(inputFC))
        arcpy.AddMessage("1 - outputXMLFile: " + str(outputFile))
        arcpy.AddMessage("2 - symbology standard: " + str(standard))
        arcpy.AddMessage("3 - MessageTypeField: " + messageTypeField)
        arcpy.AddMessage("4 - orderBy: " + orderBy)
        arcpy.AddMessage("5 - disableGeoTransform: " + disableGeoTransform)

        # initialize the standard
        MilitaryUtilities.getGeometryConverterStandard(standard)

        if DEBUG_GEOMETRY_CONVERSION:
            arcpy.AddWarning(
                "Running in Debug Geo-Transformation Mode, symbol will use default/unknown SIDC for shape"
            )

        if not ((messageTypeField == "") or (messageTypeField is None)):
            # make sure the messageTypeField exists in the input
            if messageTypeField in [field.name for field in desc.Fields]:
                MilitaryUtilities.MessageTypeField = messageTypeField
            else:
                arcpy.AddWarning("MessageTypeField does not exist in input: " +
                                 messageTypeField + " , using default")

        # Check Output Filename & see handle case if we are appending
        if (outputFile == "") or (outputFile is None):
            # For a standalone test (debug) if no output filename provided
            if DEBUG_GEOMETRY_CONVERSION:
                defaultOutputName = "Mil2525CMessages-NoTransform.xml"
            else:
                defaultOutputName = "Mil2525CMessages.xml"
            outputFile = os.path.join(os.path.dirname(__file__),
                                      defaultOutputName)
            messageFile = open(outputFile, "w")
            arcpy.AddWarning("No Output set, using default: " +
                             str(outputFile))
        else:
            arcpy.AddMessage("Append File set to " + str(appendFile))
            if (not appendFile):
                messageFile = open(outputFile, "w")
            elif (not os.path.isfile(outputFile)):
                arcpy.AddWarning(
                    "Can't Append: Output File does not exist, creating new file"
                )
                messageFile = open(outputFile, "w")
            else:
                arcpy.AddMessage("Appending Existing File...")

                # Appending the file is a bit more complicated because we have to remove the
                # "</messages>" from the end of the original file therefore it can't just be
                # opened as an append "a+"-we have to create a temp file, read the original file in,
                # except for the line "</messages>", and then write back out

                fileToAppend = open(outputFile, "r")
                # Workaround/Note: didn't work in ArcCatalog unless I opened temp file this way
                temporaryFile = tempfile.NamedTemporaryFile(mode="w",
                                                            delete=False)

                # Copy the file line by line, but don't include last end tag ex. </messages>
                finalTag = "</%s>" % MilitaryUtilities.getMessageRootTag()
                finalTagFound = False
                while True:
                    line = fileToAppend.readline()
                    if line:
                        if not finalTag in line:  # ex. "</messages>"
                            temporaryFile.write(line)
                        else:
                            finalTagFound = True
                    else:
                        break

                if (not finalTagFound):
                    arcpy.AddError(
                        "XML Append File will be corrupt: Could not find Tag: "
                        + finalTag)

                # now write those lines back
                fileToAppend.close()
                temporaryFile.close()
                messageFile = open(outputFile, "w")
                temporaryFile = open(temporaryFile.name, "r")
                while True:
                    line = temporaryFile.readline()
                    if line:
                        messageFile.write(line)
                    else:
                        break

                temporaryFile.close()

        if (messageFile is None):
            arcpy.AddError("Output file can't be created, exiting")
            return

        ##################Setup for export############################

        # We need to set overwriteOutput=true or the tools below may fail
        previousOverwriteOutputSetting = arcpy.env.overwriteOutput
        arcpy.env.overwriteOutput = True

        # Densify if this is a polygon FC
        if (shapeType == "Polygon"):
            try:
                densifiedFC = "in_memory/DensifiedFC"
                arcpy.CopyFeatures_management(inputFC, densifiedFC)
                arcpy.Densify_edit(densifiedFC, "ANGLE", "", "", 10)
                inputFC = densifiedFC
            except:
                arcpy.AddWarning(
                    "Could not densify polygons, skipping. Densify_edit tool failed - is Desktop Standard License available?"
                )

        # Get fields and coded domains
        CODE_FIELD_NAME = "code"
        DESCRIPTION_FIELD_NAME = "description"
        fieldNameList = []
        fieldNameToDomainName = {}
        for field in desc.Fields:
            if not (field.name
                    in DictionaryConstants.MILFEATURES_FIELD_EXCLUDE_LIST):
                fieldNameList.append(field.name)
                # Get domain if any
                if (field.domain is not None and field.domain != ""):
                    fieldNameToDomainName[field.name] = field.domain
                    dataPath = desc.path
                    gdbPath = dataPath.split(".gdb")[0]
                    gdbPath += ".gdb"
                    arcpy.DomainToTable_management(gdbPath, field.domain,
                                                   "in_memory/" + field.domain,
                                                   CODE_FIELD_NAME,
                                                   DESCRIPTION_FIELD_NAME)

        # print fieldNameList

        # restore this setting (set above)
        arcpy.env.overwriteOutput = previousOverwriteOutputSetting

        # Projected or geographic?
        xname = "lon"
        yname = "lat"
        isProjected = desc.spatialReference.type == "Projected"
        if (isProjected):
            xname = "x"
            yname = "y"
        wkid = desc.spatialReference.factoryCode

        ################Begin Export ##########################

        # Open a search cursor (if possible)
        try:
            rows = arcpy.SearchCursor(inputFC, "", "", "", orderBy)
        except:
            arcpy.AddError("Could not open Feature Class " + str(inputFC))
            if (not ((orderBy == "") and not (orderBy is None))):
                arcpy.AddError("OrderBy Search Option: " + orderBy)
            raise Exception("Bad Feature Class Input")

        # Dictionary to map unique designation to ID
        unitDesignationToId = dict()

        featureFields = desc.fields

        ###################### Write XML file #########################

        if not appendFile:
            # Ex: Next line writes: messageFile.write("<geomessages>\n")
            messageFile.write("<%s>\n" % MilitaryUtilities.getMessageRootTag())

        rowCount = 0

        # Iterate through the rows in the cursor
        for row in rows:
            shape = row.shape.getPart(0)

            arcpy.AddMessage("Processing row: " + str(rowCount))

            ##############################################
            # Map Unique Names to same Unique IDs
            # IMPORTANT: this section tries to keep Unique Designations mapped to the
            #            same Message Unique ID (so they will move in Message Processor), so...
            # WARNING: if you have repeated Unique Designations,
            #            they are going to get mapped to the same Unique ID
            uniqueId = "{%s}" % str(uuid.uuid4())
            uniqueDesignation = str(
                rowCount)  # fallback value in case field does not exist

            try:
                uniqueDesignation = row.getValue(
                    MilitaryUtilities.UniqueDesignationField)

                if ((uniqueDesignation is None) or (uniqueDesignation == "")):
                    arcpy.AddWarning("Unique Designation is Empty")
                elif (DEBUG_GEOMETRY_CONVERSION or FORCE_UNIQUE_IDs):
                    pass
                else:
                    # Otherwise, see if we have seen this Designation before
                    if (uniqueDesignation in unitDesignationToId):
                        arcpy.AddMessage(
                            "Creating update message for repeated Unique Designation: "
                            + uniqueDesignation)
                        uniqueId = unitDesignationToId[uniqueDesignation]
                    else:
                        unitDesignationToId[uniqueDesignation] = uniqueId
            except:
                arcpy.AddWarning(
                    "Could not find Unique Designation field in row: " +
                    str(rowCount))
            ##############################################

            # work with "sidc" or "sic"
            try:
                SymbolIdCodeVal = row.getValue(
                    MilitaryUtilities.SidcFieldChoice1)  # "sic"
            except:
                try:
                    SymbolIdCodeVal = row.getValue(
                        MilitaryUtilities.SidcFieldChoice2)  # "sidc"
                except:
                    SymbolIdCodeVal = None

            # Note/Important: attributes need to be set in converter so needs declared before geometrytoControlPoints
            attributes = {}
            conversionNotes = None
            attributes[
                DictionaryConstants.Tag_Wkid] = wkid  # needed by conversion

            if (SymbolIdCodeVal is None) or (SymbolIdCodeVal == ""):
                SymbolIdCodeVal = DictionaryConstants.getDefaultSidcForShapeType(
                    shapeType)
                if not (DEBUG_GEOMETRY_CONVERSION):
                    foundEmptySIDC = True
                    msg = "SIDC is not set, using default: " + SymbolIdCodeVal
                    arcpy.AddWarning(msg)
            # TODO: we may need to add an option to Disable the geometry conversion
            # *but* not to change the SIDC to the default one, if you don't want the SIDC to change
            # when "Disable Geometry Conversion" is checked, comment/uncomment thses lines to
            # set this to false/disable this behavior:
            # elif False :
            elif DEBUG_GEOMETRY_CONVERSION:
                print "Using Debug SIDC"
                conversionNotes = "Original SIDC: " + SymbolIdCodeVal
                uniqueDesignation = SymbolIdCodeVal  # use this label for debugging
                SymbolIdCodeVal = DictionaryConstants.getDefaultSidcForShapeType(
                    shapeType)

            controlPointsString = MilitaryUtilities.parseGeometryToControlPoints(
                shape)
            requiresConversion = MilitaryUtilities.geoConverter.requiresConversion(
                SymbolIdCodeVal)
            if requiresConversion and not DEBUG_GEOMETRY_CONVERSION:
                msg = "SIC: " + SymbolIdCodeVal + " requires conversion/translation"
                print msg
                arcpy.AddMessage(msg)
                transformedPoints, conversionNotes = \
                    MilitaryUtilities.geoConverter.geometrytoControlPoints(SymbolIdCodeVal, controlPointsString, attributes)
                if (conversionNotes ==
                        DictionaryConstants.CONVERSION_IGNORE_SECOND_LINE):
                    continue
                elif (transformedPoints is None):
                    arcpy.AddWarning("Conversion FAILED for SIC: " + SymbolIdCodeVal + \
                                     ", Notes: " + conversionNotes + " (using original points)")
                else:
                    controlPointsString = transformedPoints

            # Write Output Message
            # Ex: Next line writes: ex. "\t<geomessage v=\"1.0\">\n"
            messageFile.write("\t<%s v=\"%s\">\n" % (MilitaryUtilities.getMessageTag(), \
                                                     MilitaryUtilities.getMessageVersion()))

            messageFile.write("\t\t<sic>%s</sic>\n" % SymbolIdCodeVal)

            # Try to get a message type if the field exists
            try:
                messageTypeVal = row.getValue(
                    MilitaryUtilities.MessageTypeField)
                messageFile.write("\t\t<_type>%s</_type>\n" % messageTypeVal)
            except:
                # if not default to position_report
                messageFile.write("\t\t<_type>%s</_type>\n" %
                                  DictionaryConstants.DefaultMessageType)

            ##TODO: see if other actions are valid besides just "update"
            messageFile.write(
                "\t\t<_action>%s</_action>\n" %
                DictionaryConstants.DefaultMessageAction)  # = update

            messageFile.write("\t\t<_id>%s</_id>\n" % uniqueId)
            messageFile.write("\t\t<_control_points>%s</_control_points>\n" %
                              controlPointsString)
            if not ((conversionNotes is None) or (conversionNotes == "")):
                messageFile.write(
                    "\t\t<ConversionNotes>%s</ConversionNotes>\n" %
                    conversionNotes)

            # Note: written with attributes below: messageFile.write("\t\t<_wkid>%i</_wkid>\n" % wkid)

            if not ((uniqueDesignation is None) or (uniqueDesignation == "")):
                messageFile.write("\t\t<%s>%s</%s>\n" % (DictionaryConstants.Tag_UniqueDesignation, \
                             uniqueDesignation, DictionaryConstants.Tag_UniqueDesignation))

            # Check on Military Geometries for Lines/Areas
            if (shapeType is "Point"):
                messageFile.write("\t\t<altitude_depth>%d</altitude_depth>\n" %
                                  shape.Z)

            rowCount = rowCount + 1
            messageFile.write("\t\t<MessageCount>%s</MessageCount>\n" %
                              str(rowCount))

            for key in attributes:
                attrValAsString = str(attributes[key])
                messageFile.write("\t\t<" + key + ">" + attrValAsString +
                                  "</" + key + ">\n")

            ###################Common Fields/Attributes#####################

            # Write out remaining table fields as Tag attributes
            for field in fieldNameList:
                try:
                    # But don't repeat existing tags we've created
                    if field in DictionaryConstants.MESSAGES_TAG_LIST:
                        rowVal = None
                    else:
                        rowVal = row.getValue(field)
                except:
                    print "Could not get row val for field" + field
                    rowVal = None

                if (rowVal is not None) and (rowVal != ''):
                    try:
                        fieldValAsString = str(row.getValue(field))
                        messageFile.write("\t\t<" + field + ">" +
                                          fieldValAsString + "</" + field +
                                          ">\n")
                    except:
                        #fixed issue #19
                        fieldValAsString = row.getValue(field)
                        decodedstring = fieldValAsString.encode(
                            'ascii', 'ignore')
                        arcpy.AddMessage(
                            "trying to fix unicode problem, changing " +
                            fieldValAsString + " -> " + decodedstring)
                        messageFile.write("\t\t<" + field + ">" +
                                          decodedstring + "</" + field + ">\n")

            ###################Common Fields/Attributes#####################

            # Ex: messageFile.write("\t</geomessage>\n")
            messageFile.write("\t</%s>\n" % MilitaryUtilities.getMessageTag())

        # Ex: messageFile.write("</geomessages>")
        messageFile.write("</%s>\n" % MilitaryUtilities.getMessageRootTag())

        arcpy.AddMessage("Rows Processed: " + str(rowCount))
        if foundEmptySIDC:
            arcpy.AddWarning(
                "IMPORTANT: Some rows did not have SIDC set - you may need to run CalcSIDCField tool first."
            )
        arcpy.AddMessage("Write/Append Message File Complete")

    except:
        print "Exception: "
        tb = traceback.format_exc()
        print tb
        arcpy.AddError("Exception")
        arcpy.AddError(tb)
##Create string list of domains
domlist = []

for domain in domains:
    domlist.append(str(domain))

##Run through list of domains and create table outputs
for dom in domlist:
    print dom
    issue = "/"
    if issue in dom:
        newdome = dom.replace("/", "")
        print newdome
        output = newdome + ".dbf"
        arcpy.DomainToTable_management(sde, dom, output, "CODE", "DESCR")
        arcpy.AddField_management(output, "DOMAIN", "TEXT", "", "", 100)
    else:
        output = dom + ".dbf"
        arcpy.DomainToTable_management(sde, dom, output, "CODE", "DESCR")
        arcpy.AddField_management(output, "DOMAIN", "TEXT", "", "", 100)

    arcpy.CalculateField_management(output, "DOMAIN", "\"" + dom + "\"",
                                    'PYTHON_9.3')

    domtableout = outloc + "Domains.dbf"
    arcpy.Append_management(output, domtableout, "NO_TEST")

# Delete Working Folder - Uncomment if required
##arcpy.Delete_management(workingloc)
Example #17
0
which prints the domain name and values, 
also added the line to export the domain to table, for data diagramming

@author: kyleg
'''
import arcpy
indb = r"\\gisdata\planning\Cart\projects\ARNOLD POOLED FUND\geodata\MIRE_GDB_Template_DecodeToTable.gdb"
domains = arcpy.da.ListDomains(indb)  # @UndefinedVariable

for domain in domains:
    print('Domain name: {0}'.format(domain.name))
    if domain.domainType == 'CodedValue':
        coded_values = domain.codedValues
        for val, desc in coded_values.iteritems():
            print('{0} : {1}'.format(val, desc))

    elif domain.domainType == 'Range':
        print('Min: {0}'.format(domain.range[0]))
        print('Max: {0}'.format(domain.range[1]))
    print domain.name
    outtbl = indb + "/" + domain.name

    arcpy.DomainToTable_management(in_workspace=indb,
                                   domain_name=domain.name,
                                   out_table=outtbl,
                                   code_field="CODE",
                                   description_field="DESC",
                                   configuration_keyword="")

    #arcpy.DomainToTable_management(in_workspace=indb, domain_name=domain.name, out_table=outtbl, code_field="CODE", description_field="DESC", configuration_keyword="")
Example #18
0
def main():
    # GET PARAMETER VALUES
    Proposed_Surface_Disturbance_Eligible = arcpy.GetParameterAsText(0)

    # DEFINE DIRECTORIES
    # Get the pathname to this script
    scriptPath = sys.path[0]
    arcpy.AddMessage("Script folder: " + scriptPath)
    # Construct pathname to workspace
    workspace = arcpy.Describe(Proposed_Surface_Disturbance_Eligible).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

    # Filenames for feature classes or rasters used by this script
    ELIGIBLE_PROPOSED_FEATURES = "Proposed_Surface_Disturbance_Eligible"

    # Filenames for feature classes or rasters created by this script
    ANALYSIS_AREA = "Analysis_Area"

    # ------------------------------------------------------------------------

    # FUNCTION CALLS
    # Check tool version
    ccslib.CheckToolVersion()

    # Clear selection, if present
    ccslib.ClearSelectedFeatures(Proposed_Surface_Disturbance_Eligible)

    # Check Proposed_Surface_Disturbance_Eligible
    feature = Proposed_Surface_Disturbance_Eligible
    required_fields = ["Type", "Subtype", "Surface_Disturbance"]
    no_null_fields = required_fields
    expected_fcs = None
    ccslib.CheckPolygonInput(feature, required_fields, expected_fcs,
                             no_null_fields)

    # Update Proposed_Surface_Disturbance_Elligible layer with provided layer
    provided_input = Proposed_Surface_Disturbance_Eligible
    parameter_name = ELIGIBLE_PROPOSED_FEATURES
    Proposed_Surface_Disturbance_Eligible = ccslib.AdoptParameter(
        provided_input, parameter_name, preserve_existing=False)

    # Replace Proposed_Surface_Disturbance_Elibible layer on map
    layerFile = ccsStandard.getLayerFile("SurfaceDisturbance.lyr")
    ccslib.AddToMap(Proposed_Surface_Disturbance_Eligible, layerFile)

    # Update message
    arcpy.AddMessage("Clipping all anthropogenic features to Analysis Area "
                     "and adding templates for digitizing new anthropogenic "
                     "features")

    # Clip all provided anthropogenic feature layers and add to map
    clip_features = ANALYSIS_AREA
    anthroFeaturePath = ccsStandard.AnthroFeaturePath
    proposed_anthro = Proposed_Surface_Disturbance_Eligible
    fieldsToAdd = ["Overlap_Status", "Returned", "Subtype_As_Modified"]
    fieldTypes = ["TEXT", "TEXT", "TEXT"]
    mod_field = fieldsToAdd[0]
    removed_code = "Removed"
    retained_code = "Retained"
    ccslib.ClipAnthroFeaturesDebit(clip_features, anthroFeaturePath,
                                   proposed_anthro, fieldsToAdd, fieldTypes,
                                   mod_field, removed_code, retained_code)

    # Apply domains for Overlap_Status field and populate default
    featureList = arcpy.ListFeatureClasses("Anthro_*_Clip")
    domain_name = fieldsToAdd[0]
    code_list = ["Retained", "Removed"]
    ccslib.AddCodedTextDomain(featureList,
                              workspace,
                              domain_name,
                              code_list,
                              assign_default=True,
                              populate_default=True)

    # Apply domains for Returned field
    domain_name = fieldsToAdd[1]
    code_list = ["True", "False"]
    ccslib.AddCodedTextDomain(featureList,
                              workspace,
                              domain_name,
                              code_list,
                              assign_default=True,
                              populate_default=True)

    # Add all Subtype anthro domains because ArcGIS doesn't transfer them
    # consistently
    desc_c = arcpy.Describe(workspace)
    current_domains = desc_c.domains
    desc_w = arcpy.Describe(ccsStandard.AnthroFeaturePath)
    anthro_domains = desc_w.domains
    for domain_name in anthro_domains:
        if domain_name not in current_domains and "Subtype" in domain_name:
            source_workspace = ccsStandard.AnthroFeaturePath
            code_field = 'code'
            description_field = 'description'
            domain_table = arcpy.DomainToTable_management(
                source_workspace, domain_name, domain_name, code_field,
                description_field)
            arcpy.TableToDomain_management(domain_table, code_field,
                                           description_field, workspace,
                                           domain_name)
            arcpy.Delete_management(domain_table)

    # Apply domains for each anthro feature
    for feature in featureList:
        # Apply for each Subtype field
        field = "Subtype"
        domainName = feature[7:-5] + "_Subtypes"
        arcpy.AssignDomainToField_management(feature, field, domainName)
        subtypes = arcpy.da.ListSubtypes(feature)
        if len(subtypes) == 1 and subtypes[0]['SubtypeField'] == '':
            pass
        else:
            st_codes = [
                str(stcode) for stcode, stdict in list(subtypes.items())
            ]
            arcpy.AssignDomainToField_management(feature, field, domainName,
                                                 st_codes)

        # Apply for each Subtype As Modified Field
        field = fieldsToAdd[-1]
        domainName = feature[7:-5] + "_Subtypes"
        arcpy.AssignDomainToField_management(feature, field, domainName)
        subtypes = arcpy.da.ListSubtypes(feature)
        if len(subtypes) == 1 and subtypes[0]['SubtypeField'] == '':
            pass
        else:
            st_codes = [
                str(stcode) for stcode, stdict in list(subtypes.items())
            ]
            arcpy.AssignDomainToField_management(feature, field, domainName,
                                                 st_codes)

        # Copy current subtype to Subtype as Modified field
        arcpy.CalculateField_management(feature, field, "!Subtype!",
                                        "PYTHON_9.3")

    # Add each feature to map for editing
    for feature in featureList:
        ccslib.AddAnthroToMap(workspace, feature)

    # 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()
Example #19
0
    updatefields.append(symbolNameFieldName)

    if (EchelonField in fieldNameList):
        updatefields.append(EchelonField)

    for field in desc.Fields:
        if field.name in updatefields:
            # Get domain if any
            if (field.domain is not None and field.domain != ""):
                fieldNameToDomainName[field.name] = field.domain
                if arcpy.Exists("in_memory/" + field.domain):
                    arcpy.Delete_management("in_memory/" + field.domain)
                try:
                    #If path is feature class
                    arcpy.DomainToTable_management(desc.path, field.domain,
                                                   "in_memory/" + field.domain,
                                                   CODE_FIELD_NAME,
                                                   DESCRIPTION_FIELD_NAME)
                except:
                    #If path is feature dataset
                    arcpy.DomainToTable_management(
                        arcpy.Describe(desc.path).path, field.domain,
                        "in_memory/" + field.domain, CODE_FIELD_NAME,
                        DESCRIPTION_FIELD_NAME)

    with arcpy.da.UpdateCursor(inputFC, updatefields) as cursor:
        for row in cursor:
            #Lookup Symbol ID Value
            SymbolIdCodeVal = ""
            echelonString = ""
            if (symbolNameFieldName in fieldNameToDomainName):
                domain = fieldNameToDomainName[symbolNameFieldName]
Example #20
0
def export_domains(domains):
    for domain in domains:
        arcpy.AddMessage('Exporting %s CV to table in %s' % (domain.name, gdb))
        table = os.path.join(gdb, domain.name)
        arcpy.DomainToTable_management(gdb, domain.name, table,
            'field','description', '#')
    expression_type="VB",
    code_block="")
arcpy.AddField_management(in_table="GC_UNCO_DESPOSIT",
                          field_name="joinstr",
                          field_type="TEXT",
                          field_precision="",
                          field_scale="",
                          field_length="800",
                          field_alias="",
                          field_is_nullable="NULLABLE",
                          field_is_required="NON_REQUIRED",
                          field_domain="")
arcpy.DomainToTable_management(
    in_workspace="D:/CCW20/GIS/geocover.gdb",
    domain_name="GC_LITHO_UNCO_CD",
    out_table="D:/CCW20/GIS/geocover.gdb/domain_GC_LITHO_UNCO_CD",
    code_field="code",
    description_field="GC_LITHO_UNCO_CD",
    configuration_keyword="")
arcpy.DomainToTable_management(
    in_workspace="D:/CCW20/GIS/geocover.gdb",
    domain_name="GC_LITSTRAT_UNCO_CD",
    out_table="D:/CCW20/GIS/geocover.gdb/domain_GC_LITSTRAT_UNCO_CD",
    code_field="code",
    description_field="GC_LITSTRAT_UNCO_CD",
    configuration_keyword="")
arcpy.DomainToTable_management(
    in_workspace="D:/CCW20/GIS/geocover.gdb",
    domain_name="GC_UN_DEP_RUNC_STRUCTUR_CD",
    out_table="D:/CCW20/GIS/geocover.gdb/domain_GC_UN_DEP_RUNC_STRUCTUR_CD",
    code_field="code",