def CleanFlowline(output_workspace, stream_network, smooth_tolerance): # Set environment variables arcpy.env.overwriteOutput = True arcpy.env.workspace = output_workspace # List parameter values arcpy.AddMessage("Workspace: {}".format(arcpy.env.workspace)) arcpy.AddMessage("Stream Network: " "{}".format(arcpy.Describe(stream_network).baseName)) # Dissolve by `ReachName` field stream_network_dissolve = os.path.join(output_workspace, "stream_network_dissolve") arcpy.Dissolve_management(in_features=stream_network, out_feature_class=stream_network_dissolve, dissolve_field=["ReachName"], unsplit_lines="DISSOLVE_LINES") arcpy.AddMessage("Stream Network Dissolved") # Smooth the stream network flowline = os.path.join(output_workspace, "flowline") arcpy.SmoothLine_cartography(in_features=stream_network_dissolve, out_feature_class=flowline, algorithm="PAEK", tolerance=smooth_tolerance) arcpy.AddMessage("Stream Network Smoothed") # Return arcpy.SetParameter(3, flowline) # Cleanup arcpy.Delete_management(in_data=stream_network_dissolve)
arcpy.AddMessage("Original Hoehenlinien erstellen") arcpy.AddMessage( "*******************************************************************************" ) arcpy.AddMessage("") # Process: Contour... arcpy.Contour_sa(ScratchRaster1, cont_orig1, Aequidistanz, "450", "1") arcpy.AddMessage("Hoehenlinien glaetten") arcpy.AddMessage( "*******************************************************************************" ) arcpy.AddMessage("") # Process: Smooth Line... arcpy.SmoothLine_cartography(cont_orig1, OutputSmoothLine, "PAEK", SmoothToleranz + " Meters", "NO_FIXED", "NO_CHECK") arcpy.AddMessage("Transformation nach LV95") arcpy.AddMessage( "*******************************************************************************" ) arcpy.AddMessage("") # Projektionsobjekte definieren lv95 = arcpy.SpatialReference(2056) ch1903 = arcpy.SpatialReference(21781) transformation = "CH1903_To_CH1903+_1_NTv2" #Geodaten transformieren nach LV95 arcpy.Project_management(OutputSmoothLine, OutputFC, lv95, transformation, ch1903)
def get_centerline (feature, dem, workspace, power = 5, eu_cell_size = 10): """Returns a center line feature of the given polygon feature based on cost over an euclidean distance raster and cost path. points are seeded using minimum and maximum elevation.""" centerline = workspace + '\\centerline.shp' center_length = 0 center_slope = 0 smoothing = 4 trim_distance = "100 Meters" try: # Setup extents / environments for the current feature ARCPY.env.extent = feature.shape.extent desc = ARCPY.Describe(feature) XMin_new = desc.extent.XMin - 200 YMin_new = desc.extent.YMin - 200 XMax_new = desc.extent.XMax + 200 YMax_new = desc.extent.YMax + 200 ARCPY.env.extent = ARCPY.Extent(XMin_new, YMin_new, XMax_new, YMax_new) ARCPY.env.overwriteOutput = True ARCPY.env.cellSize = eu_cell_size ARCPY.env.snapRaster = dem # Get minimum and maximum points resample = ARCPY.Resample_management (dem, 'in_memory\\sample', eu_cell_size) masked_dem = spatial.ExtractByMask (resample, feature.shape) # Find the maximum elevation value in the feature, convert them to # points and then remove all but one. maximum = get_properties (masked_dem, 'MAXIMUM') maximum_raster = spatial.SetNull(masked_dem, masked_dem, 'VALUE <> ' + maximum) maximum_point = ARCPY.RasterToPoint_conversion(maximum_raster, 'in_memory\\max_point') rows = ARCPY.UpdateCursor (maximum_point) for row in rows: if row.pointid <> 1: rows.deleteRow(row) del row, rows # Find the minimum elevation value in the feature, convert them to # points and then remove all but one. minimum = get_properties (masked_dem, 'MINIMUM') minimum_raster = spatial.SetNull(masked_dem, masked_dem, 'VALUE <> ' + minimum) minimum_point = ARCPY.RasterToPoint_conversion(minimum_raster, 'in_memory\\min_point') rows = ARCPY.UpdateCursor (minimum_point) for row in rows: if row.pointid <> 1: rows.deleteRow(row) del row, rows # Calculate euclidean Distance to boundary line for input DEM cells. polyline = ARCPY.PolygonToLine_management(feature.shape, 'in_memory\\polyline') eucdist =spatial.EucDistance(polyline, "", eu_cell_size, '') masked_eucdist = spatial.ExtractByMask (eucdist, feature.shape) # Calculate the cost raster by inverting the euclidean distance results, # and raising it to the power of x to exaggerate the least expensive route. cost_raster = (-1 * masked_eucdist + float(maximum))**power # Run the cost distance and cost path function to find the path of least # resistance between the minimum and maximum values. The results are set # so all values equal 1 (different path segments have different values) # and convert the raster line to a poly-line. backlink = 'in_memory\\backlink' cost_distance = spatial.CostDistance(minimum_point, cost_raster, '', backlink) cost_path = spatial.CostPath(maximum_point, cost_distance, backlink, 'EACH_CELL', '') cost_path_ones = spatial.Con(cost_path, 1, '', 'VALUE > ' + str(-1)) # Set all resulting pixels to 1 r_to_p = ARCPY.RasterToPolyline_conversion (cost_path_ones, 'in_memory\\raster_to_polygon') del ARCPY.env.extent # Delete current extents (need here but do not know why) # Removes small line segments from the centerline shape. These segments are # a byproduct of cost analysis. lines = str(ARCPY.GetCount_management(r_to_p)) #check whether we have more than one line segment if float(lines) > 1: # If there is more then one line rows = ARCPY.UpdateCursor(r_to_p) for row in rows: if row.shape.length == eu_cell_size: # delete all the short 10 m lines rows.deleteRow(row) del row, rows lines = str(ARCPY.GetCount_management(r_to_p)) if float(lines) > 1: ARCPY.Snap_edit(r_to_p, [[r_to_p, "END", "50 Meters"]]) # make sure that the ends of the lines are connected r_to_p = ARCPY.Dissolve_management(r_to_p, 'in_memory\\raster_to_polygon_dissolve') # Smooth the resulting line. Currently smoothing is determined by minimum # and maximum distance. The greater change the greater the smoothing. smooth_tolerance = (float(maximum) - float(minimum)) / smoothing ARCPY.SmoothLine_cartography(r_to_p, centerline, 'PAEK', smooth_tolerance, 'FIXED_CLOSED_ENDPOINT', 'NO_CHECK') field_names = [] # List of field names in the file that will be deleted. fields_list = ARCPY.ListFields(centerline) for field in fields_list: # Loop through the field names if not field.required: # If they are not required append them to the list of field names. field_names.append(field.name) # Add new fields to the center line feature ARCPY.AddField_management(centerline, 'GLIMSID', 'TEXT', '', '', '25') ARCPY.AddField_management(centerline, 'LENGTH', 'FLOAT') ARCPY.AddField_management(centerline, 'SLOPE', 'FLOAT') ARCPY.DeleteField_management(centerline, field_names) # Remove the old fields. # Calculate the length of the line segment and populate segment data. ARCPY.CalculateField_management(centerline, 'LENGTH', 'float(!shape.length@meters!)', 'PYTHON') rows = ARCPY.UpdateCursor (centerline) for row in rows: row.GLIMSID = feature.GLIMSID # Get GLIMS ID and add it to segment center_length = row.LENGTH # Get the length of the center line # Calculate slope of the line based on change in elevation over length of line center_slope = round(math.degrees(math.atan((float(maximum) - float(minimum)) / row.LENGTH)), 2) row.SLOPE = center_slope # Write slope to Segment rows.updateRow(row) # Update the new entry del row, rows #Delete cursors and remove locks # Flip Line if needed - Turn min point and end point into a line segment if # the length of this line is greater then the threshold set, flip the line. end_point = ARCPY.FeatureVerticesToPoints_management(centerline, 'in_memory\\end_point', 'END') merged_points = ARCPY.Merge_management ([end_point, minimum_point], 'in_memory\\merged_points') merged_line = ARCPY.PointsToLine_management (merged_points, 'in_memory\\merged_line') merged_line_length = 0 # Get the line Length rows = ARCPY.SearchCursor (merged_line) for row in rows: merged_line_length += row.shape.length del row, rows # if the line length is greater then a quarter the entire feature length, flip if merged_line_length > (center_length/4): ARCPY.FlipLine_edit(centerline) # This function attempts to extend the line and clip it back to the # feature extents in order to create a line that runs from edge to edge #trimmed_line = ARCPY.Merge_management([polyline, centerline], 'in_memory\\line_merge') trimmed_line = ARCPY.Append_management (polyline, centerline, 'NO_TEST') ARCPY.TrimLine_edit (trimmed_line, trim_distance, "DELETE_SHORT") ARCPY.ExtendLine_edit(trimmed_line, trim_distance, "EXTENSION") rows = ARCPY.UpdateCursor (trimmed_line) for row in rows: if row.LENGTH == 0.0: rows.deleteRow(row) del row, rows # Recalculate length. Must be after 0.0 lengths are deleted or they will # not be removed above. ARCPY.CalculateField_management(centerline, 'LENGTH', 'float(!shape.length@meters!)', 'PYTHON') ARCPY.env.overwriteOutput = False return centerline, center_length, center_slope, False except: ARCPY.env.overwriteOutput = False return centerline, '', '', True
"/" + str(nstep)) Dissolve1ToLine = arcpy.Intersect_analysis( [Dissolve1, Dissolve1], "%ScratchWorkspace%\\Dissolve1ToLine", "", "", "LINE") UPD_SL.UpToDateShapeLengthField(Dissolve1ToLine) arcpy.DeleteIdentical_management(Dissolve1ToLine, ["Shape_Length"]) RawCenterline = arcpy.Intersect_analysis([Dissolve1ToLine, Polygon], "%ScratchWorkspace%\\RawCenterline", "ALL", "", "INPUT") ncurrentstep += 1 arcpy.AddMessage("Smoothing centerline - Step " + str(ncurrentstep) + "/" + str(nstep)) Centerline = arcpy.SmoothLine_cartography(RawCenterline, Output, "PAEK", Smoothing, "FIXED_CLOSED_ENDPOINT", "NO_CHECK") #/deleting residual fields try: arcpy.DeleteField_management(Centerline, [ "FID_Dissolve1ToLine", "FID_Dissolve1", "FID_Dissolve1_1", "ORIG_FID", "Rank_UGO", "Rank_UGO_1", "FID_" + str(name) ]) except: pass try: arcpy.DeleteField_management(Centerline, [ "FID_Dissol", "FID_Diss_1", "FID_Diss_2", "FID_" + str(name)[0:6], "ORIG_FID", "Rank_UGO", "Rank_UGO_1", "Shape_Leng", "Shape_Le_1" ])
else: if not os.path.isdir(output_workspace): os.mkdir(output_workspace) output_workspace = os.path.join(output_workspace, '_smoothed') if os.path.isdir(output_workspace): shutil.rmtree(output_workspace) os.mkdir(output_workspace) smooth = r"in_memory\smooth" tmp_smooth = r"in_memory\temp_smooth" arcpy.SmoothLine_cartography(input_f, smooth, "BEZIER_INTERPOLATION") for i in range(10): if debug and i >= helpers.max_run: break bezier_deviation = (i + 1) * 0.1 out_name_bezier = helpers.make_output_name(input_name, 'bezier', bezier_deviation) paek_tolerance = (i + 1) * 2 out_name_paek = helpers.make_output_name(input_name, 'paek', paek_tolerance) if output_workspace.strip().lower().endswith('.gdb'): out_name_bezier = re.sub(r'\.(s|S)(h|H)(p|P)$', '', out_name_bezier)
#Once everything has been checked the point to line tool is ran! #point to line lineField = "Filename" sortField = "ID" for fc in FCList: outfc = os.path.join(output_ws_plane, "{}_line".format(os.path.basename(fc))) arcpy.PointsToLine_management(fc, outfc, lineField, sortField) print("All points turned to line features") #Smooth lines REQUIRES ADVANCED LICENSE FCList = arcpy.ListFeatureClasses("*_line") for fc in FCList: outfc = os.path.join(output_ws_plane, "{}_smooth".format(os.path.basename(fc))) arcpy.SmoothLine_cartography(fc, outfc, "PAEK", "1000 Meters", "FIXED_CLOSED_ENDPOINT", "NO_CHECK") print("You're a Smooth Criminal!") #Add and calculate fields FCList = arcpy.ListFeatureClasses('*_smooth') #New field and field type AFields = [("Year", "LONG"), ("Month", "LONG"), ("Week", "LONG"), ("Day", "LONG"), ("Current", "TEXT")] #Add Fields for fc in FCList: for afc in AFields: arcpy.AddField_management(fc, afc[0], afc[1], "", "", "", "", "NULLABLE", "NON_REQUIRED", "") #Calculate Field Values CFields = [("Year", "!Filename![1:5]"), ("Month", "!Filename![5:7]"), ("Week", "!Filename![9:11]"), ("Day", "!Filename![7:9]"),
# =============== flowlines = product_db + "/Flowlines" + region highResLines = baseDirectory + "/gisFiles/NHDH" + region + "/arcHydroInput.gdb/delineationStreams" + region catchments = product_db + "/Catchments" + region # Truncated Lines # =============== simplifedLine = CA.SimplifyLine( flowlines, workspace_db + "/simplifyFlowlines" + region, "BEND_SIMPLIFY", "60 Meters", "FLAG_ERRORS", "KEEP_COLLAPSED_POINTS", "CHECK") arcpy.SmoothLine_cartography( simplifedLine, baseDirectory + "/products/NHDHRDv2.gdb/smoothedFlowlines" + region, "PAEK", "60 Meters", "FIXED_CLOSED_ENDPOINT", "FLAG_ERRORS") arcpy.CalculateField_management(product_db + "/smoothedFlowlines" + region, "LengthKM", "!SHAPE.LENGTH@KILOMETERS!", "PYTHON") # The next section is computationally intensive and may throw an error if the system requirements are not sufficient. # Detailed Lines # ============== # Creates one feature per reach dissolveLines = arcpy.Dissolve_management( highResLines, workspace_db + "/dissolve" + region, "#", "#", "MULTI_PART", "UNSPLIT_LINES")
# Local variables: rutapro = r'H:\VDCNS\protocolo\pro' for i in os.listdir(rutapro): if os.path.isdir(os.path.join(rutapro, i)): #print i escena = os.path.join(rutapro, i) for s in os.listdir(escena): if s.endswith('contour.shp'): print s try: # Local variables: contour = os.path.join(escena, s) out_contour = os.path.join( escena, 'smooth_' + os.path.split(contour)[1]) print out_contour # Process: Smooth Line arcpy.SmoothLine_cartography(contour, out_contour, "PAEK", "100 Meters", "FIXED_CLOSED_ENDPOINT", "NO_CHECK") except Exception as e: print 'Error', e continue
ncurrentstep = 1 #/copying the DEM into a usable format DEMprop = arcpy.GetRasterProperties_management(DEM, 'VALUETYPE') if (DEMprop == 9): ProcessDEM = arcpy.CopyRaster_management( DEM, "%ScratchWorkspace%\\ProcessDEM", "DEFAULTS", "", "", "", "", "32_BIT_UNSIGNED") else: ProcessDEM = DEM #/smoothing of the stream network arcpy.AddMessage("Smoothing the Stream Network - Step " + str(ncurrentstep) + "/" + str(nstep)) SmoothedNetwork = arcpy.SmoothLine_cartography( Network, "%scratchWorkspace%\\SmoothedNetwork", "PAEK", SmoothingNetwork, "FIXED_CLOSED_ENDPOINT", "NO_CHECK") #/creation of buffers ncurrentstep += 1 arcpy.AddMessage("Creating Large Buffer - Step " + str(ncurrentstep) + "/" + str(nstep)) LargeBuffer = arcpy.Buffer_analysis(Network, "%scratchWorkspace%\\LargeBuffer", LargeBufferSize, "FULL", "ROUND", "NONE", "") ncurrentstep += 1 arcpy.AddMessage("Creating Small Buffer- Step " + str(ncurrentstep) + "/" + str(nstep)) SmallBuffer = arcpy.Buffer_analysis(Network,
# Number of steps if str(DeleteTF) == "true" : nstep=7 else : nstep=6 ncurrentstep=1 #=============================================================================== # CODING #=============================================================================== #/preparation of the used features arcpy.AddMessage("Smoothing the input polyline to apply the lateral offset tolerance - Step " + str(ncurrentstep) + "/" + str(nstep)) SmoothedLine = arcpy.SmoothLine_cartography(inFC, "%Scratchworkspace%\\SmoothedLine", "PAEK", Offset) ncurrentstep+=1 arcpy.AddMessage("Creating features used during the process - Step " + str(ncurrentstep) + "/" + str(nstep)) ToPts = arcpy.FeatureVerticesToPoints_management(SmoothedLine, "%ScratchWorkspace%\\ToPts", "ALL") arcpy.AddXY_management(ToPts) arcpy.AddField_management(ToPts, "Inflection", "LONG", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.AddField_management(ToPts, "Angle", "FLOAT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") #/assessment of the angle between three successive nodes ncurrentstep+=1 arcpy.AddMessage("Iterative process to determine the angle between three successive nodes - Step " + str(ncurrentstep) + "/" + str(nstep))
def createpolyfeatureclass_2d(mainpolylist_2d, postbottomboxlist_2d, minsfirst, minslast, maxfirst, maxlast, prior, ExtendLine_edit_distance, TrimLine_edit_dangle_length, Integrate_management_distance, smooth_2d): ''' arcpy.ExtendLine_edit(joinadd("in_memory","all_lines_2d_dissolved"),"5") ExtendLine_edit_distance=The maximum distance a line segment can be extended to an intersecting feature. arcpy.TrimLine_edit (joinadd("in_memory","all_lines_2d_dissolved"),"2", "kEEP_SHORT") TrimLine_edit_dangle_length=Line segments that are shorter than the specified Dangle Length and do not touch another line at both endpoints (dangles) will be trimmed. arcpy.Integrate_management(joinadd("in_memory","all_lines_2d_dissolved"), 0.01) Integrate_management_distance=The distance that determines the range in which feature vertices aremade coincident. To minimize undesired movement of vertices, the x,ytolerance should be fairly small. ''' #arcpy.CreateFeatureclass_management("C:\Users\usuari\Desktop\Interpretation-test01-2018.mdb", "mainpolyli", "POLYLINE","", "DISABLED", "ENABLED") allpolies = list() infpolies = list() ################## 'filenames1' homeadd = joinadd(expanduser("~"), "arcgistemp_2d") #plnsadd=joinadd(homeadd,"plns_2d") ################# 'making priorpolylist [ priority number, [polyline1,polyline2,...] ]' for i in range(0, len(mainpolylist_2d)): for j in mainpolylist_2d[i][2]: allpolies.append([j[0], j[2]]) ####### #postbottomboxlist=[ [point1coord,point2coord,point 1 borehole or mid (0 or 1) ,point 2 borehole or mid (0 or 1), polyline] ,... ] for kk in postbottomboxlist_2d: allpolies.append(["post_bottombox_2d", kk[4]]) ###### pointlist = [maxfirst, minsfirst[1]] firstbhline_2d = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in pointlist]), "Unknown", False, False) allpolies.append(["firstbhline_2d", firstbhline_2d]) pointlist = [maxlast, minslast[1]] lastbhline_2d = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in pointlist]), "Unknown", False, False) allpolies.append(["lastbhline_2d", lastbhline_2d]) ####### priorpolylist = list() #print 'allpolies is:', allpolies for n in allpolies: if [n[0], []] not in priorpolylist: priorpolylist.append([n[0], []]) for m in priorpolylist: for b in allpolies: if b[0] == m[0]: m[1].append(b[1]) #print 'priorpolylist_2d' , priorpolylist ################### 'creating the main polyline featureclass' con = 0 polylineadlistmerge = [] polylineadlistmerge_smooth = [] arcpy.CreateFeatureclass_management("in_memory", "all_lines_2d", "POLYLINE", "", "DISABLED", "DISABLED", "") for ii in range(0, len(priorpolylist)): con = con + 1 'names' temppolyname = "temppoly_2d" + str(con) #plnslayername=joinadd(homeadd,"plnslayer_2d")+str(con)+".shp" #mainplnsadd=joinadd(homeadd,"mainplns_2d")+str(con)+".shp" #mainplnsadd2=joinadd(homeadd,"mainplns_2d")+str(con+1) ############ arcpy.CreateFeatureclass_management("in_memory", temppolyname, "POLYLINE", "", "DISABLED", "DISABLED", "") cursor = arcpy.da.InsertCursor(joinadd("in_memory", temppolyname), ["SHAPE@"]) for t in priorpolylist[ii][1]: cursor.insertRow([t]) del cursor ############### test 2019 cursor = arcpy.da.InsertCursor(joinadd("in_memory", "all_lines_2d"), ["SHAPE@"]) for t in priorpolylist[ii][1]: cursor.insertRow([t]) del cursor ################### #dissolve:basic #integrate: basic #ExtendLine_edit: standard #TrimLine_edit: standard #Integrate_management:basic #RepairGeometry_management:basic #FeatureToPolygon_management: advanced # arcpy.Dissolve_management( joinadd("in_memory", temppolyname), joinadd("in_memory", "plnslayertemp_2d" + str(con)), "", "", "", "UNSPLIT_LINES") arcpy.Integrate_management( joinadd("in_memory", "plnslayertemp_2d" + str(con)), 0.01) polylineadlistmerge.append( joinadd("in_memory", "plnslayertemp_2d" + str(con))) #arcpy.FeatureVerticesToPoints_management(joinadd("in_memory","plnslayertemp_2d"+str(con)),joinadd(homeadd,"dangle"+str(con)),"DANGLE") ################ if smooth_2d == True: #smoothing arcpy.SmoothLine_cartography( joinadd("in_memory", "plnslayertemp_2d" + str(con)), joinadd("in_memory", "smoothed" + str(con)), "BEZIER_INTERPOLATION", "", "FIXED_CLOSED_ENDPOINT", "") polylineadlistmerge_smooth.append( joinadd("in_memory", "smoothed" + str(con))) #############test 2019 arcpy.Dissolve_management(joinadd("in_memory", "all_lines_2d"), joinadd("in_memory", "all_lines_2d_dissolved"), "", "", "", "UNSPLIT_LINES") arcpy.ExtendLine_edit(joinadd("in_memory", "all_lines_2d_dissolved"), str(ExtendLine_edit_distance)) arcpy.TrimLine_edit(joinadd("in_memory", "all_lines_2d_dissolved"), str(TrimLine_edit_dangle_length), "kEEP_SHORT") arcpy.Integrate_management(joinadd("in_memory", "all_lines_2d_dissolved"), Integrate_management_distance) arcpy.RepairGeometry_management( joinadd("in_memory", "all_lines_2d_dissolved")) arcpy.FeatureToPolygon_management( joinadd("in_memory", "all_lines_2d_dissolved"), joinadd("in_memory", "all_lines_2d_dissolved_feat_to_poly"), "0.02", "", "") polylineadlistmerge.append( joinadd("in_memory", "all_lines_2d_dissolved_feat_to_poly")) ################### #smoothing if smooth_2d == True: arcpy.SmoothLine_cartography( joinadd("in_memory", "all_lines_2d_dissolved"), joinadd("in_memory", "all_lines_2d_dissolved_smoothed"), "BEZIER_INTERPOLATION", "", "FIXED_CLOSED_ENDPOINT", "") arcpy.FeatureToPolygon_management( joinadd("in_memory", "all_lines_2d_dissolved_smoothed"), joinadd("in_memory", "all_lines_2d_dissolved_feat_to_poly_smoothed"), "0.02", "", "") polylineadlistmerge_smooth.append( joinadd("in_memory", "all_lines_2d_dissolved_feat_to_poly_smoothed")) arcpy.CreateFileGDB_management(homeadd, "arcgistempdb_2d_smoothed.gdb") arcpy.FeatureClassToGeodatabase_conversion( polylineadlistmerge_smooth, joinadd(homeadd, "arcgistempdb_2d_smoothed.gdb")) ################### mergedpolygonsfromlines_2d = joinadd("in_memory", "mergedpolygonsfromlines_2d") arcgistempdb_2d = joinadd(homeadd, "arcgistempdb_2d.gdb") arcpy.FeatureToPolygon_management(polylineadlistmerge, mergedpolygonsfromlines_2d, "", "", "") polylineadlistmerge.append(mergedpolygonsfromlines_2d) arcpy.CreateFileGDB_management(homeadd, "arcgistempdb_2d.gdb") arcpy.FeatureClassToGeodatabase_conversion(polylineadlistmerge, arcgistempdb_2d) ##################### return arcgistempdb_2d
## gp.RasterToPolyline_conversion(LP_Extract, LongpathTemp, "ZERO", "", "NO_SIMPLIFY", "VALUE") ## #################################################################################################################################### # Try to use Stream to Feature process to convert the raster Con result to a line (DUE TO 10.5.0 BUG) AddMsgAndPrint("\tConverting Raster flow path to a line...", 0) LFP_StreamLink = watershedGDB_path + os.sep + "lfplink" #gp.StreamLink_sa(LP_Extract, FlowDir, LFP_StreamLink) tempLink = arcpy.sa.StreamLink(LP_Extract, FlowDir) tempLink.save(LFP_StreamLink) arcpy.sa.StreamToFeature(LFP_StreamLink, FlowDir, LongpathTemp, "NO_SIMPLIFY") #################################################################################################################################### # Smooth and Dissolve results arcpy.SmoothLine_cartography(LongpathTemp, LP_Smooth, "PAEK", "100 Feet", "FIXED_CLOSED_ENDPOINT", "NO_CHECK") # Intersect with watershed to get subbasin ID arcpy.Intersect_analysis(LP_Smooth + "; " + watershed, LongpathTemp1, "ALL", "", "INPUT") # Dissolve to create single lines for each subbasin arcpy.Dissolve_management(LongpathTemp1, LongpathTemp2, "Subbasin", "", "MULTI_PART", "DISSOLVE_LINES") # Add Fields / attributes & calculate length in feet AddMsgAndPrint("\tUpdating longest flow path attributes...", 0) arcpy.AddField_management(LongpathTemp2, "Reach", "SHORT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") arcpy.CalculateField_management(LongpathTemp2, "Reach",
input_fc = arcpy.GetParameterAsText(0) name_field = str(arcpy.GetParameterAsText(1)) smoothing_alg = str(arcpy.GetParameterAsText(2)) or 'None' deviation_or_tolerance = str(arcpy.GetParameterAsText(3)).strip() angle = float(str(arcpy.GetParameterAsText(4))) output = arcpy.GetParameterAsText(5) if smoothing_alg in ['Bezier', 'Paek'] and len(deviation_or_tolerance) == 0: arcpy.AddError( 'Deviation or Tolerance must be provided if a smoothing algorithm is selected' ) tmp_features = r'in_memory\tmp_feats' if smoothing_alg == 'Bezier': arcpy.SmoothLine_cartography(input_fc, tmp_features, "BEZIER_INTERPOLATION") arcpy.Densify_edit(tmp_features, "OFFSET", max_deviation=deviation_or_tolerance) elif smoothing_alg == 'Paek': arcpy.SmoothLine_cartography(input_fc, tmp_features, "PAEK", tolerance=deviation_or_tolerance) elif smoothing_alg == 'None': arcpy.CopyFeatures_management(input_fc, tmp_features) else: arcpy.AddError("smoothing algorithm not found") desc = ArcpyDescribeFeatureClass(tmp_features) finder = CurveFinder(desc.catalog_path, road_name_field=name_field)
def main(Polygon, Polyline, DisaggregationStep, Smoothing, Output): # Allow the temporary outputs overwrite arcpy.env.overwriteOutput = True # Derived variable from inputs name = os.path.split(os.path.splitext(Polygon)[0])[1] # Number of steps nstep = 12 ncurrentstep = 1 #=============================================================================== # CODING #=============================================================================== #/creation of the extreme points arcpy.AddMessage( "Looking for the extreme points of the input polyline - Step " + str(ncurrentstep) + "/" + str(nstep)) ExtremePoints = arcpy.FeatureVerticesToPoints_management( Polyline, "in_memory\\ExtremePoints", "DANGLE" ) ### Simplified the method for finding Extreme Points to use line "dangles". This appears to have removed a bunch of extra extreme points found in the temp data. ### KMW: Removed this section, I do not fully understand how this functions, but it does not appear to break the process. # arcpy.AddXY_management(ExtremePoints) # arcpy.AddField_management(ExtremePoints, "Del", "SHORT") # ExtPts.ExtremePoints(ExtremePoints) # # Make = arcpy.MakeFeatureLayer_management(ExtremePoints, "in_memory\\Make") # Selection = arcpy.SelectLayerByAttribute_management(Make, "NEW_SELECTION", "\"Del\" = 1") # # arcpy.DeleteFeatures_management(Selection) ### #/splitting of the polygon with extreme points ncurrentstep += 1 arcpy.AddMessage("Converting the input polygon to line - Step " + str(ncurrentstep) + "/" + str(nstep)) PolyToLine = arcpy.FeatureToLine_management(Polygon, "in_memory\\PolyToLine", "", "ATTRIBUTES") ncurrentstep += 1 arcpy.AddMessage( "Looking for the longer distance between extreme points and the polygon - Step " + str(ncurrentstep) + "/" + str(nstep)) NearTable = arcpy.GenerateNearTable_analysis(ExtremePoints, PolyToLine, "in_memory\\NearTable", "", "LOCATION", "NO_ANGLE") NearPoints = arcpy.MakeXYEventLayer_management(NearTable, "NEAR_X", "NEAR_Y", "NearPoints", ExtremePoints) arcpy.CopyFeatures_management("NearPoints", "in_memory\\NearPoints") ### Removed this Section. It appears to find the max distance in the table, for use in splitting the lines? #rows = arcpy.SearchCursor(NearTable) # Counter = 0 # for row in rows : # if row.NEAR_DIST > Counter : # Counter = row.NEAR_DIST # Counter+=1 ### ncurrentstep += 1 arcpy.AddMessage("Splitting polygon with the extreme points - Step " + str(ncurrentstep) + "/" + str(nstep)) FracTEMP = arcpy.SplitLineAtPoint_management( PolyToLine, "NearPoints", "in_memory\\FracTEMP", "0.1 METERS" ) ### Changed to use near points for splitting, also added "0.1 METERS" search distance to solve an esri bug in this function. ncurrentstep += 1 arcpy.AddMessage("Deleting residual segments - Step " + str(ncurrentstep) + "/" + str(nstep)) FracTEMPToPoints = arcpy.FeatureVerticesToPoints_management( FracTEMP, "in_memory\\FracTEMPToPoints", "BOTH_ENDS") arcpy.AddField_management(FracTEMP, "Fusion", "LONG", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") fieldnames = [f.name for f in arcpy.ListFields(FracTEMP)] arcpy.CalculateField_management(FracTEMP, "Fusion", "[" + fieldnames[0] + "]", "VB", "") SpatialRef = arcpy.Describe(Polygon).spatialReference XY = arcpy.MakeXYEventLayer_management(NearTable, "NEAR_X", "NEAR_Y", "in_memory\\XY", SpatialRef, "") NearTable2 = arcpy.GenerateNearTable_analysis(XY, FracTEMPToPoints, "in_memory\\NearTable2", "", "LOCATION", "NO_ANGLE", "ALL", "2") fieldnames = [f.name for f in arcpy.ListFields(FracTEMP)] arcpy.JoinField_management(FracTEMPToPoints, fieldnames[0], NearTable2, "NEAR_FID", ["NEAR_FID"]) MakeFracTEMPToPoints = arcpy.MakeFeatureLayer_management( FracTEMPToPoints, "in_memory\\MakeFracTEMPToPoints", "", "", "ORIG_FID ORIG_FID VISIBLE NONE") MakeFracTEMP = arcpy.MakeFeatureLayer_management( FracTEMP, "in_memory\\MakeFracTEMP", "", "", "ORIG_FID ORIG_FID VISIBLE NONE") SelectionPoints = arcpy.SelectLayerByAttribute_management( MakeFracTEMPToPoints, "NEW_SELECTION", "\"NEAR_FID\" IS NULL") SelectLine = arcpy.SelectLayerByLocation_management( MakeFracTEMP, "BOUNDARY_TOUCHES", SelectionPoints, "", "NEW_SELECTION") arcpy.CalculateField_management(SelectLine, "Fusion", "10000", "VB", "") FracPoly_TEMP = arcpy.Dissolve_management(FracTEMP, "in_memory\\FracPoly_TEMP", "Fusion", "", "MULTI_PART", "DISSOLVE_LINES") FracPoly = arcpy.MultipartToSinglepart_management(FracPoly_TEMP, "in_memory\\FracPoly") arcpy.DeleteField_management(FracPoly, "Fusion") ncurrentstep += 1 arcpy.AddMessage("Split the input polygon - Step " + str(ncurrentstep) + "/" + str(nstep)) PolySplitTEMP = dS.SLEM(FracPoly, DisaggregationStep, "in_memory\\PolySplitTEMP", "true") PolySplit = arcpy.Sort_management( PolySplitTEMP, "in_memory\\PolySplit", [["Rank_UGO", "ASCENDING"], ["Distance", "ASCENDING"]]) ncurrentstep += 1 arcpy.AddMessage("Converting Split polygon to points - Step " + str(ncurrentstep) + "/" + str(nstep)) PolySplitToPoint = arcpy.FeatureToPoint_management( PolySplit, "in_memory\\PolySplitToPoint", "INSIDE") #/creating the Thiessen polygons and the centerline ncurrentstep += 1 arcpy.AddMessage("Creating Thiessen polygons - Step " + str(ncurrentstep) + "/" + str(nstep)) ThiessenPoly = arcpy.CreateThiessenPolygons_analysis( PolySplitToPoint, "in_memory\\ThiessenPoly", "ALL") JoinTEMP = arcpy.SpatialJoin_analysis( ThiessenPoly, PolySplitToPoint, "in_memory\\JoinTEMP", "JOIN_ONE_TO_ONE", "KEEP_ALL", "Rank_UGO \"Rank_UGO\" true true false 4 Long 0 0 ,First,#, in_memory\\PolySplitToPoint,Rank_UGO,-1,-1; Distance \"Distance\" true true false 4 Long 0 0 ,First,#,in_memory\\PolySplitToPoint,Distance,-1,-1", "INTERSECT", "", "") Join = arcpy.Sort_management( JoinTEMP, "in_memory\\Join", [["Rank_UGO", "ASCENDING"], ["Distance", "ASCENDING"]]) ncurrentstep += 1 arcpy.AddMessage("Merging Thiessen polygons - Step " + str(ncurrentstep) + "/" + str(nstep)) Dissolve1 = arcpy.Dissolve_management(Join, "in_memory\\Dissolve1", "Rank_UGO", "", "MULTI_PART", "DISSOLVE_LINES") ncurrentstep += 1 arcpy.AddMessage("Finalizing the centerline - Step " + str(ncurrentstep) + "/" + str(nstep)) Dissolve1ToLine = arcpy.Intersect_analysis([Dissolve1, Dissolve1], "in_memory\\Dissolve1ToLine", "", "", "LINE") UPD_SL.UpToDateShapeLengthField(Dissolve1ToLine) arcpy.DeleteIdentical_management(Dissolve1ToLine, ["Shape_Length"]) RawCenterline = arcpy.Intersect_analysis([Dissolve1ToLine, Polygon], "in_memory\\RawCenterline", "ALL", "", "INPUT") ncurrentstep += 1 arcpy.AddMessage("Smoothing centerline - Step " + str(ncurrentstep) + "/" + str(nstep)) Centerline = arcpy.SmoothLine_cartography(RawCenterline, Output, "PAEK", Smoothing, "FIXED_CLOSED_ENDPOINT", "NO_CHECK") #/deleting residual fields try: arcpy.DeleteField_management(Centerline, [ "FID_Dissolve1ToLine", "FID_Dissolve1", "FID_Dissolve1_1", "ORIG_FID", "Rank_UGO", "Rank_UGO_1", "FID_" + str(name) ]) except: pass try: arcpy.DeleteField_management(Centerline, [ "FID_Dissol", "FID_Diss_1", "FID_Diss_2", "FID_" + str(name)[0:6], "ORIG_FID", "Rank_UGO", "Rank_UGO_1", "Shape_Leng", "Shape_Le_1" ]) except: pass #=============================================================================== # DELETING TEMPORARY FILES #=============================================================================== ncurrentstep += 1 arcpy.AddMessage("Deleting temporary files - Step " + str(ncurrentstep) + "/" + str(nstep)) ClearInMemory.main() return # main(Polygon,Polyline,DisaggregationStep,Smoothing,Output)
#Find endpoints that are either on the left/right side of the streamline route arcpy.AddMessage( "Finding endpoints that are river left vs. river right... ") rivLeftExpr = '"DISTANCE" <= 0' rivRightExpr = '"DISTANCE" >= 0' ptRiverLeft = arcpy.FeatureClassToFeatureClass_conversion( tableLayer, General_GDB, "ptRiverLeft", rivLeftExpr) ptRiverRight = arcpy.FeatureClassToFeatureClass_conversion( tableLayer, General_GDB, "ptRiverRight", rivRightExpr) #tableLayer was causing lock when trying to delete General_GDB (Arcgis error 000603) arcpy.Delete_management(tableLayer) #Smooth the valley walls arcpy.SmoothLine_cartography(valleyLeft, smthValleyLeft, "BEZIER_INTERPOLATION") arcpy.SmoothLine_cartography(valleyRight, smthValleyRight, "BEZIER_INTERPOLATION") #Find the nearest valley wall from the transect endpoints arcpy.Near_analysis(ptRiverLeft, smthValleyLeft, "", "LOCATION", "NO_ANGLE") arcpy.Near_analysis(ptRiverRight, smthValleyRight, "", "LOCATION", "NO_ANGLE") #Create lines from endpoints to valley wall arcpy.AddMessage("Creating lines from endpoints to valley wall... ") arcpy.XYToLine_management(ptRiverLeft, lineRiverLeft, "X_UTM", "Y_UTM", "NEAR_X", "NEAR_Y", "GEODESIC", "", spatial_reference) arcpy.XYToLine_management(ptRiverRight, lineRiverRight, "NEAR_X", "NEAR_Y",
# Flowlines # ========= currentStreams = sourceDirectory + "/correctedFlowlines" + region # Smooth the flowlines to follow a more natural path simplifedLine = CA.SimplifyLine(currentStreams, workspace_db + "/simplifyFlowlines" + region, "BEND_SIMPLIFY", "60 Meters", "FLAG_ERRORS", "KEEP_COLLAPSED_POINTS", "CHECK") smoothedLine = arcpy.SmoothLine_cartography(simplifedLine, workspace_db + "/smoothedFlowlines" + region, "PAEK", "60 Meters", "FIXED_CLOSED_ENDPOINT", "FLAG_ERRORS") # Disable z + m values arcpy.env.outputMFlag = "Disabled" arcpy.env.outputZFlag = "Disabled" # Export to geodatabase finalLines = arcpy.FeatureClassToFeatureClass_conversion(smoothedLine, hydrography_db, "Flowlines" + region) # Add length arcpy.AddField_management(finalLines,
''' contour_post.py Contour post processing Simplifies lines and smooths them based on user input regarding precision This is intended for use with DEM derived contours Steven Porter [email protected] 3/7/12 ''' import arcpy, sys contours = sys.argv[0] precision = sys.argv[2] output = sys.argv[3] from arcpy import env env.workspace = 'C:\\Windows\\Temp' #simplify line by removing unneeded vertices temp = arcpy.SimplifyLine_cartography(contours, "temp", precision) #smooth line of any sharp bends arcpy.SmoothLine_cartography(temp, output, "PAEK", precision ^ 2 * math.pi) #delete temp file arcpy.Delete_managment(temp)
arcpy.FeatureToPoint_management(mupolygon, "MU_point", "INSIDE") arcpy.MakeFeatureLayer_management('MU_lines_dis', 'MU_lines_select') arcpy.Delete_management('MU_lines_dis') arcpy.Delete_management("MU_lines") if query: arcpy.MakeFeatureLayer_management(mupolygon, 'MU_select', query) arcpy.SelectLayerByLocation_management("MU_lines_select","SHARE_A_LINE_SEGMENT_WITH",\ 'MU_select',"#","NEW_SELECTION") arcpy.SelectLayerByLocation_management("MU_lines_select","SHARE_A_LINE_SEGMENT_WITH",sapolygon,\ '#',"REMOVE_FROM_SELECTION") else: arcpy.SelectLayerByLocation_management("MU_lines_select","SHARE_A_LINE_SEGMENT_WITH",sapolygon,\ '#',"NEW_SELECTION","INVERT") arcpy.SmoothLine_cartography("MU_lines_select", "MU_lines_gen", "PAEK",\ "25 Meters","FIXED_CLOSED_ENDPOINT", "NO_CHECK") arcpy.Generalize_edit("MU_lines_gen", "2 Meters") arcpy.SelectLayerByAttribute_management("MU_lines_select", "SWITCH_SELECTION") arcpy.Merge_management("MU_lines_select;MU_lines_gen", "MU_lines_gen_merge") arcpy.FeatureToPolygon_management("MU_lines_gen_merge", "MU_gen",\ "", "ATTRIBUTES", "MU_point") arcpy.Delete_management("MU_lines_gen_merge") arcpy.Delete_management("MU_point") arcpy.Delete_management("MU_lines_gen") if query: arcpy.MakeFeatureLayer_management('MU_gen', 'MU_gen_select', query) #Step 1 #Expect to see several warnings of features dissappearing arcpy.Buffer_analysis("MU_gen_select", "MU_negbuff19", "-" + str(min_width) + " Meters")