def fill_polygon_gaps(points, master_polys, ac_polys, counter): #calculate dist of points from ac polygons arcpy.Near_analysis(points, ac_polys) #copy result into second field arcpy.AddField_management(points, "NEAR_DIST2", "FLOAT") arcpy.CalculateField_management(points, "NEAR_DIST2", "!NEAR_DIST!", "PYTHON_9.3") #calculate dist of points from bankfull polys arcpy.Near_analysis(points, master_polys) #select points that are adj to ac_polys, but not adj to bankfull polys query = "NEAR_DIST2<=5 AND NEAR_DIST>0" lyr = arcpy.MakeFeatureLayer_management(points, "layera", query) #save these points into new feature class copy_features(lyr, env.workspace, naming + "gap_points" + str(counter)) gap_points = os.path.join(env.workspace, naming + "gap_points" + str(counter)) #calculate dist of gap points to other points arcpy.Near_analysis(points, gap_points) #select points that are adj to gap points and not in ac_polys query = "NEAR_DIST<=7.071 AND NEAR_DIST2>0" lyr = arcpy.MakeFeatureLayer_management(points, "layerb", query) #save these points into new feature class copy_features(lyr, env.workspace, naming + "gap_points2" + str(counter)) gap_points = os.path.join(env.workspace, naming + "gap_points2" + str(counter)) #turn these points into polygons gap_polys = os.path.join( env.workspace, naming + "bankfull_polys_with_gaps" + str(counter)) arcpy.AggregatePoints_cartography(gap_points, gap_polys, "7.5 meters") #merge these polygons with the master bankfull polygons filled_polys = os.path.join(env.workspace, naming + "bankfull_beforeagg" + str(counter)) arcpy.Merge_management([gap_polys, master_polys], filled_polys) #aggregate polys final_polys = os.path.join(env.workspace, naming + "bankfull_polys_final" + str(counter)) arcpy.AggregatePolygons_cartography(filled_polys, final_polys, "7.5 Meters") #after aggreagating polygons there will be a bunch of BS little polygons that we don't need #use dissolve tool to eliminate these little guys, but first you must use near tool to get proper #parameters for dissolving. we are going to dissolve by nearest stream so run near on polygons and streams. ## arcpy.Near_analysis(pred_final_polys,ac_polys) ## ## final_polys=os.path.join(env.workspace,naming+"bankfull_polys_final"+str(counter)) ## arcpy.Dissolve_management(pred_final_polys, final_polys,["NEAR_FID", "TAXCODE"]) return final_polys
def crear_limite_aeus(self): arcpy.env.overwriteOutput = True path_manzana = path.join(self.path_trabajo, 'tb_manzana_procesar') arcpy.MakeFeatureLayer_management(path_manzana, "tb_manzana_procesar") for aeu in self.list_aeu: list_aeu_man = [ [d['UBIGEO'], d['ZONA'], d['MANZANA']] for d in self.list_aeu_manzanas if (d['AEU'] == aeu['AEU'] and d['UBIGEO'] == aeu['UBIGEO'] and d['ZONA'] == aeu['ZONA']) ] where_manzanas = expresion.expresion_2( list_aeu_man, [["UBIGEO", "TEXT"], ["ZONA", "TEXT"], ["MANZANA", "TEXT"]]) tb_manzana_select = arcpy.SelectLayerByAttribute_management( "tb_manzana_procesar", "NEW_SELECTION", where_manzanas) if (int(arcpy.GetCount_management(tb_manzana_select).getOutput(0)) > 0): out_feature = arcpy.AggregatePolygons_cartography( tb_manzana_select, 'in_memory/manzanas_{}{}{}'.format(aeu["UBIGEO"], aeu["ZONA"], aeu["AEU"]), "30 METERS") out_feature_1 = arcpy.Dissolve_management( out_feature, 'in_memory/dissolve_manzanas_{}{}{}'.format( aeu["UBIGEO"], aeu["ZONA"], aeu["AEU"])) add_fields = [ ["UBIGEO", "TEXT", "'{}'".format(aeu["UBIGEO"])], ["ZONA", "TEXT", "'{}'".format(aeu["ZONA"])], ["AEU", "TEXT", "'{}'".format(str(aeu["AEU"]).zfill(3))], ["TOTAL_EST", "SHORT", int(aeu["TOTAL_EST"])], ["CANT_EST", "SHORT", int(aeu["CANT_EST"])], ["MERCADO", "SHORT", int(aeu["MERCADO"])], ["PUESTO", "SHORT", int(aeu["PUESTO"])], ["N_MANZANAS", "SHORT", int(len(list_aeu_man))], ["COD_OPER", "TEXT", "'{}'".format(self.cod_oper)] ] for add_field in add_fields: arcpy.AddField_management(out_feature_1, add_field[0], add_field[1]) arcpy.CalculateField_management(out_feature_1, add_field[0], add_field[2], "PYTHON_9.3") if arcpy.Exists(self.path_aeu): arcpy.Append_management(out_feature_1, self.path_aeu, "NO_TEST") else: arcpy.CopyFeatures_management(out_feature_1, self.path_aeu)
def RasterToLandPerimeter(in_raster, out_polygon, threshold, agg_dist='30 METERS', min_area='300 SquareMeters', min_hole_sz='300 SquareMeters', manualadditions=None): """ Raster to Polygon: DEM => Reclass => MHW line """ r2p = os.path.join(arcpy.env.scratchGDB, out_polygon+'_r2p_temp') r2p_union = os.path.join(arcpy.env.scratchGDB, out_polygon+'_r2p_union_temp') # Reclassify the DEM: 1 = land above threshold; the rest is nodata rastertemp = arcpy.sa.Con(arcpy.sa.Raster(in_raster)>threshold, 1, None) # temporary layer classified from threshold # Convert the reclass raster to a polygon arcpy.RasterToPolygon_conversion(rastertemp, r2p) # polygon outlining the area above MHW if manualadditions: # Manually digitized any large areas missed by the lidar arcpy.Union_analysis([manualadditions,r2p], r2p_union, gaps='NO_GAPS') arcpy.AggregatePolygons_cartography(r2p_union, out_polygon, agg_dist, min_area, min_hole_sz) else: arcpy.AggregatePolygons_cartography(r2p, out_polygon, agg_dist, min_area, min_hole_sz) print('Aggregation distance: {}\nMinimum area: {}\nMinimum hole size: {}'.format(agg_dist, min_area, min_hole_sz)) return(out_polygon)
def Step2AggregatePolygons( Aggregation_Distance, Barrier_Features, Output_Singlepart, Output_Aggregate, Minimum_Area="0 Unknown", Minimum_Hole_Size="0 Unknown", Preserve_orthogonal_shape=False): # Step2AggregatePolygons # To allow overwriting outputs change overwriteOutput option to True. arcpy.env.overwriteOutput = False # Process: Aggregate Polygons (Aggregate Polygons) 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)
fcnames = ['LayoutNo', 'Hyperlink', 'ApplicationReferenceNo'] # Count number of outlines complete completeCount = 0 for fc in fclist: # Outpath for parcel layer copy parcelOutline = os.path.join(outGDB, fc + "_" + "outline") # Check if outline exists, if exists, delete if arcpy.Exists(parcelOutline): arcpy.AddMessage("{0} outline already exists.".format(fc)) completeCount = completeCount + 1 else: # Use aggregate polygons within 5 meters of each other arcpy.AggregatePolygons_cartography(fc, parcelOutline, 5) # Add reference no, hyperlink and layout no fields arcpy.management.AddFields( parcelOutline, [['LayoutNo', 'TEXT', 'LayoutNo', 20, '', ''], ['Hyperlink', 'TEXT', 'Hyperlink', 150, '', ''], [ 'ApplicationReferenceNo', 'TEXT', 'Application Reference No', 12, '', '' ]]) # Extract layout no and url from fc with arcpy.da.SearchCursor(fc, fcnames) as scursor: for row in scursor: if row[0] is None: continue
def xu_ly_duong_bo_nuoc(self): arcpy.env.overwriteOutput = 1 # Khai bao bien SongSuoiA = self.duong_dan_nguon + "ThuyHe/SongSuoiA" MatNuocTinh = self.duong_dan_nguon + "ThuyHe/MatNuocTinh" KenhMuongA = self.duong_dan_nguon + "ThuyHe/KenhMuongA" lop_bai_boi = self.duong_dan_nguon + "ThuyHe/BaiBoiA" SongSuoiA_Copy = SongSuoiA + "_Copy" MatNuocTinh_Copy = MatNuocTinh + "_Copy" KenhMuongA_Copy = KenhMuongA + "_Copy" lop_thuy_he_Copy_Agg = SongSuoiA_Copy + "_Agg" lop_thuy_he_Copy_Agg_Tbl = self.duong_dan_nguon + "SongSuoiA_Copy_Agg_Tbl" lop_thuy_he_DuongBoNuoc = SongSuoiA_Copy + "_DuongBoNuoc" arcpy.Snap_edit(lop_bai_boi, [[KenhMuongA, "EDGE", self.khoang_Cach], [MatNuocTinh, "EDGE", self.khoang_Cach], [SongSuoiA, "EDGE", self.khoang_Cach]]) #Append arcpy.CopyFeatures_management(SongSuoiA, SongSuoiA_Copy) arcpy.AddField_management(SongSuoiA_Copy, "LOAI_RANH_GIOI", "LONG", None, None, None, "LOAI_RANH_GIOI", "NULLABLE") arcpy.CalculateField_management(SongSuoiA_Copy, "LOAI_RANH_GIOI", 6, "PYTHON_9.3") arcpy.CopyFeatures_management(MatNuocTinh, MatNuocTinh_Copy) arcpy.AddField_management(MatNuocTinh_Copy, "LOAI_RANH_GIOI", "LONG", None, None, None, "LOAI_RANH_GIOI", "NULLABLE") arcpy.CalculateField_management(MatNuocTinh_Copy, "LOAI_RANH_GIOI", 1, "PYTHON_9.3") arcpy.CopyFeatures_management(KenhMuongA, KenhMuongA_Copy) arcpy.AddField_management(KenhMuongA_Copy, "LOAI_RANH_GIOI", "LONG", None, None, None, "LOAI_RANH_GIOI", "NULLABLE") arcpy.CalculateField_management(KenhMuongA_Copy, "LOAI_RANH_GIOI", 4, "PYTHON_9.3") arcpy.Append_management( [lop_bai_boi, MatNuocTinh_Copy, KenhMuongA_Copy], SongSuoiA_Copy, "NO_TEST", None, None) #AggregatePolygons arcpy.AggregatePolygons_cartography(SongSuoiA_Copy, lop_thuy_he_Copy_Agg, "0.001 Meters", "0 SquareMeters", "0 SquareMeters", "NON_ORTHOGONAL", "", lop_thuy_he_Copy_Agg_Tbl) DM.JoinField(lop_thuy_he_Copy_Agg_Tbl, "INPUT_FID", SongSuoiA_Copy, "OBJECTID", None) #danh dau sông có diện tích lớn nhất trong group rows2 = arcpy.SearchCursor(lop_thuy_he_Copy_Agg_Tbl, sort_fields="OUTPUT_FID A") _outPut_id = 0 _area_max = 0 my_dict = {} for row2 in rows2: if row2.getValue("LOAI_RANH_GIOI") is not None: if _outPut_id == row2.getValue("OUTPUT_FID"): if _area_max < row2.getValue("Shape_Area"): _area_max = row2.getValue("Shape_Area") my_dict[row2.getValue("OUTPUT_FID")] = _area_max else: _area_max = row2.getValue("Shape_Area") my_dict[row2.getValue("OUTPUT_FID")] = _area_max _outPut_id = row2.getValue("OUTPUT_FID") #Update lại bảng join rows_update = arcpy.UpdateCursor(lop_thuy_he_Copy_Agg_Tbl) for row_update in rows_update: if row_update.getValue("LOAI_RANH_GIOI") is None: rows_update.deleteRow(row_update) else: if row_update.getValue("Shape_Area") != my_dict[ row_update.getValue("OUTPUT_FID")]: rows_update.deleteRow(row_update) del row_update del rows_update DM.JoinField(lop_thuy_he_Copy_Agg, "OBJECTID", lop_thuy_he_Copy_Agg_Tbl, "OUTPUT_FID", None) #Xóa bãi bồi trong Aggregate rows_update = arcpy.UpdateCursor(lop_thuy_he_Copy_Agg) for row_update in rows_update: if row_update.getValue("LOAI_RANH_GIOI") is None: rows_update.deleteRow(row_update) del row_update del rows_update #FeatureToLine arcpy.FeatureToLine_management([lop_thuy_he_Copy_Agg], lop_thuy_he_DuongBoNuoc, None, "ATTRIBUTES") #Chỉnh sửa lại field arcpy.DeleteField_management(lop_thuy_he_DuongBoNuoc, [ "FID_SongSuoiA_Copy2_Agg", "OUTPUT_FID", "INPUT_FID", "loaiTrangThaiNuocMat", "ten", "doRong", "SongSuoiA_Rep_ID", "SongSuoiA_Rep_OVERRIDE", "RuleID", "Override", "Shape_Length_1", "Shape_Area_1", "loaiTrangThaiDuongBoNuoc", "loaiRanhGioiNuocMat" ]) arcpy.AddField_management(lop_thuy_he_DuongBoNuoc, "loaiTrangThaiDuongBoNuoc", "SHORT", None, None, None, "Loai trang thai duong bo nuoc", "NULLABLE", None, "LoaiTrangThaiDuongBoNuoc") arcpy.AddField_management(lop_thuy_he_DuongBoNuoc, "loaiRanhGioiNuocMat", "LONG", None, None, None, "Loai ranh gioi nuoc mat", "NULLABLE", None, "LoaiRanhGioiNuocMat") arcpy.CalculateField_management(lop_thuy_he_DuongBoNuoc, "loaiTrangThaiDuongBoNuoc", 1, "PYTHON_9.3") arcpy.CalculateField_management(lop_thuy_he_DuongBoNuoc, "loaiRanhGioiNuocMat", "!LOAI_RANH_GIOI!", "PYTHON_9.3") arcpy.AssignDefaultToField_management(lop_thuy_he_DuongBoNuoc, "maDoiTuong", "LG01", None) arcpy.CalculateField_management(lop_thuy_he_DuongBoNuoc, "maDoiTuong", "'LG01'", "PYTHON_9.3") arcpy.DeleteField_management(lop_thuy_he_DuongBoNuoc, ["LOAI_RANH_GIOI"]) DuongBoNuoc_Path = self.duong_dan_nguon + "ThuyHe/DuongBoNuoc" if int(arcpy.GetCount_management(DuongBoNuoc_Path).getOutput(0)) > 0: arcpy.DeleteFeatures_management(DuongBoNuoc_Path) duongBoNuocFields = [ "SHAPE@", "maNhanDang", "ngayThuNhan", "ngayCapNhat", "maDoiTuong", "loaiTrangThaiDuongBoNuoc", "loaiRanhGioiNuocMat", "nguonDuLieu", "maTrinhBay", "tenManh", "soPhienHieuManhBanDo" ] duongBoNuocFields2 = [ "SHAPE@", "maNhanDang", "ngayThuNhan", "ngayCapNhat", "maDoiTuong", "loaiTrangThaiDuongBoNuoc", "loaiRanhGioiNuocMat", "nguonDuLieu", "maTrinhBay", "tenManh", "soPhienHieuManhBanDo", "DuongBoNuoc_Rep_ID" ] with arcpy.da.SearchCursor(lop_thuy_he_DuongBoNuoc, duongBoNuocFields) as sCur: with arcpy.da.InsertCursor(DuongBoNuoc_Path, duongBoNuocFields2) as iCur: for sRow in sCur: iCur.insertRow([ sRow[0], sRow[1], sRow[2], sRow[3], sRow[4], sRow[5], sRow[6], sRow[7], sRow[8], sRow[9], sRow[10], 1 ]) arcpy.CopyFeatures_management( DuongBoNuoc_Path, self.duong_dan_dich + "ThuyHe/DuongBoNuoc")
def main(): """ The main routine which processes stuff """ arcpy.AddMessage("Setting up workspace and parameters.") arcpy.env.overwriteOutput = True workspace = r"in_memory" arcpy.env.workspace = workspace output_date = datetime.datetime.now().strftime("%Y%m%d") output = arcpy.GetParameterAsText(0) if output == "#" or not output: output = r"D:\Projects\TreeProject\TreeProject.gdb\treecrops_{}".format( output_date) # Set more variables output_fc = output.split("\\")[-1] output_workspace = output.split(output_fc)[0][:-1] print(output_fc) print(output_workspace) # Create output FC if it doesn't exist if arcpy.Exists(output): pass else: print("Creating output feature class") arcpy.CreateFeatureclass_management(output_workspace, output_fc, "POLYGON", spatial_reference=4283) # For feature service connection # noinspection SpellCheckingInspection gis = GIS("http://arcgis.com", "jmckechn_une", "Leoj270592") print("Credentials verified: {}".format(gis)) rest_url = "https://services5.arcgis.com/3foZbDxfCo9kcPwP/arcgis/rest/services/" \ "TreeCrops_Editing/FeatureServer/0" # Try copying editing service to local gdb trees = output_workspace + "\\fs_download_{}".format(output_date) if arcpy.Exists(trees): arcpy.Delete_management(trees) print("Removing existing {}".format(trees)) else: print("Copying from service: {}".format(rest_url)) arcpy.CopyFeatures_management(rest_url, trees) print("Copy successful: {}".format(trees)) # Copy data to memory and set up feature layer trees_memory = r"in_memory/trees" trees_lyr = "trees_lyr" query = "(commodity IS NOT NULL AND commodity <> 'other') AND (stage IS NULL OR stage = '1' OR stage = '2')" print("Copying data to memory") arcpy.CopyFeatures_management(trees, trees_memory) arcpy.MakeFeatureLayer_management(trees_memory, trees_lyr, where_clause=query) # Remove ag_ features if they exist rem_list = arcpy.ListFeatureClasses("ag_*") for i in rem_list: print("Deleting {}".format(i)) arcpy.Delete_management(workspace + r"/" + i) # Get unique values print("Getting unique attributes from fields") field_list = ["commodity", "source", "year"] com_list = [] for i in field_list: if i == "commodity": u_list = unique_values(trees_lyr, i) for j in u_list: com_list.append(j) else: pass # # Remove banana for speed :) (testing) # print("Remove banana for speed :) (testing)") # com_list.remove("banana") print(com_list) update_list = [] print("Looping through selecting unique features to aggregate") for c in com_list: print(" Working on {} features".format(c)) print(" selecting") selection_query = "commodity = '{}'".format(c) arcpy.SelectLayerByAttribute_management(trees_lyr, "NEW_SELECTION", selection_query) ag_output = "ag_{}".format(c) print(" aggregating") arcpy.AggregatePolygons_cartography(trees_lyr, ag_output, "25 METERS", "1 HECTARES", "1 HECTARES", "ORTHOGONAL") print(" Adding and calculating field") arcpy.AddField_management(ag_output, "commodity", "TEXT") arcpy.CalculateField_management(ag_output, "commodity", "'{}'".format(c), "ARCADE") print(" created {}".format(ag_output)) # Copy aggregated features to output location print(" copying to output location") arcpy.CopyFeatures_management(ag_output, output + "_{}".format(c)) update_list.append(output + "_{}".format(c)) # make a list of ag_... feature classes and loop update analysis tool print("Joining features back together with update tool") loop_no = len(com_list) update_no = 0 update_output = output + "_update{}".format(update_no) print("update_list: {}".format(update_list)) print("loop_no: {}".format(loop_no)) print("update_no: {}".format(update_no)) print("update_output: {}".format(update_output)) arcpy.CopyFeatures_management(update_list[0], update_output) while update_no + 1 <= loop_no: loop_name = update_list[update_no].split("{}_".format(output_fc))[-1] print(" {} loop ({}/{})".format(loop_name, update_no + 1, loop_no)) if update_no == 0: arcpy.Update_analysis(update_output, update_list[update_no], output + "_update{}".format(update_no + 1)) print(" variables: {}, {}, {}".format( update_output, update_list[update_no], output + "_update{}".format(update_no + 1))) else: arcpy.Update_analysis(output + "_update{}".format(update_no), update_list[update_no], output + "_update{}".format(update_no + 1)) print(" variables: {}, {}, {}".format( output + "_update{}".format(update_no), update_list[update_no], output + "_update{}".format(update_no + 1))) update_no += 1 arcpy.CopyFeatures_management(output + "_update{}".format(loop_no), output) # join attributes back to output print("Trying spatial join") arcpy.SpatialJoin_analysis(output, trees_memory, output + "_join", "JOIN_ONE_TO_ONE") # Add hectare field arcpy.AddField_management(output + "_join", "hectares", "DOUBLE") arcpy.CalculateGeometryAttributes_management( output + "_join", [["hectares", "AREA_GEODESIC"]], area_unit="HECTARES", coordinate_system=4283) # Overwrite output print("Explode, and overwriting output") arcpy.MultipartToSinglepart_management(output + "_join", output) # Clean up fields join_field_del_list = [ "Join_Count", "TARGET_FID", "comment", "other", "stage", "edit", "Shape__Area", "Shape__Length", "commodity_1", "ORIG_FID", "field", "review", "imagery", "industry", "uncertain" ] print("Deleting the following fields:") print(join_field_del_list) for i in join_field_del_list: arcpy.DeleteField_management(output, i) # Assign domains print("Assigning domains") arcpy.AssignDomainToField_management(output, "source", "source_domain") arcpy.AssignDomainToField_management(output, "commodity", "commodity_domain") arcpy.AssignDomainToField_management(output, "year", "year_domain") arcpy.env.workspace = output_workspace # Delete all working features except actual output, topology and original tree data. print("Trying to delete unnecessary data") del_fc_list = arcpy.ListFeatureClasses("{}_*".format(output_fc)) print(del_fc_list) for i in del_fc_list: print("Deleting {}".format(i)) arcpy.Delete_management(output_workspace + "\\{}".format(i)) # Derive points print("Creating points") arcpy.FeatureToPoint_management(output_fc, output + "_point", "INSIDE")
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)
else: nstep = 2 if str(SmoothingVB) != "0": nstep += 1 else: nstep = 17 ncurrentstep = 1 #/definition of the valley bottom to be cleaned UncleanedPolygonVB = UncleanedPolygonVB_USER #/cleaning of the valley bottom polygon arcpy.AddMessage("Aggregating and Deleting Holes | CleanStep 1 - Step " + str(ncurrentstep) + "/" + str(nstep)) AggregatedVB = arcpy.AggregatePolygons_cartography( UncleanedPolygonVB, "%scratchWorkspace%\\AggregatedVB", AggregationDist, 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",
# -*- coding: utf-8 -*- # --------------------------------------------------------------------------- # aggregateExport.py # Created on: 2020-05-23 01:59:21.00000 # (generated by ArcGIS/ModelBuilder) # Description: # --------------------------------------------------------------------------- # Set the necessary product code # import arcinfo # Import arcpy module import arcpy # Local variables: Input_Features = "C:\Users\owner\Downloads\Sample_scripts\ch05\NGA_adm2.shp" Aggregation_Distance = "1500 feet" Output_Feature_Class = "C:\Users\owner\Downloads\Sample_scripts\ch05\Aha.shp" Output_Table = "C:\Users\owner\Downloads\Sample_scripts\ch05\Aha_Tbl" # Process: Aggregate Polygons arcpy.AggregatePolygons_cartography(Input_Features, Output_Feature_Class, Aggregation_Distance, "0 Unknown", "0 Unknown", "NON_ORTHOGONAL", "", Output_Table)
print 'begin script on '+datetime.datetime.now().date().isoformat()+' at '+datetime.datetime.now().time().isoformat()[0:8] set_workspace = 'U:/GIS_IDFG.gdb' # location of shapefiles to merge outws = '//hqwildstat/D$/Fine scale vegetation analysis/understory_veg_model/spatial/GMU.gdb' name_poly = 'Hunt_GameUnit' # name of target feature field = 'NAME' fcs = "('6','10A','1')" title = "Units_1_6_10A" arcpy.env.overwriteOutput = True print 'set workspace' arcpy.env.workspace = outws print 'loading target shapefile' arcpy.MakeFeatureLayer_management(set_workspace+'/'+name_poly, "choose_selection") print 'selecting attribute' #arcpy.SelectLayerByAttribute_management("choose_selection", "NEW_SELECTION", "NAME IN ('6','10A','32A')") arcpy.SelectLayerByAttribute_management("choose_selection", "NEW_SELECTION", field + " IN " + fcs) print 'aggregate polygons' arcpy.AggregatePolygons_cartography("choose_selection", outws+'/'+title, 1) print 'exporting' arcpy.CopyFeatures_management("choose_selection", outws+'/'+"choose_selection") print 'script complete on '+datetime.datetime.now().date().isoformat()+' at '+datetime.datetime.now().time().isoformat()[0:8]
def CalcObservers(Simple_CQ, Observers, DataFactorsBoundaries, locationtemporal2, gv): # local variables Buffer_CQ = locationtemporal2 + '\\' + 'BufferCQ' temporal_lines = locationtemporal2 + '\\' + 'lines' Points = locationtemporal2 + '\\' + 'Points' AggregatedBuffer = locationtemporal2 + '\\' + 'BufferAggregated' temporal_lines3 = locationtemporal2 + '\\' + 'lines3' Points3 = locationtemporal2 + '\\' + 'Points3' Points3Updated = locationtemporal2 + '\\' + 'Points3Updated' EraseObservers = locationtemporal2 + '\\' + 'eraseobservers' Observers0 = locationtemporal2 + '\\' + 'observers0' NonoverlappingBuildings = locationtemporal2 + '\\' + 'Non_overlap' templines = locationtemporal2 + '\\' + 'templines' templines2 = locationtemporal2 + '\\' + 'templines2' Buffer_CQ0 = locationtemporal2 + '\\' + 'Buffer_CQ0' Buffer_CQ = locationtemporal2 + '\\' + 'Buffer_CQ' Buffer_CQ1 = locationtemporal2 + '\\' + 'Buffer_CQ1' Simple_CQcopy = locationtemporal2 + '\\' + 'Simple_CQcopy' # First increase the boundaries in 2m of each surface in the community to # analyze- this will avoid that the observers overlap the buildings and Simplify # the community vertices to only create 1 point per surface arcpy.CopyFeatures_management(Simple_CQ, Simple_CQcopy) # Make Square-like buffers arcpy.PolygonToLine_management(Simple_CQcopy, templines, "IGNORE_NEIGHBORS") arcpy.SplitLine_management(templines, templines2) arcpy.Buffer_analysis(templines2, Buffer_CQ0, "0.75 Meters", "FULL", "FLAT", "NONE", "#") arcpy.Append_management(Simple_CQcopy, Buffer_CQ0, "NO_TEST") arcpy.Dissolve_management(Buffer_CQ0, Buffer_CQ1, "Name", "#", "SINGLE_PART", "DISSOLVE_LINES") arcpy.SimplifyBuilding_cartography(Buffer_CQ1, Buffer_CQ, simplification_tolerance=8, minimum_area=None) # arcpy.Buffer_analysis(Simple_CQ,Buffer_CQ,buffer_distance_or_field=1, line_end_type='FLAT') # buffer with a flat finishing # arcpy.Generalize_edit(Buffer_CQ,"2 METERS") # Transform all polygons of the simplified areas to observation points arcpy.SplitLine_management(Buffer_CQ, temporal_lines) arcpy.FeatureVerticesToPoints_management( temporal_lines, Points, 'MID') # Second the transformation of Lines to a mid point # Join all the polygons to get extra vertices, make lines and then get points. # these points should be added to the original observation points arcpy.AggregatePolygons_cartography(Buffer_CQ, AggregatedBuffer, "0.5 Meters", "0 SquareMeters", "0 SquareMeters", "ORTHOGONAL") # agregate polygons arcpy.SplitLine_management(AggregatedBuffer, temporal_lines3) # make lines arcpy.FeatureVerticesToPoints_management(temporal_lines3, Points3, 'MID') # create extra points # add information to Points3 about their buildings arcpy.SpatialJoin_analysis(Points3, Buffer_CQ, Points3Updated, "JOIN_ONE_TO_ONE", "KEEP_ALL", match_option="CLOSEST", search_radius="5 METERS") arcpy.Erase_analysis(Points3Updated, Points, EraseObservers, "2 Meters") # erase overlaping points arcpy.Merge_management([Points, EraseObservers], Observers0) # erase overlaping points # Eliminate Observation points above roofs of the highest surfaces(a trick to make the # Import Overlaptable from function CalcBoundaries containing the data about buildings overlaping, eliminate duplicades, chose only those ones no overlaped and reindex DataNear = pd.read_csv(DataFactorsBoundaries) CleanDataNear = DataNear[DataNear['FactorShade'] == 1] CleanDataNear.drop_duplicates(subset='Name_x', inplace=True) CleanDataNear.reset_index(inplace=True) rows = CleanDataNear.Name_x.count() for row in range(rows): Field = "Name" # select field where the name exists to iterate Value = CleanDataNear.loc[ row, 'Name_x'] # set the value or name of the City quarter Where_clausule = '''''' + '"' + Field + '"' + "=" + "\'" + str( Value) + "\'" + '''''' # strange writing to introduce in ArcGIS if row == 0: arcpy.MakeFeatureLayer_management(Simple_CQ, 'Simple_lyr') arcpy.SelectLayerByAttribute_management('Simple_lyr', "NEW_SELECTION", Where_clausule) else: arcpy.SelectLayerByAttribute_management('Simple_lyr', "ADD_TO_SELECTION", Where_clausule) arcpy.CopyFeatures_management('simple_lyr', NonoverlappingBuildings) arcpy.ErasePoint_edit(Observers0, NonoverlappingBuildings, "INSIDE") arcpy.CopyFeatures_management( Observers0, Observers) # copy features to reset the OBJECTID with arcpy.da.UpdateCursor(Observers, ["OBJECTID", "ORIG_FID"]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) gv.log('complete calculating observers') return arcpy.GetMessages()
# Calculate stats on all expanded rasters fcs=arcpy.ListRasters("Expanded*") cellstatrast= arcpy.sa.CellStatistics(fcs, "VARIETY") cellstatrast.save("Cell_Variety_01") # IN FUTURE: Add another 'expand' step, with weight towards higher values out_poly= "Tree_polygons" # Convert to polygon # Merge adjacent polygons with value greater than X number of slices (default 4) # get centerpoint and save as seedpoints arcpy.RasterToPolygon_conversion(cellstatrast, out_poly, "SIMPLIFY", "Value") arcpy.MakeFeatureLayer_management(out_poly, "poly_layer") polylr = "poly_layer" arcpy.SelectLayerByAttribute_management(polylr, "NEW_SELECTION", "gridcode=%s"%num_needed) thiscount=int(arcpy.GetCount_management(polylr).getOutput(0)) arcpy.AddMessage(thiscount) arcpy.AggregatePolygons_cartography(polylr, "merge_poly", cell_size, pt_spacing) arcpy.FeatureToPoint_management("merge_poly", seedname, "CENTROID")
# set the output spatial reference arcpy.env.outputCoordinateSystem = arcpy.SpatialReference( outSpatialReference) # save the query results to feature class arcpy.FeatureClassToFeatureClass_conversion( fc_rooms[0], fds_path, 'OS_temp', condition) OSFeatureClass = fds_path + os.sep + fc_file # dissolve multiple features into single arcpy.Dissolve_management( fds_path + os.sep + 'OS_temp', fds_path + os.sep + 'OS_temp2') # dissolve boundaries to make a continuous polygon for navigable space arcpy.AggregatePolygons_cartography( fds_path + os.sep + 'OS_temp2', OSFeatureClass, aggregationDist, "0 SquareFeet", "0 SquareFeet", "NON_ORTHOGONAL", "#") # arcpy.Delete_management(OSFeatureClass) arcpy.Delete_management(fds_path + os.sep + 'OS_temp') arcpy.Delete_management(fds_path + os.sep + 'OS_temp2') #**************** Extract Doors ***************** # query doors on current floor condition = "[FLOOR] = " + str(floor_num) arcpy.MakeFeatureLayer_management( fc_doors[0], 'DR_lyr', condition) if (arcpy.Exists(OSFeatureClass)): arcpy.SelectLayerByLocation_management( 'DR_lyr', "WITHIN_A_DISTANCE", OSFeatureClass, '2 Feet', "NEW_SELECTION")