def findBraidedReaches(fcLines, perennial_network, is_verbose):
    if is_verbose:
        arcpy.AddMessage("Finding streams with mutltiple channels...")
    # Clear temporary data
    if arcpy.Exists("in_memory//DonutPolygons"):
        arcpy.Delete_management("in_memory//DonutPolygons")
    if arcpy.Exists("lyrDonuts"):
        arcpy.Delete_management("lyrDonuts")
    if arcpy.Exists("lyrBraidedReaches"):
        arcpy.Delete_management("lyrBraidedReaches")

    # Find donut reaches
    donut_polygons = "in_memory/DonutPolygons"
    if perennial_network is not None:
        arcpy.FeatureToPolygon_management(perennial_network, donut_polygons)
    else:
        arcpy.FeatureToPolygon_management(fcLines, donut_polygons)

    # delete extremely large donuts (< 0.5 sq km) since these are false positives for finding side channels
    with arcpy.da.UpdateCursor(donut_polygons, ['SHAPE@AREA']) as cursor:
        for row in cursor:
            if row[0] > 500000:
                cursor.deleteRow()

    arcpy.MakeFeatureLayer_management(donut_polygons,"lyrDonuts")
    arcpy.MakeFeatureLayer_management(fcLines,"lyrBraidedReaches")

    arcpy.SelectLayerByLocation_management("lyrBraidedReaches","SHARE_A_LINE_SEGMENT_WITH","lyrDonuts",'',"NEW_SELECTION")
    arcpy.CalculateField_management("lyrBraidedReaches","IsMultiCh",1,"PYTHON")
    arcpy.CalculateField_management("lyrBraidedReaches","IsMainCh",0,"PYTHON")
def CombineShorelinePolygons(bndMTL: str, bndMHW: str, inletLines: str,
    ShorelinePts: str, bndpoly: str, SA_bounds: str='', verbose: bool=True):
    """
    Use MTL and MHW contour polygons to create shoreline polygon.
    'Shoreline' = MHW on oceanside and MTL on bayside
    """
    start = time.clock()
    # Inlet lines must intersect the MHW polygon
    symdiff = os.path.join(arcpy.env.scratchGDB, 'shore_1symdiff')
    split = os.path.join(arcpy.env.scratchGDB, 'shore_2split')
    join = os.path.join(arcpy.env.scratchGDB, 'shore_3_oceanMTL')
    erase = os.path.join(arcpy.env.scratchGDB, 'shore_4_bayMTL')
    union_2 = os.path.join(arcpy.env.scratchGDB, 'shore_5union')

    # Create layer (symdiff) of land between MTL and MHW and split by inlets
    print("...delineating land between MTL and MHW elevations...")
    arcpy.Delete_management(symdiff) # delete if already exists
    arcpy.SymDiff_analysis(bndMTL, bndMHW, symdiff)

    # Split symdiff at inlets (and SA_bounds)
    print("...removing the MHW-MTL areas on the oceanside...")
    if len(SA_bounds) > 0:
        arcpy.FeatureToPolygon_management([symdiff, inletLines, SA_bounds], split) # Split MTL features at inlets and study area bounds
    else:
        arcpy.FeatureToPolygon_management([symdiff, inletLines], split) # Split MTL features at inlets
    # Isolate polygons touching shoreline points and erase from symdiff
    arcpy.SpatialJoin_analysis(split, ShorelinePts, split+'_join', "#","KEEP_COMMON", match_option="COMPLETELY_CONTAINS")
    arcpy.Erase_analysis(symdiff, split+'_join', erase)

    # Merge bayside MHW-MTL with above-MHW polygon
    arcpy.Union_analysis([erase, bndMHW], union_2)
    arcpy.Dissolve_management(union_2, bndpoly, multi_part='SINGLE_PART') # Dissolve all features in union_2 to single part polygons
    print('''User input required! Select extra features in {} for deletion.\nRecommended technique: select the polygon/s to keep and then Switch Selection.\n'''.format(os.path.basename(bndpoly)))
    return(bndpoly)
def NewBNDpoly(old_boundary, modifying_feature, new_bndpoly='boundary_poly', vertexdist='25 METERS', snapdist='25 METERS', verbose=True):
    """Snaps the boundary polygon to the shoreline points anywhere they don't
    already match and as long as as they are within 25 m of each other."""
    # boundary = input line or polygon of boundary to be modified by newline
    typeFC = arcpy.Describe(old_boundary).shapeType
    if typeFC == "Line" or typeFC =='Polyline':
        arcpy.FeatureToPolygon_management(old_boundary, new_bndpoly, '1 METER')
    else:
        if len(os.path.split(new_bndpoly)[0]):
            path = os.path.split(new_bndpoly)[0]
        else:
            path = arcpy.env.workspace
        arcpy.FeatureClassToFeatureClass_conversion(old_boundary, path, os.path.basename(new_bndpoly))
    typeFC = arcpy.Describe(modifying_feature).shapeType
    if typeFC == "Line" or typeFC == "Polyline":
        arcpy.Densify_edit(modifying_feature, 'DISTANCE', vertexdist)
    # elif typeFC == "Point" or typeFC == "Multipoint":
    #     arcpy.PointsToLine_management(modifying_feature, modifying_feature+'_line')
    #     modifying_feature = modifying_feature+'_line'
    #     arcpy.Densify_edit(modifying_feature, 'DISTANCE', vertexdist)
    arcpy.Densify_edit(new_bndpoly, 'DISTANCE', vertexdist)
    #arcpy.Densify_edit(modifying_feature,'DISTANCE',vertexdist)
    arcpy.Snap_edit(new_bndpoly,[[modifying_feature, 'VERTEX',snapdist]]) # Takes a while
    if verbose:
        print("Created: {} ... Should be in your home geodatabase.".format(os.path.basename(new_bndpoly)))
    return new_bndpoly # string name of new polygon
Beispiel #4
0
    def crear_limite_manzanas(self):
        arcpy.env.overwriteOutput = True
        path_manzana = path.join(self.path_trabajo, 'tb_manzana_procesar')
        path_eje_vial = path.join(self.path_trabajo, 'tb_eje_vial_procesar')
        path_zona = path.join(self.path_trabajo, 'tb_zona_procesar')

        fragmentos = arcpy.FeatureToPolygon_management(
            [path_eje_vial, path_zona, path_manzana],
            path.join(self.path_trabajo,
                      'fragmentos'), "10 Meters", "NO_ATTRIBUTES", "")
        x = arcpy.SpatialJoin_analysis(
            fragmentos, path_manzana,
            path.join(self.path_trabajo, 'fragmentos_manzanas_x'),
            'JOIN_ONE_TO_ONE', 'KEEP_ALL', '', 'HAVE_THEIR_CENTER_IN')
        arcpy.SelectLayerByAttribute_management(x, "NEW_SELECTION",
                                                " Join_Count=1")

        dissolveFields = [
            'CODDPTO', 'CODPROV', 'CODDIST', 'CODZONA', 'SUFZONA', 'CODMZNA',
            'UBIGEO	'
            'CODCCPP', 'DEPARTAMENTO', 'PROVINCIA', 'DISTRITO', 'NOMCCCPP'
            'SUF_MZNA', 'PK_MANZANA', 'ZONA', 'MANZANA'
        ]

        fragmentos_manzanas = arcpy.Dissolve_management(
            x, path.join(self.path_trabajo, 'fragmentos_manzanas'),
            dissolveFields, "", "SINGLE_PART", "DISSOLVE_LINES")
Beispiel #5
0
def create_polys(input_workspace, folder_basename):
    """"Takes input TFL lines and attempts to build polygons to a temp layer. If build
    succeeds, informs user and deletes the temp feature class. If no polygons created,
    deletes temp feature class and warns user"""

    tfl_lines = input_workspace + os.sep + folder_basename + '_Line'

    #Check if a previous temp poly exists - if so delete it first
    if arcpy.Exists(input_workspace + os.sep + 'Temp_Poly'):
        arcpy.Delete_management(input_workspace + os.sep + 'Temp_Poly')

    #select only the active and retired lines - use to build polys - retired lines are used for deletions
    arcpy.MakeFeatureLayer_management(tfl_lines, 'tfl_lines_layer',
                                      "Status_Code = 'ACTIVE'")

    arcpy.FeatureToPolygon_management('tfl_lines_layer',
                                      input_workspace + os.sep + 'Temp_Poly')
    if int(
            arcpy.GetCount_management(input_workspace + os.sep +
                                      'Temp_Poly').getOutput(0)) == 0:
        arcpy.AddWarning(
            "===== Warning - No polygons created using input active lines\n")
        arcpy.Delete_management(input_workspace + os.sep + 'Temp_Poly')
    else:
        #If there are any records then at least one polygon built - inform user
        arcpy.AddMessage(
            'One or more polygons created from active input lines\n')
        arcpy.Delete_management(input_workspace + os.sep + 'Temp_Poly')
    def execute(self, params, messages):
        workingCoreInput = params[0].valueAsText
        workingSLPInput = params[1].valueAsText
        watershedInput = params[2].valueAsText

        #Print the specification version id
        arcpy.AddMessage(
            "\n********************************************************************\n\
        Script follows specification version: \n\
        {0}.\n\
        ********************************************************************\n"
            .format(str(self.specIDVersion)))

        # Set the workspace environment
        arcpy.env.workspace = "in_memory"

        # Get eoid from core
        srows = arcpy.da.SearchCursor(workingCoreInput, ["EO_ID"])
        for srow in srows:
            eoid = srow[0]
            arcpy.AddMessage("Processing EO ID {0} at {1}".format(
                eoid,
                datetime.datetime.now().strftime("%H:%M:%S")))

            #Create EO_ID selection query
            eoidQuery = '"EO_ID" = {0}'.format(eoid)

            #Create a targetCore layer
            arcpy.MakeFeatureLayer_management(workingCoreInput, "targetCore",
                                              eoidQuery)

            #Capture all HUC-12 watersheds that intersect the target core
            arcpy.MakeFeatureLayer_management(watershedInput, "watershedLayer")
            arcpy.SelectLayerByLocation_management("watershedLayer",
                                                   "INTERSECT", "targetCore")

            # Use feature to polygon tool to remove voids and dissolve to a single feature
            arcpy.FeatureToPolygon_management("watershedLayer",
                                              "features_to_polygon")
            arcpy.Dissolve_management("features_to_polygon", "newSLP")

            #Append to the workingSLPInput
            arcpy.Append_management("newSLP", workingSLPInput, "NO_TEST")

            # Add eoid to supporting polygon
            urows = arcpy.da.UpdateCursor(workingSLPInput, ["EO_ID"],
                                          '"EO_ID" is null')
            for urow in urows:
                urow[0] = eoid
                urows.updateRow(urow)
            # Calculate attributes
            cpp.calc_attr_slp(eoid,
                              workingCoreInput,
                              workingSLPInput,
                              specid=self.specIDVersion)

            #Clear the in_memory workspace
            arcpy.Delete_management("in_memory")

        return
Beispiel #7
0
def main():
    N = len(sys.argv)
    #print N
    inputlist = ["hi"] * (N - 3)
    # print command line arguments
    print "The input features are: "
    for index in range(len(sys.argv)):
        if index == 0:
            continue
        if index == N - 2:
            break
        inputlist[index - 1] = sys.argv[index] + ".shp"
        print "    " + sys.argv[index]

    #print inputlist[0]
    outputname = sys.argv[N - 2]
    print "The temporary file name is: "
    print "    " + outputname
    tol = sys.argv[N - 1]
    print "User specified tolerance: "
    print "    " + tol

    print "ARCGIS Commands >>>"
    # STEP 1
    print "    " + "FeatureToLine_management ..."
    arcpy.FeatureToLine_management(inputlist, outputname, tol, "ATTRIBUTES")

    # STEP 2
    outputname_poly = outputname + "_poly"
    print "    " + "FeatureToPolygon_management ..."
    arcpy.FeatureToPolygon_management(outputname + ".shp", outputname_poly,
                                      tol, "ATTRIBUTES", "")
    #print outputname_poly

    # STEP 3
    print "    " + "AddField_management ..."
    arcpy.AddField_management(outputname_poly + ".shp", "ID_temp", "SHORT")
    outputname_diss = outputname_poly + "_diss"
    #print outputname_diss

    # STEP 4
    print "    " + "Dissolve_management ..."
    arcpy.Dissolve_management(outputname_poly + ".shp", outputname_diss,
                              "ID_temp")
    outputname_inter = outputname_diss + "_int"

    # STEP 5
    print "    " + "Intersect_analysis ..."
    arcpy.Intersect_analysis([outputname_diss + ".shp", inputlist[0]],
                             outputname_inter, "", tol)
    outputname_AllVerts = outputname + "_allVert"

    # STEP 6
    print "    " + "FeatureVerticesToPoints_management ..."
    arcpy.FeatureVerticesToPoints_management(outputname + ".shp",
                                             outputname_AllVerts, "ALL")
def spreadsheetToLinePolygon(dataFile, geometryType, xField, yField,
                             spreadsheetUniqueID, inputCoordinateSystemName,
                             inputCoordinateSystem, outputCoordinateSystemName,
                             outputCoordinateSystem, transformation):
    # If excel spreadsheet
    if dataFile.lower().endswith(('.xls', '.xlsx')):
        dataFile = arcpy.ExcelToTable_conversion(dataFile,
                                                 "in_memory\\DatasetExcel", "")

    # If projection needed
    if (transformation.lower() != "none"):
        printMessage("Importing CSV/Excel...", "info")
        arcpy.MakeXYEventLayer_management(dataFile, xField, yField,
                                          "InputLayer", inputCoordinateSystem,
                                          "")
        printMessage(
            "Projecting layer from " + inputCoordinateSystemName + " to " +
            outputCoordinateSystemName + "...", "info")
        arcpy.Project_management(
            "InputLayer", os.path.join(arcpy.env.scratchGDB,
                                       "Layer_Projected"),
            outputCoordinateSystem, transformation, inputCoordinateSystem,
            "NO_PRESERVE_SHAPE", "")
    else:
        printMessage("Importing CSV/Excel...", "info")
        arcpy.MakeXYEventLayer_management(dataFile, xField, yField, "Layer",
                                          inputCoordinateSystem, "")
        arcpy.CopyFeatures_management("Layer", "in_memory\\Dataset", "", "0",
                                      "0", "0")

    if (transformation.lower() != "none"):
        dataset = os.path.join(arcpy.env.scratchGDB, "Layer_Projected")
    else:
        dataset = "in_memory\\Dataset"

    printMessage("Creating layer...", "info")
    if (geometryType.lower() == "line"):
        # Convert the points to lines using the unique identifier field to create each unique line
        arcpy.PointsToLine_management(dataset, "in_memory\\DatasetLine",
                                      spreadsheetUniqueID, "", "NO_CLOSE")
        output = arcpy.MakeFeatureLayer_management("in_memory\\DatasetLine",
                                                   "Layer", "", "", "")
    if (geometryType.lower() == "polygon"):
        # Convert the points to lines using the unique identifier field to create each unique line, then close the final line
        arcpy.PointsToLine_management(dataset, "in_memory\\DatasetLine",
                                      spreadsheetUniqueID, "", "CLOSE")
        # Convert the lines to polygons and join on attribute from lines
        arcpy.FeatureToPolygon_management("in_memory\\DatasetLine",
                                          "in_memory\\DatasetPolygon", "",
                                          "ATTRIBUTES", "")
        arcpy.JoinField_management("in_memory\\DatasetPolygon", "OID",
                                   "in_memory\\DatasetLine", "OID",
                                   spreadsheetUniqueID)
        output = arcpy.MakeFeatureLayer_management("in_memory\\DatasetPolygon",
                                                   "Layer", "", "", "")
    return output
Beispiel #9
0
def optimizacion_cobertura(oid):
    global troba, tapt, identificador, vias_mfl

    query = "OBJECTID = %s" % oid
    troba_mfl = arcpy.MakeFeatureLayer_management(troba, "troba", query)


    pol_tmp = arcpy.FeatureToPolygon_management([troba_mfl, vias_mfl],  r'D:\TEMP\hora.shp')
    for m in arcpy.da.SearchCursor(pol_tmp, ['OID@', 'SHAPE@']):


        identificador += 1
        arcpy.AddMessage(identificador)
        pol = arcpy.MakeFeatureLayer_management(pol_tmp, 'pol_tmp_mfl', 'FID = {}'.format(m[0]))

        arcpy.SelectLayerByLocation_management(vias_mfl, "INTERSECT", troba_mfl, "#", 'NEW_SELECTION')

        arcpy.SelectLayerByLocation_management(tapt, "INTERSECT", pol, "#", 'NEW_SELECTION')

        if arcpy.GetCount_management(vias_mfl).__str__() == '0':
            arcpy.AddMessage("Tiene vias")

            pol = arcpy.FeatureToPolygon_management([pol, vias_mfl], "in_memory//thiessenVias")

        arcpy.env.extent = pol

        taps_thiessen = arcpy.CreateThiessenPolygons_analysis(tapt, "in_memory//taptemp")
        pol = arcpy.Clip_analysis(taps_thiessen, m[1], "in_memory//clipThiessen")

        #if pol:
          arcpy.Append_management(pol, output, 'NO_TEST')

        with arcpy.da.UpdateCursor(output, [field], "%s is null" % field) as cursor:
            for i in cursor:
                i[0] = identificador
                cursor.updateRow(i)
        del cursor

        arcpy.SelectLayerByAttribute_management(tapt, 'CLEAR_SELECTION')
        arcpy.SelectLayerByAttribute_management(vias_mfl, 'CLEAR_SELECTION')
Beispiel #10
0
 def pre_processing(self):
     print('Pre-processing...')
     for i, line in enumerate(self.lines):
         fields = arcpy.ListFields(line)
         field_names = []
         for field in fields:
             field_names.append(field.name)
         if self.weight not in field_names:
             arcpy.AddField_management(line, self.weight,
                                       'TEXT')  # Add the field 'weight'
         rows = arcpy.UpdateCursor(line)
         for row in rows:
             row.setValue(self.weight,
                          str(self.lines_level[i]))  # Set the weight
             rows.updateRow(row)
     self.lines.append(self.road)
     if not os.path.isfile(self.workspace_path + '\\' + 'merge_all.shp'):
         arcpy.Merge_management(self.lines, 'merge_all.shp')
     if not os.path.isfile(
             self.workspace_path + '\\' +
             'streets_polygon.shp'):  # Roads: lines to polygons
         arcpy.FeatureToPolygon_management('merge_all.shp',
                                           'streets_polygon.shp')
     if not os.path.exists(self.coverage_folder
                           ):  # Roads: poltgons to coverage to get topo
         arcpy.FeatureclassToCoverage_conversion(
             [['streets_polygon.shp', 'POLYGON']], self.coverage_folder)
     if not os.path.isfile(self.workspace_path + '\\' +
                           'arc.shp'):  # To get topo
         arcpy.FeatureClassToFeatureClass_conversion(
             self.coverage_folder + '\\arc', self.workspace_path, 'arc')
     if not os.path.isfile(self.workspace_path + '\\' +
                           self.__area_path):  # Coverage to polygons
         arcpy.FeatureClassToFeatureClass_conversion(
             self.coverage_folder + '\\polygon', self.workspace_path,
             self.__area_path)
     if not os.path.isfile(self.workspace_path + '\\' + self.__arc_path):
         # Create field mappings
         # Get weights for arc
         fld_mappings = arcpy.FieldMappings()
         fld_mappings.addTable('arc.shp')
         fld_map = arcpy.FieldMap()
         fld_map.addInputField('merge_all.shp', self.weight)
         fld_mappings.addFieldMap(fld_map)
         # Spatial join to get the weights
         arcpy.SpatialJoin_analysis('arc.shp', 'merge_all.shp',
                                    self.__arc_path, 'JOIN_ONE_TO_ONE',
                                    'KEEP_ALL', fld_mappings, 'CLOSEST')
     arcpy.Delete_management('arc.shp')
     arcpy.Delete_management('merge_all.shp')
     arcpy.Delete_management('streets_polygon.shp')
     print('Pre-processing done...')
Beispiel #11
0
def findBraidedReaches(fcLines):

    # Clear temporary data
    if arcpy.Exists("in_memory//DonutPolygons"):
        arcpy.Delete_management("in_memory//DonutPolygons")
    if arcpy.Exists("lyrDonuts"):
        arcpy.Delete_management("lyrDonuts")
    if arcpy.Exists("lyrBraidedReaches"):
        arcpy.Delete_management("lyrBraidedReaches")
        
    # Find donut reaches
    arcpy.FeatureToPolygon_management(fcLines,"in_memory/DonutPolygons")
    arcpy.MakeFeatureLayer_management(fcLines,"lyrBraidedReaches")
    arcpy.MakeFeatureLayer_management("in_memory/DonutPolygons","lyrDonuts")
    arcpy.SelectLayerByLocation_management("lyrBraidedReaches","SHARE_A_LINE_SEGMENT_WITH","lyrDonuts",'',"NEW_SELECTION")
    arcpy.CalculateField_management("lyrBraidedReaches","IsBraided",1,"PYTHON")
Beispiel #12
0
def create_pblks(city_info, geo_path):

	city_name, state_abbr, decade = city_info
	city_name = city_name.replace(' ','')

	pblk_shp = geo_path + city_name + "_" + str(decade) + "_Pblk.shp"
	split_grid = geo_path + city_name + "_" + str(decade) + "_stgrid_Split.shp"
	grid_uns2 = geo_path + city_name + state_abbr + "_" + str(decade) + "_stgrid_edit_Uns2.shp"

	if not os.path.isfile(split_grid) or not os.path.isfile(grid_uns2):
		print("Processing raw stgrid for %s" %decade)
		_ = process_raw_grid(city_info, geo_path)

	#Create Physical Blocks# #####
	arcpy.FeatureToPolygon_management(split_grid, pblk_shp)
	#Add a Physical Block ID
	expression="!FID! + 1"
	arcpy.AddField_management(pblk_shp, "pblk_id", "LONG", 4, "", "","", "", "")
	arcpy.CalculateField_management(pblk_shp, "pblk_id", expression, "PYTHON_9.3")
    def onRectangle(self, rectangle_geometry):
        """Occurs when the rectangle is drawn and the mouse button is released.
        The rectangle is a extent object."""

        array = arcpy.Array()
        array.add(rectangle_geometry.upperLeft)
        array.add(rectangle_geometry.upperRight)
        array.add(rectangle_geometry.lowerRight)
        array.add(rectangle_geometry.lowerLeft)
        array.add(rectangle_geometry.upperLeft)

        polygon = arcpy.Polygon(array)
        arcpy.env.overwriteOutput = True  # temporarily allow overwriting of existing datasets, then disallow.
        arcpy.FeatureToPolygon_management(
            polygon,
            r"C:\Users\s\Documents\Masters of Geospatial\GISP\Assignment2\GISdata\survey_area.shp"
        )
        arcpy.env.overwriteOutput = False

        WORKSPACE = r"C:\Users\s\Documents\Masters of Geospatial\GISP\Assignment2\GISdata"
        arcpy.env.workspace = WORKSPACE
Beispiel #14
0
    def polygon(self):
        inFeatures1 = os.path.join(workspce, cad, cad_use[0])
        outFeatureClass = os.path.join(workspce, creat_gdb, self.polygon_name)
        arcpy.FeatureToPolygon_management(inFeatures1, outFeatureClass)
    
        inFeatures2 = os.path.join(workspce, cad, cad_use[1])
        outFeatureClass = os.path.join(workspce, creat_gdb, self.point_name)
        arcpy.FeatureToPoint_management(inFeatures2, outFeatureClass)
    
        where_clause = " RefName LIKE '5%' OR RefName LIKE '3%'"
        # 筛选符合要求的编号,其都以5和3开头
        select_fc = os.path.join(workspce, creat_gdb, self.select_anno)
        arcpy.Select_analysis(os.path.join(workspce, creat_gdb, self.point_name), select_fc , where_clause)

        outFeatureClass = os.path.join(workspce, creat_gdb, self.sp_fc)
        arcpy.SpatialJoin_analysis(os.path.join(workspce, creat_gdb, self.polygon_name), 
                                   os.path.join(workspce, creat_gdb, self.select_anno), 
                                   outFeatureClass)
        
        arcpy.MakeFeatureLayer_management(os.path.join(workspce, creat_gdb, self.sp_fc), "lyr")
        arcpy.SelectLayerByLocation_management ("lyr", select_features = area_fc)
        arcpy.CopyFeatures_management("lyr", os.path.join(workspce, creat_gdb, self.final_fc))
def findBraidedReaches(fcLines, is_verbose):
    if is_verbose:
        arcpy.AddMessage("Finding streams with mutltiple channels...")
    # Clear temporary data
    if arcpy.Exists("in_memory//DonutPolygons"):
        arcpy.Delete_management("in_memory//DonutPolygons")
    if arcpy.Exists("lyrDonuts"):
        arcpy.Delete_management("lyrDonuts")
    if arcpy.Exists("lyrBraidedReaches"):
        arcpy.Delete_management("lyrBraidedReaches")

    # Find donut reaches
    arcpy.FeatureToPolygon_management(fcLines, "in_memory/DonutPolygons")
    arcpy.MakeFeatureLayer_management(fcLines, "lyrBraidedReaches")
    arcpy.MakeFeatureLayer_management("in_memory/DonutPolygons", "lyrDonuts")
    arcpy.SelectLayerByLocation_management("lyrBraidedReaches",
                                           "SHARE_A_LINE_SEGMENT_WITH",
                                           "lyrDonuts", '', "NEW_SELECTION")
    arcpy.CalculateField_management("lyrBraidedReaches", "IsMultiCh", 1,
                                    "PYTHON")
    arcpy.CalculateField_management("lyrBraidedReaches", "IsMainCh", 0,
                                    "PYTHON")
Beispiel #16
0
 def surface_in_between(self):
     arcpy.AddMessage("Started differential surface statistics... ")
     self.report.write("\n---Differential surface---\n")
     temp_merge = "in_memory\\merge"
     arcpy.Merge_management([self.original, self.simplified], temp_merge)
     temp_poly = "in_memory\\poly"
     arcpy.FeatureToPolygon_management(temp_merge, temp_poly)
     arcpy.Delete_management(temp_merge)
     arcpy.AddGeometryAttributes_management(temp_poly, "AREA", "#",
                                            "SQUARE_METERS")
     with arcpy.da.SearchCursor(temp_poly, ["POLY_AREA"]) as cursor:
         summarize = 0
         parts = 0
         for row in cursor:
             summarize += row[0]
             parts += 1
     mean = summarize / parts
     arcpy.Delete_management(temp_poly)
     self.report.write("Sum area: {:0.0f} sq m\n".format(summarize))
     self.report.write("Mean area: {:0.0f} sq m\n".format(mean))
     arcpy.AddMessage("Differential surface statistics - done.")
     return
def label_polygons(infc, labelfc, outfc):
    """ Label polygons.
    infc      input feature class (can be lines or polygons)
    labelfc   point feature class containing attributes for outfc
    outfc     where to write polygons """

    logging.info("label_polygons(%s, %s, %s)" % (infc, labelfc, outfc))
    # Notes on "FeatureToPolygon"
    # If you use the "NO ATTRIBUTES" default, then only the shapes are move from the input to the generated polygon feature class.
    # If you use "ATTRIBUTES" the attributes are copied.
    # If you use "ATTRIBUTES" and a polygon or line feature class AND a point feature class,
    #   the attributes from the points are copied to the output (the poly/line attributes are lost).
    # If there are multiple points inside a new polygon feature it picks attributes from one randomly.
    # Input features can be lines or polygons, so you can think of it as a way of just transferring the attributes if you have input polygons.
    # The blank "" arg is a tolerance, if you have sloppy input you can use this to close the polygons.
    #
    # NB when I ran it as a standalone tool in ArcMap I got a background server error, I had to run it in foreground.

    # I wish that ESRI was a bit more consistent in what DOES and DOES NOT support the workspace environment variable.
    ws = str(arcpy.env.workspace)

    logging.info("label_polygons(%s, %s, %s)" % (infc, labelfc, outfc))
    i = os.path.join(ws, infc)
    l = os.path.join(ws, labelfc)
    o = os.path.join(ws, outfc)

    try:
        arcpy.Delete_management(o)
    except Exception as e:
        logging.info("Did not delete %s, %s" % (o, e))
    try:
        arcpy.FeatureToPolygon_management(i, o, "", "ATTRIBUTES", l)
    except Exception as e:
        logging.error(e)

    return