示例#1
0
def create_points(lines, current_raster):
    points = temp_loc + "\Points.shp"  # path to temp file with points from line
    cell_size = read_cell_size(current_raster)  # gets raster cell_size

    dist = str(
        cell_size / 2
    ) + " Meters"  # calculates distance between points as 1/2 of cell_size

    temp_lines = temp_loc + "\\temp_lines"
    arcpy.FeatureClassToFeatureClass_conversion(lines, temp_loc, "temp_lines",
                                                "", "", "")
    arcpy.Densify_edit(lines, "DISTANCE", dist, "1 Meters",
                       "10")  # densifies line vertices to dist

    try:
        arcpy.FeatureVerticesToPoints_management(
            lines, points, "ALL")  # convert vertices from lines to points
    except arcpy.ExecuteError:
        error_code = get_error_code()  # gets error code
        if error_code == '000725' or error_code == '000872':  # if code means that points already exist
            arcpy.Delete_management(points, "")  # deletes old points
            arcpy.FeatureVerticesToPoints_management(
                lines, points, "ALL")  # convert vertices again
        else:  # if it's other error, prints message
            print 'Process broken by error. Info below:'
            print error_message

    arcpy.Delete_management(temp_lines, "")

    return points  # returns path to created points
def transfer_line(fcInLine, fcToLine, strStreamSide):
    outputWorkspace = arcpy.Describe(fcInLine).path
    fcOutput = gis_tools.newGISDataset(
        outputWorkspace, "LineNetworkConfinement" + strStreamSide)

    # Split Line Network by Line Ends
    fcSplitPoints = gis_tools.newGISDataset(
        outputWorkspace, "SplitPoints_Confinement" + strStreamSide)
    arcpy.FeatureVerticesToPoints_management(fcInLine, fcSplitPoints,
                                             "BOTH_ENDS")
    tblNearPointsConfinement = gis_tools.newGISDataset(
        outputWorkspace, "NearPointsConfinement" + strStreamSide)
    arcpy.GenerateNearTable_analysis(fcSplitPoints,
                                     fcToLine,
                                     tblNearPointsConfinement,
                                     location="LOCATION",
                                     angle="ANGLE")
    lyrNearPointsConfinement = gis_tools.newGISDataset(
        "Layer", "lyrNearPointsConfinement" + strStreamSide)
    arcpy.MakeXYEventLayer_management(tblNearPointsConfinement, "NEAR_X",
                                      "NEAR_Y", lyrNearPointsConfinement,
                                      fcToLine)
    arcpy.SplitLineAtPoint_management(fcToLine,
                                      lyrNearPointsConfinement,
                                      fcOutput,
                                      search_radius="0.01 Meters")

    # Prepare Fields
    strConfinementField = "Con_" + strStreamSide
    arcpy.AddField_management(fcOutput, strConfinementField, "LONG")

    # Transfer Attributes by Centroids
    fcCentroidPoints = gis_tools.newGISDataset(
        outputWorkspace, "CentroidPoints_Confinement" + strStreamSide)
    arcpy.FeatureVerticesToPoints_management(fcInLine, fcCentroidPoints, "MID")
    tblNearPointsCentroid = gis_tools.newGISDataset(
        outputWorkspace, "NearPointsCentroid" + strStreamSide)
    arcpy.GenerateNearTable_analysis(fcCentroidPoints,
                                     fcToLine,
                                     tblNearPointsCentroid,
                                     location="LOCATION",
                                     angle="ANGLE")
    lyrNearPointsCentroid = gis_tools.newGISDataset(
        "Layer", "lyrNearPointsCentroid" + strStreamSide)
    arcpy.MakeXYEventLayer_management(tblNearPointsCentroid, "NEAR_X",
                                      "NEAR_Y", lyrNearPointsCentroid,
                                      fcToLine)
    lyrToLineSegments = gis_tools.newGISDataset("Layer", "lyrToLineSegments")
    arcpy.MakeFeatureLayer_management(fcOutput, lyrToLineSegments)

    arcpy.SelectLayerByLocation_management(
        lyrToLineSegments,
        "INTERSECT",
        lyrNearPointsCentroid,
        selection_type="NEW_SELECTION")  #"0.01 Meter","NEW_SELECTION")
    arcpy.CalculateField_management(lyrToLineSegments, strConfinementField, 1,
                                    "PYTHON")

    return fcOutput
def planarizeAndGetArcEndPoints(fds,caf,mup,fdsToken):
    # returns a feature class of endpoints of all caf lines, two per planarized line segment
    addMsgAndPrint('Planarizing '+os.path.basename(caf)+' and getting segment endpoints')
    #   add LineID (so we can recover lines after planarization)
    arcpy.AddField_management(caf,'LineID','LONG')
    arcpy.CalculateField_management(caf,'LineID','!OBJECTID!','PYTHON_9.3')
    # planarize CAF by FeatureToLine
    addMsgAndPrint('  planarizing caf')
    planCaf = caf+'_xxx_plan'
    testAndDelete(planCaf)
    arcpy.FeatureToLine_management(caf,planCaf)
    #   planarize CAF (by IDENTITY with MUP)
    addMsgAndPrint('  IDENTITYing caf with mup')
    cafp = caf+'_planarized'
    testAndDelete(cafp)
    arcpy.Identity_analysis(planCaf,mup,cafp,'ALL','','KEEP_RELATIONSHIPS')
    # delete extra fields
    addMsgAndPrint('  deleting extra fields')
    fns = fieldNameList(cafp)
    deleteFields = []
    for f in fieldNameList(mup):
        if f != 'MapUnit':
            for hf in ('RIGHT_'+f,'LEFT_'+f): 
                if hf in fns:
                    deleteFields.append(hf)
    arcpy.DeleteField_management(cafp,deleteFields)   
    #   calculate azimuths startDir and endDir
    addMsgAndPrint('  adding StartAzimuth and EndAzimuth')
    for f in ('LineDir','StartAzimuth','EndAzimuth'):
        arcpy.AddField_management(cafp,f,'FLOAT')
    arcpy.AddField_management(cafp,'ToFrom','TEXT','','',4)                              
    fields = ['SHAPE@','StartAzimuth','EndAzimuth']
    with arcpy.da.UpdateCursor(cafp,fields) as cursor:
        for row in cursor:
            lineSeg = row[0].getPart(0)
            row[1],row[2] = startEndGeogDirections(lineSeg)
            cursor.updateRow(row)
    #   make endpoint feature class
    addMsgAndPrint('  converting line ends to points')
    arcEndPoints = fds+'/'+fdsToken+'xxx_EndPoints'   # will be a feature class in fds
    arcEndPoints2 = arcEndPoints+'_end'
    testAndDelete(arcEndPoints)
    arcpy.FeatureVerticesToPoints_management(cafp,arcEndPoints, 'START')
    arcpy.CalculateField_management(arcEndPoints,'LineDir','!StartAzimuth!','PYTHON')
    arcpy.CalculateField_management(arcEndPoints,'ToFrom','"From"','PYTHON')
    testAndDelete(arcEndPoints2)
    arcpy.FeatureVerticesToPoints_management(cafp,arcEndPoints2,'END')
    arcpy.CalculateField_management(arcEndPoints2,'LineDir','!EndAzimuth!','PYTHON')
    arcpy.CalculateField_management(arcEndPoints2,'ToFrom','"To"','PYTHON')
    arcpy.Append_management(arcEndPoints2,arcEndPoints)
    testAndDelete(arcEndPoints2)
    #  delete some more fields
    deleteFields = ['EndAzimuth','StartAzimuth','LEFT_MapUnitPolys','RIGHT_MapUnitPolys']
    arcpy.DeleteField_management(arcEndPoints,deleteFields)      
    addMsgAndPrint('  adding POINT_X and POINT_Y')
    arcpy.AddXY_management(arcEndPoints)
    testAndDelete(planCaf)
    return cafp, arcEndPoints
def findGaps(lines, flowline_per, find_art = 'False'):

    #  environment settings
    arcpy.env.overwriteOutput = 'TRUE'

    # add unique id field to gap lines
    arcpy.AddField_management(lines, 'LineID', 'LONG')
    ct = 1
    with arcpy.da.UpdateCursor(lines, ['LineID']) as cursor:
        for row in cursor:
            row[0] = ct
            ct += 1
            cursor.updateRow(row)

    # create gap line start and end points
    gap_start_pts = arcpy.FeatureVerticesToPoints_management(lines, 'in_memory/gap_start_pts', "START")
    gap_end_pts = arcpy.FeatureVerticesToPoints_management(lines, 'in_memory/gap_end_pts', "END")
    arcpy.MakeFeatureLayer_management(gap_start_pts, 'gap_start_pts_lyr')
    arcpy.MakeFeatureLayer_management(gap_end_pts, 'gap_end_pts_lyr')

    # create end points along dissolved perennial network
    flowline_per_dissolve = arcpy.Dissolve_management(flowline_per, 'in_memory/flowline_per_dissolve', 'GNIS_NAME', '', 'SINGLE_PART', 'UNSPLIT_LINES')
    per_end_pts = arcpy.FeatureVerticesToPoints_management(flowline_per_dissolve, 'in_memory/per_end_pts', "END")

    # if dealing with artificial gap lines - select gap starts that intersect perennial flowlines
    # if dealing with other gap lines - select gap starts that intersect a perennial end point
    if find_art == 'True':
        arcpy.SelectLayerByLocation_management('gap_start_pts_lyr', 'INTERSECT', flowline_per_dissolve, '', 'NEW_SELECTION')
    else:
        # select gap start that intersect perennial end point
        arcpy.SelectLayerByLocation_management('gap_start_pts_lyr', 'INTERSECT', per_end_pts, '', 'NEW_SELECTION')

    # select gap end that intersect perennial start point
    arcpy.SelectLayerByLocation_management('gap_end_pts_lyr', 'INTERSECT', flowline_per_dissolve, '', 'NEW_SELECTION')

    # create list of gap start and end point unique ids
    startList = [row[0] for row in arcpy.da.SearchCursor('gap_start_pts_lyr', 'LineID')]
    endList = [row[0] for row in arcpy.da.SearchCursor('gap_end_pts_lyr', 'LineID')]

    # delete gap lines that don't start and end on perennial network
    # (i.e., they aren't true gap lines)
    with arcpy.da.UpdateCursor(lines, ['LineID']) as cursor:
        for row in cursor:
            if row[0] in startList and row[0] in endList:
                pass
            else:
                cursor.deleteRow()

    return lines
示例#5
0
def main():
    arcpy.env.overwriteOutput = True
    inputFeature = sys.argv[1]
    arcpy.env.workspace = os.path.dirname(inputFeature)
    tempOut = 'boundingPoly.shp'
    arcpy.MinimumBoundingGeometry_management(inputFeature, 'boundingPoly.shp')
    arcpy.FeatureVerticesToPoints_management(tempOut, 'outerPoints.shp')
示例#6
0
文件: feat.py 项目: jasp382/glass
def vertex_to_point(shp, o):

    arcpy.FeatureVerticesToPoints_management(in_features=shp,
                                             out_feature_class=o,
                                             point_location="ALL")

    return o
示例#7
0
def getDownstreamGridCodes(gridcode, catchFC, flownet, flownetFC):
    '''Traces downstream from the project's catchment and lists all downstream catchment GRIDCODES'''
    #Get the catchment corresponding to the gridcode
    theCatchLyr = arcpy.MakeFeatureLayer_management(
        catchFC, "theCatch", "GRIDCODE = {}".format(gridcode))
    #Clip the flowine within the catchment and get its lowest point
    theFlowline = arcpy.Clip_analysis(flowlineFC, theCatchLyr,
                                      "in_memory/theFlowline")
    theFlowpoint = arcpy.FeatureVerticesToPoints_management(
        theFlowline, "in_memory/thePoint", "END")
    #Trace from this point downstream to the end of the HUC8 geometric network
    theTraceLyr = arcpy.TraceGeometricNetwork_management(
        flownet, "DownStrmLyr", theFlowpoint, "TRACE_DOWNSTREAM")
    #Extract the line feature
    theTraceLine = arcpy.SelectData_management(theTraceLyr,
                                               os.path.basename(flownetFC))
    #Make a new feature layer of catchments and select those that intersect the downstream trace
    theCatchLyr = arcpy.MakeFeatureLayer_management(catchFC, "theCatch")
    theCatchments = arcpy.SelectLayerByLocation_management(
        theCatchLyr, "INTERSECT", theTraceLine)
    #Create a list of catchment GRIDCODEs in the selected catchments
    outGridcodes = []
    with arcpy.da.SearchCursor(theCatchments, "GRIDCODE") as cur:
        for rec in cur:
            outGridcodes.append(rec[0])
    return outGridcodes
示例#8
0
def fixCurves(fc):
    arcpy.env.overwriteOutput = True
    print(
        "\tProcessing true curves in {0}... this will take awhile to complete"
    ).format(fc.name)
    whereOID, cntSource = getCurvy(fc.dataSource, True, False)
    if len(cntSource) == 1:
        whereOID = whereOID.replace(',', '')
    #arcpy.SelectLayerByAttribute_management(fc,"NEW_SELECTION",whereOID)
    #arcpy.CopyFeatures_management(fc,"curvy_" + fc.name.replace(" ","_"))
    arcpy.Select_analysis(fc.dataSource, "curvy_" + fc.name.replace(" ", "_"),
                          whereOID)
    expression, cntCopy = getCurvy(
        scratchWksp + "\curvy_" + fc.name.replace(" ", "_"), False, False)
    arcpy.Densify_edit(scratchWksp + "\curvy_" + fc.name.replace(" ", "_"),
                       "ANGLE", "200 Feet", "2 Feet", "10")
    arcpy.FeatureVerticesToPoints_management(
        scratchWksp + "\curvy_" + fc.name.replace(" ", "_"),
        scratchWksp + "\curvy_" + fc.name.replace(" ", "_") + "_Pnts", "ALL")
    arcpy.PointsToLine_management(
        scratchWksp + "\curvy_" + fc.name.replace(" ", "_") + "_Pnts",
        scratchWksp + "\\notCurvy_" + fc.name.replace(" ", "_"), "ORIG_FID")
    if getCurvy(scratchWksp + "\\notCurvy_" + fc.name.replace(" ", "_"), False,
                False):
        print("Something went horribly wrong! {0}").format(fc.name)
    flds = arcpy.ListFields(fc.dataSource)
    # use python list comprehension, removing list objects in a loop will return an error
    fldsList = [fld for fld in flds if fld.name not in passFlds]
    # a feature class may have only passFlds and script fails
    if fldsList:
        fldNames = []
        cnt = 1
        for f in fldsList:
            if cnt < len(fldsList):
                fldNames.append(f.name)
            elif cnt == len(fldsList):
                fldNames.append(f.name)
            cnt = cnt + 1
        fldNames = ';'.join(map(str, fldNames))
        if getShapeType(fc) == "Polyline":
            arcpy.TransferAttributes_edit(
                scratchWksp + "\curvy_" + fc.name.replace(" ", "_"),
                scratchWksp + "\\notCurvy_" + fc.name.replace(" ", "_"),
                fldNames, "1 Feet", "",
                "attTransfer" + fc.name.replace(" ", "_"))
            if fixTrueCurves:
                # delete coincident lines first due to ArcFM Feeder Mananger messages
                # append after delete or ArcFM Feeder Manager will present excessive messages
                arcpy.SelectLayerByAttribute_management(
                    fc, "NEW_SELECTION", whereOID)
                arcpy.DeleteFeatures_management(fc)
                arcpy.Append_management(
                    scratchWksp + "\\notCurvy_" + fc.name.replace(" ", "_"),
                    fc.dataSource, "NO_TEST")
                #pass
            else:
                pass
    print("{0}: {1} Copied: {2} notCurvy: {3}".format(fc.name, len(cntSource),
                                                      len(cntCopy),
                                                      len(curveList)))
示例#9
0
def plot_branch(in_strm_dslv, in_strm_seg, in_fields, cellSize):
    arcpy.AddMessage("    ...for stream branches.")
    # select segment furthest downstream on a stream branch
    branch_end_vrtx = arcpy.FeatureVerticesToPoints_management(
        in_strm_dslv, r"in_memory\branch_end_vrtx", "END")
    end_seg = arcpy.SelectLayerByLocation_management(in_strm_seg, "INTERSECT",
                                                     branch_end_vrtx, "#",
                                                     "NEW_SELECTION")
    # create new point feature class to store segment endpoints
    endpoint_branch = arcpy.CreateFeatureclass_management(
        "in_memory", "endpoint_branch", "POINT", "", "DISABLED", "DISABLED",
        in_strm_seg)
    arcpy.AddField_management(endpoint_branch, "LineOID", "DOUBLE")
    arcpy.AddField_management(endpoint_branch, "Value", "DOUBLE")
    # plot points at end of stream branches (upstream of end vertex at 85% of length)
    with arcpy.da.SearchCursor(end_seg, (in_fields)) as search_end:
        with arcpy.da.InsertCursor(
                endpoint_branch, ("SHAPE@", "LineOID", "Value")) as insert_end:
            for row_end in search_end:
                try:
                    line_geom = row_end[0]
                    length = float(line_geom.length)
                    oid = str(row_end[1])
                    start = arcpy.PointGeometry(line_geom.firstPoint)
                    prct_end = line_geom.positionAlongLine(
                        length - (cellSize * 4), False).firstPoint
                    insert_end.insertRow((prct_end, oid, str(length)))
                except Exception as e:
                    print e.message
    return endpoint_branch
示例#10
0
def knoten_ohne_aufbruch(environment):
    """To FIX: Knoten, die die Haltung nicht aufbrechen"""
    env.workspace = environment

    haltungen_layer = environment + "SEW/AWK_HALTUNG"
    arcpy.MakeFeatureLayer_management(haltungen_layer, "AWK_HALTUNG_lyr")

    abwasserknoten_layer = environment + "SEW/AWK_ABWASSERKNOTEN"
    arcpy.MakeFeatureLayer_management(abwasserknoten_layer,
                                      "AWK_ABWASSERKNOTEN_lyr")

    arcpy.FeatureVerticesToPoints_management(
        "AWK_HALTUNG_lyr", "in_memory\\AWK_HALTUNG_lyr_knoten", "BOTH_ENDS")
    arcpy.Buffer_analysis("in_memory\\AWK_HALTUNG_lyr_knoten",
                          "in_memory\\AWK_HALTUNG_lyr_knoten_buffer",
                          "1 Meters")
    #arcpy.ErasePoint_edit(abwasserknoten_layer, "AWK_HALTUNG_lyr_knoten_buffer", 'INSIDE')
    #arcpy.SpatialJoin("in_memory\\AWK_HALTUNG_lyr_knoten_buffer", abwasserknoten_layer, "AWK_HALTUNG_spatial_join")

    with arcpy.da.SearchCursor("AWK_HALTUNG_spatial_join",
                               ['OID@, JOIN']) as rows:
        for row in rows:
            if row[1] == 0:
                print row[0]
    del rows
    return
def delete_loops(lines):
    arcpy.Copy_management(lines, "Lines_Copy")
    ends = arcpy.FeatureVerticesToPoints_management(lines, "Ends", "BOTH_ENDS")
    identical = arcpy.FindIdentical_management(ends, "Identical",
                                               "SHAPE;ORIG_FID")
    arcpy.JoinField_management(ends,
                               "OBJECTID",
                               identical,
                               "IN_FID",
                               fields="FEAT_SEQ")
    dissolved_ends = arcpy.Dissolve_management(
        ends,
        "Ends_Dissolve",
        "ORIG_FID;FEAT_SEQ",
        statistics_fields="FEAT_SEQ COUNT")
    rows = arcpy.da.SearchCursor(dissolved_ends,
                                 ['ORIG_FID', 'COUNT_FEAT_SEQ'])
    for row in rows:
        if row[1] == 2:
            del_lines = arcpy.da.UpdateCursor(lines, ['OBJECTID'])
            for del_line in del_lines:
                if del_line[0] == row[0]:
                    arcpy.AddMessage("Deleting ID {0}".format(row[0]))
                    del_lines.deleteRow()
            del del_line, del_lines
    del row, rows
    arcpy.AddMessage("Artefacts are removed")
示例#12
0
def main():

    #  import required modules and extensions
    import arcpy

    #  environment settings
    arcpy.env.workspace = 'in_memory' # set workspace to temporary workspace
    arcpy.env.overwriteOutput = 'TRUE'

    # make a temp copy of input flowlines
    flowlines = arcpy.CopyFeatures_management(flowline_path, 'in_memory/flowlines')

    # --find gaps in flowline network--
    # need this fix to resolve issues where flowlines were omitted in nhd area and waterbody polygons

    # create points at start and end of each flowlines
    line_pts = arcpy.FeatureVerticesToPoints_management(flowlines, 'in_memory/line_pts', 'BOTH_ENDS')

    # join start/end points with flowlines to get intersecting flowline count
    # here we want to isolate points that aren't connected to another line that indicate gaps in network
    line_pts_join = arcpy.SpatialJoin_analysis(line_pts, flowlines, 'in_memory/line_pts_join', 'JOIN_ONE_TO_ONE', 'KEEP_ALL', '', 'INTERSECT')

    # remove points that intersect > 1 line feature (these are not on gaps)
    with arcpy.da.UpdateCursor(line_pts_join, ['Join_Count']) as cursor:
        for row in cursor:
            if row[0] > 1:
                cursor.deleteRow()

    # copy gap points to output path
    arcpy.CopyFeatures_management(line_pts_join, outpath)
def make_rand_road_pts():
    """
    makes the 'rd_far_fld.shp' file which is points on roads that are spaced at least 300 ft from
    each other and at least 200 ft from any flood points
    :return: 
    """
    road_shapefile = "nor_roads_centerlines.shp"
    arcpy.Densify_edit(road_shapefile, densification_method='DISTANCE', distance=30)
    road_pts_file = 'rd_pts_all_1.shp'
    arcpy.FeatureVerticesToPoints_management(road_shapefile, road_pts_file)
    rand_rd_pts_file = 'rand_road.shp'
    rand_rd_pts_lyr = 'rand_road_lyr'
    arcpy.CreateRandomPoints_management(gis_proj_dir, rand_rd_pts_file, road_pts_file,
                                        number_of_points_or_field=50000,
                                        minimum_allowed_distance='200 Feet')
    print "rand_rd_points_file"
    fld_pts_file = 'flooded_points.shp'
    fld_pts_buf = 'fld_pt_buf.shp'
    arcpy.Buffer_analysis(fld_pts_file, fld_pts_buf, buffer_distance_or_field="200 Feet",
                          dissolve_option='ALL')
    print "buffer"
    arcpy.MakeFeatureLayer_management(rand_rd_pts_file, rand_rd_pts_lyr)
    arcpy.SelectLayerByLocation_management(rand_rd_pts_lyr, overlap_type='WITHIN',
                                           select_features=fld_pts_buf,
                                           invert_spatial_relationship='INVERT')
    rd_pts_outside_buf = 'rd_far_fld.shp'
    arcpy.CopyFeatures_management(rand_rd_pts_lyr, rd_pts_outside_buf)
    arcpy.JoinField_management(rd_pts_outside_buf, in_field='CID', join_table=road_pts_file,
                               join_field='FID')
    print "rd_points_outside_buf"
示例#14
0
def overlap_segments_to_concurrent_end_points(overlap_segments, concurrent_end_points):
    """

    :param overlap_segments:
    :param concurrent_end_points:
    """
    arcpy.FeatureVerticesToPoints_management(overlap_segments, concurrent_end_points, "BOTH_ENDS")
示例#15
0
def calcNodes(fcStreamNetwork):
    arcpy.AddMessage("Calculating stream network nodes...")
    arcpy.MakeFeatureLayer_management(fcStreamNetwork, "StreamNetwork_lyr")
    networkVrtx = "in_memory\\networkVrtx"
    arcpy.CreateFeatureclass_management("in_memory", "networkVrtx", "POINT",
                                        "", "DISABLED", "DISABLED",
                                        fcStreamNetwork)
    arcpy.AddField_management(networkVrtx, "ReachID", "LONG")
    arcpy.AddField_management(networkVrtx, "PointType", "TEXT")
    arcpy.AddField_management(networkVrtx, "TO_X_Coord", "DOUBLE")
    arcpy.AddField_management(networkVrtx, "TO_Y_Coord", "DOUBLE")
    arcpy.AddField_management(networkVrtx, "FROM_X_Coord", "DOUBLE")
    arcpy.AddField_management(networkVrtx, "FROM_Y_Coord", "DOUBLE")
    arcpy.AddField_management(networkVrtx, "TO_NODE", "TEXT")
    arcpy.AddField_management(networkVrtx, "FROM_NODE", "TEXT")

    # plot start and end vertices and populate TO and FROM fields in vertex table
    pointTypes = ["START", "END"]
    for type in pointTypes:
        networkVrtx_lyr = "networkVrtx_" + type + "_lyr"
        tmpVrtx = r"in_memory\vrtx" + type
        arcpy.FeatureVerticesToPoints_management("StreamNetwork_lyr", tmpVrtx,
                                                 type)
        arcpy.MakeFeatureLayer_management(tmpVrtx, "tmpVrtx_" + type)
        arcpy.Append_management("tmpVrtx_" + type, networkVrtx, "NO_TEST")
        if type == "START":
            arcpy.MakeFeatureLayer_management(networkVrtx, networkVrtx_lyr)
            arcpy.SelectLayerByAttribute_management(networkVrtx_lyr,
                                                    "NEW_SELECTION",
                                                    """"PointType" IS NULL""")
            arcpy.CalculateField_management(networkVrtx, "PointType",
                                            "'" + type + "'", "PYTHON_9.3")
            arcpy.CalculateField_management(networkVrtx, "FROM_X_Coord",
                                            "!SHAPE.CENTROID.X!", "PYTHON_9.3")
            arcpy.CalculateField_management(networkVrtx, "FROM_Y_Coord",
                                            "!SHAPE.CENTROID.Y!", "PYTHON_9.3")
            arcpy.CalculateField_management(
                networkVrtx, "FROM_NODE",
                """str('!FROM_X_Coord!') + "_" + str(round(float('!FROM_Y_Coord!'),4))""",
                "PYTHON_9.3")
            arcpy.Delete_management(networkVrtx_lyr)
            del tmpVrtx
        else:
            arcpy.MakeFeatureLayer_management(networkVrtx, networkVrtx_lyr)
            arcpy.SelectLayerByAttribute_management(networkVrtx_lyr,
                                                    "NEW_SELECTION",
                                                    """"PointType" IS NULL""")
            arcpy.CalculateField_management(networkVrtx_lyr, "PointType",
                                            "'" + type + "'", "PYTHON_9.3")
            arcpy.CalculateField_management(networkVrtx_lyr, "TO_X_Coord",
                                            "!SHAPE.CENTROID.X!", "PYTHON_9.3")
            arcpy.CalculateField_management(networkVrtx_lyr, "TO_Y_Coord",
                                            "!SHAPE.CENTROID.Y!", "PYTHON_9.3")
            arcpy.CalculateField_management(
                networkVrtx_lyr, "TO_NODE",
                """str('!TO_X_Coord!') + "_" + str(round(float('!TO_Y_Coord!'),4))""",
                "PYTHON_9.3")
            arcpy.Delete_management(networkVrtx_lyr)
            del tmpVrtx
    return networkVrtx
示例#16
0
def Voronoi_Lines(inFC,Output):

    try:
    
        #Variables
        temp = 'in_memory\\tempdata'
        temp2 = 'in_memory\\tempdata2'

        arcpy.FeatureVerticesToPoints_management(inFC,temp, "ALL")
        arcpy.CreateThiessenPolygons_analysis(temp, temp2, "ONLY_FID")
        arcpy.PolygonToLine_management(temp2, temp)
        arcpy.Intersect_analysis([temp, inFC], temp2, "ALL")
        arcpy.MultipartToSinglepart_management(temp2, Output)

        fieldNames = []
        for field in arcpy.ListFields(Output):
            if not field.required and field.name != 'Id':
                fieldNames.append(field.name)
        arcpy.DeleteField_management(Output,fieldNames)

        Centerline(Output)
        Width(Output,inFC)
        Deviation(Output)
        
    except Exception,e:
        arcpy.AddError('%s'%(e))
示例#17
0
def get_nodes_from_links(links_shp):
    im_t = "in_memory/pp"
    arcpy.FeatureVerticesToPoints_management(links_shp, im_t, "BOTH_ENDS")
    arcpy.DeleteIdentical_management(im_t, ['Shape'])
    arcpy.AddField_management(im_t, "_ID_", "LONG")
    arcpy.CalculateField_management(im_t, "_ID_", '!FID!', "PYTHON")
    fieldnames = [x for x in [f.name for f in arcpy.ListFields(im_t)] if x not in ['FID', 'Shape', 'OID', "_ID_"]]
    arcpy.DeleteField_management(im_t, fieldnames)
    return im_t
示例#18
0
def GenerateNetworkFormDEM(DEMbuf, FlowDirFile, FlowAccFile, threshold,
                           folder):
    env.workspace = folder
    arcpy.gp.overwriteOutput = 1
    arcpy.CheckOutExtension("Spatial")

    if float(threshold) < MINI_VALUE:
        threshold = float(
            str(arcpy.GetRasterProperties_management(FlowAccFile,
                                                     "MAXIMUM"))) / 100
    Exec = "Con(\"%s\" > %s,1)" % (FlowAccFile, threshold)
    arcpy.gp.RasterCalculator_sa(Exec, "streamnet")
    Stream_shp = "streamnet.shp"
    arcpy.sa.StreamToFeature("streamnet", FlowDirFile, Stream_shp,
                             "NO_SIMPLIFY")
    StreamLinks = arcpy.sa.StreamLink("streamnet", FlowDirFile)
    StreamLinks.save("streamlinks")
    StreamLinks_shp = "streamnet.shp"
    arcpy.sa.StreamToFeature("streamlinks", FlowDirFile, StreamLinks_shp,
                             "NO_SIMPLIFY")
    StreamOrder = arcpy.sa.StreamOrder("streamnet", FlowDirFile, "STRAHLER")
    StreamOrder.save("streamorder")
    StreamOrder_shp = "StreamOrder.shp"
    arcpy.sa.StreamToFeature("streamorder", FlowDirFile, StreamOrder_shp,
                             "NO_SIMPLIFY")
    arcpy.FeatureVerticesToPoints_management(StreamOrder_shp,
                                             "StreamNDsStart.shp", "START")
    arcpy.FeatureVerticesToPoints_management(StreamOrder_shp,
                                             "StreamNDsEnd.shp", "END")
    arcpy.AddXY_management("StreamNDsStart.shp")
    arcpy.AddXY_management("StreamNDsEnd.shp")
    arcpy.sa.ExtractValuesToPoints("StreamNDsStart.shp", DEMbuf,
                                   "StreamNDsElevStart.shp", "NONE",
                                   "VALUE_ONLY")
    arcpy.sa.ExtractValuesToPoints("StreamNDsEnd.shp", DEMbuf,
                                   "StreamNDsElevEnd.shp", "NONE",
                                   "VALUE_ONLY")
    Watershed = arcpy.sa.Watershed(FlowDirFile, "streamlinks", "VALUE")
    Watershed.save("watershed")
    arcpy.RasterToPolygon_conversion("watershed", "Watershed.shp",
                                     "NO_SIMPLIFY", "VALUE")
    WatershedFile = folder + os.sep + "watershed"
    StreamFile = folder + os.sep + "streamlinks"
    return (StreamFile, WatershedFile)
示例#19
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")
示例#20
0
def vulnerabilite_rr(in_rr_layer, in_ras, vul_infra_route, id_vul_infra_route):
    # Selection des segments touches par l'alea
    # inRRLayer = 'inRRLayer'
    # arcpy.MakeFeatureLayer_management(inRR, inRRLayer)
    # arcpy.SelectLayerByLocation_management(inRRLayer,"INTERSECT",maskZIl)

    # Copie des segments selectionnes du rr pour l'analyse de la fonctionnalite
    zi_rr2 = 'zi_rr3a'  # A modifier, Generer un nom automatiquement
    arcpy.CopyFeatures_management(in_rr_layer, zi_rr2)
    arcpy.Densify_edit(zi_rr2, "DISTANCE", "10")

    # Conversion des vertex en points
    arcpy.AddMessage('  Conversion des vertex en points')
    rr_pts = 'RRpts'  # A modifier, Generer un nom automatiquement
    arcpy.FeatureVerticesToPoints_management(zi_rr2, rr_pts, 'ALL')

    # Extraction de la profondeur de submersion aux points
    arcpy.AddMessage('  Extraction de la profondeur de submersion')
    rr_pts_extract = 'RRptsExtract'  # A modifier, Generer un nom automatiquement
    arcpy.sa.ExtractValuesToPoints(rr_pts, in_ras, rr_pts_extract)

    # Changement des valeurs NoData (-9999 ou moins) pour la valeur 0
    rows = arcpy.da.UpdateCursor(rr_pts_extract, ["RASTERVALU"])
    for row in rows:
        if row[0] <= -9999:
            row[0] = 0
        rows.updateRow(row)
    del rows

    arcpy.AddMessage(
        '  Comparaison des profondeur de submersion avec les seuils')
    out_stats_table = 'stats'
    arcpy.Statistics_analysis(
        rr_pts_extract, out_stats_table, [["RASTERVALU", "MAX"]],
        [id_vul_infra_route, 'PRECISION']
    )  # MAX (hauteurs inondation positives) ou MIN (hauteurs negatives) # , 'CRCC_NO_SEQ'

    for f in arcpy.ListFields(out_stats_table):
        if 'max' in f.name.lower():  # min ou max
            maxfield = f.name
            break

    status_rr = {}

    rows = arcpy.da.SearchCursor(out_stats_table,
                                 [id_vul_infra_route, maxfield, "PRECISION"])
    for row in rows:
        # statusRR[identifiant_route] = niveau_de_fonctionnalite[hauteur eau, inonde/non-inonde]
        # print row.getValue(IDvulInfraRou)
        status_rr[row[0]] = [
            row[1], find_class(row[1], vul_infra_route[row[2]])
        ]  # '-' en face du row de "findClass( ICI row.getValue (maxfield)" #[row.CRCC_NO_SEQ]
    del rows

    return status_rr
def processShapefile(shapeName, defaultPath, record, extraDir, option = None):

    if option == 0:
        pass
    elif option == 1:
        shapeName = validateInput("shapeName", "Shapefile name: ", defaultPath, record, extraDir)
    else:
        record = validateInput("record","Record Number: ", defaultPath)
        extraDir = validateInput("extraDir", "Extra directory: ", defaultPath, record)
        shapeName = validateInput("shapeName", "Shapefile name: ", defaultPath, record, extraDir)

    shpExt = shapeName+'.shp'

    if extraDir == '':
        inlayer = os.path.join(defaultPath,record,shpExt)
        outBoundingBox = os.path.join(defaultPath,record,shapeName+'_BB.shp')
        outBoundingBoxVertices = os.path.join(defaultPath,record,shapeName+'_BB_Vert.shp')
    else:
        inlayer = os.path.join(defaultPath,record,extraDir,shpExt)
        outBoundingBox = os.path.join(defaultPath,record,extraDir,shapeName+'_BB.shp')
        outBoundingBoxVertices = os.path.join(defaultPath,record,extraDir,shapeName+'_BB_Vert.shp')

    print 'Deleting BB if found'
    if arcpy.Exists(outBoundingBox):
        arcpy.Delete_management(outBoundingBox)
    if arcpy.Exists(outBoundingBoxVertices):
        arcpy.Delete_management(outBoundingBoxVertices)

    print 'Creating bounding box'
    # Use MinimumBoundingGeometry function to get an envelop area
    arcpy.MinimumBoundingGeometry_management(inlayer, outBoundingBox,
                                             "ENVELOPE")

    print 'Convert vertices to points'
    # Convert vertices to points
    arcpy.FeatureVerticesToPoints_management(outBoundingBox, outBoundingBoxVertices, 'All')

    print 'Calculate X/Y for vertices'
    # Calculate X/Y for vertices
    arcpy.AddXY_management(outBoundingBoxVertices)

    xField = "Point_X"
    xMinValue = arcpy.SearchCursor(outBoundingBoxVertices, "", "", "", xField + " A").next().getValue(xField) #Get 1st row in ascending cursor sort
    xMaxValue = arcpy.SearchCursor(outBoundingBoxVertices, "", "", "", xField + " D").next().getValue(xField) #Get 1st row in descending cursor sort

    yField = "Point_Y"
    yMinValue = arcpy.SearchCursor(outBoundingBoxVertices, "", "", "", yField + " A").next().getValue(yField) #Get 1st row in ascending cursor sort
    yMaxValue = arcpy.SearchCursor(outBoundingBoxVertices, "", "", "", yField + " D").next().getValue(yField) #Get 1st row in descending cursor sort

    if arcpy.Exists(outBoundingBox):
        arcpy.Delete_management(outBoundingBox)
    if arcpy.Exists(outBoundingBoxVertices):
        arcpy.Delete_management(outBoundingBoxVertices)

    return {'xMin':xMinValue, 'xMax':xMaxValue,'yMin':yMinValue, 'yMax':yMaxValue}
示例#22
0
def getbbox(polygonfeat, itemgeo, isprj):

    try:
        '''
        Find the intersection between footprint polygon and clipping feature
        '''
        #Create point list to hold the point object
        point = arcpy.Point()
        array = arcpy.Array()
        itempoly = []

        #Construct polygon feature from points
        for coordPair in itemgeo:
            point.X = coordPair[0]
            point.Y = coordPair[1]
            array.add(point)

        itempoly.append(arcpy.Polygon(array))
        arcpy.env.overwriteOutput = 1
        fpfeat = "in_memory/fpfeat"
        #fpfeat = r"e:\temp\clipandship\fpfeat.shp"
        arcpy.CopyFeatures_management(itempoly, fpfeat)
        arcpy.DefineProjection_management(fpfeat, isprj)

        #Find intersection between clipping polygon and footprint
        #Note: if two features class are in different projection, output should be
        #      in image service projection
        interfeat = "in_memory/interfeat"
        #interfeat = r"e:\temp\clipandship\interfeat.shp"
        arcpy.Intersect_analysis(fpfeat + ";" + polygonfeat, interfeat)

        #Convert the intersecting polygon to vertice points
        verticespnt = "in_memory/verpnt"
        arcpy.FeatureVerticesToPoints_management(interfeat, verticespnt)

        #Get intersection polygon vertices to a list
        arcpy.AddXY_management(verticespnt)
        verticesxy = []
        fieldNames = ["POINT_X", "POINT_Y"]
        with arcpy.da.SearchCursor(verticespnt, fieldNames) as rows:
            for row in rows:
                verticesxy.append([row[0], row[1]])

        desc = arcpy.Describe(interfeat)
        bbox = []
        bbox.append(desc.extent.XMin)
        bbox.append(desc.extent.YMin)
        bbox.append(desc.extent.XMax)
        bbox.append(desc.extent.YMax)

        return bbox

    except:
        arcpy.AddError("ERROR: Failure in get bounding box")
示例#23
0
def get_old_node_connections_dict(links):
    arcpy.FeatureVerticesToPoints_management(links, temp1, "BOTH_ENDS")
    arcpy.SpatialJoin_analysis(temp1, old_nodes_shp, temp2, "JOIN_ONE_TO_ONE",
                               "KEEP_ALL", "", "CLOSEST")
    nearfid_to_fips_fid = [[row.getValue("ORIG_FID"),
                            row.getValue("ID_1")]
                           for row in arcpy.SearchCursor(temp2)]
    a = {}
    for linkid, nodeid in nearfid_to_fips_fid:
        a.setdefault(linkid, []).append(nodeid)
    return a
def makeNodeName2ArcsDict(caf, fields):
    # takes arc fc, list of fields (e.g. [Left_MapUnit, Right_MapUnit] )
    #   makes to and from node fcs, concatenates, sorts, finds arc-ends
    #   that share common XY values
    # returns dictionary of arcs at each node, keyed to nodename
    #    i.e., dict[nodename] = [[arc1 fields], [arc2 fields],...]
    fv1 = os.path.dirname(caf) + '/xxxNfv1'
    fv2 = os.path.dirname(caf) + '/xxxNfv12'

    lenFields = len(fields)
    addMsgAndPrint('  making endpoint feature classes')
    testAndDelete(fv1)
    arcpy.FeatureVerticesToPoints_management(caf, fv1, 'BOTH_ENDS')
    addMsgAndPrint('  adding XY values and sorting by XY')
    arcpy.AddXY_management(fv1)
    testAndDelete(fv2)
    arcpy.Sort_management(fv1, fv2,
                          [["POINT_X", "ASCENDING"], ["POINT_Y", "ASCENDING"]])
    ##fix fields statement and following field references
    fields.append('SHAPE@XY')
    indexShape = len(fields) - 1

    isFirst = True
    nArcs = 0
    nodeList = []
    with arcpy.da.SearchCursor(fv2, fields) as cursor:
        for row in cursor:
            x = row[indexShape][0]
            y = row[indexShape][1]
            arcFields = row[0:lenFields]
            if isFirst:
                isFirst = False
                lastX = x
                lastY = y
                arcs = [arcFields]
            elif abs(x - lastX) < searchRadius and abs(y -
                                                       lastY) < searchRadius:
                arcs.append(arcFields)
            else:
                nodeList.append([nodeName(lastX, lastY), arcs])
                lastX = x
                lastY = y
                arcs = [arcFields]
        nodeList.append([nodeName(lastX, lastY), arcs])

    addMsgAndPrint('  ' + str(len(nodeList)) + ' distinct nodes')
    addMsgAndPrint('  cleaning up')
    for fc in fv1, fv2:
        testAndDelete(fc)

    nodeDict = {}
    for n in nodeList:
        nodeDict[n[0]] = n[1]
    return nodeDict
示例#25
0
def RillIndexCalc(StreamOrderFile, DEMbuf, tempDir, StatsDir):
    print "Calculating rill indexes..."
    #input StreamOrderFile and DEMbuf,output CSV files.
    env.workspace = tempDir
    arcpy.gp.overwriteOutput = 1
    arcpy.CheckOutExtension("Spatial")
    dem_des = arcpy.gp.describe(DEMbuf)
    env.extent = dem_des.Extent
    arcpy.FeatureVerticesToPoints_management(StreamOrderFile,
                                             "StreamNDsStart.shp", "START")
    arcpy.FeatureVerticesToPoints_management(StreamOrderFile,
                                             "StreamNDsEnd.shp", "END")
    arcpy.AddXY_management("StreamNDsStart.shp")
    arcpy.AddXY_management("StreamNDsEnd.shp")
    arcpy.sa.ExtractValuesToPoints("StreamNDsStart.shp", DEMbuf,
                                   "StreamNDsElevStart.shp", "NONE",
                                   "VALUE_ONLY")
    arcpy.sa.ExtractValuesToPoints("StreamNDsEnd.shp", DEMbuf,
                                   "StreamNDsElevEnd.shp", "NONE",
                                   "VALUE_ONLY")
示例#26
0
def addReachDist(given_stream):
    """
    Calculates the ReachDist attribute using StreamID
    :param given_stream:
    :return:
    """
    print "Adding Reach Distance Attribute..."
    fields = [f.name for f in arcpy.ListFields(given_stream)]
    if 'ReachID' not in fields:
        arcpy.AddField_management(given_stream, "ReachID", "LONG")
    with arcpy.da.UpdateCursor(given_stream, ['FID', 'ReachID']) as cursor:
        for row in cursor:
            row[1] = row[0]
            cursor.updateRow(row)

    # get distance along route (LineID) for segment midpoints
    midpoints = arcpy.FeatureVerticesToPoints_management(given_stream, 'in_memory/midpoints', "MID")

    seg_network_dissolve = arcpy.Dissolve_management(given_stream, 'in_memory/seg_network_dissolve', 'StreamID', '',
                                                     'SINGLE_PART', 'UNSPLIT_LINES')

    arcpy.AddField_management(seg_network_dissolve, 'From_', 'DOUBLE')
    arcpy.AddField_management(seg_network_dissolve, 'To_', 'DOUBLE')
    with arcpy.da.UpdateCursor(seg_network_dissolve, ['SHAPE@Length', 'From_', 'To_']) as cursor:
        for row in cursor:
            row[1] = 0.0
            row[2] = row[0]
            cursor.updateRow(row)

    arcpy.CreateRoutes_lr(seg_network_dissolve, 'StreamID', 'in_memory/flowline_route', 'TWO_FIELDS', 'From_', 'To_')
    routeTbl = arcpy.LocateFeaturesAlongRoutes_lr(midpoints, 'in_memory/flowline_route', 'StreamID',
                                                  1.0,
                                                  os.path.join(os.path.dirname(given_stream), 'tbl_Routes.dbf'),
                                                  'RID POINT MEAS')

    distDict = {}
    # add reach id distance values to dictionary
    with arcpy.da.SearchCursor(routeTbl, ['ReachID', 'MEAS']) as cursor:
        for row in cursor:
            distDict[row[0]] = row[1]

    # populate dictionary value to output field by ReachID
    arcpy.AddField_management(given_stream, 'ReachDist', 'DOUBLE')
    with arcpy.da.UpdateCursor(given_stream, ['ReachID', 'ReachDist']) as cursor:
        for row in cursor:
            aKey = row[0]
            row[1] = distDict[aKey]
            cursor.updateRow(row)

    arcpy.Delete_management('in_memory')
示例#27
0
 def onLine(self, line_geometry):
     self.line_geometry = line_geometry
     try:
         arcpy.CheckOutExtension('SPATIAL')
     except Exception as e:
         arcpy.AddError('Spatial Extension required.\r\n' + str(e))
     raster_layer = raster_layer_menu.raster_layer
     poly = self.line_geometry
     use_units = meas_units.units
     poly_length = poly.getLength(units='{}'.format(use_units))
     dens_distance = int(poly_length / 400)
     arcpy.env.overwriteOutput = True
     arcpy.CopyFeatures_management(poly, 'in_memory\\Route')
     arcpy.Densify_edit(r'in_memory\Route', 'DISTANCE',
                        str(dens_distance) + ' {}'.format(use_units))
     arcpy.FeatureVerticesToPoints_management('in_memory\\Route',
                                              'in_memory\\poly_feature',
                                              'ALL')
     pts = [
         list(i[0]) for i in arcpy.da.SearchCursor(
             'in_memory\\poly_feature', 'SHAPE@XY')
     ]
     #Derive elevation values from DEM specified.
     arcpy.sa.ExtractMultiValuesToPoints('in_memory\\poly_feature',
                                         [[raster_layer, 'Z']])
     arcpy.CheckInExtension('SPATIAL')
     elev = [
         i[0] for i in arcpy.da.SearchCursor('in_memory\\poly_feature', 'Z')
     ]
     seg_length = int(poly_length / len(elev))
     splits = []
     for i in range(len(elev)):
         splits.append(i * seg_length)
     arcpy.Delete_management('poly_feature')
     #Produce and export elevation profile.
     fig, ax = plt.subplots()
     fig.canvas.set_window_title('Elevation Profile')
     ax.plot(splits, elev, linewidth=2, color='g')
     fig.add_axes(ax)
     plt.xlabel('Feet Along Route')
     plt.ylabel('Elevation')
     try:
         plt.savefig(
             pythonaddins.SaveDialog(
                 'Save Elevation Profile', 'Profile.png',
                 os.path.dirname(
                     arcpy.mapping.MapDocument("CURRENT").filePath)))
     except:
         pythonaddins.MessageBox(
             'Error during save. Click reset and re-run process.', 'Alert')
示例#28
0
def select_identify_point(pointlocation):
    try:
        selectP = arcpy.FeatureVerticesToPoints_management(
            pipeline, "selectP" + pointlocation, pointlocation)
        #print selectP
        resultP = arcpy.SpatialJoin_analysis(
            selectP, controlP, "resultP" + pointlocation)
        # print os.path.abspath( "resultP" + pointlocation)
        #print os.path.(resultP)
        # print type(resultP)
        # print resultP[0].split("\\")[-1]

        return resultP
    except arcpy.ExecuteError as e:
        print e
示例#29
0
def snap_junction_points(from_line_lyr, to_line_lyr, search_distance):
    """
    Shifts junction points (i.e. tributary confluences) in the 'From' network to same coordinates
    of junction points in the 'To' network, found within a user-specified search distance.
    :param from_line_lyr: polyline layer representing 'From' stream network
    :param to_line_lyr: polyline layer representing 'To' stream network
    :param search_distance: buffer distance around each 'To' junction point, in meters
    :return: line feature class
    """

    tempWorkspace = "in_memory"

    arcpy.AddMessage("GNAT TLA: snapping junction points in 'From' network to 'To' network")

    snapped_from_line = gis_tools.newGISDataset(tempWorkspace, "snapped_from_line")
    arcpy.CopyFeatures_management(from_line_lyr, snapped_from_line)
    snap_line_lyr  = gis_tools.newGISDataset("Layer", "snap_line_lyr")
    arcpy.MakeFeatureLayer_management(snapped_from_line, snap_line_lyr)

    list_field_objects = arcpy.ListFields(snap_line_lyr)
    list_from_fields = [f.name for f in list_field_objects if f.type != "OID" and f.type != "Geometry"]

    # Plot junction points for 'From' and 'To' stream networks
    from_junction_pnts = plot_junction_points(snap_line_lyr, "from")
    to_junction_pnts = plot_junction_points(to_line_lyr, "to")
    lyr_from_junc_pnts = gis_tools.newGISDataset("Layer", "lyr_from_junc_pnts")
    arcpy.MakeFeatureLayer_management(from_junction_pnts, lyr_from_junc_pnts)

    from_line_oidfield = arcpy.Describe(snap_line_lyr).OIDFieldName

    from_vrtx = gis_tools.newGISDataset(tempWorkspace, "from_vrtx")
    arcpy.FeatureVerticesToPoints_management(snap_line_lyr, from_vrtx, point_location="ALL")
    arcpy.AddXY_management(from_vrtx)
    from_vrtx_lyr = gis_tools.newGISDataset("Layer", "from_vrtx_lyr")
    arcpy.MakeFeatureLayer_management(from_vrtx, from_vrtx_lyr)
    arcpy.Near_analysis(from_vrtx_lyr, to_junction_pnts, search_distance, "LOCATION")
    arcpy.SelectLayerByLocation_management(from_vrtx_lyr, "INTERSECT", lyr_from_junc_pnts, "#", "NEW_SELECTION")
    update_xy_coord(from_vrtx_lyr)
    arcpy.MakeXYEventLayer_management(from_vrtx_lyr, "POINT_X", "POINT_Y", "xy_events", from_vrtx_lyr)
    xy_events_pnt = gis_tools.newGISDataset(tempWorkspace, "xy_events_pnt")
    arcpy.CopyFeatures_management("xy_events", xy_events_pnt)
    arcpy.MakeFeatureLayer_management(xy_events_pnt, "xy_events_lyr")
    xy_line = gis_tools.newGISDataset(tempWorkspace, "xy_line")
    arcpy.PointsToLine_management("xy_events_lyr", xy_line, "ORIG_FID")
    arcpy.JoinField_management(xy_line, "ORIG_FID", snap_line_lyr, from_line_oidfield, list_from_fields)
    arcpy.DeleteFeatures_management(snap_line_lyr)
    arcpy.Append_management(xy_line, snap_line_lyr, "NO_TEST")
    return snap_line_lyr
示例#30
0
def getQueryFields(serviceURL, polygonfeat):

    try:
        arcpy.AddMessage("Getting raster IDs and attributes by location...")
        # Convert polygon feature class to JSON geometry
        # Step 1: convert polygon to points
        arcpy.env.overwriteOutput = 1
        verticespnt = "in_memory/verpnt"
        arcpy.FeatureVerticesToPoints_management(polygonfeat, verticespnt)
        # Step 2: add coordinates of point to the feature class
        arcpy.AddXY_management(verticespnt)
        # Step 3: Read the point coordinate from feature class to an array
        verticesxy = []
        fieldNames = ["POINT_X", "POINT_Y"]
        with arcpy.da.SearchCursor(verticespnt, fieldNames) as rows:
            for row in rows:
                verticesxy.append([row[0], row[1]])

        # Get the spatial reference code of the polygon feature
        desc = arcpy.Describe(polygonfeat)
        factcode = desc.SpatialReference.FactoryCode

        # Constructing Query REST request
        geometry = "&geometry={ 'rings': [" + str(
            verticesxy) + "],'spatialReference':{'wkid':" + str(
                factcode) + "}}&geometryType=esriGeometryPolygon"
        content = "where=CATEGORY=1" + geometry + "&spatialRel=esriSpatialRelIntersects&outFields=*&returnGeometry=false&f=json"

        post_data = unicode(content, "utf-8")

        headers = {}
        headers["Content-Type"] = "application/x-www-form-urlencoded"

        serviceURL = serviceURL.replace("arcgis/services",
                                        "arcgis/rest/services") + "/query"

        # Send Query request to get item attributes
        req = urllib2.Request(serviceURL, post_data, headers)
        response_stream = urllib2.urlopen(req)
        response = response_stream.read()

        jsondict = json.loads(response)
        itemfields = jsondict["fields"]
        itemfeatures = jsondict["features"]

        return itemfields, itemfeatures
    except:
        arcpy.AddError("Failure in getQueryFields function")