コード例 #1
0
def esriTopology(outFds, caf, mup):
    addMsgAndPrint('Checking topology of ' + os.path.basename(outFds))
    # First delete any existing topology
    ourTop = os.path.basename(outFds) + '_topology'
    testAndDelete(outFds + '/' + ourTop)
    # create topology
    addMsgAndPrint('  creating topology ' + ourTop)
    arcpy.CreateTopology_management(outFds, ourTop)
    ourTop = outFds + '/' + ourTop
    # add feature classes to topology
    arcpy.AddFeatureClassToTopology_management(ourTop, caf, 1, 1)
    if arcpy.Exists(mup):
        arcpy.AddFeatureClassToTopology_management(ourTop, mup, 2, 2)
    # add rules to topology
    addMsgAndPrint('  adding rules to topology:')
    for aRule in ('Must Not Overlap (Line)', 'Must Not Self-Overlap (Line)',
                  'Must Not Self-Intersect (Line)',
                  'Must Be Single Part (Line)'):
        addMsgAndPrint('    ' + aRule)
        arcpy.AddRuleToTopology_management(ourTop, aRule, caf)
    for aRule in ('Must Not Overlap (Area)', 'Must Not Have Gaps (Area)'):
        addMsgAndPrint('    ' + aRule)
        arcpy.AddRuleToTopology_management(ourTop, aRule, mup)
    addMsgAndPrint('    ' + 'Boundary Must Be Covered By (Area-Line)')
    arcpy.AddRuleToTopology_management(
        ourTop, 'Boundary Must Be Covered By (Area-Line)', mup, '', caf)
    # validate topology
    addMsgAndPrint('  validating topology')
    arcpy.ValidateTopology_management(ourTop)
    nameToken = os.path.basename(caf).replace('ContactsAndFaults', '')
    if nameToken == '':
        nameToken = 'GeologicMap'
    nameToken = 'errors_' + nameToken + 'Topology'
    for sfx in ('_point', '_line', '_poly'):
        testAndDelete(outFds + '/' + nameToken + sfx)
    # export topology errors
    addMsgAndPrint('  exporting topology errors')
    arcpy.ExportTopologyErrors_management(ourTop, outFds, nameToken)
    topoStuff = []
    topoStuff.append(
        '<i>Note that the map boundary commonly results in one "Must Not Have Gaps" line error</i>'
    )
    for sfx in ('_point', '_line', '_poly'):
        fc = outFds + '/' + nameToken + sfx
        topoStuff.append(space4 + str(numberOfRows(fc)) + ' rows in <b>' +
                         os.path.basename(fc) + '</b>')
        addMsgAndPrint('    ' + str(numberOfRows(fc)) + ' rows in ' +
                       os.path.basename(fc))
        if numberOfRows(fc) == 0: testAndDelete(fc)
    return topoStuff
コード例 #2
0
 def onClick(self):
     box = pythonaddins.MessageBox("You are about to look for gaps. This process could take a long time depending on the size of the fabric. Please be patient with the interface until it shows a finished message.", \
                                   "Select Parcel Fabric", 1)
     if box == "OK":
         workspace, PFname = os.path.split(parcelFabric)
         topology = os.path.join(workspace, PFname + "_topology")
         if arcpy.Exists(topology):
             arcpy.Delete_management(topology)
         arcpy.CreateTopology_management(workspace, PFname + "_topology")
         pfl = arcpy.mapping.ListLayers(mxd, "*Parcels")
         for layer in pfl:
             if layer.name == "Tax Parcels":
                 polygons = "FabricInvestigation\\Tax Parcels"
             elif layer.name == "Parcels":
                 polygons = "FabricInvestigation\\Parcels"
             else:
                 # Adding a message box here will cause tool to fail due to
                 # the looping of the layers when it finds layers not
                 # containing the Parcels or Tax Parcels.
                 pass
         arcpy.AddFeatureClassToTopology_management(topology, polygons)
         arcpy.AddFeatureClassToTopology_management(
             topology, "FabricInvestigation\\Lines")
         polygon_fc = os.path.join(workspace, PFname + "_Parcels")
         line_fc = os.path.join(workspace, PFname + "_Lines")
         arcpy.AddRuleToTopology_management(
             topology, "Boundary Must Be Covered By (Area-Line)",
             polygon_fc, "", line_fc)
         arcpy.ValidateTopology_management(topology)
         gdb, fds_name = os.path.split(workspace)
         arcpy.ExportTopologyErrors_management(topology, gdb, "Gaps")
         arcpy.mapping.MoveLayer(
             df,
             arcpy.mapping.ListLayers(mxd, "FabricInvestigation")[0],
             arcpy.mapping.ListLayers(mxd, "Gaps_line")[0], "BEFORE")
         arcpy.mapping.RemoveLayer(
             df,
             arcpy.mapping.ListLayers(mxd, "Gaps_point")[0])
         arcpy.mapping.RemoveLayer(
             df,
             arcpy.mapping.ListLayers(mxd, "Gaps_poly")[0])
         arcpy.mapping.RemoveLayer(
             df,
             arcpy.mapping.ListLayers(mxd, PFname + "_topology")[0])
         box2 = pythonaddins.MessageBox(
             "Finished Processing Gaps. Please proceed.",
             "Finsihed Processing Gaps", 0)
         ParcelLineGaps.checked = False
コード例 #3
0
def create_topology(workspace, tfl_lines):
    """Creates topology in the edit workspace creates an ACTIVE TFL line FC and adds rules to it
    workspace is the feature dataset"""
    arcpy.env.workspace = workspace
    topology = workspace + os.sep + 'TFL_Active_Line_Topology'
    active_lines = workspace + os.sep + 'TFL_Active_Lines__do_not_edit'
    if arcpy.Exists(topology):
        arcpy.Delete_management(topology)
    #make feature layer of active lines
    if arcpy.Exists(active_lines):
        arcpy.Delete_management(active_lines)
    tfl_active_lines_layer = arcpy.MakeFeatureLayer_management(
        tfl_lines, 'tfl_active_lines_layer', "Status_Code IN ('ACTIVE')")
    arcpy.CopyFeatures_management('tfl_active_lines_layer', active_lines)
    feature_class = active_lines
    del tfl_active_lines_layer

    try:
        arcpy.CreateTopology_management(workspace, 'TFL_Active_Line_Topology',
                                        .0001)
        arcpy.AddFeatureClassToTopology_management(topology, feature_class)
        #set the rules then add them to the topology
        rules = [
            'Must Not Overlap (Line)', 'Must Not Intersect (Line)',
            'Must Not Have Dangles (Line)', 'Must Not Self-Overlap (Line)',
            'Must Not Self-Intersect (Line)', 'Must Be Single Part (Line)'
        ]
        for rule in rules:
            arcpy.AddRuleToTopology_management(topology, rule, feature_class)
        arcpy.AddMessage('Added topology to TFL Active Lines')
    except:
        arcpy.AddError('Error adding topology')
コード例 #4
0
def check_topology(input_file, workspace):
    """Create Database and check for overlapping features. This function
    is based on one previously created by Christian Kienholz, University
    of Alaska, Fairbanks, 03/2012"""
    # Create Database, add a data set and upload the features
    database = arcpy.CreateFileGDB_management(workspace, 'database.gdb')
    dataset = arcpy.CreateFeatureDataset_management(database, 'validation',
                                                    input_file)
    feature = str(dataset) + '\\feature'
    arcpy.CopyFeatures_management(input_file, feature)

    #Create topology and rules. Add feature to it
    topology = arcpy.CreateTopology_management(dataset, 'topology_rules')
    arcpy.AddFeatureClassToTopology_management(topology, feature, 1, 1)
    arcpy.AddRuleToTopology_management(topology, 'Must Not Overlap (Area)',
                                       feature)
    arcpy.ValidateTopology_management(topology)

    # Export Errors
    arcpy.ExportTopologyErrors_management(topology, database, 'Errors')
    error_count = arcpy.GetCount_management(str(database) + '\\Errors_poly')
    original_count = arcpy.GetCount_management(input_file)

    arcpy.Delete_management(database)  # Delete database

    return [str(error_count), str(original_count)]
def createTopology(workspaceWrk, inputVRI, topoName, topoFullName):
    arcpy.AddMessage("Creating %s..." % (topoName))
    arcpy.CreateTopology_management(workspaceWrk, topoName)
    arcpy.AddFeatureClassToTopology_management(topoFullName, inputVRI)
    arcpy.AddRuleToTopology_management(topoFullName, "Must Not Overlap (Area)",
                                       inputVRI)
    arcpy.ValidateTopology_management(topoFullName)
コード例 #6
0
def buildCafMupTopology(inFds, um):
    if um.upper() == 'TRUE':
        useMup = True
    else:
        useMup = False
    inCaf = getCaf(inFds)
    caf = os.path.basename(inCaf)
    nameToken = caf.replace('ContactsAndFaults', '')
    if debug:
        addMsgAndPrint('name token=' + nameToken)
    if nameToken == '':
        nameToken = 'GeologicMap'
    inMup = inCaf.replace('ContactsAndFaults', 'MapUnitPolys')

    # First delete any existing topology
    ourTop = nameToken + '_topology'
    testAndDelete(inFds + '/' + ourTop)
    # create topology
    addMsgAndPrint('  creating topology ' + ourTop)
    arcpy.CreateTopology_management(inFds, ourTop)
    ourTop = inFds + '/' + ourTop
    # add feature classes to topology
    arcpy.AddFeatureClassToTopology_management(ourTop, inCaf, 1, 1)
    if useMup and arcpy.Exists(inMup):
        addMsgAndPrint(ourTop)
        addMsgAndPrint(inMup)
        arcpy.AddFeatureClassToTopology_management(ourTop, inMup, 2, 2)
    # add rules to topology
    addMsgAndPrint('  adding rules to topology:')
    for aRule in ('Must Not Overlap (Line)', 'Must Not Self-Overlap (Line)',
                  'Must Not Self-Intersect (Line)',
                  'Must Be Single Part (Line)',
                  'Must Not Have Dangles (Line)'):
        addMsgAndPrint('    ' + aRule)
        arcpy.AddRuleToTopology_management(ourTop, aRule, inCaf)
    # If we add rules that involve MUP, topology must be deleted before polys are rebuilt
    if useMup and arcpy.Exists(inMup):
        for aRule in ('Must Not Overlap (Area)', 'Must Not Have Gaps (Area)'):
            addMsgAndPrint('    ' + aRule)
            arcpy.AddRuleToTopology_management(ourTop, aRule, inMup)
        addMsgAndPrint('    ' + 'Boundary Must Be Covered By (Area-Line)')
        arcpy.AddRuleToTopology_management(
            ourTop, 'Boundary Must Be Covered By (Area-Line)', inMup, '',
            inCaf)
    # validate topology
    addMsgAndPrint('  validating topology')
    arcpy.ValidateTopology_management(ourTop)
コード例 #7
0
def CreateTopo(fc):
    ifc = fc
#     print "ifc:",ifc
    
    Coordinate_System = ifc.replace("shp", "prj")
#     print "Coordinate_System",Coordinate_System
#     os.path.join(shpFolder,Folder + "_地类更新.prj")
#     print Coordinate_System
#     File_GDB_Name = os.path.dirname(ifc),os.path.basename(ifc)    #"PLA_Topo.gdb"
    Geodatabase = ifc.replace("shp", "gdb")
    print "Geodatabase:",Geodatabase
    try:
        #新建数据库
        arcpy.CreateFileGDB_management(os.path.dirname(ifc), os.path.basename(ifc).replace("shp", "gdb"), "CURRENT")
    except:
        print "数据库已经建好"
        
    out_dataset_path = Geodatabase
    out_name = os.path.basename(ifc).replace(".shp", "")  #数据集名称
#     print "out_name:",out_name
    print "数据集名称:",out_name
    #创建数据集
    arcpy.CreateFeatureDataset_management(out_dataset_path, out_name, Coordinate_System)

    #向数据集导入shp
    in_features = ifc  #导入的shp名称
    out_path = os.path.join(Geodatabase,out_name)   #shp导入的数据集位置
    #print u"shp导入的数据集位置:" + str(out_path)
    out_name = os.path.basename(ifc).replace(".shp", "") + "_ToPo"    #导入后shp的名称
    #print u"导入后shp的名称:" + str(out_name)
    arcpy.FeatureClassToFeatureClass_conversion (in_features, out_path, out_name)


    # Process: Create Topology
    Topo_name =os.path.basename(ifc).replace(".shp", "") + "_ToPology" #拓扑结构的名称
    #print u"拓扑结构的名称:" + str(Topo_name)
    arcpy.CreateTopology_management(out_path, Topo_name, "")   #zhiduo_tp  拓扑结构

    # Process: Add Feature Class To Topology
    Topology = os.path.join(out_path,Topo_name)  # 拓扑结构的路径
    ##print u"拓扑结构的路径:" + str(Topology)
    ToPoShp = os.path.join(out_path,out_name)    # 要做拓扑的数据集里的shp
    ##print u"要做拓扑的数据集里的shp:" + str(ToPoShp)
    arcpy.AddFeatureClassToTopology_management(Topology, ToPoShp, "1", "1")

    # Process: Add Rule To Topology
    arcpy.AddRuleToTopology_management(Topology, "Must Not Have Gaps (Area)", ToPoShp, "", "", "")
    #print u"正在添加 Must Not Have Gaps 规则"
    arcpy.AddRuleToTopology_management(Topology, "Must Not Overlap (Area)", ToPoShp, "", "", "")
    #print u"正在添加 Must Not Overlap 规则"

    # Process: Validate Topology
    try:
        arcpy.ValidateTopology_management(Topology, "true")
    except:
        print str(ifc) + "的拓扑未成功验证,请人工重新建立拓扑。"

    print "拓扑验证完成" + '\n'
    print 
コード例 #8
0
def AddFeatureToTopology(theTopology,
                         theFeatureClassName,
                         xy_rank=1,
                         z_rank=1):
    """
    
    """

    arcpy.AddFeatureClassToTopology_management(theTopology,
                                               theFeatureClassName, xy_rank,
                                               z_rank)
コード例 #9
0
 def create_topology(self):
     """
     Create topology. participate two layers: ATE and Streets
     :return: topology in datebaseset Streets
     """
     Streets_Topology = os.path.join(self.nameDataSet, "Streets_Topology")
     ate = os.path.join(self.nameDataSet, "ate")
     arcpy.CreateTopology_management(self.nameDataSet, "Streets_Topology",
                                     "")
     arcpy.AddFeatureClassToTopology_management(Streets_Topology,
                                                self.nameStreets, "1", "1")
     arcpy.AddFeatureClassToTopology_management(Streets_Topology, ate, "1",
                                                "1")
     arcpy.AddRuleToTopology_management(Streets_Topology,
                                        "Must Not Overlap (Line)",
                                        self.nameStreets, "", "", "")
     arcpy.AddRuleToTopology_management(Streets_Topology,
                                        "Must Not Self-Overlap (Line)",
                                        self.nameStreets, "", "", "")
     arcpy.AddRuleToTopology_management(Streets_Topology,
                                        "Must Be Inside (Line-Area)",
                                        self.nameStreets, "", ate, "")
コード例 #10
0
def create_topology(fc, topo_output, rule, error_output):
    '''(feature class,topology output location,topology rule,topology error output location)-> error output location
    Creates a topology in topo_output. Adds fc to newly created topology.
    Adds rule to topology. Validates topology. Exports topology errors to error_output.
    Returns error_output string.
    '''
    toponame = '{0}_topo'.format(os.path.basename(fc))
    topo_path = os.path.join(topo_output, toponame)
    arcpy.CreateTopology_management(topo_output, toponame)
    arcpy.AddFeatureClassToTopology_management(topo_path, fc, 1)
    arcpy.AddRuleToTopology_management(topo_path, rule, fc)
    arcpy.ValidateTopology_management(topo_path)
    arcpy.ExportTopologyErrors_management(
        topo_path, error_output, '{0}_errors'.format(os.path.basename(fc)))
    return error_output
コード例 #11
0
def Topo(strPathFC, strPathFDS, strPathTopo, BoolValidate=None):
    ''' Create a no gaps/no overlaps topology for a feature class.
        creates requisite featuredataset if needed.
        optionally validates topology.
        Returns the location of the new featureclass in the featuredataset.
    '''
    if BoolValidate is None:
        BoolValidate = True

    if os.path.dirname(strPathFC):
        strFC = os.path.basename(strPathFC)
    strGDB, strFDS = os.path.split(strPathFDS)
    strPathFDS_FC = strPathFDS + os.sep + strFC

    if not arcpy.Exists(strPathTopo):
        print('\tCreate FDS and add FC...')
        sr = arcpy.Describe(strPathFC).spatialreference
        if not arcpy.Exists(strPathFDS):
            arcpy.CreateFeatureDataset_management(strGDB, strFDS, sr)

        if not arcpy.Exists(strPathFDS_FC):
            arcpy.CopyFeatures_management(strPathFC, strPathFDS_FC)

        print('\tCreate topology and add rules...')
        arcpy.CreateTopology_management(strPathFDS,
                                        os.path.basename(strPathTopo))

        arcpy.AddFeatureClassToTopology_management(strPathTopo, strPathFDS_FC,
                                                   1)
        arcpy.AddRuleToTopology_management(strPathTopo,
                                           'Must Not Have Gaps (Area)',
                                           strPathFDS_FC)
        arcpy.AddRuleToTopology_management(strPathTopo,
                                           'Must Not Overlap (Area)',
                                           strPathFDS_FC)

    if BoolValidate:
        print('\tValidate...')
        arcpy.ValidateTopology_management(strPathTopo)

    return strPathFDS_FC
コード例 #12
0
def create_topology(workspace, folder_basename):
    """Creates topology in the edit workspace and adds rules to the TFL Lines"""
    arcpy.env.workspace = workspace
    cluster_tol = 0.0001
    topology = workspace + os.sep + 'TFL_Line_Topology'
    feature_class = workspace + os.sep + folder_basename + '_Line'

    try:
        arcpy.CreateTopology_management(workspace, 'TFL_Line_Topology',
                                        cluster_tol)
        arcpy.AddFeatureClassToTopology_management(topology, feature_class)
        #set the rules then add them to the topology
        rules = [
            'Must Not Overlap (Line)', 'Must Not Intersect (Line)',
            'Must Not Have Dangles (Line)', 'Must Not Self-Overlap (Line)',
            'Must Not Self-Intersect (Line)', 'Must Be Single Part (Line)'
        ]
        for rule in rules:
            arcpy.AddRuleToTopology_management(topology, rule, feature_class)
        arcpy.AddMessage('Added topology to TFL Lines')
    except:
        arcpy.AddError('Error adding topology')
コード例 #13
0
 def add_feature2ArcGISTopology(self, topology_folder, topology_name,
                                feature):
     arcpy.AddFeatureClassToTopology_management(
         topology_folder + topology_name, topology_folder + feature, "1",
         "1")
コード例 #14
0
def topologia(capa, folder_salida, ruleTopology):
    global gdb_salida
    try:
        nombre_gdb = "topologia_%s" % (
            datetime.datetime.now().strftime("%b_%d_%Y_%H_%M_%S"))
        nombre_gdb = nombre_gdb.replace(".", "")
        gdb_salida = "%s\\%s.gdb" % (folder_salida, nombre_gdb)
        nombre_dataset = "dt_topologia"

        arcpy.env.workspace = gdb_salida
        nombre_capa = arcpy.Describe(capa).name

        # Process: Create File GDB
        if not arcpy.Exists(gdb_salida):
            arcpy.CreateFileGDB_management(folder_salida, nombre_gdb)

        # Process: Create Feature Dataset
        arcpy.CreateFeatureDataset_management(
            gdb_salida, nombre_dataset,
            "PROJCS['MAGNA_Colombia_Bogota',GEOGCS['GCS_MAGNA',DATUM['D_MAGNA',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',1000000.0],PARAMETER['False_Northing',1000000.0],PARAMETER['Central_Meridian',-74.07750791666666],PARAMETER['Scale_Factor',1.0],PARAMETER['Latitude_Of_Origin',4.596200416666666],UNIT['Meter',1.0]];-4623200 -9510300 10000;-100000 10000;-100000 10000;0,001;0,001;0,001;IsHighPrecision"
        )
        path_dataset = os.path.join(gdb_salida, nombre_dataset)
        ##    correc_topo = "\\%s"%(nombre_dataset)
        # Process: Feature Class to Feature Class

        arcpy.FeatureClassToFeatureClass_conversion(capa, path_dataset,
                                                    nombre_capa)
        path_Feature = os.path.join(path_dataset, nombre_capa)
        ##    FeaClass = "%s\\%s"%(nombre_dataset, nombre_capa)
        # Process: Create Topology
        Capa_topologia = "topo_capa_%s" % (nombre_capa)
        arcpy.CreateTopology_management(path_dataset, Capa_topologia, "")
        path_topology = os.path.join(path_dataset, Capa_topologia)
        ##    Topology = "%s\\topo_capa_%s"%(nombre_dataset, nombre_capa)

        # Process: Add Feature Class To Topology
        arcpy.AddFeatureClassToTopology_management(path_topology, path_Feature,
                                                   "1", "1")

        ###########################################################################################################################

        if ruleTopology == "Huecos y sobreposición":
            contador = 0
            arcpy.AddRuleToTopology_management(path_topology,
                                               "Must Not Overlap (Area)",
                                               path_Feature, "", "", "")

            # Process: Add Rule To Topology (2)
            arcpy.AddRuleToTopology_management(path_topology,
                                               "Must Not Have Gaps (Area)",
                                               path_Feature, "", "", "")

            # Process: Validate Topology
            arcpy.ValidateTopology_management(path_topology, "Full_Extent")

            # Process: Exportar error topology
            arcpy.ExportTopologyErrors_management(path_topology, path_dataset,
                                                  "Errores")

            ErroresTopologia = "#####Validación de topología (Huecos - Sobreposición) ######\n\n"

            for fc in arcpy.ListFeatureClasses(feature_dataset=nombre_dataset):
                path = os.path.join(arcpy.env.workspace, nombre_dataset, fc)

                if "Errores" in arcpy.Describe(path).name:
                    Ctd_contar = arcpy.GetCount_management(path)
                    Ctd = int(Ctd_contar.getOutput(0))

                    if Ctd > 0:

                        if "line" in str(arcpy.Describe(path).name):
                            if Ctd > 1:
                                contador = +1
                                ErroresTopologia = ErroresTopologia + "La capa presenta %s casos de huecos. \n" % (
                                    Ctd)
                        elif "poly" in str(arcpy.Describe(path).name):
                            contador = +1
                            ErroresTopologia = ErroresTopologia + "La capa presenta %s casos de sobreposición. \n" % (
                                Ctd)

                            ####oid de los poligonos con sobreposicion
                            oid_campo = [
                                f.name for f in arcpy.Describe(capa).fields
                                if f.type == "OID"
                            ][0]
                            arreglo = []
                            with arcpy.da.SearchCursor(path, [
                                    "OID@", "OriginObjectID",
                                    "DestinationObjectID"
                            ]) as cursor:
                                for fila in cursor:
                                    arreglo.append(fila[1])
                                    arreglo.append(fila[2])
                            if len(arreglo) > 0:
                                if len(arreglo) == 1:
                                    ErroresTopologia = ErroresTopologia + 'Los siguientes OID presentan sobreposición %s in %s \n' % (
                                        oid_campo,
                                        str(tuple(list(set(arreglo)))).replace(
                                            ",", ""))
                                else:
                                    ErroresTopologia = ErroresTopologia + 'Los siguientes OID presentan sobreposición  %s in %s \n' % (
                                        oid_campo,
                                        str(tuple(list(set(arreglo)))))

                else:
                    pass

            ErroresTopologia = ErroresTopologia + "\n\n Para validar los errores topológicos por favor consulte el siguente dataset %s" % (
                path_dataset)

            ###########################################################################################################################

        elif ruleTopology == "Huecos":
            contador = 0

            # Process: Add Rule To Topology (2)
            arcpy.AddRuleToTopology_management(path_topology,
                                               "Must Not Have Gaps (Area)",
                                               path_Feature, "", "", "")

            # Process: Validate Topology
            arcpy.ValidateTopology_management(path_topology, "Full_Extent")

            # Process: Exportar error topology
            arcpy.ExportTopologyErrors_management(path_topology, path_dataset,
                                                  "Errores")

            ErroresTopologia = "#####Validación de topología (Huecos) ######\n\n"
            for fc in arcpy.ListFeatureClasses(feature_dataset=nombre_dataset):
                path = os.path.join(arcpy.env.workspace, nombre_dataset, fc)

                if "Errores" in arcpy.Describe(path).name:
                    Ctd_contar = arcpy.GetCount_management(path)
                    Ctd = int(Ctd_contar.getOutput(0))
                    if Ctd > 1:

                        if "line" in str(arcpy.Describe(path).name):
                            contador = +1
                            ErroresTopologia = ErroresTopologia + "La capa presenta %s casos de huecos. \n" % (
                                Ctd)
                else:
                    pass

            ErroresTopologia = ErroresTopologia + "\n\n Para validar los errores topológicos por favor consulte el siguente dataset %s" % (
                path_dataset)

        ###########################################################################################################################

        elif ruleTopology == "Sobreposición":
            contador = 0

            # Process: Add Rule To Topology
            arcpy.AddRuleToTopology_management(path_topology,
                                               "Must Not Overlap (Area)",
                                               path_Feature, "", "", "")

            # Process: Validate Topology
            arcpy.ValidateTopology_management(path_topology, "Full_Extent")

            # Process: Exportar error topology
            arcpy.ExportTopologyErrors_management(path_topology, path_dataset,
                                                  "Errores")

            ErroresTopologia = "#####Validación de topología (Sobreposición) ######\n\n"

            for fc in arcpy.ListFeatureClasses(feature_dataset=nombre_dataset):
                path = os.path.join(arcpy.env.workspace, nombre_dataset, fc)

                if "Errores" in arcpy.Describe(path).name:
                    Ctd_contar = arcpy.GetCount_management(path)
                    Ctd = int(Ctd_contar.getOutput(0))
                    if Ctd > 0:

                        if "poly" in str(arcpy.Describe(path).name):
                            contador = +1
                            ErroresTopologia = ErroresTopologia + "La capa presenta %s casos de sobreposición. \n" % (
                                Ctd)

                            ####oid de los poligonos con sobreposicion
                            oid_campo = [
                                f.name for f in arcpy.Describe(capa).fields
                                if f.type == "OID"
                            ][0]
                            arreglo = []
                            with arcpy.da.SearchCursor(path, [
                                    "OID@", "OriginObjectID",
                                    "DestinationObjectID"
                            ]) as cursor:
                                for fila in cursor:
                                    arreglo.append(fila[1])
                                    arreglo.append(fila[2])
                            if len(arreglo) > 0:
                                if len(arreglo) == 1:
                                    ErroresTopologia = ErroresTopologia + 'Los siguientes OID presentan sobreposición %s in %s \n' % (
                                        oid_campo,
                                        str(tuple(list(set(arreglo)))).replace(
                                            ",", ""))
                                else:
                                    ErroresTopologia = ErroresTopologia + 'Los siguientes OID presentan sobreposición  %s in %s \n' % (
                                        oid_campo,
                                        str(tuple(list(set(arreglo)))))

            ErroresTopologia = ErroresTopologia + "\n\n Para validar los errores topológicos por favor consulte el siguente dataset %s" % (
                path_dataset)
    except arcpy.ExecuteError:
        arcpy.AddMessage(arcpy.GetMessages())
        msg = arcpy.GetMessages()
        if msg.find("-2147467259") != -1:
            ErroresTopologia = "#######Evaluación Topología###### \n El Feature de entrada presenta demasiados errores topológicos, \n por lo que ArcGIS no puede crear la topología, se recomienda fraccionar en partes más pequeñas \n  e.x. sí es del territorio nacional, se puede dividir por departamentos, o emplear la herramienta Multitopology \n que se encuentra en U: \SCRIPTS_ANALISIS"
            contador = 1
    except:

        # By default any other errors will be caught here
        e = sys.exc_info()[1]
        msg = e.args[0]
        ErroresTopologia = "#######Evaluación Topología###### \n Se encontró el siguiente error %s" % (
            msg)
        contador = 1

    if contador > 0:
        return ErroresTopologia + "\n"
    elif contador == 0:
        return None
コード例 #15
0
try:
    for i in dicMes:
        if mes == i:
            valor = dicMes[i]
            path_dataset = resultados + valor
            path_mapa = resultados + valor + "\\topo_" + str(date)
            path_topo = path_dataset + "\\topology_" + str(date)
            arcpy.AddMessage("Proceso en ejecución")

            if arcpy.Exists(valor):
                arcpy.env.overwriteOutput = True
                arcpy.CopyFeatures_management(ingresados, path_mapa)
                arcpy.CreateTopology_management(path_dataset,
                                                "topology_" + str(date))
                arcpy.AddFeatureClassToTopology_management(
                    path_topo, path_mapa)
                arcpy.AddRuleToTopology_management(
                    path_topo, "Must Not Have Gaps (Area)", path_mapa)
                arcpy.AddRuleToTopology_management(path_topo,
                                                   "Must Not Overlap (Area)",
                                                   path_mapa)
                arcpy.ValidateTopology_management(path_topo, "Full_Extent")
                arcpy.ExportTopologyErrors_management(path_topo, path_dataset,
                                                      "topo" + str(date))

            else:
                arcpy.CreateFeatureDataset_management(resultados, valor, prj)
                arcpy.CopyFeatures_management(ingresados, path_mapa)
                arcpy.CreateTopology_management(path_dataset,
                                                "topology_" + str(date))
                arcpy.AddFeatureClassToTopology_management(
コード例 #16
0
#set local variables
road_input = "E:\ArcGIS_Data\South_Sudan\ConTrack_Code.gdb\SSD_Network\Road_Network"
topo_input = "E:\ArcGIS_Data\South_Sudan\ConTrack_Code.gdb\SSD_Network\SSD_Network_Topology"
network_dataset = "E:\ArcGIS_Data\South_Sudan\ConTrack_Code.gdb\SSD_Network\ConTrack_Network"

#delete old road network if it exists from a prior network and the assocaited feature class
if arcpy.Exists(network_dataset):
    arcpy.Delete_management(network_dataset)
if arcpy.Exists(topo_input):
    arcpy.Delete_management(topo_input)
if arcpy.Exists(road_input):
    arcpy.Delete_management(road_input)

#add roads to network feature dataset
arcpy.FeatureClassToFeatureClass_conversion("Selection_Lyr", "SSD_Network",
                                            "Road_Network")

#create network topology to get rid of dangles and redundant line extensions, then validate network
#create topology and add rule
arcpy.CreateTopology_management("SSD_Network", "SSD_Network_Topology")
arcpy.AddFeatureClassToTopology_management(topo_input, road_input, 1)
arcpy.AddRuleToTopology_management(topo_input, "Must Not Have Dangles (Line)",
                                   road_input)

#validate topology
arcpy.ValidateTopology_management(topo_input)

#notify user tool has executed
print "Preprocessing Finished and Network Dataset Input Updated. Please create and build a new network in ArcMap now, unfortunately this process cannot be automated."
コード例 #17
0
def main():
    logFileName = "T:/srcToWrk.log"
    logFile = file(logFileName, "w")
    managementUnitGDB = "PUT_PATH_HERE\\yourGdbName.gdb"
    year = "2020"
    inDict = "PUT_DICTIONARY_PATH_HERE\\dataDictionary_AR2020.xlsx"
    tab = "vri2wrk"
    tsas = ["ALL_BC"]

    arcpy.env.overwriteOutput = True

    worksheet = openExcel(inDict, tab)
    print str(worksheet.nrows)
    nRows = worksheet.nrows

    for tsa in tsas:
        rootTSAgdbSrc = managementUnitGDB + "\\src"
        rootTSAgdbWrk = managementUnitGDB + "\\wrk"
        tsa_number = string.replace(tsa, "tsa", "")

        managementUnitGDBtemp = "T:\\temp_ard_gdb_src_to_wrk.gdb"
        managementUnitGDBtempSrc = managementUnitGDBtemp + "\\src"
        managementUnitGDBtempWrk = managementUnitGDBtemp + "\\wrk"
        arcpy.Copy_management(managementUnitGDB, managementUnitGDBtemp)
        fieldMapping = ''
        row = 1
        for line in range(nRows - 1):
            fieldMapCompl = False
            col = 1
            # next row
            srcFeatureClass = worksheet.cell_value(row, col)
            col = col + 1
            print srcFeatureClass
            srcFieldName = worksheet.cell_value(row, col)
            col = col + 1
            print srcFieldName
            wrkFeatureClass = worksheet.cell_value(row, col)
            col = col + 1
            print wrkFeatureClass
            wrkFieldName = worksheet.cell_value(row, col)
            col = col + 1
            print wrkFieldName
            wrkShortName = worksheet.cell_value(row, col)
            col = col + 1
            print wrkShortName
            IsNullable = bool(worksheet.cell_value(row, col))
            col = col + 1
            print IsNullable
            Required = bool(worksheet.cell_value(row, col))
            col = col + 1
            print Required
            Editable = bool(worksheet.cell_value(row, col))
            col = col + 1
            print Editable
            Length = worksheet.cell_value(row, col)
            col = col + 1
            print Length
            Type = worksheet.cell_value(row, col)
            col = col + 1
            print Type
            Precision = worksheet.cell_value(row, col)
            col = col + 1
            print Precision
            Scale = worksheet.cell_value(row, col)
            print Scale
            fieldMapping = setfieldMapping(fieldMapping,
                                           managementUnitGDBtempSrc,
                                           srcFeatureClass, wrkShortName,
                                           IsNullable, Required, Editable,
                                           Length, Type, Precision, Scale,
                                           srcFieldName)
            if row + 1 < nRows:
                print "row number" + str(
                    row + 1) + "  vs  total row number " + str(nRows)
                if worksheet.cell_value(row + 1, 1) != srcFeatureClass:
                    fieldMapCompl = True
            elif row + 1 == nRows:
                fieldMapCompl = True
            if fieldMapCompl:
                inFC = managementUnitGDBtempSrc + "\\" + srcFeatureClass
                tempFC = managementUnitGDBtempWrk + "\\tempFC"
                tempFCname = "tempFC"
                wrkOutName = managementUnitGDBtempWrk + "\\" + wrkFeatureClass
                fid = wrkFeatureClass + "_fid"
                topoName = "wrk_%s_topology" % (wrkFeatureClass)
                fullTopoName = managementUnitGDBtempWrk + "\\" + topoName

                if arcpy.Exists(wrkOutName):
                    arcpy.Delete_management(fullTopoName)
                    arcpy.Delete_management(wrkOutName)

                print "creating temporary feature class with field mapping "
                try:
                    arcpy.FeatureClassToFeatureClass_conversion(
                        inFC, managementUnitGDBtempWrk, tempFCname, "",
                        fieldMapping)
                except:
                    print " FAILED creating temporary feature class with field mapping"
                    logging.warning(
                        srcFeatureClass + " " + tsa_number +
                        " failed to create temporary dataset with field mapping"
                    )

                print "Converting multipart to single part (%s)..." % (tempFC)
                try:
                    arcpy.MultipartToSinglepart_management(tempFC, wrkOutName)

                except:
                    print srcFeatureClass + " " + tsa_number + " FAILED mulitpart to single part"
                    logging.error(srcFeatureClass + " " + tsa_number +
                                  " FAILED mulitpart to single part")
                    e = sys.exc_info()[1]
                    print(e.args[0])

                try:
                    arcpy.AddMessage("Adding %s..." % (fid))
                    arcpy.AddField_management(wrkOutName, fid, "LONG")
                    arcpy.CalculateField_management(wrkOutName, fid,
                                                    "!OBJECTID!", "PYTHON_9.3")
                except:
                    print srcFeatureClass + " " + tsa_number + " FAILED to add fid"
                    logging.warning(srcFeatureClass + " " + tsa_number +
                                    " FAILED to add fid")

                print "Creating %s..." % (topoName)
                try:
                    ##                arcpy.env.workspace = managementUnitGDBtempWrk
                    arcpy.CreateTopology_management(managementUnitGDBtempWrk,
                                                    topoName)
                    arcpy.AddFeatureClassToTopology_management(
                        fullTopoName, wrkOutName)
                    arcpy.AddRuleToTopology_management(
                        fullTopoName, "Must Not Overlap (Area)", wrkOutName)
                    arcpy.ValidateTopology_management(fullTopoName)
                except:
                    print srcFeatureClass + " " + tsa_number + " FAILED topology"
                    logging.warning(srcFeatureClass + " " + tsa_number +
                                    " FAILED topology")

                print "Deleting Temp FC"
                arcpy.Delete_management(tempFC)
                print "Elapsed time: %d seconds" % (time.clock())
                row = row + 1
                print fieldMapping
                fieldMapping = ''
                gc.collect()
            else:
                row = row + 1


##            if row == 12:
##                break
        try:
            arcpy.Copy_management(managementUnitGDBtemp, managementUnitGDB)
        except:
            print tsa_number + " FAILED Copy from T:\ drive to Archive drive"
            logging.error(tsa_number +
                          " FAILED Copy from T:\ drive to Archive drive")
            e = sys.exc_info()[1]
            print(e.args[0])
            sys.exit()
        gc.collect()

    print "all done"
コード例 #18
0
    out_name = str(ifcf[:-4]) + "_ToPo"    #导入后shp的名称
    #print u"导入后shp的名称:" + str(out_name)
    arcpy.FeatureClassToFeatureClass_conversion (in_features, out_path, out_name)


    # Process: Create Topology
    Topo_name = str(ifcf[:-4]) + "_ToPology" #拓扑结构的名称
    #print u"拓扑结构的名称:" + str(Topo_name)
    arcpy.CreateTopology_management(out_path, Topo_name, "")   #zhiduo_tp  拓扑结构

    # Process: Add Feature Class To Topology
    Topology = os.path.join(out_path,Topo_name)  # 拓扑结构的路径
    ##print u"拓扑结构的路径:" + str(Topology)
    ToPoShp = os.path.join(out_path,out_name)    # 要做拓扑的数据集里的shp
    ##print u"要做拓扑的数据集里的shp:" + str(ToPoShp)
    arcpy.AddFeatureClassToTopology_management(Topology, ToPoShp, "1", "1")

    # Process: Add Rule To Topology
    arcpy.AddRuleToTopology_management(Topology, "Must Not Have Gaps (Area)", ToPoShp, "", "", "")
    #print u"正在添加 Must Not Have Gaps 规则"
    arcpy.AddRuleToTopology_management(Topology, "Must Not Overlap (Area)", ToPoShp, "", "", "")
    #print u"正在添加 Must Not Overlap 规则"

    # Process: Validate Topology
    try:
        arcpy.ValidateTopology_management(Topology, "true")
    except:
        print str(ifcf) + "的拓扑未成功验证,请人工重新建立拓扑。"

    print "拓扑验证完成" + '\n'
    
コード例 #19
0
#Feature Class to Feature Class ~ SF Points
#arcpy.FeatureClassToFeatureClass_conversion(insfpt, fdname, prjname+'p')
arcpy.FeatureClassToFeatureClass_conversion(insfpt, fdname, p)
#Feature Class to Feature Class ~ SF Lines
#arcpy.FeatureClassToFeatureClass_conversion(insfln, fdname, prjname+"l")
arcpy.FeatureClassToFeatureClass_conversion(insfln, fdname, l)
#Feature Class to Feature Class ~ Boundary Line
#arcpy.FeatureClassToFeatureClass_conversion(inbndy, fdname, prjname+'b')
arcpy.FeatureClassToFeatureClass_conversion(inbndy, fdname, b)

#Create Topology
arcpy.CreateTopology_management(fdname, prjname + 'topology', ".1")

#Add Feature Class To Topology ~ Soils
#arcpy.AddFeatureClassToTopology_management(inprname_topology, fdname+'\\'+prjname+'a')
arcpy.AddFeatureClassToTopology_management(inprname_topology,
                                           fdname + '\\' + a)
#Add Topology Rule ~ Must Not Have Gaps (Poly)
#arcpy.AddRuleToTopology_management (inprname_topology, "Must Not Have Gaps (Area)", fdname+'\\'+prjname+'a')
arcpy.AddRuleToTopology_management(inprname_topology,
                                   "Must Not Have Gaps (Area)",
                                   fdname + '\\' + a)
#Add Topology Rule ~ Must Not Overlap (Poly)
#arcpy.AddRuleToTopology_management (inprname_topology, "Must Not Overlap (Area)", fdname+'\\'+prjname+'a')
arcpy.AddRuleToTopology_management(inprname_topology,
                                   "Must Not Overlap (Area)",
                                   fdname + '\\' + a)
#Add Feature Class To Topology ~ SF Points
#arcpy.AddFeatureClassToTopology_management(inprname_topology, fdname+'\\'+prjname+'p')
arcpy.AddFeatureClassToTopology_management(inprname_topology,
                                           fdname + '\\' + p)
#Add Feature Class To Topology ~ SF Lines
コード例 #20
0
def validateCafTopology(inFds, outFds, outHtml):
    inCaf = getCaf(inFds)
    caf = os.path.basename(inCaf)
    nameToken = caf.replace('ContactsAndFaults', '')
    outCaf = outFds + '/' + caf
    inMup = inFds + '/' + nameToken + 'MapUnitPolys'
    outMup = outFds + '/' + nameToken + 'MapUnitPolys'
    inGel = inFds + '/' + nameToken + 'GeologicLines'
    outGel = outFds + '/' + nameToken + 'GeologicLines'

    # First delete any existing topology
    ourTop = os.path.basename(outFds) + '_topology'
    testAndDelete(outFds + '/' + ourTop)
    # copy CAF to _errors.gdb
    testAndDelete(outCaf)
    arcpy.Copy_management(inCaf, outCaf)
    # copy MUP to _errors.gdb
    testAndDelete(outMup)
    if arcpy.Exists(inMup):
        arcpy.Copy_management(inMup, outMup)
    # copy GeL to _errors.gdb
    testAndDelete(outGel)
    if arcpy.Exists(inGel):
        arcpy.Copy_management(inGel, outGel)

    # create topology
    addMsgAndPrint('  creating topology ' + ourTop)
    arcpy.CreateTopology_management(outFds, ourTop)
    ourTop = outFds + '/' + ourTop
    # add feature classes to topology
    arcpy.AddFeatureClassToTopology_management(ourTop, outCaf, 1, 1)
    if arcpy.Exists(outMup):
        arcpy.AddFeatureClassToTopology_management(ourTop, outMup, 2, 2)
    if arcpy.Exists(outGel):
        arcpy.AddFeatureClassToTopology_management(ourTop, outGel, 3, 3)
    # add rules to topology
    addMsgAndPrint('  adding rules to topology:')
    for aRule in ('Must Not Overlap (Line)', 'Must Not Self-Overlap (Line)',
                  'Must Not Self-Intersect (Line)',
                  'Must Be Single Part (Line)'):
        addMsgAndPrint('    ' + aRule)
        arcpy.AddRuleToTopology_management(ourTop, aRule, outCaf)
    if arcpy.Exists(outMup):
        for aRule in ('Must Not Overlap (Area)', 'Must Not Have Gaps (Area)'):
            addMsgAndPrint('    ' + aRule)
            arcpy.AddRuleToTopology_management(ourTop, aRule, outMup)
        addMsgAndPrint('    ' + 'Boundary Must Be Covered By (Area-Line)')
        arcpy.AddRuleToTopology_management(
            ourTop, 'Boundary Must Be Covered By (Area-Line)', outMup, '',
            outCaf)
    if arcpy.Exists(outGel):
        for aRule in ('Must Be Single Part (Line)',
                      'Must Not Self-Overlap (Line)',
                      'Must Not Self-Intersect (Line)'):
            addMsgAndPrint('    ' + aRule)
            arcpy.AddRuleToTopology_management(ourTop, aRule, outGel)

    # validate topology
    addMsgAndPrint('  validating topology')
    arcpy.ValidateTopology_management(ourTop)
    if nameToken == '':
        nameToken = 'GeologicMap'
    nameToken = 'errors_' + nameToken + 'Topology'
    for sfx in ('_point', '_line', '_poly'):
        testAndDelete(outFds + '/' + nameToken + sfx)
    # export topology errors
    addMsgAndPrint('  exporting topology errors')
    arcpy.ExportTopologyErrors_management(ourTop, outFds, nameToken)
    outHtml.write('<h3>Line and polygon topology</h3>\n')
    outHtml.write(
        '<blockquote><i>Note that the map boundary commonly results in a "Must Not Have Gaps" error</i></blockquote>'
    )
    for sfx in ('_point', '_line', '_poly'):
        fc = outFds + '/' + nameToken + sfx
        outHtml.write('&nbsp; ' + nameToken + sfx + '<br>\n')
        html_writeFreqTable(outHtml, fc, ['RuleDescription', 'RuleType'])
        addMsgAndPrint('    ' + str(numberOfRows(fc)) + ' rows in ' +
                       os.path.basename(fc))
        if numberOfRows(fc) == 0: testAndDelete(fc)
コード例 #21
0
ファイル: MapMergerSimp.py プロジェクト: rcrow/MapMerger
if renameAsMaster:
    arcpy.AddMessage("Overwriting the Master GDB")
    masterGDB = r"\\igswzcwwgsrio\mojo\Team\Crow\PiuteValleyGeologicMaps\MergedMaps\CR_PIUTE_MASTER.gdb"
    checkAndDeleteOS(masterGDB)
    print(exportGDBFullPath)
    shutil.copytree(exportGDBFullPath, masterGDB)
    #arcpy.Copy_management(exportGDBFullPath,masterGDB)

if buildTopology:
    topology = arcpy.CreateTopology_management(exportMergedFDSFullPath,
                                               "Topology",
                                               in_cluster_tolerance="")
    arcpy.AddFeatureClassToTopology_management(topology,
                                               exportMergedFDSFullPath + "\\" +
                                               "MapUnitPolys",
                                               xy_rank="1",
                                               z_rank="1")
    arcpy.AddFeatureClassToTopology_management(topology,
                                               exportMergedFDSFullPath + "\\" +
                                               "ContactsAndFaults",
                                               xy_rank="1",
                                               z_rank="1")
    arcpy.AddRuleToTopology_management(
        topology,
        rule_type="Must Not Have Gaps (Area)",
        in_featureclass=exportMergedFDSFullPath + "\\" + "MapUnitPolys",
        subtype="",
        in_featureclass2="#",
        subtype2="")
    arcpy.AddRuleToTopology_management(
コード例 #22
0
ファイル: topo.py プロジェクト: baranbeata/TopologyTool
def topo():
    try:

        #inicjowanie niezbednych petli
        liii = []
        lii = []
        li = []

        licznik = 0

        #przejecie parametrow od uzytkownika
        folder = arcpy.GetParameterAsText(0)
        nazwa_geo = arcpy.GetParameterAsText(1)
        nazwa_zestaw = arcpy.GetParameterAsText(2)
        shape = arcpy.GetParameterAsText(3)

        #rozdzielenie multiwartosci
        war0 = shape.split(";")

        #utworzenie listy list zawierajacych nazwe warswy, jej zrodlo i odniesienie przestrzenne
        for i in war0:

            desc = arcpy.Describe(i)

            zrodlo = str(desc.path + "\\" + desc.name)

            desc2 = arcpy.Describe(zrodlo)

            lii.append(str(i))
            lii.append(str(zrodlo))
            lii.append(str(desc2.spatialReference.name))
            liii.append(lii)
            lii = []

            licznik += 1

        #*********************************
        #udalo mi sie utworzyc liste list:
        arcpy.AddWarning(liii)

        #ale pozniej program juz nie chcial ze mna wspolpracowac:

        #arcpy.CreateFileGDB_management(folder, nazwa_geo)

        #licz = 0

        #for p in liii:
        #arcpy.CreateFeatureDataset_management(folder+"/"+nazwa_geo+".gdb", nazwa_zestaw+str(licz), liii[licz][2] )
        #licz += 1

        #i na razie tego nie mam
        #*********************************

        #***** wersja wrzucajaca wszystko do jednego zestawu danych *****

        war = str(shape).split(";")

        #utworzenie listy zawirajacej wprowadzone przez uzytkownika warstwy, dla ktorych ma zostac stworzona topologia
        for i in war:
            li.append(i)

        #stworzenie geobazy
        arcpy.CreateFileGDB_management(folder, nazwa_geo)
        #stworzenie zestawu danych
        arcpy.CreateFeatureDataset_management(
            folder + "/" + nazwa_geo + ".gdb", nazwa_zestaw)

        #iterator dla petli
        k = 0

        for j in li:
            #przeniesienie klasy obiektów do zestawu w geobazie
            arcpy.FeatureClassToFeatureClass_conversion(
                folder + "/" + li[k] + ".shp",
                folder + "/" + nazwa_geo + ".gdb" + "/" + nazwa_zestaw,
                "shapenowy" + str(k))
            #stworzenie pustej topologii
            arcpy.CreateTopology_management(
                folder + "/" + nazwa_geo + ".gdb" + "/" + nazwa_zestaw,
                "Topology" + str(k))
            #dodanie klasy obiektów do topologii
            arcpy.AddFeatureClassToTopology_management(
                folder + "/" + nazwa_geo + ".gdb" + "/" + nazwa_zestaw +
                "/Topology" + str(k), folder + "/" + nazwa_geo + ".gdb" + "/" +
                nazwa_zestaw + "/shapenowy" + str(k))
            #dodanie regul do topologii
            arcpy.AddRuleToTopology_management(
                folder + "/" + nazwa_geo + ".gdb" + "/" + nazwa_zestaw +
                "/Topology" + str(k), "Must Not Intersect (Line)",
                folder + "/" + nazwa_geo + ".gdb" + "/" + nazwa_zestaw +
                "/shapenowy" + str(k))
            arcpy.AddRuleToTopology_management(
                folder + "/" + nazwa_geo + ".gdb" + "/" + nazwa_zestaw +
                "/Topology" + str(k), "Must Not Overlap (Line)",
                folder + "/" + nazwa_geo + ".gdb" + "/" + nazwa_zestaw +
                "/shapenowy" + str(k))
            arcpy.AddRuleToTopology_management(
                folder + "/" + nazwa_geo + ".gdb" + "/" + nazwa_zestaw +
                "/Topology" + str(k), "Must Not Have Pseudo-Nodes (Line)",
                folder + "/" + nazwa_geo + ".gdb" + "/" + nazwa_zestaw +
                "/shapenowy" + str(k))
            arcpy.AddRuleToTopology_management(
                folder + "/" + nazwa_geo + ".gdb" + "/" + nazwa_zestaw +
                "/Topology" + str(k), "Must Not Have Dangles (Line)",
                folder + "/" + nazwa_geo + ".gdb" + "/" + nazwa_zestaw +
                "/shapenowy" + str(k))
            arcpy.ValidateTopology_management(folder + "/" + nazwa_geo +
                                              ".gdb" + "/" + nazwa_zestaw +
                                              "/Topology" + str(k))
            #inkrementacja iteratora
            k += 1

    except Exception, err:
        arcpy.AddError("Apka nie dziala :(")
        arcpy.AddError(sys.exc_traceback.tb_lineno)
        arcpy.AddError(err.message)
コード例 #23
0
def make_workspace_copy(inputfeatures, theworkspace, dotopologycheck,
                        dosimplify, dosimplify_method, dosimplify_tolerance,
                        thefield):
    """This function tests the input features for the topology error 'Must Be Single Part',
    and returns the Origin Feature's Object ID of the errant features to the calling module. Beware:
    the origing feature's object ID is that of the COPY of the input features. The object ID's of the copy
    may be different from the source "inputfeautures"!!!!. This is why the function passes back the name of the COPY so that the processing can
    continue on that feature class where the topologically errant features will be correctly identified
    by the values in the export topology errors geoprocessing tool."""

    ##    arcpy.AddMessage("funcs.make_workspace_copy")

    #Process the
    #roads with the simplify_line tool with the point_remove option at a tolerance of 0.001 meters so that redundant vertices on staight lines are removed.
    #If the user specifies their own parameters for simplify_line, THAT ARE NOT POINT_REMOVE AND THE TOLERANCE IS > 0.001 METERS, that is done additionally,
    #afterwards:

    #this section makes the feature class datasets, feature class names, and topology name:
    badfids = set()
    fdname = "KDOT_Topology_Check"  #the feature dataset name for the topology check
    fdnamepath = theworkspace + "\\" + fdname  #the complete pathname of the feature dataset
    tpname = "CheckTopology"  #the name of the topology
    topology_name = fdnamepath + "\\" + tpname  #the complete pathname of the topology
    ##    arcpy.AddMessage("make_workspace_copy, fdnamepath: "+fdnamepath)
    ##    arcpy.AddMessage("make_workspace_copy, topology_name: "+topology_name)
    fcname = arcpy.ParseTableName(
        inputfeatures,
        theworkspace)  #Split the inputfeatures to find the name from the path.
    namelist = fcname.split(
        ", "
    )  #the feature class name without the path. Used in creating a copy in the feature dataset.
    ##    arcpy.AddMessage('fcname = '+ namelist[2])
    topology_featureclass = fdnamepath + '\\' + namelist[
        2] + '_check'  #the copy of inputfeatures used for the topology check
    topology_featureclass_errors = namelist[
        2] + '_errors'  # the basename used for the export topology errors tool
    ##    arcpy.AddMessage(topology_featureclass)
    topology_featureclass_errors_line = fdnamepath + '\\' + namelist[
        2] + '_errors_line'  #the output name of LINE errors from the export topology errors tool

    #Delete if the feature dataset currently exists:
    doesexistfd = arcpy.Exists(fdnamepath)
    try:
        if doesexistfd:
            arcpy.AddMessage(
                'Previous topology check feature dataset exists. Now deleteing '
            )
            arcpy.Delete_management(fdnamepath)
    except arcpy.ExecuteError:
        print arcpy.GetMessages(2)
    except Exception as e:
        print e.args[0]

    #Re-create the topology feature dataset:
    arcpy.AddMessage('Generating the topology check scratch feature dataset')
    arcpy.CreateFeatureDataset_management(theworkspace, fdname, inputfeatures)

    #Make a copy of the input roads in the feature dataset that contains the topology:
    try:
        arcpy.AddMessage(
            'Generating a copy of the input feature class in the scratch feature dataset'
        )
        #This replaces the function "arcpy.CopyFeatures_management" so that we can retain the original FID:
        ##        make_copies_of_features(inputfeatures,  topology_featureclass, "Original_OID")
        make_copies_of_features(inputfeatures, topology_featureclass, thefield)
##        arcpy.CopyFeatures_management(inputfeatures, topology_featureclass)
    except arcpy.ExecuteError:
        print arcpy.GetMessages(2)
    except Exception as e:
        print e.args[0]

    #Perform the topology check, if checked ON in input parameters:
##    arcpy.AddMessage('make_workspace_copy, dotopology = ' + str(dotopologycheck))
##    if(dotopologycheck == True):
    if (str(dotopologycheck) == 'true'):
        arcpy.AddMessage('Creating the topology')
        arcpy.CreateTopology_management(fdnamepath, tpname)

        #Add the input roads to the topology
        arcpy.AddMessage(
            'Adding the copy of the input features to the topology')
        arcpy.AddFeatureClassToTopology_management(topology_name,
                                                   topology_featureclass, 1, 1)
        #Add a rule:
        arcpy.AddMessage('Adding rule "Must Be Single Part" to the topology')
        arcpy.AddRuleToTopology_management(topology_name,
                                           "Must Be Single Part (Line)",
                                           topology_featureclass)
        #Validate the topology:
        arcpy.AddMessage('Validating the topology')
        arcpy.ValidateTopology_management(topology_name)
        #Export the errant features to a feature class
        arcpy.AddMessage(
            'Exporting the topologically-errant feature to feature class ' +
            topology_featureclass_errors)
        arcpy.ExportTopologyErrors_management(topology_name, fdnamepath,
                                              topology_featureclass_errors)
        arcpy.AddMessage("Completed exporting topology errors")

        #Extract the values from field "OriginObjectID". This is a field generated to identify the OID's of errant features:
        ##        arcpy.AddMessage('Retrieving the object ID''s of the errant features')
        with arcpy.da.SearchCursor(topology_featureclass_errors_line,
                                   ["OriginObjectID"]) as cursor:
            for row in cursor:
                ##                arcpy.AddMessage(str(row[0]))
                badfids.add(row[0])

    #Perform at the least, the default line simplification of 0.001 meters or 0.00328084 feet
    #SimplifyLine(mergedFeatures, simplifiedFeatures, dosimplify_method, dosimplify_tolerance, "RESOLVE_ERRORS", "KEEP_COLLAPSED_POINTS", "CHECK")
    simplified_featureclass = fdnamepath + '\\_simplified_roads'
    arcpy.SimplifyLine_cartography(topology_featureclass,
                                   simplified_featureclass, dosimplify_method,
                                   dosimplify_tolerance, False, False, False)

    arcpy.AddMessage('completed creating a workspace copy....')
    ##    arcpy.AddMessage('completed funcs.make_workspace_copy')
    return badfids, simplified_featureclass
コード例 #24
0
arcpy.SelectLayerByLocation_management (insfln, "WITHIN_A_DISTANCE", inbndy, indist,"ADD_TO_SELECTION")

#Feature Class to Feature Class ~ Soils
arcpy.FeatureClassToFeatureClass_conversion(inFC, fdname, prjname+'a')

#Feature Class to Feature Class ~ SF Points
arcpy.FeatureClassToFeatureClass_conversion(insfpt, fdname, prjname+'p')
#Feature Class to Feature Class ~ SF Lines
arcpy.FeatureClassToFeatureClass_conversion(insfln, fdname, prjname+"l")
#Feature Class to Feature Class ~ Boundary Line
arcpy.FeatureClassToFeatureClass_conversion(inbndy, fdname, prjname+"b")
#Create Topology
arcpy.CreateTopology_management(fdname,  prjname+'topology',".01")

#Add Feature Class To Topology ~ Soils
arcpy.AddFeatureClassToTopology_management(inprname_topology, fdname+'\\'+prjname+'a')
#Add Topology Rule ~ Must Not Have Gaps (Poly)
arcpy.AddRuleToTopology_management (inprname_topology, "Must Not Have Gaps (Area)", fdname+'\\'+prjname+'a')
#Add Topology Rule ~ Must Not Overlap (Poly)
arcpy.AddRuleToTopology_management (inprname_topology, "Must Not Overlap (Area)", fdname+'\\'+prjname+'a')
#Add Feature Class To Topology ~ SF Points
arcpy.AddFeatureClassToTopology_management(inprname_topology, fdname+'\\'+prjname+'p')
#Add Feature Class To Topology ~ SF Lines
arcpy.AddFeatureClassToTopology_management(inprname_topology, fdname+'\\'+prjname+"l")

#Add Topology Rule ~ Must Not Overlap (Line)
arcpy.AddRuleToTopology_management (inprname_topology, "Must Not Overlap (Line)", fdname+'\\'+prjname+"l")
#Add Topology Rule ~ Must Be Single Part (Line)
arcpy.AddRuleToTopology_management (inprname_topology, "Must Be Single Part (Line)", fdname+'\\'+prjname+"l")
#Add Topology Rule ~ Must Not Self-Overlap (Line)
arcpy.AddRuleToTopology_management (inprname_topology, "Must Not Self-Overlap (Line)", fdname+'\\'+prjname+"l")
コード例 #25
0
def topology_repair(
    inFile=path_to_shapefile, 
    dissolve_field="", 
    gap_threshold=10000):    # threshold is max area of gaps that are considered to be errors

    # create variables for necessary paths, create gdb, import inFile into feature dataset
    gdb = os.path.basename(inFile[:-3] + 'gdb')
    gdbDir= os.path.dirname(inFile)
    arcpy.CreateFileGDB_management(gdbDir, gdb)
    arcpy.env.workspace = gdbDir + '/' + gdb
    feature_ds = arcpy.env.workspace + '/topology_ds'
    data = arcpy.env.workspace + '/topology_ds/' + os.path.basename(inFile[:-4])
    topology = feature_ds + '/Topology'
    arcpy.CreateFeatureDataset_management(arcpy.env.workspace, "topology_ds", inFile[:-3] + 'prj')
    arcpy.FeatureClassToGeodatabase_conversion([inFile], "topology_ds")

    # Create topology, add feature class, define rules
    arcpy.CreateTopology_management(feature_ds, "Topology")
    arcpy.AddFeatureClassToTopology_management(topology, data)
    arcpy.AddRuleToTopology_management(topology, "Must Not Overlap (Area)",data,"","","")
    arcpy.ValidateTopology_management(topology)

    # create polygon inFile from errors and delete
    arcpy.ExportTopologyErrors_management(topology, "", "overlapErrors")
    arcpy.AddField_management("overlapErrors_poly", dissolve_field, "STRING")
    o = "o"
    arcpy.CalculateField_management('overlapErrors_poly', dissolve_field,o)

    # Create topology, add feature class, define rules
    arcpy.CreateTopology_management(feature_ds, "Topology")
    arcpy.AddFeatureClassToTopology_management(topology, data)
    arcpy.AddRuleToTopology_management(topology, "Must Not Have Gaps (Area)",data,"","","")
    arcpy.ValidateTopology_management(topology)

    # create polygon inFile from errors and merge with original data
    arcpy.ExportTopologyErrors_management(topology, "", "gapErrors")
    arcpy.FeatureToPolygon_management("gapErrors_line","topo_errors_gaps")
    arcpy.SelectLayerByAttribute_management ("topo_errors_gaps", "NEW_SELECTION", '"Shape_Area" < ' + str(gap_threshold))
    arcpy.AddField_management("topo_errors_gaps", dissolve_field, "STRING")
    g = "g"
    arcpy.CalculateField_management('topo_errors_gaps', dissolve_field,g )
    arcpy.SelectLayerByAttribute_management ("topo_errors_gaps", "SWITCH_SELECTION")
    arcpy.DeleteRows_management("topo_errors_gaps")
    arcpy.Merge_management(["overlapErrors_poly", "topo_errors_gaps" ,inFile],"topomerged")

    # Get neighbor table and export to gdb
    arcpy.PolygonNeighbors_analysis('topomerged', 'topo_errors',['OBJECTID', dissolve_field])  # doesn't always find neighbors on all sides of polygon
    arcpy.TableToGeodatabase_conversion('topo_errors',arcpy.env.workspace)

    #table to array and array to dataframe
    nbr_field = 'nbr_' + dissolve_field
    arr = arcpy.da.FeatureClassToNumPyArray(("topo_errors"), ("src_OBJECTID", nbr_field, "LENGTH"))
    index = [str(i) for i in range(1, len(arr)+1)]
    df = pd.DataFrame(arr, index=index)
    df = df.groupby(['src_OBJECTID','nbr_TYPE'],as_index = False)['LENGTH'].sum()   #sum in case several sides of polygon have same neighbor

    #select rows from df and export to csv and to gdb
    idx = df.groupby(['src_OBJECTID'])['LENGTH'].transform(max) == df['LENGTH']
    df_select = df [idx]
    df_select.to_csv(gdbDir+'/joinme.csv', index=False)
    arcpy.TableToTable_conversion(gdbDir+'/joinme.csv', arcpy.env.workspace, "joinme")

    # Merge error polygons, join field, delete overlaps from infile, assign type to error polygons, merge all and dissolve
    arcpy.JoinField_management('topomerged', 'OBJECTID', 'joinme', 'src_OBJECTID', 'nbr_TYPE')
    arcpy.FeatureClassToFeatureClass_conversion('topomerged', "", 'topo_errors_join')
    arcpy.SelectLayerByAttribute_management("topo_errors_join", "NEW_SELECTION", "TYPE = 'o'")
    arcpy.SelectLayerByAttribute_management("topo_errors_join", "ADD_TO_SELECTION", "TYPE = 'g'")
    arcpy.SelectLayerByAttribute_management ("topo_errors_join", "SWITCH_SELECTION")
    arcpy.DeleteRows_management("topo_errors_join")   #leave only error polygons
    arcpy.AlterField_management('topo_errors_join', 'TYPE', 'orig_TYPE','orig_TYPE')
    arcpy.AlterField_management('topo_errors_join', 'nbr_TYPE', 'TYPE','TYPE')
    arcpy.Erase_analysis(inFile,'overlapErrors_poly','infile_overlaps_erased')
    arcpy.Merge_management(["topo_errors_join","infile_overlaps_erased"],"merged_neighbors")
    arcpy.Dissolve_management('merged_neighbors', 'dissolved_neighbors', 'TYPE')