def create_flow(self, vector1, vector2): """ 开始创建六边形 :param vector1: 用于创建渔网的坐标数据 :param vector2: 另一个用于创建渔网的坐标数据 :return: """ workspace = os.path.dirname(self.out_f) # print os.path.dirname(self.out_f) arcpy.env.scratchWorkspace = workspace # arcpy.env.workspace = workspace arcpy.env.overwriteOutput = True #------ first fishnet ------ # fishnet1_point -> fishnet1_p point # fishnet1_result -> fishnet1_res # fishnet1_label -> fishnet1_lb CF = arcpy.CreateFishnet_management fishnet1_path = (os.path.join(workspace, "Fishnet1")) fishnet1 = CF(fishnet1_path, vector1[0], vector1[1], self.width, self.height, "0", "0", vector1[2], "LABELS") #------ second fishnet ------ fishnet2_path = (os.path.join(workspace, "Fishnet2")) fishnet2 = CF(fishnet2_path, vector2[0], vector2[1], self.width, self.height, "0", "0", vector2[2], "LABELS") # label point fishnet1_lb = fishnet1.getOutput(1) fishnet2_lb = fishnet2.getOutput(1) arcpy.DefineProjection_management(fishnet1_lb, self.ref) arcpy.DefineProjection_management(fishnet2_lb, self.ref) # 将新旧标注点(label)合并 # global full_pt full_pt = arcpy.Append_management(fishnet2_lb, fishnet1_lb) # Create Thiessen Polygons full_theissen = arcpy.CreateThiessenPolygons_analysis( full_pt, (os.path.join(workspace, "FullTheissen"))) # 1.将完整的泰森多边形创建为要素图层 # 2.按位置选择出和输入目标图层相交的部分 # 3.导出要素图层 f_lyr = "_lyr" arcpy.MakeFeatureLayer_management(full_theissen, f_lyr) arcpy.SelectLayerByLocation_management(f_lyr, "INTERSECT", self.in_f) arcpy.CopyFeatures_management(f_lyr, self.out_f) # Delete intermediate data arcpy.Delete_management(fishnet1) arcpy.Delete_management(fishnet2) # arcpy.Delete_management(fishnet1_lb) arcpy.Delete_management(fishnet2_lb) arcpy.Delete_management(full_theissen) arcpy.Delete_management(f_lyr) arcpy.AddMessage("Completed hexagonal polygons.")
def Voronoi_Lines(inFC,Output): try: #Variables temp = 'in_memory\\tempdata' temp2 = 'in_memory\\tempdata2' arcpy.FeatureVerticesToPoints_management(inFC,temp, "ALL") arcpy.CreateThiessenPolygons_analysis(temp, temp2, "ONLY_FID") arcpy.PolygonToLine_management(temp2, temp) arcpy.Intersect_analysis([temp, inFC], temp2, "ALL") arcpy.MultipartToSinglepart_management(temp2, Output) fieldNames = [] for field in arcpy.ListFields(Output): if not field.required and field.name != 'Id': fieldNames.append(field.name) arcpy.DeleteField_management(Output,fieldNames) Centerline(Output) Width(Output,inFC) Deviation(Output) except Exception,e: arcpy.AddError('%s'%(e))
def createPolygon(self, lat, lon, extent, out_polygons, scratchWorkspace): """Create a Thiessen polygon feature class from numpy.ndarray lat and lon Each polygon represents the area described by the center point """ buffer = 2 * max(abs(lat[0] - lat[1]), abs(lon[0] - lon[1])) # Extract the lat and lon within buffered extent (buffer with 2* interval degree) lat0 = lat[(lat >= (extent.YMin - buffer)) & (lat <= (extent.YMax + buffer))] lon0 = lon[(lon >= (extent.XMin - buffer)) & (lon <= (extent.XMax + buffer))] # Spatial reference: GCS_WGS_1984 sr = arcpy.SpatialReference(4326) # Create a list of geographic coordinate pairs pointGeometryList = [] for i in range(len(lon0)): for j in range(len(lat0)): point = arcpy.Point() point.X = float(lon0[i]) point.Y = float(lat0[j]) pointGeometry = arcpy.PointGeometry(point, sr) pointGeometryList.append(pointGeometry) # Create a point feature class with longitude in Point_X, latitude in Point_Y out_points = os.path.join(scratchWorkspace, 'points_subset') result2 = arcpy.CopyFeatures_management(pointGeometryList, out_points) out_points = result2.getOutput(0) arcpy.AddGeometryAttributes_management(out_points, 'POINT_X_Y_Z_M') # Create Thiessen polygon based on the point feature result3 = arcpy.CreateThiessenPolygons_analysis( out_points, out_polygons, 'ALL') out_polygons = result3.getOutput(0) return out_points, out_polygons
def createThiessPolygonFast(CellShanXingPois,cellThiessFeature,cellThiessFinal,inOutField,ShengBianJie): print "过滤室外站生成泰森多边形" logging.info("过滤室外站生成泰森多边形") CellsOutPointsGsm=arcpy.Select_analysis(CellShanXingPois, "in_memory/CellsOutPointsGsm", inOutField+"='室外'"); print "创建小区泰森多边形" logging.info("创建小区泰森多边形") cellThiessFeatureCacheGsm = arcpy.CreateThiessenPolygons_analysis(CellsOutPointsGsm, "in_memory/cellThiessFeatureCacheGsm", "ALL") print "将泰森多边形进行省边界切割" logging.info("将泰森多边形进行省边界切割") arcpy.Clip_analysis(cellThiessFeatureCacheGsm, ShengBianJie, cellThiessFeature, "") cellsThiessPolygonCurs = arcpy.SearchCursor(cellThiessFeature) cellThiessFinalInsertCur = arcpy.InsertCursor(cellThiessFinal) row = cellsThiessPolygonCurs.next() while row: currentThiessenPolygon = row.getValue(shapefieldname) finalCellThiessRow = cellThiessFinalInsertCur.newRow() if(row.getValue("Shape.STArea()")>0.0006 or row.getValue("Shape.STLength()")>0.05): print "面积大于0.001或长度大于0.1,执行裁剪" ThiessenFID = row.ORIG_FID CurrentCellPointCur = arcpy.SearchCursor(CellShanXingPois,"ORIG_FID="+repr(ThiessenFID)) CurrentCellPoinRow = CurrentCellPointCur.next() CenterPoint = CurrentCellPoinRow.getValue(shapefieldname) CenterPointPnt = CenterPoint.getPart() rdloncos= 111*math.cos(CenterPointPnt.Y*rad) pointSingleArray = arcpy.Array() for si in range(5): singleAngle = 90*si if(singleAngle==360): singleAngle=0 rslonEndSingle = CutRad*math.sin(singleAngle*rad) rslatEndSingle = CutRad*math.cos(singleAngle*rad) lonEndSingle = CenterPointPnt.X+(rslonEndSingle/rdloncos) latEndSingle= CenterPointPnt.Y+rslatEndSingle/111 pointEndSingle = arcpy.Point(lonEndSingle, latEndSingle) pointSingleArray.add(pointEndSingle) XiaoQuShanXingSingle = arcpy.Polygon(pointSingleArray,spatialReference) CELL_TSDBX_SINGLE = currentThiessenPolygon.intersect(XiaoQuShanXingSingle,4) finalCellThiessRow.shape=CELL_TSDBX_SINGLE for XiaoQuField in XiaoQuFields: XQFieldName = XiaoQuField.name if(XQFieldName!="OBJECTID"): finalCellThiessRow.setValue(XQFieldName,row.getValue(XQFieldName)) finalCellThiessRow.Input_FID = row.Input_FID print "CI:"+str(row.CI),row.CITY_NAME cellThiessFinalInsertCur.insertRow(finalCellThiessRow) else: finalCellThiessRow.shape=currentThiessenPolygon for XiaoQuField in XiaoQuFields: XQFieldName = XiaoQuField.name if(XQFieldName!="OBJECTID"): finalCellThiessRow.setValue(XQFieldName,row.getValue(XQFieldName)) finalCellThiessRow.Input_FID = row.Input_FID print "CI:"+str(row.CI),row.CITY_NAME cellThiessFinalInsertCur.insertRow(finalCellThiessRow) row = cellsThiessPolygonCurs.next() print "删除变量~~~~" del cellsThiessPolygonCurs,cellThiessFinalInsertCur,CellsOutPointsGsm,cellThiessFeatureCacheGsm,row
def main(): arcpy.env.workspace = sys.argv[1] outspace = sys.argv[2] files = arcpy.ListFeatureClasses('*data*') for f in files: if fh.shapeType == 'Point': out = os.path.basename(f) outf = os.path.splitext(out)[0] + 'Postal' infile = os.path.join(arcpy.env.workspace, f) outfile = os.path.join(outspace, outf) arcpy.CreateThiessenPolygons_analysis(infile, outfile) print('{} created.'.format(outfile))
def createPolygon(self, extent, out_polygons, scratchWorkspace): """Create a Thiessen polygon feature class from numpy.ndarray lat and lon Each polygon represents the area described by the center point """ lsm_dx = NUM.max(NUM.absolute(NUM.diff(self.lsm_lon_array))) lsm_dy = NUM.max(NUM.absolute(NUM.diff(self.lsm_lat_array, axis=0))) lsm_lat_indices_from_lat, lsm_lon_indices_from_lat = NUM.where( (self.lsm_lat_array >= (extent.YMin - 2 * lsm_dy)) & (self.lsm_lat_array <= (extent.YMax + 2 * lsm_dy))) lsm_lat_indices_from_lon, lsm_lon_indices_from_lon = NUM.where( (self.lsm_lon_array >= (extent.XMin - 2 * lsm_dx)) & (self.lsm_lon_array <= (extent.XMax + 2 * lsm_dx))) lsm_lat_indices = NUM.intersect1d(lsm_lat_indices_from_lat, lsm_lat_indices_from_lon) lsm_lon_indices = NUM.intersect1d(lsm_lon_indices_from_lat, lsm_lon_indices_from_lon) lsm_lat_list = self.lsm_lat_array[lsm_lat_indices, :][:, lsm_lon_indices] lsm_lon_list = self.lsm_lon_array[lsm_lat_indices, :][:, lsm_lon_indices] # Spatial reference sr = arcpy.SpatialReference(4326) #CGS_WGS_1984 # Create a list of geographic coordinate pairs pointGeometryList = [] for i in range(len(lsm_lat_indices)): for j in range(len(lsm_lon_indices)): point = arcpy.Point() point.X = float(lsm_lon_list[i][j]) point.Y = float(lsm_lat_list[i][j]) pointGeometry = arcpy.PointGeometry(point, sr) pointGeometryList.append(pointGeometry) # Create a point feature class with longitude in Point_X, latitude in Point_Y out_points = os.path.join(scratchWorkspace, 'points_subset') result2 = arcpy.CopyFeatures_management(pointGeometryList, out_points) out_points = result2.getOutput(0) arcpy.AddGeometryAttributes_management(out_points, 'POINT_X_Y_Z_M') # Create Thiessen polygon based on the point feature result3 = arcpy.CreateThiessenPolygons_analysis( out_points, out_polygons, 'ALL') out_polygons = result3.getOutput(0) return out_points, out_polygons
def thiessen_poly(inFeatures): desc = arcpy.Describe(inFeatures) print("Creating thiessen polygons from : " + str(inFeatures)) if arcpy.Exists(inFeatures): if desc.dataType == "ShapeFile": inFeatures = "Emergency_Medical_Services.shp" outFeatureClass = "EMS_Thiessen" outFields = "ALL" arcpy.CreateThiessenPolygons_analysis(inFeatures, outFeatureClass, outFields) else: print("Input data not ShapeFile..") else: print("Dataset not found, please check the file path..")
def optimizacion_cobertura(oid): global troba, tapt, identificador, vias_mfl query = "OBJECTID = %s" % oid troba_mfl = arcpy.MakeFeatureLayer_management(troba, "troba", query) pol_tmp = arcpy.FeatureToPolygon_management([troba_mfl, vias_mfl], r'D:\TEMP\hora.shp') for m in arcpy.da.SearchCursor(pol_tmp, ['OID@', 'SHAPE@']): identificador += 1 arcpy.AddMessage(identificador) pol = arcpy.MakeFeatureLayer_management(pol_tmp, 'pol_tmp_mfl', 'FID = {}'.format(m[0])) arcpy.SelectLayerByLocation_management(vias_mfl, "INTERSECT", troba_mfl, "#", 'NEW_SELECTION') arcpy.SelectLayerByLocation_management(tapt, "INTERSECT", pol, "#", 'NEW_SELECTION') if arcpy.GetCount_management(vias_mfl).__str__() == '0': arcpy.AddMessage("Tiene vias") pol = arcpy.FeatureToPolygon_management([pol, vias_mfl], "in_memory//thiessenVias") arcpy.env.extent = pol taps_thiessen = arcpy.CreateThiessenPolygons_analysis(tapt, "in_memory//taptemp") pol = arcpy.Clip_analysis(taps_thiessen, m[1], "in_memory//clipThiessen") #if pol: arcpy.Append_management(pol, output, 'NO_TEST') with arcpy.da.UpdateCursor(output, [field], "%s is null" % field) as cursor: for i in cursor: i[0] = identificador cursor.updateRow(i) del cursor arcpy.SelectLayerByAttribute_management(tapt, 'CLEAR_SELECTION') arcpy.SelectLayerByAttribute_management(vias_mfl, 'CLEAR_SELECTION')
os.path.split(final_fc)[0], "Proj_Thiessen") tempWS = arcpy.GetParameterAsText(5) output_fc = os.path.join(tempWS, "Temp_Thiessen_Points") intermediate_fc = os.path.join(tempWS, "Temp_Thiessen_Polygons") feature_layer = "in_mempory\Thiessen_layer" geo = arcpy.SpatialReference("WGS 1984") mercator = arcpy.SpatialReference("WGS 1984 World Mercator") if side_unit == "Geographic Lat Long": arcpy.Project_management(study_area, projected_data, geo) elif side_unit == "Meters": arcpy.Project_management(study_area, projected_data, mercator) create_thiessen_points(projected_data, side_length, output_fc) arcpy.CreateThiessenPolygons_analysis(output_fc, intermediate_fc) if clipData == True: arcpy.MakeFeatureLayer_management(intermediate_fc, feature_layer) arcpy.SelectLayerByLocation_management(feature_layer, "INTERSECT", study_area) matchcount = int( arcpy.GetCount_management(feature_layer).getOutput(0)) if matchcount == 0: print("No features were matched...") arcpy.AddMessage("No features were matched...") else: arcpy.CopyFeatures_management(feature_layer, final_fc)
# setup for theissen polygons arcpy.Buffer_analysis('eez_basins', 'eez_basins_buf200km', '200 kilometers', dissolve_option='ALL') arcpy.env.extent = 'eez_basins_buf200km' arcpy.env.outputCoordinateSystem = sr_mol arcpy.CopyFeatures_management('basins_m', 'thie') arcpy.Densify_edit('thie', 'DISTANCE', '1 Kilometers') arcpy.FeatureVerticesToPoints_management('thie', 'thie_pts', 'ALL') # delete interior points arcpy.Dissolve_management('thie', 'thie_d') arcpy.MakeFeatureLayer_management('thie_pts', 'lyr_pts') arcpy.SelectLayerByLocation_management('lyr_pts', 'WITHIN_CLEMENTINI', 'thie_d') arcpy.DeleteFeatures_management('lyr_pts') # generate thiessen polygons arcpy.CreateThiessenPolygons_analysis('thie_pts', 'thie_polys', 'ALL') arcpy.env.outputCoordinateSystem = sr_gcs arcpy.Dissolve_management('thie_polys', 'thie_polys_d', ['basin_name']) arcpy.Erase_analysis('thie_polys_d', 'basins_m', 'thie_polys_d_e') arcpy.Merge_management(['thie_polys_d_e','basins_m'], 'thie_polys_d_e_m') arcpy.Dissolve_management('thie_polys_d_e_m', 'thie_polys_d_e_m_d', ['rgn_id','rgn_name']) # intersect expanded basins with eez's arcpy.Intersect_analysis(['sp_gcs','thie_polys_d_e_m_d'], 'sp_thie_m') arcpy.AddField_management('eez_basins_m', 'rgn_name', 'TEXT') arcpy.CalculateField_management('eez_basins_m', 'rgn_name', "'%s_%s' % (!eez_name!, !basin_name!)", 'PYTHON_9.3') arcpy.Dissolve_management('eez_basins_m', 'eez_basins', ['eez_name','basin_name','rgn_name']) arcpy.AddField_management('eez_basins', 'rgn_id', 'SHORT') arcpy.CalculateField_management('eez_basins', 'rgn_id', "!OBJECTID!", 'PYTHON_9.3')
# create theissen polygons used to split slivers arcpy.Densify_edit('c_states', 'DISTANCE', '1 Kilometers') arcpy.FeatureVerticesToPoints_management( 'c_states', 'c_states_pts', 'ALL') # delete interior points for faster thiessen rendering arcpy.Dissolve_management('c_states', 'c_states_d') arcpy.MakeFeatureLayer_management('c_states_pts', 'lyr_c_states_pts') arcpy.SelectLayerByLocation_management( 'lyr_c_states_pts', 'WITHIN_CLEMENTINI', 'c_states_d') arcpy.DeleteFeatures_management('lyr_c_states_pts') # generate thiessen polygons of gadm for intersecting with land slivers arcpy.env.extent = 'c_eezland' arcpy.CreateThiessenPolygons_analysis( 'c_states_pts', 'c_states_t', 'ALL') arcpy.Dissolve_management('c_states_t', 'c_states_t_d', 'NAME_1') arcpy.RepairGeometry_management('c_states_t_d') # add detailed interior back arcpy.Erase_analysis('c_states_t_d', 'c_states', 'c_states_t_d_e') arcpy.Merge_management(['c_states', 'c_states_t_d_e'], 'c_states_t_d_e_m') arcpy.Dissolve_management('c_states_t_d_e_m', 'c_thiessen', 'NAME_1') arcpy.RepairGeometry_management('c_thiessen') if not arcpy.Exists(c_offshore_dest): # rgn_offshore: rename NAME_1 to rgn_name
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)
def IceCliffLocation(workspace,dem,tileDebarea,pixel,skinny,minSlope,n_iterations,L_e,alpha,beta_e,A_min,phi,gamma): import sys import os import arcpy from arcpy import env from arcpy.sa import Slope, ExtractByMask, Raster, SetNull, Int import matplotlib.pyplot as plt import numpy as np from numpy import array from scipy.optimize import curve_fit env.overwriteOutput = True try: import arcinfo except: sys.exit("ArcInfo license not available") arcpy.AddMessage("ArcInfo license not available") if arcpy.CheckExtension("spatial") == "Available": arcpy.CheckOutExtension("spatial") else: sys.exit("Spatial Analyst license not available") arcpy.AddMessage("Spatial Analyst license not available") #Parameters that should be stable: slopeLimit = 90 # slope detection capped at this value ## Loop for optimizing slope if str(workspace.split("\\")[-1]) == 'Final': n = [] n.append(minSlope) else: minSlope = 0 n = np.arange(minSlope,slopeLimit,(slopeLimit-minSlope)/n_iterations) skipIteration = [] for minSlope in n: # check for existing iterations if code has previously run but crashed. if arcpy.ListFeatureClasses("*cliffMap*"): fcListPrior = arcpy.ListFeatureClasses("*cliffMap*") skipIteration = [] for prior_i in fcListPrior: if int(prior_i[14:16]) == int("%02d" % (int(minSlope),)): skipIteration = 1 if skipIteration == 1: continue ## Ice Cliff code if skinny == 'false': print 'IceCliffLocation script started...' if skinny == 'true': print 'skinny IceCliffLocation script started...' # Parameter that probably should be 0 minProb = 0 # probability associated with minSlope. arcpy.CopyFeatures_management(tileDebarea, workspace+"\\del_debarea.shp") debarea_iteration = workspace+"\\del_debarea.shp" arcpy.env.snapRaster = dem outExtractSlope = ExtractByMask(dem, debarea_iteration) outExtractSlope.save("dem_extract.TIF") if int(round(float(str(arcpy.GetRasterProperties_management(dem, "CELLSIZEX"))))) == pixel: dem = "dem_extract.TIF" else: arcpy.Resample_management("dem_extract.TIF", "dem_extractResample.TIF", pixel, "NEAREST") arcpy.env.snapRaster = dem print "DEM resampeld from "+str(int(round(float(str(arcpy.GetRasterProperties_management(dem, "CELLSIZEX"))))))+' to '+str(pixel) dem = "dem_extractResample.TIF" # Create slope raster outSlope = Slope(dem, "DEGREE", 1) outSlope.save("del_slope.TIF") # Isolate slope values above minSlope outSetNull = SetNull("del_slope.TIF", "del_slope.TIF", "VALUE <= "+ str(minSlope)) outSetNull.save("del_minSlope.TIF") # Exit process if no cliffs exist nocliff = arcpy.GetRasterProperties_management(Int("del_minSlope.TIF"), "ALLNODATA") if int(str(nocliff)) == 1: print "No area with a slope above "+str(minSlope)+"." elif float(str(arcpy.GetRasterProperties_management('del_minSlope.TIF',"MAXIMUM"))) - float(str(arcpy.GetRasterProperties_management('del_minSlope.TIF',"MINIMUM"))) == 0: print "Only one pixel with a slope above "+str(minSlope)+", iteration skipped." else: minMean = float(str(arcpy.GetRasterProperties_management("del_minSlope.TIF", "MEAN"))) minSD = float(str(arcpy.GetRasterProperties_management("del_minSlope.TIF", "STD"))) areaSlope = minMean print 'areaSlope = ' + str(areaSlope) # Isolate slope values above areaSlope outSetNull = SetNull("del_slope.TIF", "del_slope.TIF", "VALUE <= "+ str(areaSlope)) outSetNull.save("del_areaSlope.TIF") arcpy.env.snapRaster = dem # Exit process if no cliffs exist nocliff = arcpy.GetRasterProperties_management(Int("del_areaSlope.TIF"), "ALLNODATA") if int(str(nocliff)) == 1: print "No area with a slope above "+str(areaSlope)+"." elif float(str(arcpy.GetRasterProperties_management("del_areaSlope.TIF","MAXIMUM"))) - float(str(arcpy.GetRasterProperties_management("del_areaSlope.TIF","MINIMUM"))) == 0: print "Only one pixel with a slope above "+str(areaSlope)+", iteration skipped." else: seedSlope = minMean+minSD print 'seedSlope = ' + str(seedSlope) # Isolate slope values above areaSlope outSetNull = SetNull("del_slope.TIF", "del_slope.TIF", "VALUE <= "+ str(seedSlope)) outSetNull.save("del_seedSlope.TIF") # Exit process if no cliffs exist nocliff = arcpy.GetRasterProperties_management(Int("del_seedSlope.TIF"), "ALLNODATA") if int(str(nocliff)) == 1: print "No seed area with a slope above "+str(seedSlope)+"." else: # to int speeds up computation time outInt = Int("del_areaSlope.TIF") outInt.save("del_minSlopeInt.TIF") outInt = Int("del_seedSlope.TIF") outInt.save("del_seedSlopeInt.TIF") arcpy.RasterToPolygon_conversion("del_minSlopeInt.TIF", "del_minCliffSlope.shp", "NO_SIMPLIFY", "VALUE") arcpy.AddField_management("del_minCliffSlope.shp", "value", "SHORT", 1, "", "", "", "", "") arcpy.Dissolve_management("del_minCliffSlope.shp", "del_minCliff_dissolve.shp", "value") arcpy.MultipartToSinglepart_management("del_minCliff_dissolve.shp", "del_minCliff_explode.shp") arcpy.AddField_management("del_minCliff_explode.shp",'Area','FLOAT') rows = arcpy.UpdateCursor("del_minCliff_explode.shp") for row in rows: areacliff = row.shape.area row.Area = areacliff rows.updateRow(row) del row, rows arcpy.CopyFeatures_management("del_minCliff_explode.shp", "min"+str("%02d" % (minSlope,))+"_CliffArea.shp") # skinny/non-skinny fix for ending iteration. 0 = no skip, 1 = skip skip_iter = 0 # skinny ice cliffs, does not include ice cliff end extension to speed up computations if skinny == 'true': if arcpy.management.GetCount("del_minCliff_explode.shp")[0] == "0": skip_iter = 1 print "No area within del_minCliff_explode.shp, skinny iteration skipped." else: # "_FinalCliffShape.shp" and "_cliffArea.shp" are the same if skinny == true arcpy.CopyFeatures_management("del_minCliff_explode.shp", "min"+str("%02d" % (minSlope,))+"area"+str(int(areaSlope))+"_FinalCliffShape.shp") # copy working .shp, used below arcpy.CopyFeatures_management('del_minCliff_explode.shp', 'del_lineAndArea_area.shp') arcpy.CalculateAreas_stats('del_minCliff_explode.shp', 'del_lineAndArea_area.shp') arcpy.MakeFeatureLayer_management('del_lineAndArea_area.shp', 'tempLayer') expression = 'F_AREA <=' + str((pixel**2)*A_min) arcpy.SelectLayerByAttribute_management('tempLayer', 'NEW_SELECTION', expression) arcpy.DeleteFeatures_management('tempLayer') arcpy.Delete_management('tempLayer') if skinny == 'false': # buffer in/out area to break up attached features arcpy.Buffer_analysis("del_minCliff_explode.shp", "del_extendLineBuffer.shp", (pixel/2)-0.1, "FULL", "ROUND", "NONE") # Generate ice cliff centerlines from Voronoi cells if arcpy.management.GetCount("del_extendLineBuffer.shp")[0] == "0": arcpy.CreateFeatureclass_management(workspace, 'del_lineAndArea_area.shp', "POLYGON","del_minCliff_dissolve.shp") skip_iter = 1 print "No area within the criteria defined by seed area value "+str(seedSlope)+", iteration stopped before centerlines." else: arcpy.FeatureToLine_management("del_extendLineBuffer.shp","del_line.shp","","ATTRIBUTES") arcpy.Densify_edit("del_line.shp", "","5", "", "") arcpy.FeatureVerticesToPoints_management ("del_line.shp", "del_verti.shp", "ALL") arcpy.CreateThiessenPolygons_analysis("del_verti.shp","del_voronoiCells.shp" ,"ONLY_FID") arcpy.RepairGeometry_management("del_voronoiCells.shp") #use geodatabase here due to unexpected error: "Invalid Topology [Duplicate segment.]" arcpy.CreateFileGDB_management(workspace, "fGDB.gdb") fgdb = workspace+"\\fGDB.gdb" #arcpy.env.workspace = fgdb arcpy.Clip_analysis(workspace+"\\del_voronoiCells.shp", workspace+"\\del_extendLineBuffer.shp", fgdb+"\\shp","") arcpy.FeatureToLine_management(fgdb+"\\shp", workspace+"\\del_toLine.shp", "", attributes="ATTRIBUTES") arcpy.Delete_management(fgdb) #arcpy.env.workspace = workspace #arcpy.FeatureToLine_management("del_voronoiCellsClip.shp","del_toLine.shp", "", attributes="ATTRIBUTES") arcpy.MakeFeatureLayer_management("del_toLine.shp", "tempLayer", "", "", "") arcpy.SelectLayerByLocation_management("tempLayer", "CROSSED_BY_THE_OUTLINE_OF","del_minCliff_explode.shp","","NEW_SELECTION") arcpy.DeleteFeatures_management("tempLayer") arcpy.Delete_management("tempLayer") arcpy.Intersect_analysis(["del_toLine.shp",'del_minCliff_explode.shp'],"del_lineIntersect.shp") arcpy.Dissolve_management("del_lineIntersect.shp", "del_toLineDis.shp", "", "", "SINGLE_PART", "DISSOLVE_LINES") arcpy.UnsplitLine_management("del_toLineDis.shp","del_unsplit.shp","Id") arcpy.MakeFeatureLayer_management("del_unsplit.shp", "tempLayer2", "", "", "") arcpy.SelectLayerByLocation_management("tempLayer2", "BOUNDARY_TOUCHES","del_minCliff_explode.shp","","NEW_SELECTION") arcpy.DeleteFeatures_management("tempLayer2") arcpy.Delete_management("tempLayer2") arcpy.cartography.SimplifyLine("del_unsplit.shp","del_clineSimpExp.shp","POINT_REMOVE",10) arcpy.AddField_management("del_clineSimpExp.shp", "value", "SHORT", 1, "", "", "", "", "") arcpy.Dissolve_management("del_clineSimpExp.shp", "del_clineSimp.shp", "value") arcpy.TrimLine_edit("del_clineSimp.shp", "8 meters", "KEEP_SHORT") arcpy.CopyFeatures_management("del_unsplit.shp", "min"+str("%02d" % (minSlope,))+"_Centerlines.shp") #refine centerline for final map if arcpy.management.GetCount("del_clineSimp.shp")[0] == "0": arcpy.CreateFeatureclass_management(workspace, 'del_lineAndArea_area.shp', "POLYGON","del_minCliff_dissolve.shp") skip_iter = 1 print "No area big enough to generate a centerline, iteration skipped." else: # extend lines to capture cliff ends count = 0 print "Extend line started..." jlist = [(pixel/2)-0.1] * int(round(L_e/(pixel/2))) for j in jlist: #create buffer out to set the limit a line will be extended to arcpy.Buffer_analysis("del_clineSimp.shp", "del_clineSimpBuff1.shp", j, "FULL", "ROUND", "ALL") arcpy.PolygonToLine_management("del_clineSimpBuff1.shp","del_clineSimpBuff1line.shp") #merge centerline and bufferline arcpy.Merge_management(["del_clineSimp.shp","del_clineSimpBuff1line.shp"], "del_clineSimpBuff1merge_dis.shp") arcpy.Delete_management("del_clineSimp.shp") print "Extend line "+str(count)+" started..." arcpy.MultipartToSinglepart_management("del_clineSimpBuff1merge_dis.shp", "del_clineSimpBuff1merge.shp") arcpy.MakeFeatureLayer_management("del_clineSimpBuff1merge.shp", "lineLayer", "", "", "") arcpy.SelectLayerByLocation_management("lineLayer", "SHARE_A_LINE_SEGMENT_WITH", "del_clineSimpBuff1.shp", "", "NEW_SELECTION", "INVERT") arcpy.ExtendLine_edit("del_clineSimpBuff1merge.shp", str(j+1)+" meters", "EXTENSION") #select share a line segment with buffer to remove buffer arcpy.SelectLayerByLocation_management("lineLayer", "SHARE_A_LINE_SEGMENT_WITH", "del_clineSimpBuff1.shp", "", "NEW_SELECTION") arcpy.DeleteFeatures_management("lineLayer") arcpy.Delete_management("lineLayer") arcpy.CopyFeatures_management("del_clineSimpBuff1merge.shp", "del_clineSimp.shp") arcpy.Delete_management("del_clineSimpBuff1.shp") arcpy.Delete_management("del_clineSimpBuff1line.shp") arcpy.Delete_management("del_clineSimpBuff1merge.shp") count = count + j del j, jlist #remove last short ribs with a lenght threhold then reattach centerlines that may have been split # calculate lenght of each centerline if arcpy.management.GetCount("del_clineSimp.shp")[0] == "0": arcpy.CreateFeatureclass_management(workspace, 'del_lineAndArea_area.shp', "POLYGON","del_minCliff_explode.shp") skip_iter = 1 print "Centerline shape empty, iteration skipped." else: arcpy.AddField_management("del_clineSimp.shp",'L','FLOAT') rows = arcpy.UpdateCursor("del_clineSimp.shp") for row in rows: areacliff = row.shape.length row.L = areacliff rows.updateRow(row) del row, rows arcpy.CopyFeatures_management("del_clineSimp.shp", "min"+str("%02d" % (minSlope,))+"_extendedCenterlines.shp") # buffer out centerlines to capture end area removed in earlier buffer arcpy.Buffer_analysis("del_clineSimp.shp", "del_CliffCenterlineOut.shp", ((alpha*pixel*(2**(1/2)))/2), "FULL", "ROUND", "NONE") # define area with a slope less than that which defined "del_minCliff_dissolve.shp" edgeAreaSlope = areaSlope-beta_e print "Edge area defined by slope "+str(edgeAreaSlope) outSetNull = SetNull("del_slope.TIF", "del_slope.TIF", "VALUE <= "+ str(edgeAreaSlope)) outSetNull.save("del_edgeSlope.TIF") outInt = Int("del_edgeSlope.TIF") outInt.save("del_edgeSlopeInt.TIF") arcpy.RasterToPolygon_conversion("del_edgeSlopeInt.TIF", "del_edgeAreaSlope.shp", "NO_SIMPLIFY", "VALUE") arcpy.AddField_management("del_edgeAreaSlope.shp", "value", "SHORT", 1, "", "", "", "", "") arcpy.Dissolve_management("del_edgeAreaSlope.shp", "del_edgeAreaSlope_dissolve.shp", "value") arcpy.CopyFeatures_management("del_edgeAreaSlope_dissolve.shp", "min"+str("%02d" % (minSlope,))+"_edgeArea.shp") arcpy.Intersect_analysis (["del_edgeAreaSlope_dissolve.shp", "del_CliffCenterlineOut.shp"], "del_betaF_edgeArea.shp") # merge buffered lines with buffered area arcpy.Merge_management(["del_betaF_edgeArea.shp", "del_minCliff_explode.shp"], "del_lineAndArea.shp") arcpy.AddField_management("del_lineAndArea.shp", "valueDis", "SHORT", 1, "", "", "", "", "") arcpy.Dissolve_management("del_lineAndArea.shp", "del_lineAndArea_dissolve1.shp", "valueDis") arcpy.RepairGeometry_management("del_lineAndArea_dissolve1.shp") # fill holes and remove shapes less than one pixel to avoid error from buffer tool arcpy.MultipartToSinglepart_management("del_lineAndArea_dissolve1.shp", "del_lineAndArea_explode1.shp") arcpy.CalculateAreas_stats("del_lineAndArea_explode1.shp", 'del_lineAndArea_area1.shp') arcpy.MakeFeatureLayer_management('del_lineAndArea_area1.shp', 'tempLayer') expression = 'F_AREA <' + str(pixel**2) # m2 arcpy.SelectLayerByAttribute_management('tempLayer', 'NEW_SELECTION', expression) arcpy.DeleteFeatures_management('tempLayer') arcpy.Delete_management('tempLayer') arcpy.cartography.AggregatePolygons('del_lineAndArea_area1.shp', "del_lineAndArea_dissolve.shp", 1, 0, pixel**2, 'NON_ORTHOGONAL') arcpy.RepairGeometry_management("del_lineAndArea_dissolve.shp") # buffer in to reomve sliver geometries and out to make a diagonal set of single pixel shapes one feature arcpy.Buffer_analysis("del_lineAndArea_dissolve.shp", "del_lineAndArea_dissolveSmallBufferIn.shp", -0.5, "FULL", "ROUND", "ALL") arcpy.Buffer_analysis("del_lineAndArea_dissolveSmallBufferIn.shp", "del_lineAndArea_dissolveSmallBuffer.shp", 1, "FULL", "ROUND", "ALL") arcpy.MultipartToSinglepart_management("del_lineAndArea_dissolveSmallBuffer.shp", "del_lineAndArea_explode.shp") arcpy.CalculateAreas_stats('del_lineAndArea_explode.shp', 'del_lineAndArea_area.shp') arcpy.MakeFeatureLayer_management('del_lineAndArea_area.shp', 'tempLayer') expression = 'F_AREA <=' + str((pixel**2)*A_min) arcpy.SelectLayerByAttribute_management('tempLayer', 'NEW_SELECTION', expression) arcpy.DeleteFeatures_management('tempLayer') arcpy.Delete_management('tempLayer') if arcpy.management.GetCount("del_lineAndArea_area.shp")[0] == "0": print "del_lineAndArea_area.shp empty, iteration stopped." skip_iter = 1 else: arcpy.AddField_management("del_lineAndArea_area.shp", "value", "SHORT", 1, "", "", "", "", "") arcpy.CopyFeatures_management('del_lineAndArea_area.shp', "min"+str("%02d" % (minSlope,))+"area"+str(int(areaSlope))+"_FinalCliffShape.shp") if skip_iter == 0: # CDF for values between minSlope and maxSlope outSetNull = SetNull("del_slope.TIF", "del_slope.TIF", "VALUE >= "+ str(minSlope)) outSetNull.save("del_min.TIF") arcpy.RasterToFloat_conversion("del_min.TIF", "del_min.flt") minsl = Raster('del_min.flt') slopemin = minsl*0.0 slopemin.save('del_minSl.TIF') outSetNull = SetNull("del_slope.TIF", "del_slope.TIF", "VALUE > "+ str(seedSlope)) outSetNull = SetNull(outSetNull, outSetNull, "VALUE < "+ str(minSlope)) outSetNull.save("del_mid.TIF") arcpy.RasterToFloat_conversion("del_mid.TIF", "del_mid.flt") midsl = Raster('del_mid.flt') b = (1-(((1-minProb)/(seedSlope-minSlope))*seedSlope)) slopemid = (((1-minProb)/(seedSlope-minSlope))*midsl)+b arcpy.env.snapRaster = dem slopemid.save('del_midSl.TIF') arcpy.env.snapRaster = dem outSetNull = SetNull("del_slope.TIF", "del_slope.TIF", "VALUE <= "+ str(seedSlope)) outSetNull.save("del_max.TIF") arcpy.RasterToFloat_conversion("del_max.TIF", "del_max.flt") maxsl = Raster('del_max.flt') slopemax = maxsl*0.0+1.0 arcpy.env.snapRaster = dem slopemax.save('del_maxSl.TIF') arcpy.env.snapRaster = dem arcpy.MosaicToNewRaster_management("del_minSl.TIF;del_midSl.TIF;del_maxSl.TIF", workspace, "del_cliffProbabilitySlope.TIF", "", "32_BIT_FLOAT", "", "1", "LAST","FIRST") arcpy.env.snapRaster = dem # extract cliff probability and apply reduction factor to area outside of buffer.shp if arcpy.management.GetCount("del_lineAndArea_area.shp")[0] == "0": print "del_lineAndArea_area.shp is empty, did not create: CliffProbability_betai" + str("%02d" % (int(minSlope),)) + "betaA" + str(int(areaSlope))+".TIF" else: outExtractSlope = ExtractByMask("del_cliffProbabilitySlope.TIF", "del_lineAndArea_area.shp") outExtractSlope.save("del_final_cliffs_found.TIF") arcpy.RasterToFloat_conversion("del_cliffProbabilitySlope.TIF", "del_CliffProbabilitySlope.flt") CliffProbabilitySlope = Raster('del_CliffProbabilitySlope.flt') CliffProbabilitySlopeREDUCED = CliffProbabilitySlope*phi arcpy.env.snapRaster = dem CliffProbabilitySlopeREDUCED.save('del_CliffProbabilitySlopeREDUCED.TIF') arcpy.MosaicToNewRaster_management("del_final_cliffs_found.TIF;del_CliffProbabilitySlopeREDUCED.TIF", workspace, "CliffProbability_betai" + str("%02d" % (int(minSlope),)) + "betaA" + str(int(areaSlope))+".TIF", "", "32_BIT_FLOAT", "", "1", "FIRST","FIRST") arcpy.env.snapRaster = dem del CliffProbabilitySlope del CliffProbabilitySlopeREDUCED del minsl del midsl del maxsl ## ---------------------------------- ## Compute percent cliff in total spatial domain cliff_area_sum = 0 debris_area_sum = 0 Perc_Cliff = 0 arcpy.CalculateAreas_stats(debarea_iteration, 'del_debris_area.shp') with arcpy.da.SearchCursor('del_debris_area.shp', ['F_AREA']) as cursor: for row in cursor: debris_area_sum += row[0] if os.path.isfile(workspace+'\\del_lineAndArea_area.shp') == False: print "'del_lineAndArea_area.shp'does not exist." elif arcpy.management.GetCount('del_lineAndArea_area.shp')[0] == "0": print "No area within 'del_lineAndArea_area.shp'." else: with arcpy.da.SearchCursor('del_lineAndArea_area.shp', ['F_AREA']) as cursor: for row in cursor: cliff_area_sum += row[0] Perc_Cliff = (cliff_area_sum/debris_area_sum)*100 arcpy.Dissolve_management("del_lineAndArea_area.shp", 'cliffMap_betai' + str("%02d" % (int(minSlope),)) + 'betaA' + str(int(areaSlope)) + '.shp', "value") arcpy.AddField_management('cliffMap_betai' + str("%02d" % (int(minSlope),)) + 'betaA' + str(int(areaSlope)) + '.shp','minSlope','FLOAT') arcpy.AddField_management('cliffMap_betai' + str("%02d" % (int(minSlope),)) + 'betaA' + str(int(areaSlope)) + '.shp','Area_Cliff','FLOAT') arcpy.AddField_management('cliffMap_betai' + str("%02d" % (int(minSlope),)) + 'betaA' + str(int(areaSlope)) + '.shp','Area_Deb','FLOAT') arcpy.AddField_management('cliffMap_betai' + str("%02d" % (int(minSlope),)) + 'betaA' + str(int(areaSlope)) + '.shp','Perc_Cliff','FLOAT') rows = arcpy.UpdateCursor('cliffMap_betai' + str("%02d" % (int(minSlope),)) + 'betaA' + str(int(areaSlope)) + '.shp') for row in rows: row.setValue('Area_Cliff', cliff_area_sum) row.setValue('Area_Deb', debris_area_sum) row.setValue('minSlope', minSlope) row.setValue('Perc_Cliff', Perc_Cliff) rows.updateRow(row) del row, rows print 'IceCliffLocation script [minSlope: ' + str("%02d" % (int(minSlope),)) + ' areaSlope: ' + str(int(areaSlope))+ '] done...' rasterList = arcpy.ListRasters("*del*") for raster in rasterList: arcpy.Delete_management(raster) del raster del rasterList fcList = arcpy.ListFeatureClasses("*del*") for fc in fcList: arcpy.Delete_management(fc) del fc del fcList print "intermediate files deleted" del minSlope del n if str(workspace.split("\\")[-1]) == 'Final': print "Script complete" else: initialSlope_doubles = [] percentCliffs_doubles = [] initialSlope = [] percentCliffs = [] xfit = [] yfit = [] fcList = [] arr = [] fcList = arcpy.ListFeatureClasses("*cliffMap*") arcpy.Merge_management(fcList, "mergedSolutions.shp") arr = arcpy.da.TableToNumPyArray("mergedSolutions.shp", ('Perc_Cliff','minSlope')) arcpy.Delete_management("del_mergedSolutions.shp") initialSlope_doubles = [row[1] for row in arr] percentCliffs_doubles = [row[0] for row in arr] #remove rows that are repeated due to (possible) earlier tiled dissolve from insufficient memory for i,j in enumerate(initialSlope_doubles): if j != initialSlope_doubles[(i-1) % len(initialSlope_doubles)]: initialSlope.append(j) del i,j for i,j in enumerate(percentCliffs_doubles): if j != percentCliffs_doubles[(i-1) % len(percentCliffs_doubles)]: percentCliffs.append(j) del i,j def func(x,a,b,c): return a*np.exp(-((x-b)/c)**2) try: popt, pcov = curve_fit(func,initialSlope,percentCliffs, maxfev=1000) except RuntimeError: fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(initialSlope, percentCliffs, 'ko');plt.draw() fig.show() print("Error - curve_fit failed") xfit = np.linspace(min(initialSlope), max(initialSlope), 100) yfit = popt[0]*np.exp(-((xfit-popt[1])/popt[2])**2) def secondDer(x): return popt[0]*(((4*(x-popt[1])**2*np.exp(-(x-popt[1])**2/popt[2]**2))/popt[2]**4)-((2*np.exp(-(x-popt[1])**2/popt[2]**2))/popt[2]**2)) a1 = [] a1 = [i for i in xrange(91)] a2 = secondDer(a1) #the next 3 for loops and a[x] variables define 1 of the 2 points to derive the optimization line. a3 = [] a4 = [] # values of second derivative where slope is below 'gamma' for i, j in enumerate(a2): if j <= gamma: a3.append(i) == i # find the steepest point (in the middle of the side of the bell) for i, j in enumerate(a2): if j == max(a2): m=i # take only values to the right of 'm' in case the curve is flat at 0 slope for i in a3: if i > m: a4.append(i) == i del i,j ax = min(a4) ay = popt[0]*np.exp(-((ax-popt[1])/popt[2])**2) #find max of bell for first point in optmization line yfit_array = array(yfit) ftup = (np.where(yfit_array == max(yfit_array))) f = int(ftup[0]) # x,y index of max yfit # d = distance from fit Equation 2 (Herreid and Pellicciotti, 2018) to line definded by ((xfit[0],yfit[0]),(ax,yx)) d = abs((yfit[f]-ay)*xfit-(xfit[f]-ax)*yfit+xfit[f]*ay-yfit[f]*ax)/((yfit[f]-ay)**2+(xfit[f]-ax)**2)**(1/2) # crit is the index of the longest d crit = np.where(d == max(d)) m = (yfit[f]-ay)/(xfit[f]-ax) b = yfit[f]-m*xfit[f] x_crit = (xfit[crit]+m*yfit[crit]-m*b)/(m**2+1) y_crit = m*((xfit[crit]+m*yfit[crit]-m*b)/(m**2+1))+b fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(initialSlope, percentCliffs, 'ko'); plt.plot([xfit[f],ax],[yfit[f],ay]); plt.plot([xfit[crit],x_crit],[yfit[crit],y_crit]); plt.plot(xfit,yfit);plt.xlim(0, 100);plt.ylim(0, 100);plt.gca().set_aspect('equal', adjustable='box');plt.draw() ax1.set_xlabel(r'$\mathrm{\beta_i (^\circ)}$') ax1.set_ylabel('Ice cliff fraction (%)') fig.show() #fig.canvas.flush_events() import time time.sleep(1) #plt.pause(0.01) #plt.waitforbuttonpress() #save data used to make figure np.save(workspace+'\\figureData', (initialSlope, percentCliffs,[xfit[f],ax],[yfit[f],ay],[xfit[crit],x_crit],[yfit[crit],y_crit],xfit,yfit)) IceCliffLocation.minSlope = float(xfit[crit])
desc = arcpy.Describe(in_features_polygon) arcpy.env.extent = desc.extent arcpy.env.overwriteOutput = True # arcpy.AddMessage() # Calculate total population cursor = arcpy.da.SearchCursor(in_table_population, [in_field_pop]) total_pop = 0 cursor.reset() for row in cursor: total_pop += row[0] # Create Thiessen using library locations use same extent as in_features polygon thiessen = arcpy.env.scratchGDB + '/thiessen1' arcpy.CreateThiessenPolygons_analysis(in_features_point, thiessen, "ALL") # Intersect Thiessen with in_polygon intersect = arcpy.env.scratchGDB + '/intersect1' arcpy.Intersect_analysis([thiessen, in_features_polygon], intersect) # Join population table to intersected polygons using common field arcpy.JoinField_management(intersect, in_field_join_features, in_table_population, in_field_join_table) # Calculate new field by multiplying population with the ratio of area after and before intersection arcpy.AddField_management(intersect, "POP", "DOUBLE") cursor = arcpy.da.UpdateCursor( intersect, [in_field_oldarea, 'Shape_Area', in_field_pop, 'POP']) cursor.reset()
["Id", "ORIG_FID", output, "SUM_AREA"]) #Se crea una figura mayor que el edificio para teselar a partir de los puntos de las estacias, #se utiliza este teselado como divisiones input = "AUXILIAR2\\" + str(oid) + ".shp" output = "AUXILIAR2\\" + str(oid) + "_10c.shp" arcpy.Buffer_analysis(input, output, "9", "FULL", "ROUND", "ALL") output2 = "AUXILIAR2\\" + str(oid) + "_10b.shp" arcpy.MinimumBoundingGeometry_management(output, output2, "ENVELOPE") output = "AUXILIAR2\\" + str(oid) + "_10d.shp" arcpy.FeatureVerticesToPoints_management(output2, output, "ALL") output2 = "AUXILIAR2\\" + str(oid) + "_10e.shp" arcpy.Merge_management([output3, output], output2) output = "AUXILIAR2\\" + str(oid) + "_10f.shp" try: arcpy.CreateThiessenPolygons_analysis(output2, output, "ALL") except Exception: arcpy.Select_analysis("AUXILIAR2\\0_10.shp", output, "FID = -1") #crea capa en blanco output3 = "AUXILIAR2\\" + str(oid) + "_8.shp" output2 = "AUXILIAR2\\" + str(oid) + "_10.shp" arcpy.Intersect_analysis([output, output3], output2, "ALL", "", "") #Seleccion de los cuartos con fachada menor de 1m, eliminacion y recalculo output = "AUXILIAR2\\" + str(oid) + "_11b.shp" try: arcpy.FeatureToLine_management(output2, output) except Exception: arcpy.Select_analysis("AUXILIAR2\\0_1.shp", output, "FID = -1") #crea capa en blanco output2 = "AUXILIAR2\\" + str(oid) + "_1.shp"
def execute_WidthWatershed(r_flowdir, str_poly, str_line, str_ptscs, result, r_dem, str_zbed, messages, language="FR"): """The source code of the tool.""" arcpy.env.extent = r_flowdir # Copie des points de calcul ptscs = r"in_memory\ptscs" arcpy.CopyFeatures_management(str_ptscs, ptscs) # Polygones de Thiessen pour affecter un tronçon de rivière à chaque section transversale thiessen = r"in_memory\thiessen" arcpy.CreateThiessenPolygons_analysis(ptscs, thiessen) # Intersections des polytgones de Thiessen avec les rivières (polygones et lignes) reaches_poly = r"in_memory\reaches_poly" arcpy.Intersect_analysis([thiessen, str_poly], reaches_poly) reaches_line = r"in_memory\reaches_line" arcpy.Intersect_analysis([thiessen, str_line], reaches_line) # Dissolved selon l'ID des points de sections transversales (pour les cas de confluences - plusieurs lignes pour un # point - et les cas de chenaux multiples - plusieurs polygones pour un point) reaches_poly_d = r"in_memory\reaches_poly_d" arcpy.Dissolve_management(reaches_poly, reaches_poly_d, "Input_FID") reaches_line_d = r"in_memory\reaches_line_d" arcpy.Dissolve_management(reaches_line, reaches_line_d, "Input_FID") # Calcul des aires et des longueurs arcpy.AddGeometryAttributes_management(reaches_poly_d, "AREA_GEODESIC") arcpy.AddGeometryAttributes_management(reaches_line_d, "LENGTH_GEODESIC") # Jointures arcpy.JoinField_management(ptscs, arcpy.Describe(ptscs).OIDFieldName, reaches_poly_d, "Input_FID", "AREA_GEO") arcpy.JoinField_management(ptscs, arcpy.Describe(ptscs).OIDFieldName, reaches_line_d, "Input_FID", "LENGTH_GEO") # Ajout du champ pour la largeur et calcul arcpy.AddField_management(ptscs, "Width", "FLOAT") arcpy.CalculateField_management(ptscs, "Width", "!AREA_GEO!/!LENGTH_GEO!", "PYTHON_9.3") # Conversion en raster arcpy.env.extent = r_flowdir arcpy.env.snapRaster = r_flowdir # Calcul de l'élévation moyenne if str_zbed is not None and r_dem is not None: zbed_table = r"in_memory\zbed_table" arcpy.sa.ZonalStatisticsAsTable(reaches_poly_d, "Input_FID", r_dem, zbed_table, statistics_type="MEAN") arcpy.JoinField_management(ptscs, arcpy.Describe(ptscs).OIDFieldName, zbed_table, "Input_FID", "MEAN") arcpy.PointToRaster_conversion(ptscs, "MEAN", str_zbed, cellsize=r_flowdir) return
"SIMPLIFY", "VALUE") arcpy.AddMessage("Step 4/12 Completed") # Process: Feature Vertices To Points arcpy.AddMessage("Step 5/12 Started- Creating Points at Vertices") if rastercheck: arcpy.FeatureVerticesToPoints_management(ExpandPolygon_shp, ExpandPolygonVertices_shp, "ALL") if vectorcheck: arcpy.FeatureVerticesToPoints_management(ExpandPolygon_shp2, ExpandPolygonVertices_shp, "ALL") arcpy.AddMessage("Step 5/12 Completed") # Process: Create Thiessen Polygons arcpy.AddMessage("Step 6/12 Started- Creating Thiessen Polygons") arcpy.CreateThiessenPolygons_analysis(ExpandPolygonVertices_shp, Thiessen_shp, "ALL") arcpy.AddMessage("Step 6/12 Completed") # Process: Feature To Line arcpy.AddMessage("Step 7/12 Started- Creating Lines from Thiessen Polygons") arcpy.FeatureToLine_management("%scratchWorkspace%\\Thiessen.shp", Thiessen_Lines_shp, "", "ATTRIBUTES") arcpy.AddMessage("Step 7/12 Completed") # Process: Make Feature Layer arcpy.AddMessage("Step 8/12 Started- Making Thiessen Lines into Feature Layer") arcpy.MakeFeatureLayer_management( Thiessen_Lines_shp, Thiessen_Lines_Layer, "", "", "Shape Shape VISIBLE NONE;FID FID VISIBLE NONE;ID ID VISIBLE NONE;GRIDCODE GRIDCODE VISIBLE NONE;ORIG_FID ORIG_FID VISIBLE NONE;Input_FID Input_FID VISIBLE NONE" ) arcpy.AddMessage("Step 8/12 Completed")
def hexagon_polygon(inputAOI, outputTheissen, width='500', *args): """A function to check for correct field types between the from and to fields.""" descInput = arcpy.Describe(inputAOI) if descInput.dataType == 'FeatureLayer': inputAreaOfInterest = descInput.CatalogPath else: inputAreaOfInterest = inputAOI # Describe the Input and get its extent properties desc = arcpy.Describe(inputAreaOfInterest) ext = desc.extent xcoord = ext.XMin ycoord = ext.YMin urxcoord = ext.XMax urycoord = ext.YMax height = float(width) * math.sqrt(3) # Invert the height and width so that the flat side of the hexagon is on the bottom and top tempWidth = width width = height height = tempWidth # Calculate new offset origin, opposite corner and Y axis point coordinates factor1 = -2.0 origin = str(xcoord + float(width) * factor1) + " " + str(ycoord + float(height) * factor1) originX = str(xcoord + float(width) * factor1) originY = str(ycoord + float(height) * factor1) factor2 = 2.0 oppositeCorner = str(urxcoord + float(width) * factor2) + " " + str(urycoord + float(height) * factor2) oppositeCornerX = str(urxcoord + float(width) * factor2) oppositeCornerY = str(urycoord + float(height) * factor2) factor3 = 0.5 newOrigin = str(float(originX) + float(width) * factor3) + " " + str(float(originY) + float(height) * factor3) newOriginX = str(float(originX) + float(width) * factor3) newOriginY = str(float(originY) + float(height) * factor3) newOppositeCorner = str(float(oppositeCornerX) + float(width) * factor3) + " " + str(float(oppositeCornerY) + float(height) * factor3) newOppositeCornerX = str(float(oppositeCornerX) + float(width) * factor3) newOppositeCornerY = str(float(oppositeCornerY) + float(height) * factor3) yAxisCoordinates1 = str(float(originX)) + " " + str(float(oppositeCornerY)) yAxisCoordinates2 = str(float(newOriginX)) + " " + str(float(newOppositeCornerY)) # Calculate Length, hexagonal area and number of columns sideLength = float(height) / math.sqrt(3) hexagonArea = 2.598076211 * pow(sideLength, 2) numberOfColumns = int((urxcoord - xcoord) / int(width)) # Add Messages arcpy.AddMessage("------------------------") arcpy.AddMessage("Width: " + str(height)) arcpy.AddMessage("Height: " + str(width)) arcpy.AddMessage("Hexagon Area: " + str(hexagonArea)) arcpy.AddMessage("Number of Columns: " + str(numberOfColumns)) arcpy.AddMessage("------------------------") try: outputWorkspace = os.path.dirname(outputTheissen) arcpy.env.scratchWorkspace = os.path.dirname(outputTheissen) # Process: Create Fishnet... fishnetPath1 = (os.path.join(outputWorkspace, "Fishnet_1")) fishnet1 = arcpy.CreateFishnet_management(fishnetPath1, origin, yAxisCoordinates1, width, height, "0", "0", oppositeCorner, "LABELS", "") # Process: Create Fishnet (2)... fishnetPath2 = (os.path.join(outputWorkspace, "Fishnet_2")) fishnet2 = arcpy.CreateFishnet_management(fishnetPath2, newOrigin, yAxisCoordinates2, width, height, "0", "0", newOppositeCorner, "LABELS") # Process: Create Feature Class... spatialRef = arcpy.Describe(inputAreaOfInterest).spatialReference hexPoints = arcpy.CreateFeatureclass_management(outputWorkspace, "hex_points", "POINT", "", "", "", spatialRef) # Get fishnet labels from the results of the fishnet tool... fishnetLabel1 = fishnet1.getOutput(1) fishnetLabel2 = fishnet2.getOutput(1) # Define projection for the fishnet labels arcpy.DefineProjection_management(fishnetLabel1, spatialRef) arcpy.DefineProjection_management(fishnetLabel2, spatialRef) # Process: Append... inputForAppend = "{0};{1}".format(fishnetLabel1, fishnetLabel2) arcpy.Append_management(inputForAppend, hexPoints, "NO_TEST", "", "") # Process: Create Thiessen Polygons... fullTheissen = arcpy.CreateThiessenPolygons_analysis(hexPoints, (os.path.join(outputWorkspace, "FullTheissen")), "ONLY_FID") arcpy.AddMessage("Creating hexagonal polygons.") # Process: Minimum Bounding Geometry... AOIEnvelope = arcpy.MinimumBoundingGeometry_management(inputAreaOfInterest, (os.path.join(outputWorkspace, "AOIEnvelope")), "ENVELOPE", "ALL" ) # Process: Make Feature Layer... hexLayer = arcpy.MakeFeatureLayer_management(fullTheissen, "Hex_Layer", "", "", "") # Process: Select Layer By Location... arcpy.SelectLayerByLocation_management(hexLayer, "INTERSECT", AOIEnvelope) # Process: Add Field (1)... arcpy.AddField_management(hexLayer, "X_Coord", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") # Process: Add Field (2)... arcpy.AddField_management(hexLayer, "Y_Coord", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") # Process: Calculate X Value... arcpy.CalculateField_management(hexLayer, "X_Coord", "GetXValue(!shape.centroid!)", "PYTHON", "def GetXValue(centroid):\\n coords = centroid.split(\" \")\\n return round(float(coords[0]),2)") # Process: Calculate Y Value... arcpy.CalculateField_management(hexLayer, "Y_Coord", "GetYValue(!shape.centroid!)", "PYTHON", "def GetYValue(centroid):\\n coords = centroid.split(\" \")\\n return round(float(coords[1]),2)") # Process: Add Field (3)... arcpy.AddField_management(hexLayer, "hexagonID", "LONG", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") #Calculate Hexagon Polygon ID(hexLayer) cur = arcpy.UpdateCursor(hexLayer, "", "", "", "y_coord A; x_coord A") for ID, row in enumerate(cur, 1): row.hexagonID = ID cur.updateRow(row) # Process: Add Spatial Index... arcpy.AddSpatialIndex_management(hexLayer) arcpy.AddMessage("Adding Hexagon Id to polygons.") arcpy.CopyFeatures_management(hexLayer, outputTheissen) # Delete all intermediate data arcpy.Delete_management(fishnet1) arcpy.Delete_management(fishnet2) arcpy.Delete_management(fishnetLabel1) arcpy.Delete_management(fishnetLabel2) arcpy.Delete_management(hexPoints) arcpy.Delete_management(fullTheissen) arcpy.Delete_management(AOIEnvelope) arcpy.AddMessage("Congratulations! You have created the most beautiful polygons ever :)") except: # get the traceback object tb = sys.exc_info()[2] # tbinfo contains the line number that the code failed on and the code from that line tbinfo = traceback.format_tb(tb)[0] # concatenate information together concerning the error into a message string pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n " + \ str(sys.exc_type)+ ": " + str(sys.exc_value) + "\n" # generate a message string for any geoprocessing tool errors msgs = "GP ERRORS:\n" + arcpy.GetMessages(2) + "\n" # return gp messages for use with a script tool arcpy.AddError(msgs) arcpy.AddError(pymsg) # print messages for use in Python/PythonWin print msgs print pymsg
Inside = arcpy.GetParameterAsText(1) if Inside == '#' or not Inside: Inside = True # provide a default value if unspecified Final_Output = arcpy.GetParameterAsText(2) # Local variables: Output_Centroids = "" ThiessanPolygons = "" Polygonal_Bounday = "" # Set Geoprocessing environments arcpy.env.outputCoordinateSystem = "GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]" arcpy.env.cellSize = "MAXOF" arcpy.env.geographicTransformations = "" arcpy.env.mask = Polygonal_Bounday # Process: Create Centroids arcpy.FeatureToPoint_management(Input_Polygons, Output_Centroids, Inside) # Process: Create Thiessen Polygons arcpy.CreateThiessenPolygons_analysis(Output_Centroids, ThiessanPolygons, "ONLY_FID") # Process: Dissolve arcpy.Dissolve_management(Input_Polygons, Polygonal_Bounday, "", "", "MULTI_PART", "DISSOLVE_LINES") # Process: Clip arcpy.Clip_analysis(ThiessanPolygons, Polygonal_Bounday, Final_Output, "")
arcpy.CalculateField_management('lyr','sp_type',"'eez-ccamlr'",'PYTHON_9.3') arcpy.Select_analysis('sp_okBlack', 'aq_ccamlr', "sp_type = 'ccamlr'") # create theissen polygons used to split slivers arcpy.Densify_edit('aq_ccamlr', 'DISTANCE', '10 Kilometers') arcpy.FeatureVerticesToPoints_management('aq_ccamlr', 'aq_ccamlr_pts', 'ALL') # delete interior points arcpy.Dissolve_management('aq_ccamlr', 'aq_ccamlr_d') arcpy.MakeFeatureLayer_management('aq_ccamlr_pts', 'lyr_aq_ccamlr_pts') arcpy.SelectLayerByLocation_management('lyr_aq_ccamlr_pts', 'WITHIN_CLEMENTINI', 'aq_ccamlr_d') arcpy.DeleteFeatures_management('lyr_aq_ccamlr_pts') # generate thiessen polygons of gadm for intersecting with land slivers arcpy.env.extent = 'aq_land' arcpy.CreateThiessenPolygons_analysis('aq_ccamlr_pts', 'aq_thiessen', 'ALL') arcpy.Dissolve_management('aq_thiessen', 'aq_thiessen_d', ['sp_type','sp_id','sp_name','sp_key','rgn_type','rgn_id','rgn_name','rgn_key','cntry_id12','rgn_id12','rgn_name12']) arcpy.RepairGeometry_management('aq_thiessen_d') # get slivers, which are land but not identified by gadm, intersect with thiessen so break at junctions arcpy.Intersect_analysis(['aq_thiessen_d', 'aq_land'], 'aq_thiessen_d_land') arcpy.CalculateField_management('aq_thiessen_d_land','sp_type',"'land-ccamlr'",'PYTHON_9.3') arcpy.CalculateField_management('aq_thiessen_d_land','rgn_type',"'land'",'PYTHON_9.3') # return to geographic coordinate system arcpy.env.outputCoordinateSystem = sr_gcs arcpy.CopyFeatures_management('aq_thiessen_d_land','aq_landccamlr_gcs') arcpy.RepairGeometry_management('aq_landccamlr_gcs') flds_del = list(set([x.name for x in arcpy.ListFields('aq_landccamlr_gcs')]).difference(set([x.name for x in arcpy.ListFields('sp_okBlack')]))) arcpy.DeleteField_management('aq_landccamlr_gcs', flds_del) arcpy.Merge_management(['sp_okBlack', 'aq_landccamlr_gcs'], 'sp_okAQ')
print(n_set) for i in range(len(n_set)): points_shp = random_pts + str(i) arcpy.CreateRandomPoints_management(path, points_shp, boundary, "", str(n_set[i]), "0 Feet", "POINT", "0") arcpy.CalculateField_management(path + points_shp + '.shp', "CID", str(i), "PYTHON_9.3") ########################################################################## # Process: Create Thiessen Polygons based on layers of resouce points (except markets) ########################################################################## start2 = time.time() for i in range(1, n_rsc): points_shp = random_pts + str(i) voronoi_shp = path + resouce_vor + str(i) + ".shp" arcpy.CreateThiessenPolygons_analysis(path + points_shp + ".shp", voronoi_shp, "ONLY_FID") inFeatures.append(voronoi_shp) end2 = time.time() - start2 print end2 ########################################################################## # Process: Intersect ########################################################################## start3 = time.time() inFeatures.append(boundary) multi_voronoi = path + vor_intersect + "_" + str(n_pts) + "_" + str( n_rsc) + "_" + str(n_mkts) + ".shp" arcpy.Intersect_analysis(inFeatures, multi_voronoi, "ALL", "", "INPUT") end3 = time.time() - start3 print end3
with arcpy.da.SearchCursor(troba_mfl, ['OID@', 'SHAPE@']) as cursor: for m in cursor: identificador += 1 arcpy.AddMessage(identificador) nuevotroba = arcpy.MakeFeatureLayer_management( troba_mfl, 'troba_tmp_mfl', 'OBJECTID = {}'.format(m[0])) arcpy.SelectLayerByLocation_management(tapt, "INTERSECT", nuevotroba, "#", 'NEW_SELECTION') extentArea = extents(nuevotroba) arcpy.env.extent = "%s %s %s %s" % (extentArea[0], extentArea[1], extentArea[2], extentArea[3]) taps_thiessen = arcpy.CreateThiessenPolygons_analysis( tapt, "in_memory//taptemp") trobaNuevo = arcpy.Clip_analysis(taps_thiessen, m[1], "in_memory//clipThiessen") arcpy.Append_management(trobaNuevo, output, 'NO_TEST') with arcpy.da.UpdateCursor(output, [field], "%s is null" % field) as cursor: for i in cursor: i[0] = identificador cursor.updateRow(i) del cursor arcpy.SelectLayerByAttribute_management(tapt, 'CLEAR_SELECTION')
"%ScratchWorkspace%\\PolySplitTEMP", ScratchW, "true") PolySplit = arcpy.Sort_management( PolySplitTEMP, "%ScratchWorkspace%\\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, "%ScratchWorkspace%\\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, "%ScratchWorkspace%\\ThiessenPoly", "ALL") JoinTEMP = arcpy.SpatialJoin_analysis( ThiessenPoly, PolySplitToPoint, "%ScratchWorkspace%\\JoinTEMP", "JOIN_ONE_TO_ONE", "KEEP_ALL", "Rank_UGO \"Rank_UGO\" true true false 4 Long 0 0 ,First,#, %ScratchWorkspace%\\PolySplitToPoint,Rank_UGO,-1,-1; Distance \"Distance\" true true false 4 Long 0 0 ,First,#,%ScratchWorkspace%\\PolySplitToPoint,Distance,-1,-1", "INTERSECT", "", "") Join = arcpy.Sort_management( JoinTEMP, "%ScratchWorkspace%\\Join", [["Rank_UGO", "ASCENDING"], ["Distance", "ASCENDING"]]) ncurrentstep += 1 arcpy.AddMessage("Merging Thiessen polygons - Step " + str(ncurrentstep) + "/" + str(nstep)) Dissolve1 = arcpy.Dissolve_management(Join, "%ScratchWorkspace%\\Dissolve1", "Rank_UGO", "", "MULTI_PART",
import arcpy from arcpy import env arcpy.env.overwriteOutput = True env.workspace = r"C:\NRS_528\Assignment4" # Input point features to go through thiessen polygon execution. # In this case, I used emergency medical locations downloaded from RIGIS to visualize areas with the closest EMS location. inFeatures = "Emergency_Medical_Services.shp" outFeatureClass = "EMS_Thiessen" outFields = "ALL" print('Creating Thiessen Polygons from:' + inFeatures) arcpy.CreateThiessenPolygons_analysis(inFeatures, outFeatureClass, outFields) # Clip data for desired analysis location. In this example, I clipped the thiessen data to RI, as the # thiessen data from earlier goes beyond the extent of RI. in_features = "EMS_Thiessen.shp" clip_features = "Municipalities__1997_.shp" out_feature_class = "EMS_Thiessen_riclipped" print('Clipping study area from:' + clip_features) arcpy.Clip_analysis(in_features, clip_features, out_feature_class) if arcpy.Exists(out_feature_class + ".shp"): print('Complete!')
def main(fcInputCenterline, fcInputPolygon, fcSegmentedPolygons, dblPointDensity=10.0, dblJunctionBuffer=100.00, workspaceTemp="in_memory"): # Manage Environments env_extent = arcpy.env.extent env_outputmflag = arcpy.env.outputMFlag env_outputzflag = arcpy.env.outputZFlag arcpy.env.outputMFlag = "Disabled" arcpy.env.outputZFlag = "Disabled" arcpy.env.extent = fcInputPolygon ## Set full extent to build Thiessan polygons over entire line network. # Copy centerline to temporary workspace fcCenterline = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_Centerline") arcpy.CopyFeatures_management(fcInputCenterline, fcCenterline) if "FromID" not in [ field.name for field in arcpy.ListFields(fcCenterline) ]: arcpy.AddField_management(fcCenterline, "FromID", "LONG") arcpy.CalculateField_management( fcCenterline, "FromID", "!{}!".format(arcpy.Describe(fcCenterline).OIDFieldName), "PYTHON_9.3") # Build Thiessan polygons arcpy.AddMessage("GNAT DPS: Building Thiessan polygons") arcpy.Densify_edit(fcCenterline, "DISTANCE", "{} METERS".format(dblPointDensity)) fcTribJunctionPoints = gis_tools.newGISDataset( workspaceTemp, "GNAT_DPS_TribJunctionPoints") arcpy.Intersect_analysis([fcCenterline], fcTribJunctionPoints, output_type="POINT") fcThiessanPoints = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_ThiessanPoints") arcpy.FeatureVerticesToPoints_management(fcCenterline, fcThiessanPoints, "ALL") lyrThiessanPoints = gis_tools.newGISDataset("Layer", "lyrThiessanPoints") arcpy.MakeFeatureLayer_management(fcThiessanPoints, lyrThiessanPoints) arcpy.SelectLayerByLocation_management( lyrThiessanPoints, "INTERSECT", fcTribJunctionPoints, "{} METERS".format(dblJunctionBuffer)) fcThiessanPoly = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_ThiessanPoly") # arcpy.CreateThiessenPolygons_analysis(lyrThiessanPoints,fcThiessanPoly,"ONLY_FID") arcpy.CreateThiessenPolygons_analysis(lyrThiessanPoints, fcThiessanPoly, "ALL") # Clean polygons # lyrInputPolygon = gis_tools.newGISDataset("Layer", "lyrInputPolygon") # arcpy.MakeFeatureLayer_management(fcInputPolygon, lyrInputPolygon) arcpy.RepairGeometry_management(fcInputPolygon, "KEEP_NULL") fcThiessanPolyClip = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_TheissanPolyClip") arcpy.Clip_analysis(fcThiessanPoly, fcInputPolygon, fcThiessanPolyClip) # Split the junction Thiessan polygons arcpy.AddMessage("GNAT DPS: Split junction Thiessan polygons") lyrTribThiessanPolys = gis_tools.newGISDataset("Layer", "lyrTribThiessanPolys") arcpy.MakeFeatureLayer_management(fcThiessanPolyClip, lyrTribThiessanPolys) arcpy.SelectLayerByLocation_management(lyrTribThiessanPolys, "INTERSECT", fcTribJunctionPoints) fcSplitPoints = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_SplitPoints") arcpy.Intersect_analysis([lyrTribThiessanPolys, fcCenterline], fcSplitPoints, output_type="POINT") arcpy.AddMessage("GNAT DPS: Moving starting vertices of junction polygons") geometry_functions.changeStartingVertex(fcTribJunctionPoints, lyrTribThiessanPolys) arcpy.AddMessage("GNAT DPS: Vertices moved") fcThiessanTribPolyEdges = gis_tools.newGISDataset( workspaceTemp, "GNAT_DPS_ThiessanTribPolyEdges") arcpy.FeatureToLine_management(lyrTribThiessanPolys, fcThiessanTribPolyEdges) fcSplitLines = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_SplitLines") arcpy.SplitLineAtPoint_management(fcThiessanTribPolyEdges, fcSplitPoints, fcSplitLines, "0.1 METERS") fcMidPoints = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_MidPoints") arcpy.FeatureVerticesToPoints_management(fcSplitLines, fcMidPoints, "MID") arcpy.Near_analysis(fcMidPoints, fcTribJunctionPoints, location="LOCATION") arcpy.AddXY_management(fcMidPoints) fcTribToMidLines = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_TribToMidLines") arcpy.XYToLine_management(fcMidPoints, fcTribToMidLines, "POINT_X", "POINT_Y", "NEAR_X", "NEAR_Y") ### Select polygons by centerline ### arcpy.AddMessage("GNAT DPS: Select polygons by centerline") fcThiessanEdges = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_ThiessanEdges") arcpy.FeatureToLine_management(fcThiessanPolyClip, fcThiessanEdges) fcAllEdges = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_AllEdges") arcpy.Merge_management([fcTribToMidLines, fcThiessanEdges, fcCenterline], fcAllEdges) # include fcCenterline if needed fcAllEdgesPolygons = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_AllEdgesPolygons") arcpy.FeatureToPolygon_management(fcAllEdges, fcAllEdgesPolygons) fcAllEdgesPolygonsClip = gis_tools.newGISDataset( workspaceTemp, "GNAT_DPS_AllEdgesPolygonsClip") arcpy.Clip_analysis(fcAllEdgesPolygons, fcInputPolygon, fcAllEdgesPolygonsClip) fcPolygonsJoinCenterline = gis_tools.newGISDataset( workspaceTemp, "GNAT_DPS_PolygonsJoinCenterline") arcpy.SpatialJoin_analysis(fcAllEdgesPolygonsClip, fcCenterline, fcPolygonsJoinCenterline, "JOIN_ONE_TO_MANY", "KEEP_ALL", match_option="SHARE_A_LINE_SEGMENT_WITH") fcPolygonsDissolved = gis_tools.newGISDataset( workspaceTemp, "GNAT_DPS_PolygonsDissolved") arcpy.Dissolve_management(fcPolygonsJoinCenterline, fcPolygonsDissolved, "FromID", multi_part="SINGLE_PART") lyrPolygonsDissolved = gis_tools.newGISDataset("Layer", "lyrPolygonsDissolved") arcpy.MakeFeatureLayer_management(fcPolygonsDissolved, lyrPolygonsDissolved) arcpy.SelectLayerByAttribute_management(lyrPolygonsDissolved, "NEW_SELECTION", """ "FromID" IS NULL """) arcpy.Eliminate_management(lyrPolygonsDissolved, fcSegmentedPolygons, "LENGTH") arcpy.AddMessage("GNAT DPS: Tool complete") # Reset env arcpy.env.extent = env_extent arcpy.env.outputMFlag = env_outputmflag arcpy.env.outputZFlag = env_outputzflag return
def main(fcInputCenterline, fcInputPolygon, fcSegmentedPolygons, workspaceTemp, dblPointDensity=10.0, dblJunctionBuffer=120.00): arcpy.AddMessage("GNAT Divide Polygon By Segment Tool") arcpy.AddMessage("GNAT DPS: Saving Polygon Results to: " + fcSegmentedPolygons) arcpy.AddMessage("GNAT DPS: Saving Temporary Files to: " + workspaceTemp) arcpy.env.OutputMFlag = "Disabled" arcpy.env.OutputZFlag = "Disabled" arcpy.AddMessage("arcpy M Output Flag: " + str(arcpy.env.OutputMFlag)) ## Copy Centerline to Temp Workspace fcCenterline = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_Centerline") arcpy.CopyFeatures_management(fcInputCenterline, fcCenterline) ## Build Thiessan Polygons arcpy.AddMessage("GNAT DPS: Building Thiessan Polygons") arcpy.env.extent = fcInputPolygon ## Set full extent to build Thiessan polygons over entire line network. arcpy.Densify_edit(fcCenterline, "DISTANCE", str(dblPointDensity) + " METERS") fcTribJunctionPoints = gis_tools.newGISDataset( workspaceTemp, "GNAT_DPS_TribJunctionPoints") # All Segment Junctions?? #gis_tools.findSegmentJunctions(fcCenterline,fcTribJunctionPoints,"ALL") arcpy.Intersect_analysis(fcCenterline, fcTribJunctionPoints, output_type="POINT") fcThiessanPoints = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_ThiessanPoints") arcpy.FeatureVerticesToPoints_management(fcCenterline, fcThiessanPoints, "ALL") lyrThiessanPoints = gis_tools.newGISDataset("Layer", "lyrThiessanPoints") arcpy.MakeFeatureLayer_management(fcThiessanPoints, lyrThiessanPoints) arcpy.SelectLayerByLocation_management(lyrThiessanPoints, "INTERSECT", fcTribJunctionPoints, str(dblJunctionBuffer) + " METERS", "NEW_SELECTION") fcThiessanPoly = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_ThiessanPoly") arcpy.CreateThiessenPolygons_analysis(lyrThiessanPoints, fcThiessanPoly, "ONLY_FID") fcThiessanPolyClip = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_TheissanPolyClip") arcpy.Clip_analysis(fcThiessanPoly, fcInputPolygon, fcThiessanPolyClip) ### Code to Split the Junction Thiessan Polys ### arcpy.AddMessage("GNAT DPS: Split Junction Thiessan Polygons") lyrTribThiessanPolys = gis_tools.newGISDataset("Layer", "lyrTribThiessanPolys") arcpy.MakeFeatureLayer_management(fcThiessanPolyClip, lyrTribThiessanPolys) arcpy.SelectLayerByLocation_management(lyrTribThiessanPolys, "INTERSECT", fcTribJunctionPoints, selection_type="NEW_SELECTION") fcSplitPoints = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_SplitPoints") arcpy.Intersect_analysis([lyrTribThiessanPolys, fcCenterline], fcSplitPoints, output_type="POINT") arcpy.AddMessage("GNAT DPS: Moving Starting Vertices of Junction Polygons") geometry_functions.changeStartingVertex(fcTribJunctionPoints, lyrTribThiessanPolys) arcpy.AddMessage("GNAT DPS: Vertices Moved.") fcThiessanTribPolyEdges = gis_tools.newGISDataset( workspaceTemp, "GNAT_DPS_ThiessanTribPolyEdges") arcpy.FeatureToLine_management(lyrTribThiessanPolys, fcThiessanTribPolyEdges) fcSplitLines = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_SplitLines") arcpy.SplitLineAtPoint_management(fcThiessanTribPolyEdges, fcSplitPoints, fcSplitLines, "0.1 METERS") fcMidPoints = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_MidPoints") arcpy.FeatureVerticesToPoints_management(fcSplitLines, fcMidPoints, "MID") arcpy.Near_analysis(fcMidPoints, fcTribJunctionPoints, location="LOCATION") arcpy.AddXY_management(fcMidPoints) fcTribToMidLines = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_TribToMidLines") arcpy.XYToLine_management(fcMidPoints, fcTribToMidLines, "POINT_X", "POINT_Y", "NEAR_X", "NEAR_Y") ### Select Polys by Centerline ### arcpy.AddMessage("GNAT DPS: Select Polygons By Centerline") fcThiessanEdges = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_ThiessanEdges") arcpy.FeatureToLine_management(fcThiessanPolyClip, fcThiessanEdges) fcAllEdges = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_AllEdges") arcpy.Merge_management([fcTribToMidLines, fcThiessanEdges, fcCenterline], fcAllEdges) # include fcCenterline if needed fcAllEdgesPolygons = gis_tools.newGISDataset(workspaceTemp, "GNAT_DPS_AllEdgesPolygons") arcpy.FeatureToPolygon_management(fcAllEdges, fcAllEdgesPolygons) fcAllEdgesPolygonsClip = gis_tools.newGISDataset( workspaceTemp, "GNAT_DPS_AllEdgesPolygonsClip") arcpy.Clip_analysis(fcAllEdgesPolygons, fcInputPolygon, fcAllEdgesPolygonsClip) fcPolygonsJoinCenterline = gis_tools.newGISDataset( workspaceTemp, "GNAT_DPS_PolygonsJoinCenterline") arcpy.SpatialJoin_analysis(fcAllEdgesPolygonsClip, fcCenterline, fcPolygonsJoinCenterline, "JOIN_ONE_TO_MANY", "KEEP_ALL", match_option="SHARE_A_LINE_SEGMENT_WITH") fcPolygonsDissolved = gis_tools.newGISDataset( workspaceTemp, "GNAT_DPS_PolygonsDissolved") arcpy.Dissolve_management(fcPolygonsJoinCenterline, fcPolygonsDissolved, "JOIN_FID", multi_part="SINGLE_PART") #fcSegmentedPolygons = gis_tools.newGISDataset(workspaceOutput,"SegmentedPolygons") lyrPolygonsDissolved = gis_tools.newGISDataset("Layer", "lyrPolygonsDissolved") arcpy.MakeFeatureLayer_management(fcPolygonsDissolved, lyrPolygonsDissolved) arcpy.SelectLayerByAttribute_management(lyrPolygonsDissolved, "NEW_SELECTION", """ "JOIN_FID" = -1 """) arcpy.Eliminate_management(lyrPolygonsDissolved, fcSegmentedPolygons, "LENGTH") arcpy.AddMessage("GNAT DPS: Tool Complete.") return
Xmax = float(ext[2].replace(",", ".")) Ymax = float(ext[3].replace(",", ".")) chaine = str(Xmin) + " " + str(Ymin) + " " + str(Xmax) + " " + str(Ymax) arcpy.AddMessage(" Extent : Xmin=" + str(Xmin) + " ; Ymin=" + str(Ymin)) arcpy.AddMessage(" Xmax=" + str(Xmax) + " ; Ymax=" + str(Ymax)) #/creation of the Thiessen polygons ncurrentstep += 1 arcpy.AddMessage("Creating Thiessen polygons - Step " + str(ncurrentstep) + "/" + str(nstep)) arcpy.env.extent = chaine ThiessenPolyCenterline = arcpy.CreateThiessenPolygons_analysis( SplitCenterlineToPoint, "%ScratchWorkspace%\\ThiessenPolyCenterline", "ALL") arcpy.env.extent = chaine #/extraction of the Thiessen polygons overlaying the polygon ncurrentstep += 1 arcpy.AddMessage( "Clipping Thiessen polygons with the in polygon feature - Step " + str(ncurrentstep) + "/" + str(nstep)) Segmentation_TEMP = arcpy.Clip_analysis( ThiessenPolyCenterline, inFC, "%ScratchWorkspace%\\Segmentation_TEMP", "") #/transfer of the ordination information # ordination fields are contained in the split centerline ncurrentstep += 1
# Local variables: fc = "Data/Interp/"+evname+".gdb/"+evname+"_fc" Thiessen = "Data/Interp/"+evname+".gdb/"+evname+"_Thiessen" Thiessen_ocean = "Data/Interp/"+evname+".gdb/"+evname+"_Thiessen_ocean" Thiessen_single = "Data/Interp/"+evname+".gdb/"+evname+"_Thiessen_single" Thiessen_clipped = "Data/Interp/"+evname+".gdb/"+evname+"_Interp" # 1) # Create geodatabase file arcpy.CreateFileGDB_management ("Data/Interp", evname) # Add env. points to geodatabase arcpy.CopyFeatures_management (s, fc) # 2) # Create Thiessen Polygons arcpy.CreateThiessenPolygons_analysis (fc, Thiessen, "ALL") # 4) # Overlay with ocean layer arcpy.Intersect_analysis ([Thiessen, ocean], Thiessen_ocean) arcpy.MultipartToSinglepart_management(Thiessen_ocean, Thiessen_single) # 5) # Select Layer By Location # Remove polygons over 50 m from original points arcpy.MakeFeatureLayer_management (Thiessen_single, "tmp") arcpy.SelectLayerByLocation_management ("tmp", "WITHIN_A_DISTANCE", fc, "50 Meters", "NEW_SELECTION") arcpy.CopyFeatures_management ("tmp", Thiessen_clipped)
arcpy.AddMessage("Splitting the network - Step " + str(ncurrentstep) + "/" + str(nstep)) SplitNetwork = dS.SLEM(SmoothedNetwork, DisaggregationStep, "%ScratchWorkspace%\\SplitNetwork", ScratchW, "true") ncurrentstep += 1 arcpy.AddMessage("Converting Split network to points - Step " + str(ncurrentstep) + "/" + str(nstep)) SplitNetworkToPoints = arcpy.FeatureVerticesToPoints_management( SplitNetwork, "%scratchWorkspace%\\SplitNetworkToPoints", "MID") ncurrentstep += 1 arcpy.AddMessage("Creating Thiessen polygons - Step " + str(ncurrentstep) + "/" + str(nstep)) ThiessenPolygons = arcpy.CreateThiessenPolygons_analysis( SplitNetworkToPoints, "%scratchWorkspace%\\ThiessenPolygons", "ALL") #/creation of the reference DEM ncurrentstep += 1 arcpy.AddMessage("Clipping Thiessen polygons with Large Buffer - Step " + str(ncurrentstep) + "/" + str(nstep)) ClippedThiessenPolygons = arcpy.Clip_analysis( ThiessenPolygons, LargeBuffer, "%scratchWorkspace%\\ClippedThiessenPolygons", "") ncurrentstep += 1 arcpy.AddMessage("Creating DEM with the Small Buffer - Step " + str(ncurrentstep) + "/" + str(nstep)) MinDEM = arcpy.gp.ExtractByMask_sa(ProcessDEM, SmallBuffer, "%scratchWorkspace%\\MinDEM")
def main(): arcpy.env.workspace = 'C:\Users\owner\Downloads\Sample_scripts\ch06' inputFeature = 'C:\Users\owner\Documents\Learning Materials\Johanson - 500 level\PROJECT\\adm&gaz\NGA_adm\NGA_adm1.shp' tempOut = 'Feat2Pt.shp' arcpy.FeatureToPoint_management(inputFeature, tempOut) arcpy.CreateThiessenPolygons_analysis(tempOut, 'voronoi.shp')