def estabFOVfootprint(DEM_raster_layer,Camera_point_layer,Smoothing_Tolerance): # Spatial Analyst Tools > Surface > Visibility arcpy.gp.Visibility_sa(DEM_raster_layer,Camera_point_layer,"in_memory\\rawVisRast",\ "","FREQUENCY","NODATA","0.00001201","FLAT_EARTH","0.13","","",\ "OFFSETA","","","AZIMUTH1","AZIMUTH2","VERT1","VERT2") # Spatial Analyst Tools > Generalization > Boundary Clean arcpy.gp.BoundaryClean_sa("in_memory\\rawVisRast","in_memory\\clnVisRast","ASCEND","TWO_WAY") arcpy.Delete_management("in_memory\\rawVisRast") # Conversion Tools > From Raster > Raster to Polygon arcpy.RasterToPolygon_conversion("in_memory\\clnVisRast","in_memory\\visPoly","NO_SIMPLIFY","") arcpy.Delete_management("in_memory\\clnVisRast") # Cartographic Tools > Generalization > Smooth Polygon arcpy.SmoothPolygon_cartography("in_memory\\visPoly","in_memory\\smthVisPoly","PAEK",\ Smoothing_Tolerance,"NO_FIXED","NO_CHECK") arcpy.Delete_management("in_memory\\visPoly") # Analysis Tools > Overlay > Union arcpy.Union_analysis("in_memory\\smthVisPoly","in_memory\\uniVisPoly","ALL","","NO_GAPS") arcpy.Delete_management("in_memory\\smthVisPoly") # Data Management Tools > Generalization > Dissolve footprintFOVout = "in_memory\\whlVisPoly" arcpy.Dissolve_management("in_memory\\uniVisPoly",footprintFOVout,"","",\ "SINGLE_PART","DISSOLVE_LINES") arcpy.Delete_management("in_memory\\uniVisPoly") return footprintFOVout
def updateMDLASGeometry(geometry_type, filegdb_path, md_path, area_percent, point_interval): ''' geometry_type = ["BOUNDARY", "FOOTPRINT"] ''' geometry_name = "LAS" # Create an in-memory feature class to hold the geometry geometry_export = os.path.join(filegdb_path, "{}_{}_Export".format(geometry_type, geometry_name)) if arcpy.Exists(geometry_export): arcpy.Delete_management(geometry_export) Utility.addToolMessages() # Export the geometry to the in-memory feature class arcpy.ExportMosaicDatasetGeometry_management(md_path, geometry_export, where_clause="#", geometry_type=geometry_type) Utility.addToolMessages() # Remove the holes and save to a feature class in the file geodatabase geometry_no_holes = os.path.join(filegdb_path, "{}_{}_NoHoles".format(geometry_type, geometry_name)) if arcpy.Exists(geometry_no_holes): arcpy.Delete_management(geometry_no_holes) Utility.addToolMessages() arcpy.EliminatePolygonPart_management(geometry_export, geometry_no_holes, condition="PERCENT", part_area="0 SquareMeters", part_area_percent=area_percent, part_option="CONTAINED_ONLY") Utility.addToolMessages() # Smooth the polygons geometry_smooth = os.path.join(filegdb_path, "{}_{}".format(geometry_type, geometry_name)) if arcpy.Exists(geometry_smooth): arcpy.Delete_management(geometry_smooth) Utility.addToolMessages() arcpy.SmoothPolygon_cartography(geometry_no_holes, geometry_smooth, "PAEK", point_interval, "FIXED_ENDPOINT", "NO_CHECK") Utility.addToolMessages() # Clean up if arcpy.Exists(geometry_export): arcpy.Delete_management(geometry_export) Utility.addToolMessages() if arcpy.Exists(geometry_no_holes): arcpy.Delete_management(geometry_no_holes) Utility.addToolMessages() # import simplified Footprints/boundary arcpy.ImportMosaicDatasetGeometry_management(md_path, target_featureclass_type=geometry_type, target_join_field="OBJECTID", input_featureclass=geometry_smooth, input_join_field="OBJECTID") Utility.addToolMessages()
def Step4SmoothPolygon( Input_Barrier_Layers_2_, Smoothing_Tolerance, Output_Simplify, Output_Smooth, Smoothing_Algorithm="PAEK", Preserve_endpoint_for_rings=True, Handling_Topological_Errors_2_="NO_CHECK"): # Step4SmoothPolygon # To allow overwriting outputs change overwriteOutput option to True. arcpy.env.overwriteOutput = False # Process: Smooth Polygon (Smooth Polygon) arcpy.SmoothPolygon_cartography( in_features=Output_Simplify, out_feature_class=Output_Smooth, algorithm=Smoothing_Algorithm, tolerance=Smoothing_Tolerance, endpoint_option=Preserve_endpoint_for_rings, error_option=Handling_Topological_Errors_2_, in_barriers=Input_Barrier_Layers_2_)
def execute(in_feature, out_feature, contour_level=None): arcpy.env.overwriteOutput = True arcpy.env.workspace = "in_memory" workspace = "in_memory" # Maintain a list so we can easily merge them back fn_list = [] temp_file = [] cntr = os.path.basename(in_feature) if contour_level is None: levels = range(15, 50, 5) else: levels = contour_level for value in levels: try: out1 = arcpy.CreateUniqueName( arcpy.ValidateTableName(cntr.replace(".shp", "_%d" % value)), workspace) arcpy.Select_analysis(in_feature, out1, where_clause="CONTOUR=%d" % value) print "Select into %s where contour=%d" % (out1, value) temp_file.append(out1) out2_0 = arcpy.CreateUniqueName(out1, workspace) arcpy.FeatureToPolygon_management(out1, out2_0) out2_1 = arcpy.CreateUniqueName(out2_0, workspace) arcpy.Union_analysis([out2_0], out2_1, join_attributes="ONLY_FID", gaps="NO_GAPS") out2 = arcpy.CreateUniqueName(out2_1, workspace) arcpy.Dissolve_management(out2_1, out2, multi_part="SINGLE_PART") temp_file.append(out2_0) temp_file.append(out2_1) temp_file.append(out2) out3 = arcpy.CreateUniqueName(out2, workspace) # Remove some points arcpy.Generalize_edit(out2, "200 Meters") # Then do a smooth out3 = arcpy.CreateUniqueName(out2, workspace) arcpy.SmoothPolygon_cartography(out2, out3, "PAEK", "7000 Meters", "NO_FIXED") print "Copy and smooth %s -> %s" % (out2, out3) calc_field(out3, { "AREA1": "!shape.area!", "dbZ": "%d" % value }, True) temp_file.append(out3) out4 = arcpy.CreateUniqueName(out3, workspace) arcpy.Select_analysis(out3, out4, where_clause="AREA1>30000000") temp_file.append(out4) fn_list.append(out4) except Exception, ex: print ex.message continue
# define local variables from the CSV headings CSV_x = "X" CSV_y = "Y" CSV_z = "D" # make the event layer arcpy.MakeXYEventLayer_management(csv_file, CSV_x, CSV_y, temp1, CSV_coordinate_system, CSV_z) # save to temporary shapefile arcpy.CopyFeatures_management(temp1, temp2) # make feature layer for select by attribute tool arcpy.MakeFeatureLayer_management(temp2, temp2a) # select only depths greater than 0.05 ft arcpy.SelectLayerByAttribute_management(temp2a, "NEW_SELECTION", "D>0.05") # save only selected features to shapefile arcpy.CopyFeatures_management(temp2a, output1) # clear selection arcpy.SelectLayerByAttribute_management(temp2a, "CLEAR_SELECTION") # aggregate point features to create temporary polygon arcpy.AggregatePoints_cartography(output1, temp3, "50") # smooth temporary polygon arcpy.SmoothPolygon_cartography(temp3, output2, "PAEK", 30) # delete in_memory objects (temps) arcpy.Delete_management("in_memory")
arcpy.Buffer_analysis(Aggregate_Polygon, Buffer_Polygon, Buffer_Distance, sideType, endType, dissolveType, dissolveField, Method) # Dissolve buffered polygon arcpy.AddMessage( "Creating concave polygon based on maximum point distances (step 3 of 3)..." ) arcpy.Dissolve_management(Buffer_Polygon, Dissolve_Polygon, "", "", "MULTI_PART", "DISSOLVE_LINES") # Smooth polygon using Bezier Interpolation and export without clipping if Clip_Dataset == "": arcpy.AddMessage( "No clip dataset was specified, exporting concave hull polygon...") arcpy.SmoothPolygon_cartography(Dissolve_Polygon, Concave_Hull, "BEZIER_INTERPOLATION", "0 Meters", "FIXED_ENDPOINT", "NO_CHECK") # Smooth polygon using Bezier Interpolation and clip the output elif Clip_Dataset != "": arcpy.SmoothPolygon_cartography(Dissolve_Polygon, Smooth_Polygon, "BEZIER_INTERPOLATION", "0 Meters", "FIXED_ENDPOINT", "NO_CHECK") xy_tolerance = "" arcpy.AddMessage("Clipping concave hull polygon to the clip dataset...") arcpy.Clip_analysis(Smooth_Polygon, Clip_Dataset, Concave_Hull, xy_tolerance) else: arcpy.AddError("An invalid clip dataset was entered.") # Delete intermediate data arcpy.Delete_management(Search_Raster)
def ExtractRange(outRaster, outFilePath, file): inSQLClause = "VALUE > 0" try: # Execute ExtractByAttributes attExtract = arcpy.sa.ExtractByAttributes(outRaster, inSQLClause) print('87') sys.stdout.flush() # Save the output #attExtract.save("F:\\ree\\PM25T08.tif") rasfile = os.path.split(outRaster)[1] in_point_features = os.path.join(file, u"RasterToPoint_conversion.shp") out_feature_class = os.path.join(file, u"AggregatePoints_cartography.shp") out_SmoothPolygon_class = os.path.join(file, u"out_SmoothPolygon_class.shp") calculate_output = os.path.join(file, u"calculate_output.shp") try: arcpy.RasterToPoint_conversion(attExtract, in_point_features, "VALUE") except: pass try: arcpy.AggregatePoints_cartography(in_point_features, out_feature_class, 30) except: pass try: arcpy.SmoothPolygon_cartography(out_feature_class, out_SmoothPolygon_class, 'PAEK', 30) except: pass try: # Process: Calculate Areas... arcpy.CalculateAreas_stats(out_SmoothPolygon_class, calculate_output) except: # If an error occurred when running the tool, print out the error message. traceback.print_exc() try: arcpy.Delete_management(in_point_features) except: traceback.print_exc() try: arcpy.DeleteFeatures_management(out_SmoothPolygon_class) except: traceback.print_exc() try: arcpy.DeleteFeatures_management(out_feature_class) except: traceback.print_exc() try: arcpy.Delete_management(out_feature_class) except: traceback.print_exc() try: arcpy.Delete_management(out_SmoothPolygon_class) except: traceback.print_exc() except Exception as err: arcpy.AddMessage("ExtractByAttributes Failed") arcpy.AddMessage(err) traceback.print_exc() return
def Overview(Input_Geologic_Features, Output_Finished, Aggregation_Distance, Minimum_Area="0 Unknown", Minimum_Hole_Size="0 Unknown", Preserve_orthogonal_shape=False, Barrier_Features, Simplification_Algorithm="POINT_REMOVE", Simplification_Tolerance, Minimum_Area_2_="0 Unknown", Handling_Topological_Errors="RESOLVE_ERRORS", Keep_collapsed_points=True, Input_Barrier_Layers, Smoothing_Algorithm="PAEK", Smoothing_Tolerance, Preserve_endpoint_for_rings=True, Handling_Topological_Errors_2_="NO_CHECK", Input_Barrier_Layers_2_, Distance_value_or_field_, Side_Type="FULL", End_Type="ROUND", Dissolve_Type="NONE", Dissolve_Field_s_, Method="PLANAR", Condition="AREA", Area="0 Unknown", Percentage=0, Eliminate_contained_parts_only=True): # Overview # To allow overwriting outputs change overwriteOutput option to True. arcpy.env.overwriteOutput = False # Process: Union (Union) Output_Union = "" arcpy.Union_analysis(in_features=Input_Geologic_Features, out_feature_class=Output_Union, join_attributes="ALL", cluster_tolerance="", gaps="GAPS") # Process: Multipart To Singlepart (Multipart To Singlepart) Output_Singlepart = "" arcpy.MultipartToSinglepart_management(in_features=Output_Union, out_feature_class=Output_Singlepart) # Process: Aggregate Polygons (Aggregate Polygons) Output_Aggregate = "" arcpy.AggregatePolygons_cartography( in_features=Output_Singlepart, out_feature_class=Output_Aggregate, aggregation_distance=Aggregation_Distance, minimum_area=Minimum_Area, minimum_hole_size=Minimum_Hole_Size, orthogonality_option=Preserve_orthogonal_shape, barrier_features=Barrier_Features, out_table=Output_Table) # Process: Simplify Polygon (Simplify Polygon) Output_Simplify = "" output_feature_class_Pnt = \ arcpy.SimplifyPolygon_cartography(in_features=Output_Aggregate, out_feature_class=Output_Simplify, algorithm=Simplification_Algorithm, tolerance=Simplification_Tolerance, minimum_area=Minimum_Area_2_, error_option=Handling_Topological_Errors, collapsed_point_option=Keep_collapsed_points, in_barriers=Input_Barrier_Layers)[0] # Process: Smooth Polygon (Smooth Polygon) Output_Smooth = "" arcpy.SmoothPolygon_cartography( in_features=Output_Simplify, out_feature_class=Output_Smooth, algorithm=Smoothing_Algorithm, tolerance=Smoothing_Tolerance, endpoint_option=Preserve_endpoint_for_rings, error_option=Handling_Topological_Errors_2_, in_barriers=Input_Barrier_Layers_2_) # Process: Buffer (Buffer) Output_Buffer = "" arcpy.Buffer_analysis(in_features=Output_Smooth, out_feature_class=Output_Buffer, buffer_distance_or_field=Distance_value_or_field_, line_side=Side_Type, line_end_type=End_Type, dissolve_option=Dissolve_Type, dissolve_field=Dissolve_Field_s_, method=Method) # Process: Eliminate Polygon Part (Eliminate Polygon Part) arcpy.EliminatePolygonPart_management( in_features=Output_Buffer, out_feature_class=Output_Finished, condition=Condition, part_area=Area, part_area_percent=Percentage, part_option=Eliminate_contained_parts_only)
#set workspace from arcpy import env env.workspace = os.path.dirname(v_points) #set overwrite and warn if needed env.overwriteOutput = True if arcpy.Exists(v_output): arcpy.AddWarning("Overwritting "+v_output) arcpy.Copy_management(v_points, "Input") #Check inputs errorFlag = False if arcpy.Describe("Input").shapeType == "Polygon": arcpy.AddWarning("Converting Polygons to Vertex Points, this will increase time to solve") arcpy.SmoothPolygon_cartography("Input","SmoothInput","BEZIER_INTERPOLATION",0, False ) arcpy.FeatureVerticesToPoints_management("SmoothInput","Input2") arcpy.Delete_management("Input") arcpy.Delete_management("SmoothInput") arcpy.Rename_management("Input2","Input") if arcpy.Describe("Input").shapeType == "Polyline": arcpy.AddWarning("Converting Lines to Vertex Points, this will increase time to solve") arcpy.FeatureVerticesToPoints_management("Input","Input2") arcpy.Delete_management("Input") arcpy.Rename_management("Input2","Input") if not arcpy.Describe("Input").shapeType == "Point": arcpy.AddError("Final Input Not Points, Check input feature class") errorFlag = True
MinimumArea, MinimumHoleSize, "NON_ORTHOGONAL") if str(SmoothingVB) != "0": ncurrentstep += 1 arcpy.AddMessage("Eliminating Polygon Parts | CleanStep 2 - Step " + str(ncurrentstep) + "/" + str(nstep)) EliminatedVB = arcpy.EliminatePolygonPart_management( AggregatedVB, "%scratchWorkspace%\\EliminatedVB", "AREA", MinimumHoleSize, "", "ANY") ncurrentstep += 1 arcpy.AddMessage("Smoothing Valley Bottom | CleanStep 3 - Step " + str(ncurrentstep) + "/" + str(nstep)) VB = arcpy.SmoothPolygon_cartography(EliminatedVB, Output, "PAEK", SmoothingVB, "FIXED_ENDPOINT", "NO_CHECK") else: ncurrentstep += 1 arcpy.AddMessage("Eliminating Polygon Part | CleanStep 2 - Step " + str(ncurrentstep) + "/" + str(nstep)) VB = arcpy.EliminatePolygonPart_management(AggregatedVB, Output, "AREA", MinimumHoleSize, "", "ANY") #=============================================================================== # DELETING TEMPORARY FILES #=============================================================================== if str(DeleteTF) == "true": ncurrentstep += 1 arcpy.AddMessage("Delete temporary files - Step " + str(ncurrentstep) +
arcpy.sa.ExtractMultiValuesToPoints(deepest_point, [[bathy_dataset, "DEPTH"]], "NONE") # Add fields to depression polygons for calculations float_fields = ["MAJ_AXIS", "MIN_AXIS", "ECC", "AZIMUTH", "THIN_RAT", "PERIMETER", "AREA_M", "DIDP_RAT"] for field in float_fields: arcpy.AddField_management(depression_polygons, field, "FLOAT") # Add morphological characteristics and azimuth field. arcpy.AddField_management(depression_polygons, "MORP_CHAR", "TEXT", field_length=80) arcpy.AddField_management(depression_polygons, "DEP_ID", "SHORT") # Smooth depression polygons describe = arcpy.Describe(bathy_dataset) cell_size = describe.meanCellWidth min_area = (cell_size * 2) ** 2 tolerance = cell_size * 3 depression_polygons = arcpy.SmoothPolygon_cartography(depression_polygons, None, "PAEK", tolerance, "NO_FIXED") arcpy.AddMessage("Polygons smoothed.") # Calculate major axis, minor axis, azimuth, and eccentricity fields with arcpy.da.UpdateCursor(depression_polygons, ["SHAPE@", "DEP_ID", "AREA_M", "PERIMETER", "MAJ_AXIS", "MIN_AXIS", "ECC", "AZIMUTH", "THIN_RAT", "MORP_CHAR", "DIDP_RAT", "POCK_DEP"]) as cursor: dep_id = 1 for row in cursor: shape_object = row[0] row[1] = dep_id row[2] = shape_object.area row[3] = shape_object.length x1, y1, x2, y2, x3, y3, x4, y4 = [float(coord) for coord in shape_object.hullRectangle.split(" ")] distance1 = math.hypot((x1 - x2), (y1 - y2)) distance2 = math.hypot((x2 - x3), (y2 - y3))
# Calculate raster mean within a 1.5 km grid arcpy.AddMessage("Calculating spatial certainty of sample representation...") sample_zonal = FocalStatistics(sample_nowater, NbrRectangle(50, 50, "CELL"), "MEAN", "DATA" ) extract_zonal = ExtractByMask(sample_zonal, area_of_interest) arcpy.CopyRaster_management(extract_zonal, spatial_certainty, "", "", -9999, "NONE", "NONE", "32_BIT_FLOAT", "NONE", "NONE", "TIFF", "NONE") # Resample spatial certainty to 1 km grid arcpy.AddMessage("Resampling spatial certainty to 1 km grid...") arcpy.Resample_management(spatial_certainty, certainty_resample, "1000", "BILINEAR") # Set the values below a threshold to null arcpy.AddMessage("Converting spatial certainty to study area raster...") threshold = int(threshold)/100 resample_null = SetNull(certainty_resample, 1, "VALUE < %f" % threshold) # Convert raster to polygon arcpy.AddMessage("Converting raster to polygon...") arcpy.RasterToPolygon_conversion(resample_null, initial_studyarea, "SIMPLIFY", "VALUE", "SINGLE_OUTER_PART", "") # Simplify the polygon arcpy.AddMessage("Simplifying study area polygon...") arcpy.SimplifyPolygon_cartography(initial_studyarea, simplify_studyarea, "POINT_REMOVE", 1000, 1000000000, "", "NO_KEEP", "") # Smooth the polygon arcpy.AddMessage("Smoothing study area polygon...") arcpy.SmoothPolygon_cartography(simplify_studyarea, study_area, "PAEK", 50000, "FIXED_ENDPOINT", "NO_CHECK") # Delete intermediate files arcpy.Delete_management(certainty_resample) arcpy.Delete_management(initial_studyarea) arcpy.Delete_management(simplify_studyarea)
# --- Raster to polygon (need to be feature type to use the function smooth) arcpy.RasterToPolygon_conversion(os.path.join(rasterfolder, "Raster123_Extract.tif"), "Autokast_Polygon", simplify="NO_SIMPLIFY", raster_field="Value") print("Raster to Feature type complete") # ---------------------------------------------------------------------------------------------------------------------- # --- Smooth polygons arcpy.SmoothPolygon_cartography(in_features="Autokast_Polygon", out_feature_class="Autokast_Smooth", algorithm="PAEK", tolerance="500 Meters", endpoint_option="FIXED_ENDPOINT", error_option="NO_CHECK") print("Smoothed") # --- Dissolve arcpy.Dissolve_management(in_features="Autokast_Smooth", out_feature_class="Autokast_Dissolve", dissolve_field="gridcode", statistics_fields="", multi_part="MULTI_PART", unsplit_lines="DISSOLVE_LINES") print("Dissolved")
import removeholes import arcpy workspace="C:/temp/outlines.gdb" inputNames=["D3_Q25","D3_R5","D3_R10"] arcpy.env.overwriteOutput=True arcpy.env.workspace=workspace for inputName in inputNames: print("Processing: " + inputName) desc = arcpy.Describe(inputName) baseName=desc.baseName arcpy.MultipartToSinglepart_management(inputName, baseName + "_single") removeholes.RemovePolygonHoles_management(baseName + "_single", baseName + "_noholes", 300) arcpy.CopyFeatures_management(baseName + "_noholes", baseName + "_nosmalls") expression = arcpy.AddFieldDelimiters("tempLayer", "SHAPE_AREA") + " < 300" arcpy.MakeFeatureLayer_management(baseName + "_nosmalls", "tempLayer") arcpy.SelectLayerByAttribute_management("tempLayer", "NEW_SELECTION", expression) arcpy.DeleteFeatures_management("tempLayer") arcpy.SmoothPolygon_cartography(baseName + "_nosmalls", baseName + "_carto", "PAEK", 100)