def main(): # Setup script path and output folder outWorkspace = flmc.SetupWorkspace("FLM_RLA_output") arcpy.env.workspace = outWorkspace arcpy.env.overwriteOutput = True # Load arguments from file args = flmc.GetArgs("FLM_RLA_params.txt") # Tool arguments Input_Lines = args[0].rstrip() Input_Raster = args[1].rstrip() SamplingType = args[2].rstrip() Measure_Interval = float(args[3].rstrip()) Segment_Length = float(args[4].rstrip()) Tolerance_Radius = float(args[5].rstrip()) Sampling_Method = args[6].rstrip() Attributed_Segments = args[7].rstrip() # Local variables: FLM_RLA_Measure_Points = outWorkspace + "\\FLM_RLA_Measure_Points.shp" FLM_RLA_Attributed_Points = outWorkspace + "\\FLM_RLA_Attributed_Points.shp" flmc.log("Generating sample points along lines...") arcpy.GeneratePointsAlongLines_management(Input_Lines, FLM_RLA_Measure_Points, "DISTANCE", Measure_Interval, "", "") flmc.logStep("Spawning sample points") flmc.log("Extracting raster values at sample points...") arcpy.gp.ExtractValuesToPoints_sa(FLM_RLA_Measure_Points, Input_Raster, FLM_RLA_Attributed_Points) flmc.logStep("Raster sampling") # Find RASTERVALU field and set user defined sampling (merge) method fieldmappings = arcpy.FieldMappings() fieldmappings.addTable(FLM_RLA_Attributed_Points) RastervaluIndex = fieldmappings.findFieldMapIndex("RASTERVALU") fieldmap = fieldmappings.getFieldMap(RastervaluIndex) fieldmap.mergeRule = Sampling_Method #Set sampling method (Mean, Minimum, Maximum, Standard Deviation, Etc..) fieldmappings = arcpy.FieldMappings() fieldmappings.addFieldMap(fieldmap) flmc.log("Splitting lines...") FLM_RLA_Segmented_Lines = flma.FlmLineSplit(outWorkspace, Input_Lines, SamplingType, Segment_Length, Tolerance_Radius) flmc.logStep("Line split") flmc.log("Generating raster statistics along line segments") arcpy.SpatialJoin_analysis(FLM_RLA_Segmented_Lines, FLM_RLA_Attributed_Points, Attributed_Segments, "JOIN_ONE_TO_ONE", "KEEP_COMMON", fieldmappings, "INTERSECT", Tolerance_Radius, "")
def generate_points_along_lines(self, o_dir): path_split = os.path.splitext(self.line_shp.split("\\")[-1]) print path_split print path_split[0] o_file = "{}\{}_point.shp".format(o_dir, path_split[0].decode("utf-8")) print o_file arcpy.GeneratePointsAlongLines_management(self.line_shp, o_file, 'DISTANCE', Distance='100 meters', Include_End_Points=False)
def IDW_REM(DEM, NHDFlowline, RiverName, PointDistance_meters, SearchRadius, Output_gdb_path): # Set environment arcpy.env.workspace = Output_gdb_path # Names for selecting and saving rivername = RiverName.replace(' ', '') # Create path object for Output_gdb_path Output_gdb_filepath = Path(Output_gdb_path) # Create Output_gdb if it does not already exist if not Output_gdb_filepath.exists(): arcpy.CreateFileGDB_management(str(Output_gdb_filepath.parent), str(Output_gdb_filepath.name)) # Define River Channel and create feature class with single line feature river_flowline = arcpy.SelectLayerByAttribute_management( NHDFlowline, 'New_Selection', "GNIS_Name = '" + RiverName + "'") river_name_path = str(Output_gdb_filepath / rivername) arcpy.CopyFeatures_management(river_flowline, river_name_path) diss_river_name_path = str(Output_gdb_filepath / str(rivername + '_diss')) arcpy.Dissolve_management(river_name_path, diss_river_name_path) # Generate points along channel line river_points_path = str(Output_gdb_filepath / str(rivername + '_points')) arcpy.GeneratePointsAlongLines_management( diss_river_name_path, river_points_path, 'DISTANCE', Distance=(str(PointDistance_meters) + ' meters')) # Extract elevation to points river_points_elev = str(Output_gdb_filepath / str(rivername + '_elev')) arcpy.sa.ExtractValuesToPoints(river_points_path, DEM, river_points_elev) # IDW to create detrended DEM idw_detrended = str(Output_gdb_filepath / str(rivername + '_IDW_detrend')) DEM_cellsize = float( str(arcpy.GetRasterProperties_management(DEM, "CELLSIZEX"))) idw = arcpy.sa.Idw(river_points_elev, 'RASTERVALU', DEM_cellsize, 2, RadiusFixed(SearchRadius, 0)) idw.save(idw_detrended) # Create Relative Elevation Model relative_elevation_model = str( str(Output_gdb_filepath / str(rivername + '_RelElevModel'))) REM = arcpy.sa.Minus(DEM, idw_detrended) REM.save(relative_elevation_model)
def generate_sample_points(in_fc, out_fc, sample_percentage=10): """This will take in a feature class and return a feature class of points. Polygons and points have feature to point used, and line files have sample points created along the line in lengths an equal distance apart as close to the distance set in this function in the units of the current projection.""" describe_obj = arcpy.Describe(in_fc) shape_type = str(describe_obj.shapeType) if shape_type == "Polyline": arcpy.GeneratePointsAlongLines_management(in_fc, out_fc, "PERCENTAGE", None, int(sample_percentage), 'END_POINTS') else: arcpy.FeatureToPoint_management(in_fc, out_fc, True) return out_fc
def split_line(workspacePath, tempGDB, inputFlsplit, splitDistance): import arcpy import os arcpy.env.workspace = workspacePath includeEndPoints = 'NO_END_POINTS' arcpy.env.overwriteOutput = True mxd = arcpy.mapping.MapDocument('CURRENT') df = arcpy.mapping.ListDataFrames(mxd)[0] #Generate points along line for split arcpy.SetProgressorLabel("Generating points to split by...") outputPointFC = os.path.join(tempGDB, inputFlsplit + "Points") arcpy.GeneratePointsAlongLines_management( inputFlsplit, outputPointFC, 'DISTANCE', splitDistance, Include_End_Points=includeEndPoints) #Split line into separate segments based on previous points with a 2 meter radius tolerance around the point arcpy.SetProgressorLabel("Splitting initial line into segments...") outputFCsplit = os.path.join(tempGDB, inputFlsplit + "Split") arcpy.SplitLineAtPoint_management(inputFlsplit, outputPointFC, outputFCsplit, search_radius='1 Meters') # Get filename part of outputFCsplit flName = os.path.basename(outputFCsplit) #Create a feature layer to be used for AddGeometryAttributes arcpy.MakeFeatureLayer_management(outputFCsplit, flName) #Create a layer object from the feature layer #tempLayer = arcpy.mapping.Layer(flName) #Add attributes for line start,mid, and end to determine order of segments for new feature classes; for some reason line segments are not in proper order arcpy.AddGeometryAttributes_management(flName, "LINE_START_MID_END") #Add layer to the map #arcpy.mapping.AddLayer(df,tempLayer) return outputFCsplit
def __init__(self, inputfc, terreng, tempfc_punkter): self.inputfc = inputfc self.terreng = terreng self.tempfc_punkter = tempfc_punkter #Langer punkt kvar 1 meter langs input profil arcpy.GeneratePointsAlongLines_management(inputfc, tempfc_punkter, 'DISTANCE', Distance='1 Meters') #Legger z koordinater på punkter ut frå valt raster surface arcpy.ddd.AddSurfaceInformation(tempfc_punkter, terreng, 'Z', 'BILINEAR') #Tar ut koordinatlister frå puntkter feature class with arcpy.da.SearchCursor(tempfc_punkter, ["SHAPE", 'Z']) as cursor: x_list = [] y_list = [] z_list = [] for row in cursor: x, y = row[0] x_list.append(x) y_list.append(y) z_list.append(row[1]) #Etablerer Pandas dataframe for forenkling av vidare databehandling self.df = pd.DataFrame(list(zip(x_list, y_list, z_list)), columns=['X', 'Y', 'Z']) #Regner ut distanse mellom punkter (muligens unødvening, kan kanskje bruke index #til punkter istadenfor? Sidan kvar punkt er etalbert per meter?. self.df['DIST'] = np.sqrt(((self.df.X - self.df.X.shift(1))**2) + ((self.df.Y - self.df.Y.shift(1))**2)) self.df['M'] = self.df.DIST + self.df.DIST.shift(1) self.df.loc[0, 'M'] = 0 self.df.loc[0, 'DIST'] = 0 self.df.loc[1, 'M'] = self.df.loc[1, 'DIST'] self.df.loc[0, 'H'] = 0 #Regner ut lengden basert på avstand mellom punkter for i in range(2, len(self.df)): self.df.loc[i, 'M'] = self.df.loc[i - 1, 'DIST'] + self.df.loc[i - 1, 'M'] #Runder av meterverdien self.df['M'] = self.df['M'].round(0)
def FlmLineSplit(workspace, Input_Lines, SamplingType, Segment_Length, Tolerance_Radius): if SamplingType == "IN-FEATURES": return Input_Lines arcpy.env.workspace = workspace arcpy.env.overwriteOutput = True FLA_Line_Unsplit = workspace + "\\FLA_Line_Unsplit.shp" FLA_Line_Unsplit_Single = workspace + "\\FLA_Line_Unsplit_Single.shp" FLA_Line_Split_Vertices = workspace + "\\FLA_Line_Split_Vertices.shp" FLA_Segmented_Lines = workspace + "\\FLA_Segmented_Lines.shp" flmc.log("FlmLineSplit: Executing UnsplitLine") flmc.log("Input_Lines: " + Input_Lines) flmc.log("FLA_Line_Unsplit: " + FLA_Line_Unsplit) # TODO: resume UnsplitLine after defining disolve fields # arcpy.UnsplitLine_management(Input_Lines, FLA_Line_Unsplit) arcpy.Copy_management(Input_Lines, FLA_Line_Unsplit) arcpy.MultipartToSinglepart_management(FLA_Line_Unsplit, FLA_Line_Unsplit_Single) #arcpy.Delete_management(FLA_Line_Unsplit) if SamplingType == "ARBITRARY": arcpy.GeneratePointsAlongLines_management(FLA_Line_Unsplit_Single, FLA_Line_Split_Vertices, "DISTANCE", Segment_Length, "", "NO_END_POINTS") elif SamplingType == "LINE-CROSSINGS": arcpy.Intersect_analysis(PathFile(FLA_Line_Unsplit_Single), PathFile(FLA_Line_Split_Vertices), join_attributes="ALL", cluster_tolerance=Tolerance_Radius, output_type="POINT") if SamplingType != "WHOLE-LINE": # "ARBITRARY" or "LINE-CROSSINGS" arcpy.SplitLineAtPoint_management(FLA_Line_Unsplit_Single, FLA_Line_Split_Vertices, FLA_Segmented_Lines, Tolerance_Radius) arcpy.Delete_management(FLA_Line_Unsplit_Single) arcpy.Delete_management(FLA_Line_Split_Vertices) else: # "WHOLE-LINE" FLA_Segmented_Lines = FLA_Line_Unsplit_Single return FLA_Segmented_Lines
splitDistance = arcpy.GetParameterAsText(3) includeEndPoints = 'NO_END_POINTS' inputLineFLsplit = arcpy.GetParameterAsText(1) inputPointFLsplit = arcpy.GetParameterAsText(2) outputFCsplit = arcpy.GetParameterAsText(4) arcpy.env.overwriteOutput = True mxd = arcpy.mapping.MapDocument('CURRENT') df = arcpy.mapping.ListDataFrames(mxd)[0] #Generate points along line for split arcpy.SetProgressorLabel("Generating points to split by...") arcpy.GeneratePointsAlongLines_management(inputLineFLpoints, outputPointFC, 'DISTANCE', splitDistance, Include_End_Points=includeEndPoints) #Split line into separate segments based on previous points with a 2 meter radius tolerance around the point arcpy.SetProgressorLabel("Splitting initial line into segments...") arcpy.SplitLineAtPoint_management(inputLineFLsplit, outputPointFC, outputFCsplit, search_radius='2 Meters') # Get filename part of outputFCsplit flName = os.path.basename(outputFCsplit) #Create a feature layer to be used for AddGeometryAttributes arcpy.MakeFeatureLayer_management(outputFCsplit, flName)
# Loop the cursor to append the X and Y values to startXYArray startCursor= arcpy.SearchCursor(startPoint) for row in startCursor: xCoordVal = row.POINT_X yCoordVal = row.POINT_Y startXYArray.append(xCoordVal) startXYArray.append(yCoordVal) del startCursor xStart = startXYArray[0] yStart = startXYArray[1] # Generate points along the plan profile line each 6 meters and calculate their coordinates pointsAlongLine = arcpy.GeneratePointsAlongLines_management(planProfileLineFC, 'in_memory\pointsAlongLineT', "DISTANCE", "6 meters", "", "END_POINTS") arcpy.AddXY_management(pointsAlongLine) # Add Distance field and calculate the distance between start point and each generated point arcpy.AddField_management(pointsAlongLine, "Distance", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.CalculateField_management(pointsAlongLine, "Distance", "math.sqrt( ( !POINT_X! - "+str(xStart) +")**2 + ( !POINT_Y! - "+str(yStart) +")**2 )", "PYTHON_9.3", "") # Join Geology attributes to points along the plan profile line geologyPoints = arcpy.SpatialJoin_analysis(pointsAlongLine, geologyFC, 'in_memory\geologyPointsT', "JOIN_ONE_TO_ONE", "KEEP_ALL", "", "INTERSECT", "", "") # Interpolate the points along the plan profile line with the DEM geologyPoints3D = arcpy.InterpolateShape_3d(DEM, geologyPoints, 'in_memory\geologyPoints3DT', "", "1", "BILINEAR", "DENSIFY", "0") # Add X Y Z Coordinates arcpy.AddXY_management(geologyPoints3D)
buffDist = cellsize * 2 pointDistance = str(cellsize) + ' Meters' arcpy.env.snapRaster = DTM arcpy.env.outputCoordinateSystem = arcpy.Describe(DTM).spatialReference #complete all the geoprocessing steps up to iterator arcpy.Buffer_analysis(flowObs, bufferedFlowObs, buffDist, 'FULL', 'FLAT', '', '', '') arcpy.PolygonToLine_management(bufferedFlowObs, lines, '') arcpy.SplitLine_management(lines, splitlines) arcpy.MakeFeatureLayer_management(splitlines, FLsplitlines, '', '', '') arcpy.SelectLayerByLocation_management(FLsplitlines, 'INTERSECT', flowObs, '', 'NEW_SELECTION', 'INVERT') arcpy.DeleteRows_management(FLsplitlines) arcpy.CopyFeatures_management(FLsplitlines, endLines, '', '', '', '') arcpy.GeneratePointsAlongLines_management(endLines, endPoints, 'DISTANCE', pointDistance, '', 'END_POINTS') arcpy.gp.ExtractMultiValuesToPoints_sa(endPoints, str(DTM) + ' Heights', 'None') arcpy.MakeFeatureLayer_management(endPoints, endPointsLyr) IDs = [] with arcpy.da.SearchCursor(endPointsLyr, ('RIGHT_FID', )) as cursor: for row in cursor: if row not in IDs: IDs.append(row) IDlist = [] for values in IDs: for x in values: IDlist.append(x) for patchID in IDlist:
arcpy.AddField_management(xSecResultsTable, "TO_Y", "DOUBLE") arcpy.AddField_management(xSecResultsTable, "m", "DOUBLE") arcpy.AddField_management(xSecResultsTable, "c", "DOUBLE") arcpy.AddField_management(xSecResultsTable, "s", "DOUBLE") fieldNameList = ["ID", "FROM_X", "FROM_Y", "TO_X", "TO_Y", "m", "c", "s"] cursor = arcpy.da.InsertCursor(xSecResultsTable, (fieldNameList)) for row in clRowVal: cursor.insertRow(row) arcpy.XYToLine_management(xSecResultsTable, xSecLineResults, "FROM_X", "FROM_Y", "TO_X", "TO_Y", "", "ID", xSecPoints) arcpy.AddMessage("Generating Points...") arcpy.GeneratePointsAlongLines_management(xSecLineResults, newXSecPoints, 'DISTANCE', '1 meters') if (deleteAndAppend == "true"): arcpy.AddMessage("Deleting and Appending...") with arcpy.da.UpdateCursor( xSecPoints, "ID", "ID >= " + str(xSecStartID) + " AND ID <= " + str(xSecEndID)) as cursor: for row in cursor: cursor.deleteRow() arcpy.Append_management(newXSecPoints, xSecPoints, 'NO_TEST') if (newPointXSecOut): arcpy.AddMessage("Copying features to " + newPointXSecOut) arcpy.CopyFeatures_management(newXSecPoints, newPointXSecOut) arcpy.RefreshActiveView()
"FID FID VISIBLE NONE;Shape Shape VISIBLE NONE;reference reference VISIBLE NONE" ) print("FID selected") # --- Polygon to polyline arcpy.PolygonToLine_management(in_features="polygon", out_feature_class="polyline", neighbor_option="IGNORE_NEIGHBORS") print("Polygon to polyline") # --- Generate points along lines every 10m arcpy.GeneratePointsAlongLines_management(Input_Features="line", Output_Feature_Class="points", Point_Placement="DISTANCE", Distance="10 Meters", Percentage="", Include_End_Points="") print("Points generated every 10m") # --- Extract values to points arcpy.gp.ExtractValuesToPoints_sa("points", ras, "points_ras", "NONE", "VALUE_ONLY") print("Values extracted to points") # --- Distance between point and outline of avalanche arcpy.Near_analysis(in_features="points_ras", near_features="polyline", search_radius="",
arcpy.AddMessage('Simplified/cleaned up data') arcpy.AddMessage('\n') # Clip rotated lines to input boundary # tmp_fishnet_clip = os.path.join(tmp_gdb, bdy_name + '_fishnet_r_s_c') arcpy.Clip_analysis(tmp_fishnet_rotated_simpl, bdy_fc_path, tmp_fishnet_clip) arcpy.AddMessage('>> Clipped new trap lines to input boundary') arcpy.AddMessage('\n') # Generate points along the clipped lines at set point intervals # tmp_pts_along_line = os.path.join(tmp_gdb, bdy_name + '_fishnet_r_s_c_pts') dist = '{0} meters'.format(point_interval) # US formatted spelling... arcpy.GeneratePointsAlongLines_management(tmp_fishnet_clip, tmp_pts_along_line, 'DISTANCE', Distance=dist) arcpy.AddMessage( '>> Generated points along lines at interval: {0}'.format(dist)) arcpy.AddMessage('\n') # Convert projection WGS84 # tmp_pts_along_line_WGS = os.path.join(tmp_gdb, bdy_name + '_fishnet_r_s_c_pts_WGS') WGS84 = arcpy.SpatialReference(4326) # GCS WGS 1984 # transform_method = 'NZGD_2000_To_WGS_1984_1' # this isn't required in the tool arcpy.Project_management(tmp_pts_along_line, tmp_pts_along_line_WGS, WGS84) arcpy.AddMessage('>> Converted data to WGS84 coordinate system') arcpy.AddMessage('\n')
def valley(riv_in, wet_in, cd, outp, val): # Start time start = datetime.datetime.now() print("Valley extraction started at %s" % start) arcpy.AddMessage ("Valley extraction started at %s" % start) arcpy.AddMessage ("\n") # Check out spatial extention arcpy.CheckOutExtension("Spatial") # Set environment settings arcpy.ResetEnvironments () env.workspace = cd env.scratchWorkspace = "in_memory" env.overwriteOutput = True # Get a list of the rasters in the workspace rasters = arcpy.ListRasters("*") # If code is stuck and would like to continue then uncomment these codes # rasters.sort() # rasters_sub = rasters[54:] # if you want to pick up where you left off (start a number before) # Dissolve wetland layer wetdis = "wetdis" arcpy.Dissolve_management(wet_in, os.path.join(outp, wetdis), "", "", "", "") # Loop through the list of rasters for inRaster in rasters: # change here if you desire to continue from where you left (raster_sub) # Workspace containing cost distance rasters env.workspace = cd # Check that cd rasters have values check = arcpy.sa.Raster (inRaster).maximum if isinstance(check, float): # Get OID number num = int("".join(filter(str.isdigit, inRaster))) field = arcpy.Describe(os.path.join(outp, "cat_riv")).OIDFieldName # field_short = field[0:3] # Select respective catchment print("Selected catchment %s at %s" % (num, datetime.datetime.now())) arcpy.AddMessage ("Selected catchment %s" % num) arcpy.AddMessage ("\n") attr_selection = arcpy.SelectLayerByAttribute_management(os.path.join(outp, "cat_riv"), "NEW_SELECTION", "%s = %s" % (field, num), None) # Extract rivers rivers = "rivers_" + "%s" % (num) arcpy.Clip_analysis(riv_in, attr_selection, os.path.join(outp, rivers), "") print("Rivers extracted for OID %s at %s" % (inRaster, datetime.datetime.now())) # Check if any wetlands are available for calibration arcpy.Intersect_analysis([os.path.join(outp, rivers), os.path.join(outp, wetdis)], os.path.join(outp, "checkint"), "ALL", None, "INPUT") numrows = int((arcpy.GetCount_management (os.path.join(outp, "checkint"))).getOutput(0)) if numrows > 0: print("Calibration wetlands available for OID %s at %s" % (inRaster, datetime.datetime.now())) # Get points on river rivpts = "rivpts_" + "%s" % (num) arcpy.GeneratePointsAlongLines_management(os.path.join(outp, rivers), os.path.join(outp, rivpts), "DISTANCE", "100 Unknown", None, "END_POINTS") print("Points on river extracted for OID %s at %s" % (inRaster, datetime.datetime.now())) # Create thiessen polygons thies = "thies_" + "%s" % (num) thiesmsk = "thiesmsk_" + "%s" % (num) arcpy.CreateThiessenPolygons_analysis(os.path.join(outp, rivpts), os.path.join(outp, thies), "ONLY_FID") arcpy.Clip_analysis(os.path.join(outp, thies), attr_selection, os.path.join(outp, thiesmsk), "") print("Thiessen polygons computed for OID %s at %s" % (inRaster, datetime.datetime.now())) # Clip out wetland layer wetclip = "wetclip_" + "%s" % (num) arcpy.Clip_analysis(os.path.join(outp, wetdis), attr_selection, os.path.join(outp, wetclip), "") print("Wetlands clipped out for OID %s at %s" % (inRaster, datetime.datetime.now())) del attr_selection # Split wetlands splitwet = "splitwet_" + "%s" % (num) arcpy.Clip_analysis(os.path.join(outp, thiesmsk), os.path.join(outp, wetclip), os.path.join(outp, splitwet), None) print("Wetland split completed for OID %s at %s" % (inRaster, datetime.datetime.now())) # Multipart to Singlepart singwet = "singwet_" + "%s" % (num) arcpy.MultipartToSinglepart_management(os.path.join(outp, splitwet), os.path.join(outp, singwet)) print("Multi to singlepart completed for OID %s at %s" % (inRaster, datetime.datetime.now())) # Extract wetlands that's within extent of rivers wetriv = "wetriv_" + "%s" % (num) arcpy.SpatialJoin_analysis(os.path.join(outp, singwet), os.path.join(outp, rivers), os.path.join(outp, wetriv), "", "KEEP_COMMON", "", "INTERSECT", "", "") print("Wetlands within rivers extracted for OID %s at %s" % (inRaster, datetime.datetime.now())) # Extract cost distance values using wetlands wetcd = "wetcd_" + "%s" % (num) env.mask = os.path.join(outp, wetriv) con = arcpy.sa.Con(inRaster, inRaster, None, "VALUE > 0 And VALUE <= 500"); con.save(os.path.join(outp, wetcd)) # Check for zero cd rasters check2 = arcpy.sa.Raster (os.path.join(outp, wetcd)).maximum if isinstance(check2, float): print("Calibration wetlands coincide within rivers for OID %s at %s" % (inRaster, datetime.datetime.now())) arcpy.ClearEnvironment("mask") meanResult = arcpy.GetRasterProperties_management (os.path.join(outp, wetcd), "MEAN", "") mean = str(meanResult.getOutput(0)) print("Cost distance accumulation within wetlands extracted for OID %s at %s" % (inRaster, datetime.datetime.now())) # Extract valley from estimate made from wetland layer print("Cutoff cost distance for OID %s is %s" % (inRaster, mean)) valR = "valR_" + "%s" % (num) valley = arcpy.sa.Con(inRaster, 1, None, "VALUE <=" + mean); valley.save(os.path.join(outp, valR)) print("Valley extracted for OID %s at %s" % (inRaster, datetime.datetime.now())) # Convert raster to polygon valP = "valP_" + "%s" % (num) arcpy.conversion.RasterToPolygon(os.path.join(outp, valR), os.path.join(outp, valP), "SIMPLIFY", "Value", "SINGLE_OUTER_PART", None) print("Completed conversion to polygon for OID %s at %s" % (inRaster, datetime.datetime.now())) # Make sure that rasters are saved before the next loop con = None valley = None print("Completed valley extraction for OID %s at %s" % (inRaster, datetime.datetime.now())) arcpy.AddMessage ("Completed valley extraction for OID %s at %s" % (inRaster, datetime.datetime.now())) arcpy.AddMessage('\n') print(".........................................................") arcpy.AddMessage (".........................................................") arcpy.AddMessage ("\n") else: print("Calibration wetlands do not coincide with rivers for OID %s at %s" % (inRaster, datetime.datetime.now())) continue else: print("No calibration wetlands available for OID %s at %s" % (inRaster, datetime.datetime.now())) continue else: continue # Find all delineated river valleys env.workspace = outp all_val = arcpy.ListFeatureClasses("val*") # Merge all delineated river valleys mer = "mer" arcpy.Merge_management (all_val, os.path.join(outp, mer)) print("Completed merging river valleys at %s" % datetime.datetime.now()) arcpy.AddMessage ("Completed merging river valleys at %s" % datetime.datetime.now()) arcpy.AddMessage ("\n") # Dissolve river valleys arcpy.Dissolve_management (os.path.join(outp, mer), val, "", "", "", "") print("Completed dissolving river valleys at %s" % datetime.datetime.now()) arcpy.AddMessage ("Completed dissolving river valleys at %s" % datetime.datetime.now()) arcpy.AddMessage ("\n") # End time end = datetime.datetime.now() print("Valley extraction ended at %s" % end) arcpy.AddMessage ("Valley extraction ended at %s" % end) arcpy.AddMessage ("\n") time_elapsed = end - start print("Time elapsed %s" % (time_elapsed)) arcpy.AddMessage ("Time elapsed %s" % time_elapsed) arcpy.AddMessage ("\n")
out_name = "PROFILE_POINTS" geometry_type = "POINT" template = "" has_m = "DISABLED" has_z = "ENABLED" Point_Feature_Class = arcpy.CreateFeatureclass_management(out_path, out_name, geometry_type, template, has_m, has_z) Input_Features = Profile_line_Input Output_Feature_Class = Point_Feature_Class Point_Placement = "DISTANCE" Point_Feature_Class = arcpy.GeneratePointsAlongLines_management (Input_Features, Output_Feature_Class, Point_Placement, Distance_Input + " Meters", Include_End_Points='END_POINTS') point = arcpy.Point() point2 = arcpy.Point() array = arcpy.Array() array2 = arcpy.Array() for row in arcpy.da.SearchCursor(Point_Feature_Class, ["SHAPE@", "SHAPE@XY"]): surface = arcpy.SelectLayerByLocation_management(Surface, "INTERSECT", row[0], None, "NEW_SELECTION") X4, Y4 = row[1] Z4 = 100 point_tmp = arcpy.Point(X4,Y4,Z4) array.add(point_tmp)
list_excel.append(sum(percent_slope)) # Step 7 # taking the road length within contributing area for **time of concentration** # design_road_1_Project = design_road xy_tolerance = "" Points_on_Tc = os.path.join(output_loc,"X_PointsOnLineTc") # we are taking the design road itself as the critical path arcpy.GeneratePointsAlongLines_management(design_road, Points_on_Tc, "DISTANCE", "100000 meters", "", "END_POINTS") # generate points only at the end from arcpy.sa import * # Set local variables inZoneData = Points_on_Tc zoneField = "OBJECTID" inValueRaster = SRTM_Digital_Elevation_Data_30m_tif outTable = os.path.join(output_loc,"X_ZonalStatsTc") # Check out the ArcGIS Spatial Analyst extension license arcpy.CheckOutExtension("Spatial") # Execute ZonalStatisticsAsTable X_zonalStats_Tc = ZonalStatisticsAsTable(inZoneData, zoneField, inValueRaster,
def interpolate(mobilityUser, city, userID, commutingtype): global logfile # convert the points to .csv files #logfile.write("Saving the Google Maps API points to CSV file...\n") transport_modes = "" for word in mobilityUser['transport_modes']: transport_modes = transport_modes + "_" + word # Creating the needed csv filename1 = city + "_" + commutingtype + "_" + str( userID ) + "_" + transport_modes + "_non_interpolated_route_points_" + str( mobilityUser['routeNumber']) path_csvs = "C:\Users\Joel\Documents\\altice_ODPaths\\" + city + "\\" + commutingtype + "\\non_interpolated_route_points_csvs\\" with open(path_csvs + filename1 + ".csv", mode='w') as fp: fp.write("latitude, longitude, sequence") fp.write("\n") sequence = 0 for point in mobilityUser['route']: line = str(point[0]) + "," + str(point[1]) + "," + str(sequence) fp.write(line) fp.write("\n") sequence += 1 fp.close() # Creating a GIS Layer from the CSV file arcpy.MakeXYEventLayer_management(path_csvs + filename1 + ".csv", "longitude", "latitude", filename1 + "_Layer", arcpy.SpatialReference("WGS 1984"), "sequence") # Creating a shapefile of the route points path_shapefile1 = "C:/Users/Joel/Documents/altice_ODPaths/" + city + "/" + commutingtype + "/non_interpolated_route_points_shapefiles/" arcpy.FeatureClassToFeatureClass_conversion(filename1 + "_Layer", path_shapefile1, filename1) # Execute PointsToLine # Rendering the route line filename2 = city + "_" + commutingtype + "_" + str( userID) + "_" + transport_modes + "_route_line_" + str( mobilityUser['routeNumber']) path_shapefile2 = "C:/Users/Joel/Documents/altice_ODPaths/" + city + "/" + commutingtype + "/route_lines_shapefiles/" arcpy.PointsToLine_management(path_shapefile1 + filename1 + ".shp", path_shapefile2 + filename2, "", "sequence") # Creating a shapefile with the interpolated route points filename3 = city + "_" + commutingtype + "_" + str( userID) + "_" + transport_modes + "_interpolated_route_points_" + str( mobilityUser['routeNumber']) path_shapefile3 = "C:/Users/Joel/Documents/altice_ODPaths/" + city + "/" + commutingtype + "/interpolated_route_points_shapefiles/" arcpy.GeneratePointsAlongLines_management( path_shapefile2 + filename2 + ".shp", path_shapefile3 + filename3 + ".shp", 'DISTANCE', Distance='20 meters', Include_End_Points='END_POINTS') # Converting the shapefile to a layer layer = arcpy.MakeFeatureLayer_management( path_shapefile3 + filename3 + ".shp", filename3) # Obtaining the interpolated points from the layer fld_list = arcpy.ListFields(layer) fld_names = [fld.name for fld in fld_list] cursor = arcpy.da.SearchCursor(layer, fld_names) interpolated_route = [] for row in cursor: interpolated_route.append((row[1][1], row[1][0])) return interpolated_route
def main(): #import logic for splitting line into multiple parts based on distance from scripts directory from SplitLineFunctionOutsideArcmap import split_line #import logic for line transects from TransectFunction import generate_transects import os import arcpy import time start_time = time.clock() print "Script started at {}".format(start_time) #arcpy.env.workspace = arcpy.GetParameterAsText(0) arcpy.env.workspace = "C:\Users\jason\Documents\ArcMapStuff\TrinityRiver\Trinity_River.gdb" #Save a copy of the workspace to switch back to after temporary processing is done permWorkspace = arcpy.env.workspace #tempWorkspacePath = arcpy.GetParameterAsText(1) tempWorkspacePath = os.path.split(permWorkspace)[0] #inputFLsplit = arcpy.GetParameterAsText(2) inputFLsplit = "C:\Users\jason\Documents\ArcMapStuff\TrinityRiver\Trinity_River.gdb\TrinityRiverCenterline" #splitDistance = arcpy.GetParameterAsText(3) splitDistance = "2 miles" #generatePoints = arcpy.GetParameterAsText(4) generatePoints = "false" tempGDB = os.path.join(tempWorkspacePath, "TEMP.gdb") if (arcpy.Exists(tempGDB) == False): arcpy.CreateFileGDB_management(tempWorkspacePath, "TEMP", "CURRENT") print "Creating directories..." #Set folder variables for output based on workspace directory; for .gdb go back one level if permWorkspace.endswith(".gdb"): riverSegmentsGDB = os.path.join( os.path.split(permWorkspace)[0], "RIVER_SEGMENTS") if os.path.isdir(riverSegmentsGDB) == False: #arcpy.CreateFileGDB_management(os.path.split(permWorkspace)[0],"RIVER_SEGMENTS","CURRENT") os.mkdir( os.path.join((os.path.split(permWorkspace)[0]), "RIVER_SEGMENTS")) transectLinesGDB = os.path.join( os.path.split(permWorkspace)[0], "TRANSECT_LINES") if os.path.isdir(transectLinesGDB) == False: #arcpy.CreateFileGDB_management(os.path.split(permWorkspace)[0],"TRANSECT_LINES","CURRENT") os.mkdir( os.path.join((os.path.split(permWorkspace)[0]), "TRANSECT_LINES")) transectPointsGDB = os.path.join( os.path.split(permWorkspace)[0], "TRANSECT_POINTS") if os.path.isdir(transectPointsGDB) == False: #arcpy.CreateFileGDB_management(os.path.split(permWorkspace)[0],"TRANSECT_POINTS","CURRENT") os.mkdir( os.path.join((os.path.split(permWorkspace)[0]), "TRANSECT_POINTS")) else: riverSegmentsGDB = os.path.join(permWorkspace, "RIVER_SEGMENTS") if os.path.isdir(riverSegmentsGDB) == False: os.mkdir(os.path.join(permWorkspace, "RIVER_SEGMENTS")) transectLinesGDB = os.path.join(permWorkspace, "TRANSECT_LINES") if os.path.isdir(transectLinesGDB) == False: os.mkdir(os.path.join(permWorkspace, "TRANSECT_LINES")) transectPointsGDB = os.path.join(permWorkspace, "TRANSECT_POINTS") if os.path.isdir(transectPointsGDB) == False: os.mkdir(os.path.join(permWorkspace, "TRANSECT_POINTS")) #run split line function print "Beginning split line..." split_line(permWorkspace, tempGDB, inputFLsplit, splitDistance) #redefine outputFCsplit and flName to be used that were created in split_line outputFCsplit = os.path.join(tempGDB, inputFLsplit + "Split") flName = os.path.basename(outputFCsplit) #Create searh cursor from split feature class with object id and start and end points of the line segment fields = ['START_X', 'START_Y', 'END_X', 'END_Y', 'OBJECTID'] #Set workspace to temporary gdb to be removed at end of processing searchCursor = arcpy.da.SearchCursor(outputFCsplit, fields) segment_list = [] # Add all start and end points with shape token for line segments to a list for row in searchCursor: segment_list.append([[row[0], row[1]], [row[2], row[3]], row[4]]) del searchCursor #Arrange line segments in proper order #arcpy.SetProgressorLabel("Ordering line segments...") print "Ordering line segments..." segment_list.sort() #initialize loop variables i = 1 zeroPrefix = "" #Create new feature class from each segment for segment in segment_list: segmentNumber = str(i) if i < 10: zeroPrefix = "0" else: zeroPrefix = "" segmentNumber = zeroPrefix + segmentNumber segmentName = flName + "_segment_" + segmentNumber arcpy.SelectLayerByAttribute_management( flName, 'NEW_SELECTION', "OBJECTID = " + str(segment[2])) #Copy each line segment as a feature class to the temporary geodatabase #arcpy.CopyFeatures_management(flName,os.path.join(tempGDB,segmentName)) arcpy.CopyFeatures_management( flName, os.path.join(riverSegmentsGDB, segmentName)) #Create a feature layer to be used by transects #arcpy.MakeFeatureLayer_management(os.path.join(tempGDB,segmentName),segmentName) arcpy.MakeFeatureLayer_management( os.path.join(riverSegmentsGDB, segmentName + ".shp"), segmentName + ".shp") #Add transect FC name to the path for our workspace #outputTransectFC = os.path.join(arcpy.env.workspace,segmentName+"Transects") #Add full output path to transectLines FC outputTransectFC = os.path.join(transectLinesGDB, flName + "_transect_" + segmentNumber) #Store transect fc name to be used for points full path outputTransectFCname = os.path.split(outputTransectFC)[1] #Create path for transect tool to work in; base directory so as not to interfere with current geodatabase transectWorkspace = os.path.split(arcpy.env.workspace)[0] totalSegments = zeroPrefix + str(len(segment_list)) #arcpy.SetProgressorLabel("Generating transects for segment {0} of {1}".format(segmentNumber,totalSegments)+"...") print "Generating transects for segment {0} of {1}...".format( segmentNumber, totalSegments) generate_transects(transectWorkspace, segmentName + ".shp", "Split at approximate distance", 3, 200, "Meters", outputTransectFC + ".shp") #Switch back to permanent workspace from temp workspace in transects arcpy.env.workspace = permWorkspace #Add full output path to transectPoints FC outputPointFC = os.path.join(transectPointsGDB, outputTransectFCname + "_points") #Only generate points on the transects when the checkbox is selected; ** GREATLY INCREASES PROCESSING TIME ** if i == 1: if generatePoints == 'true': #arcpy.SetProgressorLabel("Generating points on transect {0} of {1}".format(segmentNumber,totalSegments)+"...") print "Generating points on transect {0} of {1}...".format( segmentNumber, totalSegments) print "OutputTransectFC: {} OutputPointFC: {}".format( outputTransectFC, outputPointFC) #arcpy.GeneratePointsAlongLines_management(outputTransectFC, outputPointFC, 'DISTANCE', Distance = '1 meters',Include_End_Points = 'END_POINTS') arcpy.GeneratePointsAlongLines_management( outputTransectFC + ".shp", outputPointFC + ".shp", 'DISTANCE', Distance='1 meters', Include_End_Points='END_POINTS') i += 1 end_time = (time.clock() - start_time) / 60 print "Script took {} minutes to run".format(time.clock() - start_time)
#Segundo buffer de fachada: franja de estancias y zona de posible corredor output = "AUXILIAR2\\" + str(oid) + "_1.shp" output2 = "AUXILIAR2\\" + str(oid) + "_5.shp" arcpy.Buffer_analysis(output, output2, "3,5", "FULL", "ROUND", "ALL") output = "AUXILIAR2\\" + str(oid) + "_6.shp" arcpy.Erase_analysis(input, output2, output) output = "AUXILIAR2\\" + str(oid) + "_5.shp" output2 = "AUXILIAR2\\" + str(oid) + "_8.shp" arcpy.Intersect_analysis([input, output], output2, "ALL", "", "") #Se estiman los centros de las estancias poniendo una cadena de puntos de lado a lado de fachada output = "AUXILIAR2\\" + str(oid) + "_4.shp" output2 = "AUXILIAR2\\" + str(oid) + "_9b.shp" arcpy.GeneratePointsAlongLines_management(output, output2, 'DISTANCE', Distance='3') output3 = "AUXILIAR2\\" + str(oid) + "_9c.shp" arcpy.GeneratePointsAlongLines_management(output, output3, 'DISTANCE', Distance='1,5') output = "AUXILIAR2\\" + str(oid) + "_9d.shp" arcpy.Erase_analysis(output3, output2, output) output3 = "AUXILIAR2\\" + str(oid) + "_9.shp" arcpy.Erase_analysis(output, "AUXILIAR2\\MED_.shp", output3) arcpy.AddField_management(output3, "CUARTO", "SHORT") output = "FID_" + str(oid) + "_3" arcpy.DeleteField_management(output3, ["Id", "ORIG_FID", output, "SUM_AREA"])
# Intersect older fire and reburn area to get perimeter of older fire within newer burn shared_line = os.path.join(ws, "shared_line" + str(n_poly) + ".shp") arcpy.Intersect_analysis(["in_memory/older_fc", "in_memory/reburn_poly"], shared_line, "ALL", "#", "LINE") # Convert reburn polygon to polyline arcpy.PolygonToLine_management("in_memory/reburn_poly", "in_memory/reburn_line") # Get section of reburn perimeter that excludes previously id'd shared line inverse_line = os.path.join(ws, "inverse_line" + str(n_poly) + ".shp") arcpy.SymDiff_analysis("in_memory/reburn_line", shared_line, inverse_line) # Generate points along the inverse intersection line print 'generating points' inverse_pts = os.path.join(ws, "inverse_pts" + str(n_poly) + ".shp") arcpy.GeneratePointsAlongLines_management(inverse_line, inverse_pts, 'DISTANCE', Distance='500 meters') # Get distance from each point on the line to the intersected line. This is the distance of newer fire within older print 'getting distance' arcpy.Near_analysis(inverse_pts, shared_line, "#", "LOCATION", "ANGLE") # Add id fields (older, newer fire IDs) to each point. Otherwise no way to tell # which points are associated with which fires arcpy.AddField_management(inverse_pts, "parentid1", "LONG") arcpy.AddField_management(inverse_pts, "parentid2", "LONG") # Get parent ids from intersected line shapefile newrows = arcpy.SearchCursor(shared_line) for newrow in newrows: parent_id1 = newrow.getValue("parentid") parent_id2 = newrow.getValue("parentid_2")
def Kernel_Density_REM(DEM, NHDFlowline, RiverName, PointDistance_meters, SearchRadius, Output_gdb_path): # Set environment arcpy.env.workspace = Output_gdb_path # Names for selecting and saving rivername = RiverName.replace(' ', '') # Create path object for Output_gdb_path Output_gdb_filepath = Path(Output_gdb_path) # Create Output_gdb if it does not already exist if not Output_gdb_filepath.exists(): arcpy.CreateFileGDB_management(str(Output_gdb_filepath.parent), str(Output_gdb_filepath.name)) # Define River Channel and create feature class with single line feature river_flowline = arcpy.SelectLayerByAttribute_management( NHDFlowline, 'New_Selection', "GNIS_Name = '" + RiverName + "'") river_name_path = str(Output_gdb_filepath / rivername) arcpy.CopyFeatures_management(river_flowline, river_name_path) diss_river_name_path = str(Output_gdb_filepath / str(rivername + '_diss')) arcpy.Dissolve_management(river_name_path, diss_river_name_path) # Generate points along channel line river_points_path = str(Output_gdb_filepath / str(rivername + '_points')) arcpy.GeneratePointsAlongLines_management( diss_river_name_path, river_points_path, 'DISTANCE', Distance=(str(PointDistance_meters) + ' meters')) # Extract elevation to points river_points_elev = str(Output_gdb_filepath / str(rivername + '_elev')) arcpy.sa.ExtractValuesToPoints(river_points_path, DEM, river_points_elev) # Kernel Density Point PointKernel = str(Output_gdb_filepath / str(rivername + '_PntKernel')) DEM_cellsize = float( str(arcpy.GetRasterProperties_management(DEM, "CELLSIZEX"))) PointKernelDensity = arcpy.sa.KernelDensity(river_points_elev, "NONE", DEM_cellsize, SearchRadius, "SQUARE_METERS") PointKernelDensity.save(PointKernel) # Kernel Density Elevation StreamKernel = str(Output_gdb_filepath / str(rivername + '_StreamKernel')) StreamElevKernelDensity = arcpy.sa.KernelDensity(river_points_elev, "RASTERVALU", DEM_cellsize, SearchRadius, "SQUARE_METERS") StreamElevKernelDensity.save(StreamKernel) # Create the detrended DEM by dividing the cumulative stream elevation raster by the point density raster det_DEM = str(Output_gdb_filepath / str(rivername + '_DetDEM')) detrended_DEM = arcpy.sa.Divide(StreamElevKernelDensity, PointKernelDensity) detrended_DEM.save(det_DEM) # Create Relative Elevation Model relative_elevation_model = str( str(Output_gdb_filepath / str(rivername + '_RelElevModel'))) REM = arcpy.sa.Minus(DEM, detrended_DEM) REM.save(relative_elevation_model)
#!/usr/bin/env python # -*- coding:utf-8 -*- # Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script # The following inputs are layers or table views: "1" import arcpy import os import sys reload(sys) sys.setdefaultencoding("utf-8") shp_file = r"E:\janpan_data\order1.shp" out_fc_1 = r"E:\janpan_data\order1_1.shp" print shp_file if os.path.exists(shp_file): print "ok" else: print "file is not exist" exit(1) arcpy.GeneratePointsAlongLines_management(shp_file, out_fc_1, 'DISTANCE', Distance='100 meters', Include_End_Points=False) arcpy.close()
# Arcpy create midpoint in in_memory workspace... try: if state in ["AS", "IN", "OR"]: HighwayTunnelTEMP = "_" + state + ".dbo.hifld_HighwayTunnelTEMP" stateSDE = "_" + state + ".sde" else: HighwayTunnelTEMP = state + ".dbo.hifld_HighwayTunnelTEMP" stateSDE = state + ".sde" HighwayTunnelMidPointScratch = r"in_memory\hifld_HighwayTunnel" inputpath = os.path.join(userDefinedSDEConnectionFolder, stateSDE, HighwayTunnelTEMP) outputpathScratch = HighwayTunnelMidPointScratch arcpy.GeneratePointsAlongLines_management(Input_Features = inputpath, \ Output_Feature_Class = outputpathScratch, \ Point_Placement = "PERCENTAGE", \ Distance = "", \ Percentage = "50", \ Include_End_Points = "") except Exception as e: print " cursor execute create centerpoints: {}".format((e)) # Arcpy calculate midpoint x,y fields in scratch... try: arcpy.AddGeometryAttributes_management( HighwayTunnelMidPointScratch, "POINT_X_Y_Z_M") except Exception as e: print " cursor execute calculate scratch fields: {}".format((e)) # Arcpy copy from scratch to sql server... try: if state in ["AS", "IN", "OR"]: HighwayTunnelMidPoint = "[_" + state + "].dbo.hifld_HighwayTunnel" else:
import os import arcpy #Make temporary directory os.mkdir(r"D:\\SHP\\Temp") os.mkdir(r"D:\\SHP\\Output") # Local variables: cl_line_shp = r"D:\\SHP\\test\\cl_line.shp" cl_line_Buffer = r"D:\\SHP\\Temp\\BufferL.shp" cl_line_Buffer_PolygonToLine = r"D:\\SHP\\Temp\\PolygonToLine.shp" gcp_shp = r"D:\\SHP\\Output\\gcp_test.shp" x = input("Please enter the distance from road:") #Please enter value in Meter y = input("Please enter the distance for GCP:") #Please enter value in Meter # Process: Buffer arcpy.Buffer_analysis(cl_line_shp, cl_line_Buffer, x, "FULL", "FLAT", "NONE", "", "PLANAR") # Process: Polygon To Line arcpy.PolygonToLine_management(cl_line_Buffer, cl_line_Buffer_PolygonToLine, "IDENTIFY_NEIGHBORS") # Process: Generate Points Along Lines arcpy.GeneratePointsAlongLines_management(cl_line_Buffer_PolygonToLine, gcp_shp, "DISTANCE", y, "", "") # Process: Add XY Coordinates arcpy.AddXY_management(gcp_shp) print "Completed Successfully!"
def getSinuosity(shape): ## This functions calculates the sinuosity of a polyline. ## Needs as an input a polyline shapefile. ## And a list of the years that the shapefiles are refering to. ## Also divides the line into section in order to calculate the sinuosity per section. ############################################# # Catching possible Errors - Error handling. ############################################# # Catch the error of using an empty shapefile (i.e. with no features in it) f_count = arcpy.GetCount_management(shape) if int(f_count[0]) > 0: arcpy.AddMessage("The input {0} has {1} features".format( shape.split("\\")[-1], f_count)) else: arcpy.AddError( 'The input {} has no features the execution of the script will fail ... Please check the input shapefiles ...' .format(shape.split("\\")[-1])) sys.exit(0) # Catch the error of having an unknown spatial reference for the input data. spatial_ref = arcpy.Describe(shape).spatialReference if spatial_ref.name != "Unknown": arcpy.AddMessage("The spatial reference of {0} is {1}".format( shape.split("\\")[-1], spatial_ref.name)) else: arcpy.AddError( "Beware ... the used input {0} has Unknown spatial reference ... Please check the Spatial Reference of the input shapefiles ... The execution of the script will be terminated soon ..." .format(shape)) sys.exit(0) # Catch the geometry Type error (of the input shapefiles not being polyline) desc = arcpy.Describe(shape) geometryType = desc.shapeType if str(geometryType) == 'Polyline': pass else: arcpy.AddError( '{} is not a line/polyline ... Please check the input shapefiles ...' .format(shape.split("\\")[-1])) sys.exit(0) ##################### # Calculate Sinuosity ##################### arcpy.AddMessage( "### Calculating sinuosity index for the whole river ###") for year in year_list: # Go through all the different Years the user enter as input (stored in a list). if year in shape: # If the Year input connects to a shapefile input (i.e. the user did not put wrong Year). try: if int( f_count[0] ) > 1: # If the input consits of multiple features dissolve it to 1. arcpy.AddMessage( "{0} has {1} features and it will be dissolved into 1 feature ..." .format(shape.split("\\")[-1], f_count)) shape_dissolve = r'river_dissolved.shp' # Name of the shapefile for the dissolved river arcpy.Dissolve_management( shape, shape_dissolve) # Perform dissolve shape = shape_dissolve # From now on the dissolved shape is going to be the variable shape. arcpy.AddMessage("Adding Geometry field ...") arcpy.AddGeometryAttributes_management( shape, "LENGTH", "METERS" ) # Add a Geometry field to calculate the length of each feature. arcpy.AddMessage("Adding field ...") arcpy.AddField_management( shape, 'TOT_LENGTH', 'DOUBLE' ) # Add another field "TOT_LENGTH" to copy the values ofthe length field - fixing field names to avoid confusions. arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management( shape, "TOT_LENGTH", "!LENGTH!", "PYTHON" ) # Actually copying the values of "LENGTH" to the new field added above. arcpy.AddMessage("Deleting field ...") arcpy.DeleteField_management( shape, "LENGTH" ) # Delete the geometry field that was just created. arcpy.AddMessage( "Calculating total length of the river ...") cursor = arcpy.da.SearchCursor( shape, ["TOT_LENGTH"] ) # Use a search cursor to go through the "TOT_LENGTH" of the input shapefile. length = 0 for row in cursor: # For all the individual features / lines in a polyline. length += row[0] arcpy.AddMessage( "Extracting the ending point of the river ...") river_end_shp = r'end_' + str( year ) + '.shp' # Variable for the shapefile of the end point of the polyline. arcpy.AddMessage( "Extracting the starting point of the river ...") river_start_shp = r'start_' + str( year ) + '.shp' # Variable for the shapefile of the start point of the polyline. arcpy.AddMessage( "Feature Vertices to Points for the 'start' and 'end' vertices of the river ..." ) arcpy.FeatureVerticesToPoints_management( shape, river_end_shp, "end" ) # Convert the last-end vertex of the polyline (river) to point, output River_end arcpy.FeatureVerticesToPoints_management( shape, river_start_shp, "start" ) # Convert the first-start vertex of the polyline (river) to point, output River_start. arcpy.AddMessage( "Calculating straight distance between start and end vertices of the river ..." ) distance_table = r'distance' + str(year) + '.dbf' arcpy.PointDistance_analysis( river_end_shp, river_start_shp, distance_table, "" ) # Calculate the straight distance between start and end and save it to a table cursor = arcpy.da.SearchCursor( distance_table, "DISTANCE" ) # Use a search cursor to go through the distance collumn in the created distance table. d = 0 # Variable for straight distance - direct distance for rows in cursor: # For the different rows of the distance collumn in the distance_table d = rows[ 0] # Add the different rows (the distance will always in the first row though) arcpy.AddMessage( "The straight distance between the starting and ending point is now computed and stored in the {}" .format(distance_table)) if normalize_sin_bool == 'true': sinuosity = d / length # Defined as Length / d but reverse is used, Max possible sinuosity = 1 . else: sinuosity = length / d # Normalized sinuosity index as used by ESRI toolbox. except: arcpy.AddMessage(arcpy.GetMessages()) arcpy.AddMessage("Adding field ...") arcpy.AddField_management( shape, 'sinuosity', 'DOUBLE' ) # Add a field in the river shapefile to store the sinuosity value arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management( shape, 'sinuosity', sinuosity, 'VB' ) # Calculate the sinuosity field - actually store the value in the table of the shapefile. ############################### ## Sinuosity per Section Part. ############################### if river_section_bool == 'true': # This condition is satisfied if the user selected to also calculate the Sinuosity Index per section. arcpy.AddMessage( "### Calculating sinuosity index for different parts of the river ####" ) arcpy.AddMessage( "You have selected {0} sections ".format(sections) ) # Need to move in the IF for the section statement arcpy.AddMessage("Creating new shapefiles ...") points_along_shape_shp = r'points_along_shape_' + str( year ) + '.shp' # Variable for the shapefile of the points along the river line. river_section_shp = 'river_sections_year_' + str( year ) + '.shp' # Variable for the shapefile of the river divided into sections. arcpy.AddMessage( "Calculating the length of sections in % of total length ..." ) per = 100 / int( sections ) # Calculate the percentage of each section based on the Number of Sections that the user asked with his input. arcpy.AddMessage( "The percentage of the total length for each section is :{}" .format(per)) arcpy.AddMessage( "Generating points along the river line ...") arcpy.GeneratePointsAlongLines_management( shape, points_along_shape_shp, "PERCENTAGE", Percentage=per, Include_End_Points='NO_END_POINTS' ) # Generate points along the based on the above calculate percentage. ##Added to delete the last point of the points along lines. points_temp = 'points_along_shape' + str( year ) + 'filtered.shp' # Temporary shapefile used to delete the point the the edge of the line from the points along the line. arcpy.MakeFeatureLayer_management(points_along_shape_shp, points_temp) sel_exp = "\"FID\"=" + str( int(sections) - 1 ) # The last one will have FID the number of sections -1 arcpy.SelectLayerByAttribute_management( points_temp, "NEW_SELECTION", sel_exp) if int( arcpy.GetCount_management(points_temp)[0] ) > 0: # If there are any features satisfying this condition - Will be! arcpy.DeleteFeatures_management( points_temp) # Delete them. ## arcpy.AddMessage("Spliting line on points ...") arcpy.SplitLineAtPoint_management( shape, points_along_shape_shp, river_section_shp, "2000 Meters" ) # Splitting the line into sections by using the above generate points. arcpy.AddMessage("Adding Geometry field ...") arcpy.AddGeometryAttributes_management( river_section_shp, "LENGTH", "METERS") # Get the length of each section arcpy.AddMessage("Adding field ...") arcpy.AddField_management( river_section_shp, 'SEC_LENGTH', 'DOUBLE' ) # Store the length in a new field "SEC_LENGTH" to be more clear - avoid confusion. arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management(river_section_shp, "SEC_LENGTH", "!LENGTH!", "PYTHON") arcpy.AddMessage( "Deleting field ..." ) # Delete the "LENGTH" field in the same logic. arcpy.DeleteField_management(river_section_shp, "LENGTH") arcpy.AddMessage( "The calculation of the length of each section was successful, the values are stored in the field " "\"SEC_LENGTH\"" " ") river_section_shp_lvl2 = 'river_sections_year_' + str( year ) + 'lvl2' + '.shp' # Variable for the shapefile of the river sections that will be used to be sure that the script will delete all the sections # that are substantially 'small' because in such a case the sinuosity values of that sections will be missleading arcpy.CopyFeatures_management(river_section_shp, river_section_shp_lvl2) temp_sec_len_l = [ ] # Create an empty list that will store all the length values of the different sections. cursor = arcpy.da.SearchCursor( river_section_shp_lvl2, "SEC_LENGTH" ) # Use a search cursor to go through the section length field. for row in cursor: temp_sec_len_l.append( int(row[0]) ) # Populate/Append each value of the field to the list we just created. minimum_section_length = min( temp_sec_len_l) # Find the minimum length per section. mean_section_length = sum(temp_sec_len_l) / len( temp_sec_len_l ) # And find the average length per section. arcpy.AddMessage("Minimum section length :{}".format( minimum_section_length)) arcpy.AddMessage("Average section length :{}".format( mean_section_length)) arcpy.AddMessage( "Deleting the substantially small sections ...") temp = 'river_sections_year_' + str( year ) + 'lvl3' + '.shp' # Temporary shapefile used to delete the 'small' sections arcpy.MakeFeatureLayer_management(river_section_shp_lvl2, temp) delete_thres = 0.35 # Threshold of deletion (Small section) is defined as 0.35 of the average length of the sections exp_sec_len = "\"SEC_LENGTH\" <" + str( delete_thres * mean_section_length) arcpy.SelectLayerByAttribute_management( temp, "NEW_SELECTION", exp_sec_len ) # Select the features by attributes based on the above threshold/expression if int( arcpy.GetCount_management(temp)[0] ) > 0: # If there are any features satisfying this condition - arcpy.AddWarning( "{} of the generated sections were substantially smaller than the average section length, and they are being deleted ..." .format(int(arcpy.GetCount_management(temp)[0]))) arcpy.DeleteFeatures_management(temp) # Delete them ###### arcpy.AddMessage("Adding field ...") arcpy.AddField_management( river_section_shp_lvl2, "startx", "DOUBLE" ) # Field that will store the X coordinate of the starting point of each section. arcpy.AddMessage("Adding field ...") arcpy.AddField_management( river_section_shp_lvl2, "starty", "DOUBLE" ) # Field that will store the Y coordinate of the starting point of each section. arcpy.AddMessage("Adding field ...") arcpy.AddField_management( river_section_shp_lvl2, "endx", "DOUBLE" ) # Field that will store the X coordinate of the ending point of each section. arcpy.AddField_management( river_section_shp_lvl2, "endy", "DOUBLE" ) # Field that will store the Y coordinate of the ending point of each section. arcpy.AddMessage("Adding field ...") arcpy.AddField_management( river_section_shp_lvl2, 'dirdis', 'DOUBLE' ) # Field that will store the direct distance for each section of the river from starting to ending vertex. arcpy.AddMessage("Adding field ...") arcpy.AddField_management( river_section_shp_lvl2, "sec_sin", "DOUBLE" ) # Field that will store the sinuosity of EACH Section. #Expressions for the calculations of the new fields. # Create the expressions in order to populate the fields that were just created above. exp_start_X = "!Shape!.positionAlongLine(0.0,True).firstPoint.X" # expression for starting X exp_start_Y = "!Shape!.positionAlongLine(0.0,True).firstPoint.Y" # expression for starting Y exp_end_X = "!Shape!.positionAlongLine(1.0,True).firstPoint.X" # expression for ending X exp_end_Y = "!Shape!.positionAlongLine(1.0,True).firstPoint.Y" # expression for ending Y arcpy.AddMessage("Calculating field ...") # Finally arcpy.CalculateField_management( river_section_shp_lvl2, "startx", exp_start_X, "PYTHON" ) # Populate/Calculate the starting X-coordinate of each section. arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management( river_section_shp_lvl2, "starty", exp_start_Y, "PYTHON" ) # Populate/Calculate the starting X-coordinate of each section. arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management( river_section_shp_lvl2, "endx", exp_end_X, "PYTHON" ) # Populate/Calculate the starting X-coordinate of each section arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management( river_section_shp_lvl2, "endy", exp_end_Y, "PYTHON" ) # Populate/Calculate the starting X-coordinate of each section # Based on the above (Xstart-Xend,Ystart,Yend) and using dd_exp = "math.sqrt((!startx!-!endx!)**2+(!starty!-!endy!)**2)" # The pythagoreum we can now get straight distance. arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management( river_section_shp_lvl2, "dirdis", dd_exp, "PYTHON" ) # Populate the field based on the pythagoreum expression for each section. if normalize_sin_bool == 'true': sin_exp = "!dirdis!/!SEC_LENGTH!" # Defined as Length / d but reverse is used, Max possible sinuosity = 1 . else: # Expression for Sinuosity Formula (direct distance / Length). sin_exp = "!SEC_LENGTH!/!dirdis!" arcpy.AddMessage("Calculating field ...") arcpy.CalculateField_management( river_section_shp_lvl2, "sec_sin", sin_exp, "PYTHON" ) # Populate/Calculate the sections sinuosity field based on the sinuosity expression for each section. arcpy.AddMessage( "The calculation of the sinuosity per section was successful, the values are stored in a field named " "\"sec_sin\"" " ")
def proclines(OID, currentreach, pointpath, reachfeaturefile, upreaches, downreaches, centerlinepath): arcpy.MakeFeatureLayer_management(reachfeaturefile, "reach_lyr") upreaches = list(filter(None, upreaches)) downreaches = list(filter(None, downreaches)) upreaches.extend(downreaches) upreaches.append(currentreach) field = arcpy.AddFieldDelimiters("reach_lyr", "NOID") unsplitfile = os.path.join( "in_memory", "unsplit_" + os.path.basename(reachfeaturefile) + str(OID).zfill(4)) outpointfile_unsort = os.path.join( "in_memory", "unsort_" + os.path.basename(reachfeaturefile) + str(OID).zfill(4)) outpointfile_sort = os.path.join( pointpath, os.path.basename(reachfeaturefile) + str(OID).zfill(4) + ".shp") centerlinefile = "centerline_" + os.path.basename(reachfeaturefile) + str( OID).zfill(4) bufferfile = "in_memory/buffer" for i in upreaches: selection = '{field} = {val}'.format(field=field, val=i) updown = arcpy.SelectLayerByAttribute_management( "reach_lyr", "ADD_TO_SELECTION", selection) arcpy.FeatureClassToFeatureClass_conversion(updown, "in_memory", centerlinefile) arcpy.UnsplitLine_management(in_features=os.path.join( "in_memory", centerlinefile), out_feature_class=unsplitfile, dissolve_field="", statistics_fields="") arcpy.GeneratePointsAlongLines_management( Input_Features=unsplitfile, Output_Feature_Class=outpointfile_unsort, Point_Placement="DISTANCE", Distance="100 Meters", Percentage="", Include_End_Points="END_POINTS") arcpy.CalculateField_management(in_table=outpointfile_unsort, field="ORIG_FID", expression="!OID!", expression_type="PYTHON_9.3", code_block="") arcpy.MakeFeatureLayer_management(outpointfile_unsort, "unsortedpoints") arcpy.MakeFeatureLayer_management( os.path.join("in_memory", centerlinefile), "centerline") arcpy.SelectLayerByAttribute_management(in_layer_or_view="unsortedpoints", selection_type="NEW_SELECTION", where_clause='"ORIG_FID" =1') arcpy.Buffer_analysis(in_features="unsortedpoints", out_feature_class=bufferfile, buffer_distance_or_field="10 Meters", line_side="FULL", line_end_type="ROUND", dissolve_option="NONE", dissolve_field="", method="GEODESIC") min_value = arcpy.da.SearchCursor( os.path.join("in_memory", centerlinefile), "UPLAND_SKM", "{} IS NOT NULL".format("UPLAND_SKM"), sql_clause=(None, "ORDER BY {} ASC".format("UPLAND_SKM"))).next()[0] #print (min_value) arcpy.SelectLayerByLocation_management( in_layer="centerline", overlap_type="INTERSECT", select_features=bufferfile, search_distance="30 Meters", selection_type="NEW_SELECTION", invert_spatial_relationship="NOT_INVERT") selected_value = arcpy.da.SearchCursor( "centerline", "UPLAND_SKM", "{} IS NOT NULL".format("UPLAND_SKM")).next()[0] if min_value == selected_value: arcpy.Sort_management(in_dataset=outpointfile_unsort, out_dataset=outpointfile_sort, sort_field=[["ORIG_FID", "ASCENDING"]]) else: arcpy.Sort_management(in_dataset=outpointfile_unsort, out_dataset=outpointfile_sort, sort_field=[["ORIG_FID", "DESCENDING"]]) arcpy.CopyFeatures_management( os.path.join("in_memory", centerlinefile), os.path.join(centerlinepath, centerlinefile + ".shp")) arcpy.Delete_management("reach_lyr") arcpy.Delete_management("unsortedpoints") arcpy.Delete_management("centerline") arcpy.Delete_management("in_memory/buffer") arcpy.Delete_management(outpointfile_unsort) arcpy.Delete_management(unsplitfile) arcpy.Delete_management(os.path.join("in_memory", centerlinefile)) return (upreaches)
spatial_roads_above20m = intermediate_layers + "/spatial_roads_above20m.shp" arcpy.AddField_management(attr_roads, "lengt_road", "DOUBLE", 30, 15, "#", "#", "NULLABLE", "NON_REQUIRED", "#") arcpy.CalculateField_management(attr_roads, "lengt_road", "!shape.geodesicLength@meters!", "PYTHON_9.3") arcpy.MakeFeatureLayer_management(attr_roads, "attr_roads") arcpy.SelectLayerByAttribute_management("attr_roads", "NEW_SELECTION", ' "lengt_road" >= 20 ') arcpy.CopyFeatures_management("attr_roads", spatial_roads_above20m) segmented_roads = intermediate_layers + "/segmented_roads.shp" _40m_points = intermediate_layers + "/_40m_points.shp" arcpy.GeneratePointsAlongLines_management(spatial_roads_above20m, _40m_points, 'DISTANCE', Distance='40 meters') arcpy.SplitLineAtPoint_management(spatial_roads_above20m, _40m_points, 'segmented_roads') arcpy.CopyFeatures_management('segmented_roads', segmented_roads) step2_endTime = bk_logger.currentSecondsTime() bk_logger.showPyMessage( " -- Step 2 done. Took {}".format( bk_logger.timeTaken(step2_startTime, step2_endTime)), logger) #Step 3: Selecting all roads that are less than 40m from a property and then export layer bk_logger.showPyMessage( "Step 3: Selecting all roads that are less than 40m from a property and then export layer ", logger) step3_startTime = bk_logger.currentSecondsTime()
#if arcpy.CheckExtension("Spatial") == "Available": # arcpy.CheckOutExtension("Spatial") #else: # raise LicenseError # Set Parameters workSpace=arcpy.GetParameterAsText(0) # Workspace lineFeature=arcpy.GetParameterAsText(1) # Feature Set elvInterval=arcpy.GetParameterAsText(2) # Linear Unit dem=arcpy.GetParameterAsText(3) # Raster Layer #output=arcpy.GetParameterAsText(3) # Table geodatabase # Generate points along the lineFeature outFC="distance_interval" Points=arcpy.GeneratePointsAlongLines_management(lineFeature,outFC,'DISTANCE',elvInterval) # Extract DEM values from the Points elevPoints=ExtractMultiValuesToPoints(Points,dem,"BILINEAR") # need bilinear? #elevPoints=ExtractMultiValuesToPoints(Points,dem,"NONE") # need bilinear? # Add X, Y coordinates arcpy.AddXY_management(elevPoints) # Copy and add Field #outFiles="temp" #elevPointsCopy=arcpy.CopyFeatures_management(elevPoints,outFiles) #arcpy.AddField_management(elevPointsCopy,field_name="Distance",field_type="long") fieldName="Distance" arcpy.AddField_management(elevPoints,field_name=fieldName,field_type="long")
arcpy.env.workspace = "C:\Users\romeo\Documents\Class\GEOG 380\Final Project" #creating a variable for the map document. INPUT YOUR MAP DOC HERE mxd = arcpy.mapping.MapDocument("CURRENT") #listing dataframes df = arcpy.mapping.ListDataFrames(mxd,"*")[0] #insert your INPUT:Street Center Lines shp here #creates shp variable and adds the Streets as a layer to mxd Streetsshp = "GrandwoodParkRoads\GrandwoodParkRoads.shp" Streets = arcpy.mapping.Layer(Streetsshp) Streetsfc = arcpy.mapping.AddLayer(df,Streets,"TOP") #generating points along every street, 200 ft apart. arcpy.GeneratePointsAlongLines_management("GrandwoodParkRoads", "Streetlights", "DISTANCE", "200 Feet", "", "") #adding Streetlights as layer streetlights = arcpy.mapping.Layer("Streetlights") arcpy.mapping.AddLayer(df,streetlights,"TOP") #Zooming to the Selected features (Streetlights) expression = "'Shape' = 'Point'" arcpy.SelectLayerByAttribute_management(streetlights,"NEW_SELECTION",expression) df.extent = streetlights.getSelectedExtent() arcpy.RefreshActiveView() #Adjusting Legend Elements. #Turning auto add on so that the streetlights and streets are added to legend. #If contents of legend are overflowing, increase width by .1 pixel until it's not. legend = arcpy.mapping.ListLayoutElements(mxd,"LEGEND_ELEMENT", "Legend")[0]
for row in cursor: x = row.getValue('Domain') originalDomain = str(originalDomainsFolder) + '\\' + x[8:] + '_Domain.shp' domainName = x[8:] + '_Domain' originalNode = str(originalNodesFolder) + '\\Nodes_' + x[8:] + '.shp' nodeName = 'Nodes_' + x[8:] domainEdgesFL = arcpy.MakeFeatureLayer_management(domainEdges,'in_memory\domainEdgesFL' + x) selectedDomainEdges = arcpy.SelectLayerByAttribute_management(domainEdgesFL,'NEW_SELECTION','"Domain" = ' + "'" + str(x) + "'") #complete the geoprocessing steps for the selected nodes and domains and copies the node bufferedSelectedDomainEdges = arcpy.Buffer_analysis(selectedDomainEdges,'in_memory\\bufferedSelectedDomainEdges' + x,str(pointBufferDistance) + ' METERS') bufferedDomain = arcpy.Buffer_analysis(originalDomain,'in_memory\\bufferedDomain' + x,str(bufferDistance) + ' METERS') bufferedDomainPoints = arcpy.GeneratePointsAlongLines_management(bufferedDomain,'in_memory\\bufferedDomainPoints' + x,'DISTANCE','30 METERS') domainPoints = arcpy.GeneratePointsAlongLines_management(originalDomain,'in_memory\\domainPoints' + x,'DISTANCE','30 METERS') fl1 = arcpy.MakeFeatureLayer_management(domainPoints,'in_memory\\fl1' + x) domainPointsSelected = arcpy.SelectLayerByLocation_management(fl1,'WITHIN_A_DISTANCE',selectedDomainEdges,'200 METERS') fl2 = arcpy.MakeFeatureLayer_management(bufferedDomainPoints,'in_memory\\fl2' + x) bufferedDomainPointsSelected = arcpy.SelectLayerByLocation_management(fl2,'WITHIN_A_DISTANCE',domainPointsSelected,str(bufferDistance + 1) + ' METERS') extendAreaPoints = arcpy.Merge_management([domainPointsSelected,bufferedDomainPointsSelected],'in_memory\\extendpoints' + x) extendAreaPoly = arcpy.MinimumBoundingGeometry_management(extendAreaPoints,'in_memory\\extendAreaPoly' + x,'CONVEX_HULL') domainshape = arcpy.Union_analysis([originalDomain, extendAreaPoly, bufferedSelectedDomainEdges],'in_memory\\shape' + x,'','',"NO_GAPS") arcpy.env.workspace = outputDomainsFolder arcpy.Dissolve_management(domainshape,domainName) arcpy.env.workspace = outputNodesFolder arcpy.CopyFeatures_management(originalNode,nodeName) arcpy.Delete_management('in_memory') print('All Processes Complete')