コード例 #1
0
def create_team_subtype(gdb, fc, subtype_dict):
    # Process: Set Subtype Field...
    arcpy.SetSubtypeField_management(os.path.join(gdb, fc), "TEAM_ID")

    # use a for loop to cycle through the dictionary
    for code in subtype_dict:
        arcpy.AddSubtype_management(os.path.join(gdb, fc), code,
                                    subtype_dict[code])
コード例 #2
0
def addSubtypes(schemasFolder, schema, featureClass, fieldName):

    # Sets the field used to determine the subtype of each feature
    # Populates the subtypes for the specified feature class

    try:
        arcpy.AddMessage("Starting: AddSubtypes")

        # Initialize a dict

        subTypes = {}

        # Set the subtype field

        arcpy.SetSubtypeField_management(featureClass, fieldName)

        # Populate the subtypes from the provided subtype schema file

        subtypesSchemaFile = os.path.join(schemasFolder,
                                          "Subtypes_" + schema + ".csv")

        if os.path.exists(subtypesSchemaFile):
            with open(subtypesSchemaFile, 'r') as csvFile:
                reader = csv.reader(csvFile, dialect='excel')

                # Skip the headers
                header = next(reader)

                defaultSubtype = 0
                isFirst = True

                # Read the lines and add them as subtypes
                for line in reader:
                    arcpy.AddSubtype_management(featureClass, int(line[0]),
                                                line[1])

                    subTypes[line[0]] = line[1]

                    if isFirst == True:
                        # Set the default subtype value
                        arcpy.SetDefaultSubtype_management(
                            featureClass, int(line[0]))
                        isFirst = False

    except Exception as err:
        arcpy.AddError(
            traceback.format_exception_only(type(err), err)[0].rstrip())

    else:
        arcpy.AddMessage("Success! - Completed: AddSubtypes")

    finally:
        arcpy.AddMessage("Exiting: AddSubtypes")

        return subTypes
コード例 #3
0
 def set_gsi_subtype(input_feature_class, field):
     arcpy.SetSubtypeField_management(input_feature_class, field)
     # Store all the subtype values in a dictionary with the subtype code as the "key" and the
     # subtype description as the "value" (subtypeDict[code])
     gsi_subtype_dict = {"1": "TRENCH", "2": "BUMPOUT", "3": "RAIN GARDEN", "4": "WETLAND", \
                         "5": "BASIN", "6": "TREE TRENCH", "7": "PLANTER", "8": "PERVIOUS PLANTER", \
                         "9": "SWALE", "10": "GREEN ROOF", "11": "CISTERN"}
     for code in gsi_subtype_dict:
         arcpy.AddSubtype_management(input_feature_class, code,
                                     gsi_subtype_dict[code])
     # Set Default Subtype...
     arcpy.SetDefaultSubtype_management(input_feature_class, "1")
コード例 #4
0
 def create_mdb_DateBase(self):
     """
         Create *mdb DataBase with DateSet, and polyline layer with fields ("Name_ATE", "Name", "Name_EVA", "ID_ATE", "ID_EVA").
         Set sybtype for field "Name_ATE" and add sybtypes.
         :return: DateBase
         """
     # create mdb
     arcpy.CreatePersonalGDB_management(
         self.work_path, '{0}_streets.mdb'.format(self.name_district))
     # create dataset Streets
     arcpy.CreateFeatureDataset_management(self.nameDataBase, "Streets",
                                           wgs84)
     # create shp Streets
     arcpy.CreateFeatureclass_management(self.nameDataSet, "Streets",
                                         "POLYLINE", "", "DISABLED",
                                         "DISABLED", wgs84, "", "0", "0",
                                         "0")
     # create fields in shp Streets
     arcpy.AddField_management(self.nameStreets, "Name_ATE", "LONG", "", "",
                               "", "", "NULLABLE", "REQUIRED", "")
     arcpy.AddField_management(self.nameStreets, "Name", "LONG", "", "", "",
                               "", "NULLABLE", "REQUIRED", "")
     arcpy.AddField_management(self.nameStreets, "Name_EVA", "LONG", "", "",
                               "", "", "NULLABLE", "REQUIRED", "")
     arcpy.AddField_management(self.nameStreets, "ID_ATE", "LONG", "", "",
                               "", "", "NULLABLE", "REQUIRED", "")
     arcpy.AddField_management(self.nameStreets, "ID_EVA", "LONG", "", "",
                               "", "", "NULLABLE", "REQUIRED", "")
     # set Sybtypefield - Name_ATE
     arcpy.SetSubtypeField_management(self.nameStreets, "Name_ATE")
     # create sybtypes in DateBase
     if self.name_district != "Минск":
         for element in self.new_dict_syptypes.items():
             arcpy.AddSubtype_management(self.nameStreets, element[1][0],
                                         element[0])
     else:
         arcpy.AddSubtype_management(self.nameStreets, 17030, 'Минск')
コード例 #5
0
    def create_table_EVA_Vitebsk(self):
        """
        This function is created only for city Vitebsk, cause it didn't work correctly.
        :return: domain and sybtypes Vitebsk in DateBase Vitebski district
        """
        conn = pyodbc.connect(
            "DRIVER={Oracle in OraClient10g_home1};DBQ=NCABASE:1521/WIN.MINSK.NCA;UID="
            + self.login_to_DB + ";PWD=" + self.password_to_DB)
        cursor = conn.cursor()
        # SQL expression
        expression = """with tabl1 as (SELECT  * from ATEOBJECT r3 where r3.CATEGORY = 103 AND r3.UIDOPERIN=( SELECT MAX (r4.UIDOPERIN)
                FROM ATEREESTR.ATEOBJECT r4
                WHERE r3.OBJECTNUMBER=r4.OBJECTNUMBER
                GROUP BY r3.OBJECTNUMBER))

                SELECT j.IAEUID AS "ID_EVA", j.OBJECTNUMBER as "ID_ATE",  j.ELEMENTNAME, x.SHORTNAME_RUS,  R.NAMEOBJECT, p.SHORTNAME, t.OBJECTNUMBER as "SELSOV", r.CATEGORY, j.ELEMENTTYPE

                FROM IAE.ADRELEMENTS j, ATEREESTR.X_ATECATEGORY p, ATEREESTR.X_ATEDISTRICTS i, ATEREESTR.X_ATEREGION g, NKA_SPR.X_EVA_TYPES_ADDR x, ATEREESTR.ATEOBJECT r

                LEFT JOIN tabl1 t  ON r.SOATODEPEND = t.SOATO
                LEFT JOIN ATEREESTR.X_ATECATEGORY p2 ON t.CATEGORY = p2.CATEGORY

                where r.UIDOPEROUT is null and  j.OBJECTNUMBER = R.OBJECTNUMBER and R.UIDDISTR = I.UIDDISTR and R.UIDREGION = G.UIDREGION and R.CATEGORY = p.CATEGORY and  j.JRNREG_OUT is null and j.ELEMENTTYPE < 50 and  R.OBJECTNUMBER = 9387 and x.CODE_1 =  j.ELEMENTTYPE

                order by R.NAMEOBJECT, j.ELEMENTNAME"""
        cursor.execute(expression)
        self.table_EVA_Vitebsk = cursor.fetchall()
        arcpy.AddSubtype_management(self.nameStreets, 9387, "Витебск")
        arcpy.CreateTable_management(self.nameDataBase, "Витебск_EVA", "", "")
        name_etalon_eva = os.path.join(self.nameDataBase, "Витебск_EVA")
        arcpy.AddField_management(name_etalon_eva, "ID_ATE", "LONG", "", "",
                                  "", "", "NULLABLE", "REQUIRED", "")
        arcpy.AddField_management(name_etalon_eva, "ID_EVA", "LONG", "", "",
                                  "", "", "NULLABLE", "REQUIRED", "")
        arcpy.AddField_management(name_etalon_eva, "Name_EVA", "TEXT", "", "",
                                  "", "", "NULLABLE", "REQUIRED", "")
        cursor_arc = arcpy.da.InsertCursor(name_etalon_eva,
                                           ["ID_ATE", "ID_EVA", "Name_EVA"])
        for el in self.table_EVA_Vitebsk:
            cursor_arc.insertRow([
                el[1], el[0], '{0}_{1}'.format(el[2].encode('utf-8'),
                                               el[3].encode('utf-8'))
            ])

        arcpy.TableToDomain_management(name_etalon_eva, "ID_EVA", "Name_EVA",
                                       self.nameDataBase, "Витебск_EVA", "EVA",
                                       "APPEND")
        # arcpy.AssignDomainToField_management(self.nameStreets, "Name_EVA", "Витебск_EVA", 9387)
        arcpy.Delete_management(name_etalon_eva, "Table")
コード例 #6
0
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 main():

    #### Create a folder based on the date (ie: Year_Month_Day = 2018_4_16)
    now = datetime.datetime.now()
    year = now.year
    month = now.month
    day = now.day
    folder_name = str(year) + "_" + str(month) + "_" + str(day)
    # create the folder
    print "Creating Directory..."
    directory = "C:\\Users\\gbunce\\Documents\\projects\\NetworkDataset\\RecentBuilds\\" + folder_name
    if not os.path.exists(directory):
        print "Creating Directory: " + str(directory) + " ..."
        os.makedirs(directory)
    else:
        print "Directory: " + str(directory) + " exists."


    # create new fgdb
    print "Creating File Geodatabase..."
    network_fgdb = arcpy.CreateFileGDB_management(directory, 'UtahRoadsNetworkAnalysis.gdb')

    # create dataset in the fgdb
    print "Creating Feature Dataset..."
    arcpy.CreateFeatureDataset_management(network_fgdb, 'NetworkDataset', sgid_roads)

    # import the sgid roads fc
    print "Importing SGID Roads ..."
    #expression = "ZIPCODE_L in ('84108', '84106', '84105')" ##TESTING STUFF##
    expression = ""
    network_roads = arcpy.FeatureClassToFeatureClass_conversion(sgid_roads, str(network_fgdb) + r'/NetworkDataset', 'Roads', expression)

    ## add the needed fields ##
    print "Add needed network fields to fgdb road data"
    arcpy.AddField_management(network_roads,"NETSUBTYPE", "SHORT", "","","")
    arcpy.AddField_management(network_roads,"USEEXIST", "TEXT", "","","1")
    arcpy.AddField_management(network_roads,"URBTRAFFIC", "TEXT", "","","1")
    arcpy.AddField_management(network_roads,"EXCL_WALK", "TEXT", "","","1")
    arcpy.AddField_management(network_roads,"IMPED_MIN","DOUBLE","6","2")
    arcpy.AddField_management(network_roads,"F_T_IMP_MIN","DOUBLE","6","2")
    arcpy.AddField_management(network_roads,"T_F_IMP_MIN","DOUBLE","6","2")
    arcpy.AddField_management(network_roads,"IMPED_PED","DOUBLE","6","2")
    #arcpy.AddField_management(network_roads,"STARTX","DOUBLE","7","1")  # add geometry attributes below, instead
    #arcpy.AddField_management(network_roads,"ENDX","DOUBLE","7","1")  # add geometry attributes below, instead
    #arcpy.AddField_management(network_roads,"STARTY","DOUBLE","7","1")  # add geometry attributes below, instead
    #arcpy.AddField_management(network_roads,"ENDY","DOUBLE","7","1")  # add geometry attributes below, instead
    #arcpy.CalculateGeometryAttributes_management(network_roads, [["STARTX", "LINE_START_X"], ["ENDX", "LINE_END_X"]])  # add geometry attributes below, instead

    ## Add geometry fields with start and end XY values ##
    # but, do this for only limited access roads
    arcpy.MakeFeatureLayer_management(network_roads, 'network_roads_lyr', "DOT_HWYNAM <> ''")
    arcpy.AddGeometryAttributes_management('network_roads_lyr', "LINE_START_MID_END")
    arcpy.Delete_management('network_roads_lyr')


    ## create the needed scratch data (ie: the urban areas) and assign the segments that intersect the urban bounaries with an URBTRAFFIC = Yes or No ##
    urban_areas = generate_scratch_data(directory)   
    #arcpy.MakeFeatureLayer_management(urban_areas, 'urban_areas_lyr')
    arcpy.MakeFeatureLayer_management(network_roads, 'network_roads_lyr')
    urban_roads_selected = arcpy.SelectLayerByLocation_management('network_roads_lyr', 'intersect', urban_areas)
    # Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script
    arcpy.CalculateField_management(urban_roads_selected, field="URBTRAFFIC", expression='"Y"', expression_type='VB', code_block='')
    # calculte the segments that were not in an urban area to "N"
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "URBTRAFFIC is NULL")
    arcpy.CalculateField_management(urban_roads_selected, field="URBTRAFFIC", expression='"N"', expression_type='VB', code_block='')
   

    ## begin calculating the field values ##
    ## USEEXIST ##
    print "Calculate USEEXIST fields..."
    # Yes    
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "not (SPEED_LMT is null) and ( SPEED_LMT >= 5 and SPEED_LMT <= 80)")
    arcpy.CalculateField_management(urban_roads_selected, field="USEEXIST", expression='"Y"', expression_type='VB', code_block='')
    # No - also set SPEED_LMT to 25 for these records as well
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "USEEXIST is null or USEEXIST <> '1'")
    arcpy.CalculateField_management(urban_roads_selected, field="USEEXIST", expression='"N"', expression_type='VB', code_block='')
    arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='25', expression_type='VB', code_block='')

    ## SPEED_LMT ##
    print "Calculate speed limits..."
    # 70 mph - UDOT limited access highway and freeways
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "CARTOCODE = '1' OR ((DOT_RTNAME = '0201P' OR DOT_RTNAME = '0201N') and CARTOCODE = '4') OR CARTOCODE = '2'")
    arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='70', expression_type='VB', code_block='')

    # 65 mph - major state and US highways
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(CARTOCODE = '2' OR CARTOCODE = '3' OR CARTOCODE = '4' OR CARTOCODE = '5') AND USEEXIST = 'N'")
    arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='65', expression_type='VB', code_block='')

    # 55 mph - UDOT freeway collectors/feeders
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "DOT_RTNAME like '%C%' and (USEEXIST is null or USEEXIST <> 'Y')")
    arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='55', expression_type='VB', code_block='')

    # 40 mph - UDOT ramps
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "DOT_RTNAME like '%R%' and (USEEXIST is null or USEEXIST <> 'Y')")
    arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='40', expression_type='VB', code_block='')

    # 50 mph - invalid speeds on major local roads
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(USEEXIST is null or  USEEXIST <> 'Y') AND ( CARTOCODE = '8')")
    arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='55', expression_type='VB', code_block='')

    # 45 mph - unpaved major roads
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(USEEXIST is null or  USEEXIST <> 'Y') AND ( CARTOCODE = '9')")
    arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='45', expression_type='VB', code_block='')


    # downgrade speeds all non-divided major local and major highways in the urban buffer to 40 mph.  However, exclude Timp Highway, MountainView, Legacy, Bangerter Highway and fast portion of US 89 in Davis County
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(CARTOCODE = '2' OR CARTOCODE = '3' OR CARTOCODE = '4' OR CARTOCODE = '5' OR CARTOCODE = '8' OR CARTOCODE = '9') AND URBTRAFFIC = 'Y' AND NOT (DOT_RTNAME = '0201P' OR DOT_RTNAME = '0201N' OR DOT_RTNAME = '0154P' or DOT_RTNAME = '0154N' OR DOT_RTNAME = '0085P' or DOT_RTNAME = '0085N' or (DOT_RTNAME Like '0%' and (CARTOCODE = '2' or CARTOCODE = '4')) or DOT_RTNAME LIKE '0092PC%' or DOT_RTNAME LIKE '0092NC%' or (DOT_RTNAME LIKE '0089%' and DOT_RTPART = '10'))")
    arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='40', expression_type='VB', code_block='')

    # downgrade the speeds on all freeways in settled areas to 65
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(CARTOCODE = '1' OR ((DOT_RTNAME = '0201P' OR DOT_RTNAME = '0201N') and CARTOCODE = '4') OR CARTOCODE = '2') and URBTRAFFIC = 'Y'")
    arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='65', expression_type='VB', code_block='')

    ## Fix roads with a speed limit of zero
    # apply manual corrections - US89 , Timp Highway collector
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "DOT_RTNAME like '0092%' and DOT_RTNAME like '%C%'")
    arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='65', expression_type='VB', code_block='')

    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "DOT_RTNAME like '0085%'")
    arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='55', expression_type='VB', code_block='')

    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "DOT_RTNAME like '0154%'")
    arcpy.CalculateField_management(urban_roads_selected, field="SPEED_LMT", expression='55', expression_type='VB', code_block='')


    #### PART 2: Calculate Travel Cost Impedance ####
    print "Calculate Travel Cost Impedance..."
    # calculate impedance (in minutes) for all ramp-accessed roads (freeways)
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "CARTOCODE = '1' or CARTOCODE = '2' or CARTOCODE = '4' or DOT_RTNAME like '%R%' or DOT_RTNAME like '%C%' or URBTRAFFIC = 'N'")
    arcpy.CalculateField_management(urban_roads_selected, field="IMPED_MIN", expression='([SHAPE_Length]/1609 * 60) / [SPEED_LMT]', expression_type='VB', code_block='')
    # switch selection and calculate the impedance (in minutes) for all traffic controlled roads by increasing the travel time by a factor of 1.5 to account for stop signs, signals, and turns
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','SWITCH_SELECTION')
    arcpy.CalculateField_management(urban_roads_selected, field="IMPED_MIN", expression='([SHAPE_Length]/1609 * 60) / [SPEED_LMT] * 1.5', expression_type='VB', code_block='')
    arcpy.CalculateField_management(urban_roads_selected, field="IMPED_PED", expression='[SHAPE_Length] / 84', expression_type='VB', code_block='')
    # select limited access roadways (ie: freeways/ramps) and multiply by 1.2
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "CARTOCODE = '1' OR ((DOT_RTNAME = '0201P' OR DOT_RTNAME = '0201N') and CARTOCODE = '4') OR CARTOCODE = '2' or CARTOCODE = '7'")
    arcpy.CalculateField_management(urban_roads_selected, field="IMPED_MIN", expression='([SHAPE_Length]/1609 * 60) / [SPEED_LMT] * 1.2', expression_type='VB', code_block='')

    ## impedance needed to be be set differently for each direction on one way streets and routes. Check to see if ONE_WAY attributes for limited access freeways/highways need to be fixed
    print "Calculate one ways..."
    # for both directions of travel on I-215 (semi-looping), set the ONE_WAY attribute using manual selection so that all features oriented in the true direction of travel are set to 1 and the others to 2
    # oneway codes [0 = Two way travel; 1 = One way travel in direction of arc; 2 = One way travel in opposite direction of arc]
    # set oneway to '1'
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0215N' and DOT_F_MILE > DOT_T_MILE) or (DOT_RTNAME = '0215P' and DOT_F_MILE < DOT_T_MILE)")
    arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='1', expression_type='VB', code_block='')
    # set oneway to '2'
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0215N' and DOT_F_MILE < DOT_T_MILE) or (DOT_RTNAME = '0215P' and DOT_F_MILE > DOT_T_MILE)")
    arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='2', expression_type='VB', code_block='')

    ## For the positive (eastbound) travel direction for x (E-W) trending routes
    # query the coordinate values for these selected records (using two temporary fields populated by the calculate geometry field tool), to set the ONE_WAY attribute for these selected records as follows:
    # where x coordinate at start point is < then x coordinate at end point: set oneway = 1
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0080P' or DOT_RTNAME = '0084P' or DOT_RTNAME = '0070P' or (DOT_RTNAME = '0201P' and DOT_RTPART = '2' ) or (DOT_RTNAME = '0007P' and DOT_RTPART = '2')) and START_X < END_X")
    arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='1', expression_type='VB', code_block='')
    # where x coordinate at start point is > then x coordinate at end point: set oneway = 2
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0080P' or DOT_RTNAME = '0084P' or DOT_RTNAME = '0070P' or (DOT_RTNAME = '0201P' and DOT_RTPART = '2' ) or (DOT_RTNAME = '0007P' and DOT_RTPART = '2')) and START_X > END_X")
    arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='2', expression_type='VB', code_block='')

    ## For the negative (westbound) travel direction for X Trending (E-W) routes
    # Query the coordinate values for these selected records (using two temporary fields populated by the calculate geometry field tool), to set the ONE_WAY attribute for these selected records as follows:
    # where x coordinate at start point is > then x coordinate at end point: set oneway = 1
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0080N' or DOT_RTNAME = '0084N' or DOT_RTNAME = '0070N' or DOT_RTNAME = '0201N' or DOT_RTNAME = '0007N') and START_X > END_X")
    arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='1', expression_type='VB', code_block='')
    # where x coordinate at start point is < then x coordinate at end point: set oneway = 2
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0080N' or DOT_RTNAME = '0084N' or DOT_RTNAME = '0070N' or DOT_RTNAME = '0201N' or DOT_RTNAME = '0007N') and START_X < END_X")
    arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='2', expression_type='VB', code_block='')

    ## For the positive (northbound) travel direction for Y Trending (N-S) routes
    # Query the coordinate values for these selected records (using two temporary fields populated by the calculate geometry field tool), to set the ONE_WAY attribute for these selected records as follows:
    # where y coordinate at start point is < then y coordinate at end point: set oneway = 1
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0015P' or (DOT_RTNAME = '0152P' and DOT_RTPART ='2') or (DOT_RTNAME = '0154P' and DOT_RTPART ='2') or DOT_RTNAME = '0067P' or (DOT_RTNAME = '0189P' and DOT_RTPART ='2') or (DOT_RTNAME = '0191P' and DOT_RTPART ='2') or (DOT_RTNAME = '0089P' and (DOT_RTPART ='4' or DOT_RTPART ='7' or DOT_RTPART ='9' or DOT_RTPART ='11'))) and START_Y < END_Y")
    arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='1', expression_type='VB', code_block='')
    # where y coordinate at start point is > then y coordinate at end point: set oneway = 2
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0015P' or (DOT_RTNAME = '0152P' and DOT_RTPART ='2') or (DOT_RTNAME = '0154P' and DOT_RTPART ='2') or DOT_RTNAME = '0067P' or (DOT_RTNAME = '0189P' and DOT_RTPART ='2') or (DOT_RTNAME = '0191P' and DOT_RTPART ='2') or (DOT_RTNAME = '0089P' and (DOT_RTPART ='4' or DOT_RTPART ='7' or DOT_RTPART ='9' or DOT_RTPART ='11'))) and START_Y > END_Y")
    arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='2', expression_type='VB', code_block='')

    ## For the negative (southbound) travel direction for south north (y) trending routes and exception for a couple sections of us40 and us6
    # Query the coordinate values for these selected records (using two temporary fields populated by the calculate geometry field tool), to set the ONE_WAY attribute for these selected records as follows:
    # where y coordinate at start point is > then y coordinate at end point: set oneway = 1
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0015N' or DOT_RTNAME = '0152N' or DOT_RTNAME = '0154N' or DOT_RTNAME = '0067N' or DOT_RTNAME = '0189N' or DOT_RTNAME = '0191N ' or DOT_RTNAME = '0040N' or DOT_RTNAME = '0006N' or DOT_RTNAME = '0089N' or (DOT_RTNAME = '0040P' and DOT_RTPART ='2') or (DOT_RTNAME = '0006P' and DOT_RTPART ='3')) and START_Y > END_Y")
    arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='1', expression_type='VB', code_block='')
    # where y coordinate at start point is < then y coordinate at end point: set oneway = 2
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "(DOT_RTNAME = '0015N' or DOT_RTNAME = '0152N' or DOT_RTNAME = '0154N' or DOT_RTNAME = '0067N' or DOT_RTNAME = '0189N' or DOT_RTNAME = '0191N ' or DOT_RTNAME = '0040N' or DOT_RTNAME = '0006N' or DOT_RTNAME = '0089N' or (DOT_RTNAME = '0040P' and DOT_RTPART ='2') or (DOT_RTNAME = '0006P' and DOT_RTPART ='3')) and START_Y < END_Y")
    arcpy.CalculateField_management(urban_roads_selected, field="ONEWAY", expression='2', expression_type='VB', code_block='')


    ## Calculate the travel cost fields and then inflate the travel cost for the wrong direction of travel on one way segments by a large factor (100 x current impedance is currently used)
    print "Calculate T_F_IMP_MIN and F_T_IMP_MIN values..."
    # Transfer over all IMPED_MIN values to both T_F_IMP_MIN and F_T_IMP_MIN fields.
    # clear selection 
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','CLEAR_SELECTION')
    arcpy.CalculateField_management(urban_roads_selected, field="T_F_IMP_MIN", expression='[IMPED_MIN]', expression_type='VB', code_block='')
    arcpy.CalculateField_management(urban_roads_selected, field="F_T_IMP_MIN", expression='[IMPED_MIN]', expression_type='VB', code_block='')
    # Now, inflate the travel time on one ways...
    # Select all roads where the ONEWAY attribute = 1
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "ONEWAY = '1'")
    arcpy.CalculateField_management(urban_roads_selected, field="T_F_IMP_MIN", expression='[IMPED_MIN] * 100', expression_type='VB', code_block='')
    # Select all roads where the ONEWAY attribute = 2
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "ONEWAY = '2'")
    arcpy.CalculateField_management(urban_roads_selected, field="F_T_IMP_MIN", expression='[IMPED_MIN] * 100', expression_type='VB', code_block='')


    ## Part 3 - Build the network dataset
    # Create 2 different values for the NETSUBTYPE field so connectivity can be modeled at endpoints for limited access highways and ramps and at any vertex for other, surface streets:
    # Query for limited access features and set NETSUBTYPE = 1 and set EXCL_WALK = ‘Y’
    print "Calculate NETSUBTYPE values..." 
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','NEW_SELECTION', "CARTOCODE = '1' or CARTOCODE = '2' or CARTOCODE = '4' or DOT_RTNAME like '%R%' or DOT_RTNAME like '%C%'")
    arcpy.CalculateField_management(urban_roads_selected, field="NETSUBTYPE", expression='1', expression_type='VB', code_block='')
    arcpy.CalculateField_management(urban_roads_selected, field="EXCL_WALK", expression='Y', expression_type='VB', code_block='')
    # Switch selection and set remaining records NETSUBTYPE = 2 and set EXCL_WALK = ‘N’
    urban_roads_selected = arcpy.SelectLayerByAttribute_management('network_roads_lyr','SWITCH_SELECTION')
    arcpy.CalculateField_management(urban_roads_selected, field="NETSUBTYPE", expression='2', expression_type='VB', code_block='')
    arcpy.CalculateField_management(urban_roads_selected, field="EXCL_WALK", expression='N', expression_type='VB', code_block='')

    # clean up resources and memory
    arcpy.Delete_management('network_roads_lyr')

    # create ‘Subtypes’ to define the two geodatabase subtypes using the NETSUBTYPE field
    # Code: "1" || Description "Limited Access & Ramps"
    # Code: "2" || Description "Other"
    print "Create SUBTYPES for Limited Access & Ramps and Other..." 
    arcpy.SetSubtypeField_management(network_roads, field="NETSUBTYPE", clear_value="false")
    arcpy.AddSubtype_management(network_roads, subtype_code="1", subtype_description="Limited Access & Ramps")
    arcpy.AddSubtype_management(network_roads, subtype_code="2", subtype_description="Other")

    # build the netork based on an existing network .xml file template
    ## this is done in a seperate script b/c it needs to be run in Desktop 10.6 (or higher) or Pro
    ## use this script: "agrc_roadnetwork_create_and_build_network_run2nd.py"
    print "Done!"
コード例 #8
0
    ##Add the unit code sub_type to the output polygon feature class

    #Create empty sub type for the Unit Code field
    arcpy.SetSubtypeField_management(unitsUpdatedFCPath, unitCodeFieldName)

    #create a new numpy array from the Unit polygon attributes we just created. This array is a 1d array of tuples
    fields = ['OID@', unitCodeFieldName]
    UnitCodeSubTypeArray = arcpy.da.TableToNumPyArray(validUnitTableName,
                                                      fields)

    #loop through the unit code sub-type array and add each value to the sub-types for the unit code field
    #the array is a 1d array of tuples, so we need to use "array[][]" to access individual values
    for i in range(UnitCodeSubTypeArray.shape[0]):
        arcpy.AddSubtype_management(unitsUpdatedFCPath,
                                    UnitCodeSubTypeArray[i][0],
                                    UnitCodeSubTypeArray[i][1])

##Delete the temp units layer
    arcpy.Delete_management(os.path.join(digitisingFDPath, unitsTempFCName))

##Script Finished

#code to provide error messages. From SURV319 2017 Tutorial 4 instructions
except arcpy.ExecuteError:
    # Get the tool error messages
    #
    msgs = arcpy.GetMessages(2)

    # Return tool error messages for use with a script tool
    #
コード例 #9
0
            else:
                row[1] = 9

            calcursor.updateRow(row)

            arcpy.AddMessage("Region codes updated for {0}.".format(fc))
try:
    for fc in fcList:
        # Set subtype on Planning Region Code field
        arcpy.SetSubtypeField_management(fc, "PlanningRegionCode")

        arcpy.AddMessage("Subtype set for {0}.".format(fc))

        # Add subtypes
        for code in subtypeDict:
            arcpy.AddSubtype_management(fc, code, subtypeDict[code])

            arcpy.AddMessage("Subtypes added {0}.".format(fc))

except:
    arcpy.AddMessage("Subtype could not created for {0}.".format(fc))

try:
    # Create T1 Communities domain
    arcpy.CreateDomain_management(inGDB, "T1Communities",
                                  "Valid T1 communities", "TEXT", "CODED")
    t1CommsDomain = "T1Communities"
    # Add values from T1 Comms dict to domain
    for code in t1CommsDict:
        arcpy.AddCodedValueToDomain_management(inGDB, t1CommsDomain, code,
                                               t1CommsDict[code])
                              unitCodeFieldName, "LONG")

    #Create empty sub type for the Unit Code field
    arcpy.SetSubtypeField_management(
        os.path.join(digitisingFDPath, unitsFCName), unitCodeFieldName)

    #create a new numpy array from the Unit polygon attributes we just created. This array is a 1d array of tuples
    fields = ['OID@', unitCodeFieldName]
    UnitCodeSubTypeArray = arcpy.da.TableToNumPyArray(validUnitTableName,
                                                      fields)

    #loop through the unit code sub-type array and add each value to the sub-types for the unit code field
    #the array is a 1d array of tuples, so we need to use "array[][]" to access individual values
    for i in range(UnitCodeSubTypeArray.shape[0]):
        arcpy.AddSubtype_management(
            os.path.join(digitisingFDPath, unitsFCName),
            UnitCodeSubTypeArray[i][0], UnitCodeSubTypeArray[i][1])

##Script Finished

#code to provide error messages. From SURV319 2017 Tutorial 4 instructions
except arcpy.ExecuteError:
    # Get the tool error messages
    #
    msgs = arcpy.GetMessages(2)

    # Return tool error messages for use with a script tool
    #
    arcpy.AddError(msgs)

    # Print tool error messages for use in Python/PythonWin
コード例 #11
0
def main():
    # GET PARAMETER VALUES
    New_Anthro_Features = arcpy.GetParameterAsText(0)
    Existing_Anthro_Features = arcpy.GetParameterAsText(1)
    replace_subtypes = arcpy.GetParameterAsText(2)

    # Overwrite outputs
    arcpy.env.overwriteOutput = True

    # Helper functions (from ccslib)
    def Str2Bool(string):
        """
        Converts a string to Python boolean. If not 'true' in lowercase, returns
        False.
        :param string: a string of True or False, not cap sensitive
        :return: Boolean
        """
        if string == 'True' or string == 'true':
            return True
        else:
            return False

    def AddFields(input_feature,
                  field_to_add,
                  field_types,
                  copy_existing=False):
        """
        Adds provided fields to the input_feature, removes or copies existing of
        the same name.
        :param input_feature: a feature class
        :param field_to_add: a list of field names as strings
        :param field_types: a list of field types as strings, in order of fields_
        to_add
        :param copy_existing: True to create a copy of any existing field with
        same name as field to add
        :return: None
        """

        # Create dictionary of field types mapped to fields to add
        fieldTypesDict = dict(zip(field_to_add, field_types))

        # Copy fields if they exist and delete original
        existingFields = arcpy.ListFields(input_feature)
        fieldNames = [each.name.lower() for each in existingFields]
        for field in field_to_add:
            if field.lower() in fieldNames:
                arcpy.AddMessage(field + " field exists.")
                if copy_existing:
                    arcpy.AddMessage("Copying to new field named " + field +
                                     "_copy.")
                    fieldIndex = fieldNames.index(field.lower())
                    if field.lower() + "_copy" in fieldNames:
                        arcpy.AddMessage("Deleting field " + field + "_copy")
                        arcpy.DeleteField_management(input_feature,
                                                     field + "_copy")
                    arcpy.AddField_management(input_feature, field + "_copy",
                                              existingFields[fieldIndex].type)
                    with arcpy.da.UpdateCursor(
                            input_feature, [field, field + "_copy"]) as cursor:
                        try:
                            for row in cursor:
                                row[1] = row[0]
                                cursor.updateRow(row)
                        except arcpy.ExecuteError:
                            arcpy.AddMessage("Unable to copy from " + field +
                                             " to " + field + "_copy.")
                arcpy.AddMessage("Deleting original field.")
                arcpy.DeleteField_management(input_feature, field)

        # Add fields
        for field in field_to_add:
            # arcpy.AddMessage("Adding " + field + " field")
            arcpy.AddField_management(input_feature,
                                      field,
                                      fieldTypesDict[field],
                                      field_length=50)

    # Main script

    # Get path to existing anthro features
    desc = arcpy.Describe(Existing_Anthro_Features)
    anthro_feature_path = desc.catalogPath

    # List subtypes from the existing anthro features
    subtypes = arcpy.da.ListSubtypes(Existing_Anthro_Features)

    # Add new field "Feature"
    AddFields(New_Anthro_Features, ['Feature'], ['SHORT'])

    # Copy new features over existing
    feature = arcpy.CopyFeatures_management(New_Anthro_Features,
                                            anthro_feature_path)

    replace_subtypes = Str2Bool(replace_subtypes)

    if replace_subtypes:
        # Set Feature field to Subtype field
        arcpy.SetSubtypeField_management(feature, "Feature")

        # Create subtypes
        for stcode, stdict in list(subtypes.items()):
            arcpy.AddSubtype_management(feature, stcode, stdict['Name'])

        # Iterate through subtypes and update feature code
        def get_feature_code(subtype_name):
            for stcode, stdict in list(subtypes.items()):
                if stdict['Name'] == subtype_name:
                    return stcode

        with arcpy.da.UpdateCursor(feature, ["Feature", "Subtype"]) as cursor:
            for row in cursor:
                row[0] = get_feature_code(row[1])
                cursor.updateRow(row)

        # Apply domains
        feature_basename = desc.baseName
        domain_name = feature_basename + "_Subtypes"

        arcpy.AssignDomainToField_management(feature, "Subtype", domain_name)
        if len(subtypes) == 1 and subtypes[0]['SubtypeField'] == '':
            pass
        else:
            st_codes = [
                str(stcode) for stcode, stdict in list(subtypes.items())
            ]
            arcpy.AssignDomainToField_management(feature, "Subtype",
                                                 domain_name, st_codes)

        # Apply defaults
        for st_code, st_dict in list(subtypes.items()):
            default = subtypes[st_code]['Name']
            arcpy.AssignDefaultToField_management(feature, "Subtype", default,
                                                  st_code)

        default_type = feature_basename
        st_codes = [str(stcode) for stcode, stdict in list(subtypes.items())]
        arcpy.AssignDefaultToField_management(feature, "Type", default_type,
                                              st_codes)
コード例 #12
0
 def creerSubtype(self, catalogue, workspace, classe, subtype='CODE_SPEC'):
 #-------------------------------------------------------------------------------------
     """
     Permet de créer les SubTypes dans les classes de la Géodatabase.
     
     Paramètres:
     -----------
     catalogue   : Numéro du catalogue.
     workspace   : Nom de la géodatabase ou les domaines seront créés.
     classe      : Liste des noms de classe contenus dans la géodatabase utilisés pour créer les domaines.
     subtype     : Nom de l'attribut contenant les subtypes.
     
     """
     
     #Envoyer un message
     arcpy.AddMessage(" ")
     arcpy.AddMessage("- Créer les SubTypes dans les classes de la Géodatabase")
     
     #Définir le workspace par défaut
     arcpy.env.workspace = workspace
     
     #Extraire la description de la Géodatabase
     for fc in classe.split(","):
         #Afficher le message
         arcpy.AddMessage(" SetSubtypeField_management('" + fc + "', '" + subtype + "')")
         #Définir l'attribut qui contient le Subtype
         arcpy.SetSubtypeField_management(fc, subtype)
         
         #Définir aucun propriétaire de la classe par défaut
         prop = ""
         #Vérifier si le propriétaire est présent dans le nom de la classe
         if "." in fc:
             #Définir le propriétaire de la classe
             prop = fc.split(".")[0] + "."
         
         #Créer la SQL pour extraire les subtypes
         sql = ("select distinct B.feat_type_code_bd, B.feat_type_name_fr"
                "  from feat_catalogue A, feat_type B"
                " where A.feat_catal_type=" + catalogue.split(":")[0] + " and A.feat_catal_id=B.feat_catal_fk"
                "   and B.feat_type_name_database='" + fc.replace(prop,"") + "'"
                " order by B.feat_type_code_bd")
         
         #arcpy.AddMessage(sql)
         #Exécuter la SQL
         resultat = self.BDG.query(sql)
         
         #Vérifier le résultat
         if resultat:
             #Traiter tous les résultats
             for valeur in resultat:
                 #Afficher le message
                 arcpy.AddMessage(" AddSubtype_management('" + fc + "', " + str(valeur[0]) + ", '" + str(valeur[0]) + ":" + valeur[1] + "')")
                 #Ajouter un subtype à la classe
                 arcpy.AddSubtype_management(fc, valeur[0], str(valeur[0]) + ":" + valeur[1])   
             
             #Afficher le message
             arcpy.AddMessage(" SetDefaultSubtype_management('" + fc + "', " + str(resultat[0][0]) + ")")
             #Définir le Subtype par défaut
             arcpy.SetDefaultSubtype_management(fc, resultat[0][0])
     
     #Sortir
     return
コード例 #13
0
ファイル: gdb.py プロジェクト: fstraw/history
def create_structures_fc(gdb):
    """
    Create Historic Structures feature class
    """
    arcpy.env.workspace = gdb
    fc = "HistoricStructures"
    spatref = arcpy.SpatialReference(
        "WGS 1984 Web Mercator (auxiliary sphere)")
    if arcpy.Exists(fc):
        arcpy.Delete_management(os.path.join(gdb, fc))
    has_m = "DISABLED"
    has_z = "DISABLED"
    # Execute CreateFeatureclass
    arcpy.CreateFeatureclass_management(gdb, fc, "POINT", "", has_m, has_z,
                                        spatref)
    arcpy.AddField_management(fc, "ResourceID", "LONG", "", "", "",
                              "Resource ID", "NULLABLE", "NON_REQUIRED", "")
    arcpy.AddField_management(fc, "PropName", "TEXT", "", "", 100,
                              "Resource Name", "NULLABLE", "NON_REQUIRED", "")
    arcpy.AddField_management(fc, "StrucType", "LONG", "", "", "",
                              "Structure Type", "NON_NULLABLE", "NON_REQUIRED",
                              "")
    arcpy.AddField_management(fc, "BldType", "TEXT", "", "", 3,
                              "Building Type", "NON_NULLABLE", "NON_REQUIRED",
                              "")
    arcpy.AddField_management(fc, "StyleType", "TEXT", "", "", 3,
                              "Architectural Style", "NON_NULLABLE",
                              "NON_REQUIRED", "")
    arcpy.AddField_management(fc, "Eligibility", "TEXT", "", "", 3,
                              "Eligibility Status", "NON_NULLABLE",
                              "NON_REQUIRED", "")
    arcpy.AddField_management(fc, "ConstYr", "LONG", "", "", "",
                              "Construction Year", "NULLABLE", "NON_REQUIRED",
                              "")
    arcpy.AddField_management(fc, "Address", "TEXT", "", "", 200, "Address",
                              "NULLABLE", "NON_REQUIRED", "")
    arcpy.AddField_management(fc, "Notes", "TEXT", "", "", 200, "Notes",
                              "NULLABLE", "NON_REQUIRED", "")
    arcpy.AddGlobalIDs_management(fc)
    arcpy.AddField_management(fc, "EPProject", "TEXT", "", "", 20,
                              "EPEI Project ID", "NULLABLE", "NON_REQUIRED",
                              "")
    arcpy.SetSubtypeField_management(fc, "StrucType")
    for item in subtypes.items():
        arcpy.AddSubtype_management(fc, item[0], item[1])
    arcpy.SetDefaultSubtype_management(fc, 5)
    for item in subtypes.items():
        arcpy.AssignDomainToField_management(fc, "BldType", item[1], item[0])
    arcpy.AssignDomainToField_management(
        fc, "StyleType", "Styles",
        ['0', '1', '2', '3', '4', '5', '6', '7', '8'])
    arcpy.AssignDomainToField_management(
        fc, "Eligibility", "Eligibility",
        ['0', '1', '2', '3', '4', '5', '6', '7', '8'])
    arcpy.AssignDefaultToField_management(
        fc, "Eligibility", "U", ['0', '1', '2', '3', '4', '5', '6', '7', '8'])
    arcpy.AssignDefaultToField_management(
        fc, "StyleType", "NS", ['0', '1', '2', '3', '4', '5', '6', '7', '8'])
    arcpy.AssignDefaultToField_management(
        fc, "BldType", "OT", ['0', '1', '2', '3', '4', '6', '7', '8'])
    arcpy.AssignDefaultToField_management(fc, "BldType", "NAT", '5')
    return os.path.join(gdb, fc)
コード例 #14
0
    GWRutils.logMessage(log, '...Assigned all universal domains to fields')

except Exception as e:
    print('Failed to assign universal domains to fields! Exiting...')
    print(e)
    GWRutils.logMessage(
        log, 'Failed to assign universal domains to fields! ' + 'Exiting...')
    GWRutils.logMessage(log, str(e))
    sys.exit()

# Create subtypes in Activity and Chemical tables based on propertyOID
try:
    arcpy.SetSubtypeField_management(activity_fc, 'PropertyOID')
    arcpy.SetSubtypeField_management(chem_app_table, 'PropertyOID')
    for prop in props_dict:
        arcpy.AddSubtype_management(activity_fc, prop, props_dict[prop])
        arcpy.AddSubtype_management(chem_app_table, prop, props_dict[prop])
    print('...Created propertyOID subtypes in Activity and Chemical datasets')
    GWRutils.logMessage(
        log, '...Created propertyOID subtypes in Activity ' +
        'and Chemical datasets')

except Exception as e:
    print('Failed to create propertyOID subtypes in Activity and Chemical ' +
          'datasets! Exiting...')
    print(e)
    GWRutils.logMessage(
        log, 'Failed to create propertyOID subtypes in ' +
        'Activity and Chemical datasets! Exiting...')
    GWRutils.logMessage(log, str(e))
    sys.exit()
コード例 #15
0
##Create accuracy field in the contacts feature class and add sub type containing valid accuracy types
    
    #add the accuracy field
    arcpy.AddField_management(os.path.join(digitisingFDName,contactsFCName),accuracyFieldName,"LONG","")

    #Create empty sub type to go in the Accuracy Field
    arcpy.SetSubtypeField_management(os.path.join(digitisingFDName,contactsFCName),accuracyFieldName)

    #define a sub-type(ST) array for accuracy fields as tuples
    accuracySTArray = [(1,"Accurate"),(2,"Approximate"),(3,"Inferred")]
    
    #loop through the unit code sub-type array and add each value to the sub-types for the unit code field
    #the array is a 1d array of tuples, so we need to use "array[][]" to access individual values
    for i in range(len(accuracySTArray)):
        arcpy.AddSubtype_management(os.path.join(digitisingFDName,contactsFCName),accuracySTArray[i][0],accuracySTArray[i][1])

##Script Finished

#code to provide error messages. From SURV319 2017 Tutorial 4 instructions
except arcpy.ExecuteError: 
    # Get the tool error messages 
    # 
    msgs = arcpy.GetMessages(2) 
    
    # Return tool error messages for use with a script tool 
    #
    arcpy.AddError(msgs) 

    # Print tool error messages for use in Python/PythonWin 
    # 
コード例 #16
0
    # Process: Set Subtype Field...
    arcpy.SetSubtypeField_management(featureClass, "subtype")

    # Process: Add Subtypes...
    # Store all the suptype values in a dictionary with the subtype code as the "key" and the
    # subtype description as the "value" (stypeDict[code])
    # stypeDict = {"0": "'ODF-ი'","1": "P2P ინსტალაცია","2": "არხის მშენებლობა","3": "ბოძის მონტაჟი","4": "კაბელის მონტაჟი","5": "კარადის მონტაჟი","6": "სპლიტერი","7":"ქურო","8": "ჭის მონტაჟი",}
    #Create dict from list!!!
    subtypeDict = {}
    for i in range(len(subtype_list)):
        subtypeDict[str(i)] = subtype_list[i]
    print(subtypeDict)

    # use a for loop to cycle through the dictionary
    for code in subtypeDict:
        arcpy.AddSubtype_management(featureClass, code, subtypeDict[code])

    # Process: Set Default Subtype...
    # arcpy.SetDefaultSubtype_management(featureClass, 4)
except Exception as err:
    print(err.args[0])

#### DOMAINS: ###
try:
    # დომეინების შექმნა ბუღალტრული კატეგორიის სახელების მიხედვით
    for key, value in domains_dict.items():
        domain_name = key
        domain_description = key
        arcpy.CreateDomain_management(GDB, domain_name, domain_description,
                                      "SHORT", "CODED", "DEFAULT", "DEFAULT")