def minimal_geometry(feature): arcpy.MinimumBoundingGeometry_management( feature, "C:/Studia/PPG_II/Egzamin/Wyniki/rectangle_by_area.shp", "RECTANGLE_BY_AREA") arcpy.MinimumBoundingGeometry_management( feature, "C:/Studia/PPG_II/Egzamin/Wyniki/rectangle_by_width.shp", "RECTANGLE_BY_WIDTH") arcpy.MinimumBoundingGeometry_management( feature, "C:/Studia/PPG_II/Egzamin/Wyniki/convex_hull.shp", "CONVEX_HULL") arcpy.MinimumBoundingGeometry_management( feature, "C:/Studia/PPG_II/Egzamin/Wyniki/circle.shp", "CIRCLE") arcpy.MinimumBoundingGeometry_management( feature, "C:/Studia/PPG_II/Egzamin/Wyniki/envelope.shp", "ENVELOPE") list = [ r"C:/Studia/PPG_II/Egzamin/Wyniki/rectangle_by_area.shp", r"C:/Studia/PPG_II/Egzamin/Wyniki/rectangle_by_width.shp", r"C:/Studia/PPG_II/Egzamin/Wyniki/convex_hull.shp", r"C:/Studia/PPG_II/Egzamin/Wyniki/circle.shp", r"C:/Studia/PPG_II/Egzamin/Wyniki/envelope.shp" ] polygon_geometry_list = [] polyline_geometry_list = [] for i in list: polyline_geometry_list.append(polygon_to_polyline(i)) for row in arcpy.da.SearchCursor(i, ["SHAPE@"]): polygon_geometry_list.append(row[0]) return polyline_geometry_list
def main(): arcpy.env.overwriteOutput = True inputFeature = sys.argv[1] arcpy.env.workspace = os.path.dirname(inputFeature) tempOut = 'boundingPoly.shp' arcpy.MinimumBoundingGeometry_management(inputFeature, 'boundingPoly.shp') arcpy.FeatureVerticesToPoints_management(tempOut, 'outerPoints.shp')
def create_boundary(NAME, meter): input_path = os.path.abspath("input_folder") output_path = os.path.abspath("output_folder/shp_files") if os.path.isdir("output_folder/"): rmtree('output_folder/') os.mkdir("output_folder/") os.mkdir("output_folder/shp_files") else: os.mkdir("output_folder/") os.mkdir("output_folder/shp_files") asc_file_path = os.path.join(input_path, NAME + ".tif") boundary = os.path.join(output_path, "{}_boundary.shp".format(NAME)) bound_neg2m = os.path.join(output_path, "{}_bound_neg2m.shp".format(NAME)) bound_rec = os.path.join(output_path, "{}_bound_rec.shp".format(NAME)) reclassified = arcpy.sa.Reclassify( asc_file_path, "VALUE", "101.102745 105.156837 1;105.156837 108.940979 1") arcpy.RasterToPolygon_conversion(reclassified, boundary, "NO_SIMPLIFY") arcpy.Buffer_analysis(boundary, bound_neg2m, "{} Meters".format(meter), "FULL", "ROUND", "NONE", "", "PLANAR") # require user input for meters arcpy.MinimumBoundingGeometry_management(bound_neg2m, bound_rec, "RECTANGLE_BY_AREA", "NONE", "", "NO_MBG_FIELDS")
def MBR(self, fc): """ Construct the Minimum Bounding Box of all trajectory points. :return: null """ arcpy.MinimumBoundingGeometry_management(fc, self.workspace + "MBB output", "RECTANGLE_BY_AREA")
def zoomAER3(mxd, df, emp): lista = [] lista2 = [] lista_revisar_zoom = [] for i in arcpy.mapping.ListLayers(mxd): if i.name == 'AER': aer = i if i.name == 'CCPP_EM': centropoblado = i lista.append(i) if i.name == 'CCPP_CC': pass # lista.append(i) if i.name == 'CCPP_CN': pass # lista.append(i) area = [x[0] for x in arcpy.da.SearchCursor(aer, ["SHAPE@AREA"])][0] # area = [x[0] for x in arcpy.da.SearchCursor(aer, ["SHAPE@AREA"])] for i in lista: a = arcpy.GetCount_management(i)[0] lista2.append(int(a)) cantCCPP = sum(filter(None, lista2)) if area < 0.022: # print "Menor al área" df.extent = aer.getSelectedExtent() # ZOOM EXTEND A LA CAPA DE AERS df.scale = df.scale * 1.15 arcpy.RefreshActiveView() # df.scale = df.scale * 12 elif area >= 0.022: print "Mayor al área" # ccpp = arcpy.Merge_management(lista, 'in_memory\ccpp1') ccpp = centropoblado if cantCCPP < 3: print "Menor a 3" mfl = arcpy.MakeFeatureLayer_management(ccpp , 'CentroPoblados') layerFileArea = arcpy.mapping.Layer('CentroPoblados') arcpy.RefreshActiveView() df.extent = layerFileArea.getSelectedExtent() # ZOOM EXTEND A LA CAPA DE AERS df.scale = 90000 # df.scale = 150000 arcpy.RefreshActiveView() lista_revisar_zoom.append(emp) else: print "Mayor a 3" nameArea = 'areaMfl' mfl = arcpy.MakeFeatureLayer_management(ccpp, 'area1') areaBound = arcpy.MinimumBoundingGeometry_management(mfl, r'D:\SegmentacionRuralV2\Procesamiento\Croquis\Croq_proceso\area.shp', "RECTANGLE_BY_AREA", "ALL") mfl = arcpy.MakeFeatureLayer_management(areaBound, nameArea) layerFileArea = arcpy.mapping.Layer(nameArea) arcpy.RefreshActiveView() df.extent = layerFileArea.getSelectedExtent() # ZOOM EXTEND A LA CAPA DE AERS df.scale = df.scale * 1.8 arcpy.RefreshActiveView() # if len(lista_revisar_zoom) != 0: return lista_revisar_zoom
def study_area_circle(in_fc, out_fc): arcpy.MinimumBoundingGeometry_management( in_features=in_fc, out_feature_class=out_fc, geometry_type="CIRCLE", group_option="ALL", group_field="", mbg_fields_option="NO_MBG_FIELDS", )
def envelopePoints(readTable): arcpy.AddMessage("Running convex hull...") for row in readTable: arcpy.MinimumBoundingGeometry_management( in_features=makeFullPath(arcpy.env.workspace, row["Name"]), out_feature_class=makeFullPath(tempGDB, row["Name"] + "_Conv"), geometry_type="CONVEX_HULL", group_option="LIST", group_field=groupingFieldsFromMetaDataForConvexHull(row)) row["Envelope"] = row["Name"] + "_Conv"
def processShapefile(shapeName, defaultPath, record, extraDir, option = None): if option == 0: pass elif option == 1: shapeName = validateInput("shapeName", "Shapefile name: ", defaultPath, record, extraDir) else: record = validateInput("record","Record Number: ", defaultPath) extraDir = validateInput("extraDir", "Extra directory: ", defaultPath, record) shapeName = validateInput("shapeName", "Shapefile name: ", defaultPath, record, extraDir) shpExt = shapeName+'.shp' if extraDir == '': inlayer = os.path.join(defaultPath,record,shpExt) outBoundingBox = os.path.join(defaultPath,record,shapeName+'_BB.shp') outBoundingBoxVertices = os.path.join(defaultPath,record,shapeName+'_BB_Vert.shp') else: inlayer = os.path.join(defaultPath,record,extraDir,shpExt) outBoundingBox = os.path.join(defaultPath,record,extraDir,shapeName+'_BB.shp') outBoundingBoxVertices = os.path.join(defaultPath,record,extraDir,shapeName+'_BB_Vert.shp') print 'Deleting BB if found' if arcpy.Exists(outBoundingBox): arcpy.Delete_management(outBoundingBox) if arcpy.Exists(outBoundingBoxVertices): arcpy.Delete_management(outBoundingBoxVertices) print 'Creating bounding box' # Use MinimumBoundingGeometry function to get an envelop area arcpy.MinimumBoundingGeometry_management(inlayer, outBoundingBox, "ENVELOPE") print 'Convert vertices to points' # Convert vertices to points arcpy.FeatureVerticesToPoints_management(outBoundingBox, outBoundingBoxVertices, 'All') print 'Calculate X/Y for vertices' # Calculate X/Y for vertices arcpy.AddXY_management(outBoundingBoxVertices) xField = "Point_X" xMinValue = arcpy.SearchCursor(outBoundingBoxVertices, "", "", "", xField + " A").next().getValue(xField) #Get 1st row in ascending cursor sort xMaxValue = arcpy.SearchCursor(outBoundingBoxVertices, "", "", "", xField + " D").next().getValue(xField) #Get 1st row in descending cursor sort yField = "Point_Y" yMinValue = arcpy.SearchCursor(outBoundingBoxVertices, "", "", "", yField + " A").next().getValue(yField) #Get 1st row in ascending cursor sort yMaxValue = arcpy.SearchCursor(outBoundingBoxVertices, "", "", "", yField + " D").next().getValue(yField) #Get 1st row in descending cursor sort if arcpy.Exists(outBoundingBox): arcpy.Delete_management(outBoundingBox) if arcpy.Exists(outBoundingBoxVertices): arcpy.Delete_management(outBoundingBoxVertices) return {'xMin':xMinValue, 'xMax':xMaxValue,'yMin':yMinValue, 'yMax':yMaxValue}
def getExtentOfMap(linjesymboler, SlopeL=101.000, SlopeL2=102.000): try: hoydekurver = arcpy.Select_analysis( linjesymboler, os.path.join(basePath, r"Trash", r"a1"), '"SYMBOL"=' + str(SlopeL) + ' OR "SYMBOL"=' + str(SlopeL2)) utsnitt1 = arcpy.MinimumBoundingGeometry_management( hoydekurver, os.path.join(basePath, r"Trash", r"a2"), "CONVEX_HULL") arcpy.AddField_management(utsnitt1, "UTSNITT", "DOUBLE") features = arcpy.UpdateCursor(utsnitt1) for feature in features: feature.UTSNITT = 1 features.updateRow(feature) del feature, features dissolved = arcpy.Dissolve_management( utsnitt1, os.path.join(basePath, r"Trash", r"a3"), "UTSNITT") return arcpy.MinimumBoundingGeometry_management( dissolved, os.path.join(basePath, r"Trash", r"a4"), "CONVEX_HULL") except: print("Tried to get extent of OCAD-map but failed")
def make_boundary_shp(self): print(" * creating boundary shapefile (%s) ..." % self.boundary_shp) print(" - source file: %s" % self.point_shp) arcpy.env.workspace = self.out_dir arcpy.env.outputCoordinateSystem = self.sr arcpy.MinimumBoundingGeometry_management( in_features=self.point_shp, out_feature_class=self.boundary_shp, geometry_type="CONVEX_HULL", group_option="ALL") print(" - OK")
def Mcp(pointList): if type(pointList[0]) != arcpyPointType: pointList = [arcpy.Point(point[0], point[1]) for point in pointList] #MinimumBoundingGeometry() will not accept a list or an arcpy.Array of geometries, #only a single geometry works (Polyline or Multipoint is much faster than a Polygon). points = arcpy.Multipoint(arcpy.Array(pointList)) empty = arcpy.Geometry() #correct results are dependent on having arcpy.env.outputCoordinateSystem set mcpList = arcpy.MinimumBoundingGeometry_management(points, empty, "CONVEX_HULL", "ALL") return mcpList[0]
def main(): arcpy.env.workspace = 'C:\Users\owner\Downloads\Sample_scripts\ch06\shapefiles' arcpy.env.overwriteOutput = True features = arcpy.ListFeatureClasses() for feature in features: try: outfile = feature[:-4] + 'Bound.shp' arcpy.MinimumBoundingGeometry_management(feature, outfile) print('{} created'.format(outfile)) except arcpy.ExecuteError: print(arcpy.GetMessage(2)) print(arcpy.GetMessage(3))
def main(infc, outfc): try: if 'shp' in outfc: arcpy.AddError('Output parameter must be saved in a geodatabase') sys.exit() arcpy.Buffer_analysis(infc, "in_memory\\buffer", 1, "FULL", "ROUND") arcpy.MinimumBoundingGeometry_management("in_memory\\buffer", outfc, "ENVELOPE", "ALL") except Exception, e: arcpy.AddError('%s' % (e))
def geoProcess(in_data1, destination_data): # basePath = .../apps/findbestroute/workfiles/ print('pleaaaase ' + basePath) arcpy.MinimumBoundingGeometry_management(in_features=destination_data, out_feature_class=os.path.join( basePath, "Trash", "box"), geometry_type="ENVELOPE") # original box over box = os.path.join(basePath, "Trash", "box.shp") # fields = arcpy.ListFields(boxobj) # for field in fields: # print(field.name) arcpy.AddGeometryAttributes_management(Input_Features=box, Geometry_Properties="EXTENT") # # arcpy.AddGeometryAttributes_management(Input_Features=os.path.join(basePath, "Trash", "box.shp"), Geometry_Properties="EXTENT") # fields2 = arcpy.ListFields(boxobj) # for field2 in fields2: # print(field2.name) # for field in arcpy.ListFields(dataset=box): # print(field.__str__()) raster = arcpy.Raster(in_data1) inXMax = raster.extent.XMax inYMax = raster.extent.YMax inXMin = raster.extent.XMin inYMin = raster.extent.YMin XminValues = [row[0] for row in arcpy.da.SearchCursor(box, "EXT_MIN_X")] YMinValues = [row[0] for row in arcpy.da.SearchCursor(box, "EXT_MIN_Y")] XMaxValues = [row[0] for row in arcpy.da.SearchCursor(box, "EXT_MAX_X")] YMaxValues = [row[0] for row in arcpy.da.SearchCursor(box, "EXT_MAX_Y")] destXMin = min(XminValues) destYMin = min(YMinValues) destXMax = max(XMaxValues) destYMax = max(YMaxValues) sourceCP = "'" + str(inXMax) + " " + str(inYMax) + "';'" + str( inXMax) + " " + str(inYMin) + "';'" + str(inXMin) + " " + str( inYMax) + "';'" + str(inXMin) + " " + str(inYMin) + "'" targetCP = "'" + str(destXMax) + " " + str(destYMax) + "';'" + str( destXMax) + " " + str(destYMin) + "';'" + str(destXMin) + " " + str( destYMax) + "';'" + str(destXMin) + " " + str(destYMin) + "'" return arcpy.Warp_management( raster, sourceCP, targetCP, os.path.join(basePath, r"Results", r"geoKart.jpg"), "POLYORDER1")
def convex_hull(self): """ Creates a Convex Hull for all Geometries. Output: SpatialDataFrame """ geom = arcpy.MinimumBoundingGeometry_management( in_features=self.geometry.tolist(), out_feature_class=Geometry(), geometry_type="CONVEX_HULL")[0] gs = GeoSeries([geom]) gs.sr = geom.spatialReference.factoryCode or None return SpatialDataFrame(geometry=gs, data=[])
def execute(self, parameters, messages): inFeatures = parameters[0].valueAsText outFeatures = parameters[1].valueAsText geometryType = parameters[2].valueAsText if (not geometryType): geometryType = "ENVELOPE" # arcinfo user use [MinimumBoundingGeometry_management] if (arcpy.ProductInfo() != "ArcInfo" or geometryType != "CONVEX_HULL"): arcpy.MinimumBoundingGeometry_management(inFeatures, outFeatures, geometryType) return # only CONVEX_HULL inDesc = arcpy.Describe(inFeatures) if (inDesc.dataType == "FeatureLayer"): inDesc = inDesc.featureClass dirName, fcName = os.path.split(outFeatures) #create output arcpy.CreateFeatureclass_management(dirName, fcName, "POLYGON", inFeatures, "SAME_AS_TEMPLATE", "SAME_AS_TEMPLATE", inDesc.spatialReference) fields = arcpy.ListFields(outFeatures) fieldList = [] for field in fields: #messages.addMessage("{0} is a type of {1} with a length of {2}" # .format(field.name, field.type, field.length)) if (field.type != "OID" or field.type != "Geometry" ): fieldList.append(field.name) fieldList.append("SHAPE@") # for Progress step count result = arcpy.GetCount_management(inFeatures) count = int(result.getOutput(0)) arcpy.SetProgressor("step", "Inserting ...", 0, count, 1) with arcpy.da.InsertCursor(outFeatures, fieldList) as inCursor: with arcpy.da.SearchCursor(inFeatures, fieldList) as cursor: for row in cursor: if (isinstance(row[-1] , arcpy.Polygon)): insertRow = row[:-1] + (row[-1].convexHull(),) inCursor.insertRow( insertRow ) #step count arcpy.SetProgressorPosition()
def SetupRaster(features, smoothingFactor, sr=None, cellSize=None): #Describe() will get the envelope in the feature's Spatial Reference #extent = arcpy.Describe(features).extent #This will return the extent in the environment's Output Spatial Reference mcpList = arcpy.MinimumBoundingGeometry_management(features, arcpy.Geometry(), "ENVELOPE", "ALL") extent = mcpList[0].extent if utils.IsFloat(cellSize): cellSize = float(cellSize) # all parameters from ArcToolbox are text else: cellSize = DefaultCellSize(extent) # FIXME explain why r=2*h searchRadius = 2 * smoothingFactor return extent, cellSize, searchRadius
def minimal_bounding_poly(in_features, where=''): """get a bounding multipart geometry around the given features Parameters ---------- in_features : str full path to input features iout_features : str full path to output features where : str, optional where clause Returns ------- polygon : arcpy.Polygon """ ws_tmp = arcpy.env.scratchGDB feat_tmp = join(ws_tmp, 'feat_tmp') feat_single = join(ws_tmp, 'feat_single') feat_minimal = join(ws_tmp, 'feat_minimal') out_union = join(ws_tmp, 'out_union') out_features = join(ws_tmp, 'out') #arcpy.Delete_management(ws_tmp) def del_tmp(): for f in [ feat_tmp, feat_single, feat_minimal, out_features, out_union ]: arcpy.Delete_management(f) del_tmp() arcpy.FeatureClassToFeatureClass_conversion(in_features, ws_tmp, split(feat_tmp)[1], where_clause=where) arcpy.MultipartToSinglepart_management(feat_tmp, feat_single) arcpy.MinimumBoundingGeometry_management(feat_single, feat_minimal, "RECTANGLE_BY_AREA", "NONE") arcpy.Union_analysis(feat_minimal, out_union, gaps="NO_GAPS") arcpy.Dissolve_management(out_union, out_features, "", "", "MULTI_PART", "DISSOLVE_LINES") #arcpy.FillGaps_production(out_features) cursor = arcpy.da.SearchCursor(out_features, ['SHAPE@']) polygon = cursor.next()[0] del (cursor) del_tmp() return polygon
def photo2env(rootdir, bufferDist): """ Creates a point layer from geotagged photos, buffers to set distance, creates polygon to encompass all buffered areas. Assumes directory structure of rootdir\refID\sensor\output... """ for dir in os.listdir(rootdir): refID = rootdir + "\\" + dir for subdir in os.listdir(refID): inFolder = refID + "\\" + subdir outFeatures = refID + "\\points2" if subdir == "Sequoia": print(inFolder + " Processing") arcpy.GeoTaggedPhotosToPoints_management(inFolder, outFeatures) arcpy.Buffer_analysis(outFeatures + ".shp", outFeatures + "_buff2", bufferDist) arcpy.MinimumBoundingGeometry_management(outFeatures + "_buff2.shp", outFeatures + "_ENV2", "ENVELOPE", "ALL")
def Optimized_HotSpot_Analysis(facilityName): ''' To conduct Optimized Hot Spot Analysis :param facilityName: feature class name of the facility :return: ''' try: #Get the raster dataset of facility density surface arcpy.env.mask = "basemap_dissolved" arcpy.MinimumBoundingGeometry_management(facilityName,facilityName+"_MBG","CONVEX_HULL","ALL","#","NO_MBG_FIELDS") ohsa = arcpy.OptimizedHotSpotAnalysis_stats(facilityName,facilityName+"_ohsaSnap","","SNAP_NEARBY_INCIDENTS_TO_CREATE_WEIGHTED_POINTS", facilityName+"_MBG","",facilityName+"_ohsaRaster" ) ohsa2 = arcpy.OptimizedHotSpotAnalysis_stats(facilityName, facilityName+"_ohsaFishnet","","COUNT_INCIDENTS_WITHIN_FISHNET_POLYGONS", "basemap_dissolved") if arcpy.Exists(facilityName+"_MBG"): arcpy.Delete_management(facilityName+"_MBG") print "Complete hot spot analysis" except: print (arcpy.GetMessages())
def getWidth(inShpPath, indexField): # Process Path if not os.path.exists('Process'): os.makedirs('Process') processPath = "./Process/" # Process Data Path outShpTempPath = processPath + "temp.shp" outputBoundary = processPath + "boundary.shp" # Output Path if not os.path.exists('Result'): os.makedirs('Result') # Output Data Path outShpPath = "./Result/subcatchments.shp" # Execute CopyFeatures arcpy.CopyFeatures_management(inShpPath, outShpTempPath) # Use MinimumBoundingGeometry function to get a convex hull area arcpy.MinimumBoundingGeometry_management(outShpTempPath, outputBoundary, "RECTANGLE_BY_AREA", "NONE") # Execute AddField arcpy.AddField_management(outputBoundary, "MaxEdge", "DOUBLE", "", "", "", "maxEdge", "NULLABLE", "NON_REQUIRED", "") # Calculate Max Edge expression = "(!shape.geodesicLength@METERS! + math.sqrt(math.pow(!shape.geodesicLength@METERS!, 2) - 16 *" \ " !shape.geodesicArea@METERS!))/4" arcpy.CalculateField_management(outputBoundary, "MaxEdge", expression, "PYTHON") # Execute AddField arcpy.AddField_management(outShpTempPath, "Width", "DOUBLE", "", "", "", "slope", "NULLABLE", "NON_REQUIRED", "") # Create a feature layer layerName = "tempShp" arcpy.MakeFeatureLayer_management(outShpTempPath, layerName) # Join the feature layer to a table arcpy.AddJoin_management(layerName, indexField, outputBoundary, indexField) # Calculate Width arcpy.CalculateField_management( layerName, "Width", "!shape.geodesicArea@METERS!/!boundary.MaxEdge!", "PYTHON") # Remove the join arcpy.RemoveJoin_management(layerName, "boundary") # Copy the layer to a new permanent feature class arcpy.CopyFeatures_management(layerName, outShpPath) return outShpPath
def Centerline(infc): edges = {} temp3 = 'in_memory\\tempdata3' temp4 = 'in_memory\\tempdata4' arcpy.MinimumBoundingGeometry_management(infc, temp3,"RECTANGLE_BY_WIDTH", "ALL") arcpy.Intersect_analysis([temp3, inFC], temp4, "","","POINT") arcpy.MultipartToSinglepart_management(temp4,temp3) values = [f[0] for f in arcpy.da.SearchCursor(temp3,['SHAPE@'])] distance = 0 for feature in values: startx,starty = feature.firstPoint.X,feature.firstPoint.Y for feature2 in values: endx,endy = feature2.firstPoint.X,feature2.firstPoint.Y dx = startx-endx dy = starty-endy dist = math.sqrt((dx**2)+(dy**2)) if dist > distance: distance = dist pnt = (startx,starty) for feature in arcpy.da.SearchCursor(infc,['SHAPE@','Id']): try: start = feature[0].firstPoint end = feature[0].lastPoint pnts1,pnts2 = [(start.X,start.Y),(end.X,end.Y)] Length = feature[0].length ID = feature[1] if ID in edges: edges[ID].add_edge(pnts1,pnts2,weight=Length) else: Graph = nx.Graph() Graph.add_edge(pnts1,pnts2,weight=Length) edges[ID] = Graph except Exception,e: arcpy.AddError('%s'%(e))
def getConvexHullShapefile(self, shapefile, buffer): arcpy.AddMessage("getConvexHullShapefile") convex_hull = os.path.join("in_memory", 'convex_hull' + str(random.randint(1, 100))) # Process: Minimum Bounding Geometry arcpy.MinimumBoundingGeometry_management(shapefile, convex_hull, "CONVEX_HULL", "ALL", "", "NO_MBG_FIELDS") if buffer: # Process: Buffer convex_hull_buffer = os.path.join( "in_memory", 'convex_hull_buffer' + str(random.randint(1, 100))) arcpy.Buffer_analysis(convex_hull, convex_hull_buffer, buffer, "FULL", "ROUND", "NONE", "", "PLANAR") return convex_hull_buffer else: return convex_hull
def CreateMCP(locationLayer, mcpFeatureClass, percentUsed, removalMethod, userPoint, sr=None, shapeName=None): if percentUsed == 100: #correct results are dependent on having arcpy.env.outputCoordinateSystem set arcpy.MinimumBoundingGeometry_management(locationLayer, mcpFeatureClass, "CONVEX_HULL", "ALL") else: if removalMethod == "Area_Added": AddArea(locationLayer, mcpFeatureClass, percentUsed, sr, shapeName) elif removalMethod == "User_Point": # the lambda function should act like MeanPoint(), except # it takes an (unused) list of points and return the constant user point FixedCenter(locationLayer, mcpFeatureClass, percentUsed, (lambda x: userPoint), sr, shapeName) elif removalMethod == "Floating_Mean": FloatingCenter(locationLayer, mcpFeatureClass, percentUsed, MeanPoint, sr, shapeName) elif removalMethod == "Floating_Median": FloatingCenter(locationLayer, mcpFeatureClass, percentUsed, MedianPoint, sr, shapeName) elif removalMethod == "Fixed_Median": FixedCenter(locationLayer, mcpFeatureClass, percentUsed, MedianPoint, sr, shapeName) elif removalMethod == "Fixed_Mean": FixedCenter(locationLayer, mcpFeatureClass, percentUsed, MeanPoint, sr, shapeName) else: utils.warn("Removal Method was unrecognized. Using Fixed_Mean.") FixedCenter(locationLayer, mcpFeatureClass, percentUsed, MeanPoint, sr, shapeName)
def minimum_bounding_geometry(the_scenario, logger): logger.info("start: minimum_bounding_geometry") arcpy.env.workspace = the_scenario.main_gdb # Clean up any left of layers from a previous run if arcpy.Exists("road_lyr"): arcpy.Delete_management("road_lyr") if arcpy.Exists("rail_lyr"): arcpy.Delete_management("rail_lyr") if arcpy.Exists("water_lyr"): arcpy.Delete_management("water_lyr") if arcpy.Exists("pipeline_prod_trf_rts_lyr"): arcpy.Delete_management("pipeline_prod_trf_rts_lyr") if arcpy.Exists("pipeline_crude_trf_rts_lyr"): arcpy.Delete_management("pipeline_crude_trf_rts_lyr") if arcpy.Exists("Locations_MBG"): arcpy.Delete_management("Locations_MBG") if arcpy.Exists("Locations_MBG_Buffered"): arcpy.Delete_management("Locations_MBG_Buffered") # Determine the minimum bounding geometry of the scenario arcpy.MinimumBoundingGeometry_management("Locations", "Locations_MBG", "CONVEX_HULL") # Buffer the minimum bounding geometry of the scenario arcpy.Buffer_analysis("Locations_MBG", "Locations_MBG_Buffered", "100 Miles", "FULL", "ROUND", "NONE", "", "GEODESIC") # Select the roads within the buffer # ----------------------------------- arcpy.MakeFeatureLayer_management("road", "road_lyr") arcpy.SelectLayerByLocation_management("road_lyr", "INTERSECT", "Locations_MBG_Buffered") result = arcpy.GetCount_management("road") count_all_roads = float(result.getOutput(0)) result = arcpy.GetCount_management("road_lyr") count_roads_subset = float(result.getOutput(0)) roads_percentage = count_roads_subset / count_all_roads # Only subset if the subset will result in substantial reduction of the road network size if roads_percentage < 0.75: # Switch selection to identify what's outside the buffer arcpy.SelectLayerByAttribute_management("road_lyr", "SWITCH_SELECTION") # Delete the features outside the buffer with arcpy.da.UpdateCursor('road_lyr', ['OBJECTID']) as ucursor: for ucursor_row in ucursor: ucursor.deleteRow() arcpy.Delete_management("road_lyr") # Select the rail within the buffer # --------------------------------- arcpy.MakeFeatureLayer_management("rail", "rail_lyr") arcpy.SelectLayerByLocation_management("rail_lyr", "INTERSECT", "Locations_MBG_Buffered") # Switch selection to identify what's outside the buffer arcpy.SelectLayerByAttribute_management("rail_lyr", "SWITCH_SELECTION") # Delete the features outside the buffer with arcpy.da.UpdateCursor('rail_lyr', ['OBJECTID']) as ucursor: for ucursor_row in ucursor: ucursor.deleteRow() arcpy.Delete_management("rail_lyr") # Select the water within the buffer # ----------------------------------- arcpy.MakeFeatureLayer_management("rail", "rail_lyr") arcpy.SelectLayerByLocation_management("rail_lyr", "INTERSECT", "Locations_MBG_Buffered") # Switch selection to identify what's outside the buffer arcpy.SelectLayerByAttribute_management("rail_lyr", "SWITCH_SELECTION") # Delete the features outside the buffer with arcpy.da.UpdateCursor('rail_lyr', ['OBJECTID']) as ucursor: for ucursor_row in ucursor: ucursor.deleteRow() arcpy.Delete_management("rail_lyr") # Select the water within the buffer # ----------------------------------- arcpy.MakeFeatureLayer_management("water", "water_lyr") arcpy.SelectLayerByLocation_management("water_lyr", "INTERSECT", "Locations_MBG_Buffered") # Switch selection to identify what's outside the buffer arcpy.SelectLayerByAttribute_management("water_lyr", "SWITCH_SELECTION") # Delete the features outside the buffer with arcpy.da.UpdateCursor('water_lyr', ['OBJECTID']) as ucursor: for ucursor_row in ucursor: ucursor.deleteRow() arcpy.Delete_management("water_lyr") # Select the pipeline_prod_trf_rts within the buffer # -------------------------------------------------- arcpy.MakeFeatureLayer_management("pipeline_prod_trf_rts", "pipeline_prod_trf_rts_lyr") arcpy.SelectLayerByLocation_management("pipeline_prod_trf_rts_lyr", "INTERSECT", "Locations_MBG_Buffered") # Switch selection to identify what's outside the buffer arcpy.SelectLayerByAttribute_management("pipeline_prod_trf_rts_lyr", "SWITCH_SELECTION") # Delete the features outside the buffer with arcpy.da.UpdateCursor('pipeline_prod_trf_rts_lyr', ['OBJECTID']) as ucursor: for ucursor_row in ucursor: ucursor.deleteRow() arcpy.Delete_management("pipeline_prod_trf_rts_lyr") # Select the pipeline_crude_trf_rts within the buffer # -------------------------------------------------- arcpy.MakeFeatureLayer_management("pipeline_crude_trf_rts", "pipeline_crude_trf_rts_lyr") arcpy.SelectLayerByLocation_management("pipeline_crude_trf_rts_lyr", "INTERSECT", "Locations_MBG_Buffered") # Switch selection to identify what's outside the buffer arcpy.SelectLayerByAttribute_management("pipeline_crude_trf_rts_lyr", "SWITCH_SELECTION") # Delete the features outside the buffer with arcpy.da.UpdateCursor('pipeline_crude_trf_rts_lyr', ['OBJECTID']) as ucursor: for ucursor_row in ucursor: ucursor.deleteRow() arcpy.Delete_management("pipeline_crude_trf_rts_lyr") arcpy.Delete_management("Locations_MBG") arcpy.Delete_management("Locations_MBG_Buffered") # finally, compact the geodatabase so the MBG has an effect on runtime. arcpy.Compact_management(the_scenario.main_gdb) logger.debug("finish: minimum_bounding_geometry")
def SpatialJoinLines_LargestOverlap(target_features, join_features, outgdb, out_fc, bufsize, keep_all, fields_select): arcpy.env.extent = target_features arcpy.env.workspace = outgdb #Split target and join lines at intersections print('Selecting lines...') joinhull = arcpy.MinimumBoundingGeometry_management(join_features, 'joinhull', 'CONVEX_HULL', group_option='ALL') targethull = arcpy.MinimumBoundingGeometry_management(target_features, 'targethull', 'CONVEX_HULL', group_option='ALL') print('Splitting lines...') lyr = arcpy.MakeFeatureLayer_management(target_features) arcpy.SelectLayerByLocation_management(lyr, 'WITHIN', joinhull, selection_type='NEW_SELECTION') arcpy.FeatureToLine_management( lyr, 'target_split') #Feature to line splits lines at intersections lyr = arcpy.MakeFeatureLayer_management(join_features) arcpy.SelectLayerByLocation_management(lyr, 'WITHIN', targethull, selection_type='NEW_SELECTION') arcpy.FeatureToLine_management(join_features, 'joinfeat_split') #Bufferize both datasets print('Buffering...') arcpy.Buffer_analysis('target_split', 'target_buf', bufsize, method='GEODESIC') arcpy.Buffer_analysis('joinfeat_split', 'joinfeat_buf', bufsize, method='GEODESIC') #Get buffer area for target feature arcpy.AddGeometryAttributes_management('target_buf', 'AREA_GEODESIC', Area_Unit='SQUARE_METERS') #Spatial join with largest overlap # Calculate intersection between Target Feature and Join Features print('Intersecting...') arcpy.Intersect_analysis(['target_buf', 'joinfeat_buf'], 'lines_intersect', join_attributes='ALL') arcpy.AlterField_management('lines_intersect', 'AREA_GEO', 'AREA_targetbuf', 'AREA_targetbuf') arcpy.AddGeometryAttributes_management('lines_intersect', 'AREA_GEODESIC', Area_Unit='SQUARE_METERS') arcpy.AlterField_management('lines_intersect', 'AREA_GEO', 'AREA_inters', 'AREA_inters') #Dissolve to sum intersecting area over print('Computing statistics...') arcpy.Statistics_analysis( 'lines_intersect', 'lines_intersect_stats', statistics_fields=[['AREA_inters', 'SUM'], ['AREA_targetbuf', 'FIRST']], case_field=['FID_joinfeat_buf', 'FID_target_buf']) print('Joining by largest overlap...') #[f.name for f in arcpy.ListFields('lines_intersect_stats')] # Find which Join Feature has the largest overlap with each Target Feature fields = [ 'FID_target_buf', 'FID_joinfeat_buf', "SUM_AREA_inters", "FIRST_AREA_targetbuf" ] overlap_dict = {} with arcpy.da.SearchCursor('lines_intersect_stats', fields) as scur: for row in scur: try: if row[2] > overlap_dict[row[0]][1]: overlap_dict[row[0]] = [row[1], row[2], row[3]] except: overlap_dict[row[0]] = [row[1], row[2], row[3]] # Copy the target features and write the largest overlap join feature ID to each record # Set up all fields from the target features + ORIG_FID fieldmappings = arcpy.FieldMappings() fieldmappings.addTable(target_features) fieldmap = arcpy.FieldMap() fieldmap.addInputField(target_features, arcpy.Describe(target_features).OIDFieldName) fld = fieldmap.outputField fld.type, fld.name, fld.aliasName = "LONG", "ORIG_FID", "ORIG_FID" fieldmap.outputField = fld fieldmappings.addFieldMap(fieldmap) # Perform the copy print('Copying...') arcpy.conversion.FeatureClassToFeatureClass('target_split', os.path.dirname(out_fc), os.path.basename(out_fc), "", fieldmappings) # Add a new field JOIN_FID to contain the fid of the join feature with the largest overlap arcpy.AddField_management(out_fc, "JOIN_FID", "LONG") arcpy.AddField_management(out_fc, "AREA_inters", "DOUBLE") arcpy.AddField_management(out_fc, "AREA_targetbuf", "DOUBLE") arcpy.AddField_management(out_fc, "intersper", "DOUBLE") # Calculate the JOIN_FID field with arcpy.da.UpdateCursor( out_fc, ["ORIG_FID", "JOIN_FID", "AREA_inters", "AREA_targetbuf", "intersper" ]) as ucur: for row in ucur: try: row[1] = overlap_dict[row[0]][0] row[2] = overlap_dict[row[0]][1] row[3] = overlap_dict[row[0]][2] row[4] = overlap_dict[row[0]][1] / overlap_dict[row[0]][ 2] #intersper = AREA_inters/AREA_targetbuf ucur.updateRow(row) except: if not keep_all: ucur.deleteRow() # Join all attributes from the join features to the output joinfields = [ x.name for x in arcpy.ListFields('joinfeat_split') if not x.required and x.name in fields_select ] arcpy.JoinField_management(out_fc, "JOIN_FID", 'joinfeat_split', arcpy.Describe('joinfeat_split').OIDFieldName, joinfields) #Add length attribute to be able to remove outliers from crossings arcpy.AddGeometryAttributes_management(out_fc, 'LENGTH_GEODESIC', Length_Unit='METERS') #Delete intermediate outputs for outlyr in [ 'joinfeat_split', 'target_slip', 'target_buf', 'joinfeat_buf', 'lines_intersect', 'lines_intersect_stats' ]: print('Deleting {}'.format(outlyr)) arcpy.Delete_management(outlyr)
def execute(self, parameters, messages): """The source code of the tool.""" arcpy.env.overwriteOutput = True scratchWorkspace = arcpy.env.scratchWorkspace if not scratchWorkspace: scratchWorkspace = arcpy.env.scratchGDB in_nc = parameters[0].valueAsText in_nc_lat_var = parameters[1].valueAsText in_nc_lon_var = parameters[2].valueAsText in_rapid_connect_file = parameters[3].valueAsText in_catchment = parameters[4].valueAsText streamID = parameters[5].valueAsText out_WeightTable = parameters[6].valueAsText # validate the netcdf dataset self.dataValidation(in_nc, messages) # Obtain catchment extent in lat and lon in GCS_WGS_1984 sr_cat = arcpy.Describe(in_catchment).SpatialReference extent = arcpy.Describe(in_catchment).extent #if (sr_cat.name == 'World_Equidistant_Cylindrical'): if (sr_cat.name == 'GCS_WGS_1984'): extent = extent else: envelope = os.path.join(scratchWorkspace, 'envelope') result0 = arcpy.MinimumBoundingGeometry_management( in_catchment, envelope, 'ENVELOPE', 'ALL') envelope = result0.getOutput(0) sr_out = arcpy.SpatialReference(4326) # GCS_WGS_1984 envelope_proj = os.path.join(scratchWorkspace, 'envelope_proj') result1 = arcpy.Project_management(envelope, envelope_proj, sr_out) envelope_proj = result1.getOutput(0) extent = arcpy.Describe(envelope_proj).extent #Open nc file data_nc = NET.Dataset(in_nc) # Obtain geographic coordinates self.lsm_lon_array = data_nc.variables[ in_nc_lon_var][:] #assume [-180, 180] self.lsm_lat_array = data_nc.variables[ in_nc_lat_var][:] #assume [-90,90] data_nc.close() #convert 3d to 2d if time dimension if (len(self.lsm_lon_array.shape) == 3): self.lsm_lon_array = self.lsm_lon_array[0] self.lsm_lat_array = self.lsm_lat_array[0] # Create Thiessen polygons based on the points within the extent arcpy.AddMessage("Generating Thiessen polygons...") polygon_thiessen = os.path.join(scratchWorkspace, 'polygon_thiessen') result4 = self.createPolygon(extent, polygon_thiessen, scratchWorkspace) polygon_thiessen = result4[1] # Intersect the catchment polygons with the Thiessen polygons arcpy.AddMessage("Intersecting Thiessen polygons with catchment...") intersect = os.path.join(scratchWorkspace, 'intersect') result5 = arcpy.Intersect_analysis([in_catchment, polygon_thiessen], intersect, 'ALL', '#', 'INPUT') intersect = result5.getOutput(0) # Calculate the geodesic area in square meters for each intersected polygon (no need to project if it's not projected yet) arcpy.AddMessage("Calculating geodesic areas...") arcpy.AddGeometryAttributes_management(intersect, 'AREA_GEODESIC', '', 'SQUARE_METERS', '') # Calculate the total geodesic area of each catchment based on the contributing areas of points fields = [streamID, 'POINT_X', 'POINT_Y', 'AREA_GEO'] area_arr = arcpy.da.FeatureClassToNumPyArray(intersect, fields) arcpy.AddMessage("Writing the weight table...") #get list of COMIDs in rapid_connect file so only those are included in computations connectivity_table = self.csvToList(in_rapid_connect_file) streamID_unique_arr = [int(row[0]) for row in connectivity_table] #if point not in array append dummy data for one point of data lon_dummy = area_arr['POINT_X'][0] lat_dummy = area_arr['POINT_Y'][0] #find point index in 2d grid lsm_lat_indices_from_lat, lsm_lon_indices_from_lat = NUM.where( self.lsm_lat_array == lat_dummy) lsm_lat_indices_from_lon, lsm_lon_indices_from_lon = NUM.where( self.lsm_lon_array == lon_dummy) index_lat_dummy = NUM.intersect1d(lsm_lat_indices_from_lat, lsm_lat_indices_from_lon)[0] index_lon_dummy = NUM.intersect1d(lsm_lon_indices_from_lat, lsm_lon_indices_from_lon)[0] with open(out_WeightTable, 'wb') as csvfile: connectwriter = csv.writer(csvfile, dialect='excel') connectwriter.writerow( [streamID, 'area_sqm', 'lon_index', 'lat_index', 'npoints']) for streamID_unique in streamID_unique_arr: ind_points = NUM.where( area_arr[streamID] == streamID_unique)[0] num_ind_points = len(ind_points) if num_ind_points <= 0: #FEATUREID,area_sqm,lon_index,lat_index,npoints,Lon,Lat connectwriter.writerow([ streamID_unique, 0, index_lon_dummy, index_lat_dummy, 1 ]) else: for ind_point in ind_points: area_geo_each = float(area_arr['AREA_GEO'][ind_point]) lon_each = area_arr['POINT_X'][ind_point] lat_each = area_arr['POINT_Y'][ind_point] #find point index in 2d grid lsm_lat_indices_from_lat, lsm_lon_indices_from_lat = NUM.where( self.lsm_lat_array == lat_each) lsm_lat_indices_from_lon, lsm_lon_indices_from_lon = NUM.where( self.lsm_lon_array == lon_each) index_lat_each = NUM.intersect1d( lsm_lat_indices_from_lat, lsm_lat_indices_from_lon)[0] index_lon_each = NUM.intersect1d( lsm_lon_indices_from_lat, lsm_lon_indices_from_lon)[0] #write to file connectwriter.writerow([ streamID_unique, area_geo_each, index_lon_each, index_lat_each, num_ind_points ]) return
def generate_dispersiveness(polygon, levels, workspace="in_memory"): arcpy.env.workspace = workspace dispersiveness = "" closure_str = "" fragmentation = "" roundness = "" adv_elongation = "" for l in levels: with arcpy.da.SearchCursor(polygon, [ "AREA", "TO_EYE", "SHAPE@", "EYE_X", "EYE_Y", "AREA_CVX", "PERIM", "SUM_AREA" ], where_clause="dBZ=%d AND TO_EYE<=600000" % l) as cur: cur.reset() # list for dispersiveness dlist = [] # list for fragmentation flist = [] # list for roundness rlist = [] # list to collect areas _areas_list = [] # dict for closure closure = dict(zip(range(360), [False] * 360)) for row in cur: # Dispersiveness dlist.append([row[0], row[1]]) # For closure, we need exclude polygon in 50km buffer closed to the eye if row[1] >= 50000: geom, x0, y0 = row[2:5] cl = calc_closure(geom, x0, y0) closure.update(cl) # Fragment flist.append([row[0], row[5]]) # Roundness rlist.append([row[0], row[6], row[7]]) # Area list _areas_list.append(row[0]) # Calculate dispersiveness areas = numpy.array(dlist) if areas.shape != (0, ): total_areas = numpy.sum(areas[:, 0]) area_frac = areas[:, 0] / total_areas dist_weight = areas[:, 1] / 600000.0 dispersiveness += "%f," % numpy.sum(area_frac * dist_weight) else: dispersiveness += "," # Calculate closure # Actually we don't need the closure dict in each level, we just need a final number. total_deg = sum(closure.values()) if total_deg: closure_str += "%f," % (total_deg / 360.0) else: closure_str += "," # Calculate fragementation. fareas = numpy.array(flist) if fareas.shape != (0, ): total_cvx_areas = numpy.sum(fareas[:, 1]) solidity = total_areas / total_cvx_areas # Connectivity sareas = fareas.shape[0] conn = 1 - ((sareas - 1) / ((total_areas / 9)**0.5 + sareas)) fragmentation += "%f," % (1 - solidity * conn) else: fragmentation += "," # Assymetry/Roundness # I think, it should be OK for each polygon, but I think it hurt nothing to calculate it here. rareas = numpy.array(rlist) if fareas.shape != (0, ): max_rareas = rareas[numpy.argmax(rareas, 0)] # R = base_roundness * size_factor R = numpy.mean(4 * max_rareas[:, 0] * math.pi / numpy.square(max_rareas[:, 1]) * (numpy.log(max_rareas[:, 0]) / numpy.log(max_rareas[:, 2]))) roundness += "%f," % (1 - R) else: roundness += "," # Get largest 3 polygons if _areas_list: if len(_areas_list) < 3: _area = min(_areas_list) else: _area = sorted(_areas_list)[-3] # Second pass, get larget N polygons delete_list = ["in_memory\\L3", "in_memory\\BOX"] select3 = arcpy.Select_analysis(polygon, delete_list[0], where_clause="AREA>=%f" % _area) # Get bounding box for entire area arcpy.MinimumBoundingGeometry_management( delete_list[0], delete_list[1], "RECTANGLE_BY_AREA", mbg_fields_option="MBG_FIELDS", group_option="ALL") with arcpy.da.SearchCursor( delete_list[1], ["MBG_Width", "MBG_Length"]) as cur2: for r in cur2: adv_elongation += "%f," % (row[1] / row[0]) map(arcpy.Delete_management, delete_list) else: adv_elongation += "," return dispersiveness, closure_str, fragmentation, roundness, adv_elongation
'RADIUS2': 4000, 'REMOVE_SPOT': False } # Copy defensive position to its own feature layer for calculations tower = arcpy.MakeFeatureLayer_management( towerFC, scrubbedTowerName, "OBJECTID = " + str(row.getValue("OBJECTID"))) # Do a Minimum Bounding Geometry (MBG) on the input tower observers_mbg = os.path.join( env.scratchWorkspace, "observers_mbg_towerlos_" + scrubbedTowerName) delete_me.append(observers_mbg) arcpy.AddMessage("...Finding observer's minimum bounding envelope ...") arcpy.MinimumBoundingGeometry_management(tower, observers_mbg) # Now find the center of the (MBG) arcpy.AddMessage("...Finding center of tower ...") mbgCenterPoint = os.path.join( env.scratchWorkspace, "mbgCenterPoint_towerlos_" + scrubbedTowerName) mbgExtent = arcpy.Describe(observers_mbg).extent mbgSR = arcpy.Describe(observers_mbg).spatialReference mbgCenterX = mbgExtent.XMin + (mbgExtent.XMax - mbgExtent.XMin) mbgCenterY = mbgExtent.YMin + (mbgExtent.YMax - mbgExtent.YMin) arcpy.CreateFeatureclass_management(os.path.dirname(mbgCenterPoint), os.path.basename(mbgCenterPoint), "POINT", "#", "DISABLED", "DISABLED", mbgSR) mbgShapeFieldName = arcpy.Describe(mbgCenterPoint).ShapeFieldName
pass import arcpy ws = r"//gisdata/arcgis/GISdata/KDOT/BTP/Projects/MAPINDEX/IndexProcess.mdb/KSLAM" PLSS_IN = "DW_PLSS_MV" PLSS_1 = "PLSS" PLSS_2 = "PLSSTR1" BndU = "Bnd_U" BndUD = "Bnd_UD" BndLyr = "CCL_ENV" BndIndx = "CITYNO" BndEnv = "CCL_ENV" arcpy.env.overwriteOutput = True #Bnd Bounding Polygons #arcpy.MakeRouteEventLayer_lr("SDE.CMLRS","LRS_KEY","SDE.Bnd_Lane","LRSKEY LINE BEGMILEPOST ENDMILEPOST","Bnd_LINES","#","ERROR_FIELD","NO_ANGLE_FIELD","NORMAL","ANGLE","LEFT","POINT") arcpy.MinimumBoundingGeometry_management(BndLyr, BndEnv, "ENVELOPE", "LIST", BndIndx, "MBG_FIELDS") #City Limit Bounding Polygons #Build PLSS SEctions for T&R arcpy.env.workspace = ws if arcpy.Exists(PLSS_1): print("Using " + PLSS_1 + " to merge township and range") else: print("MAking the Township and Range dissolve from PLSS") arcpy.FeatureClassToFeatureClass_conversion(PLSS_IN, ws, PLSS_1, "#", "#") arcpy.Dissolve_management(PLSS_1, ws + "//" + PLSS_2, "TOWNSHIP;RANGE", "#", "MULTI_PART", "DISSOLVE_LINES") arcpy.AddField_management(PLSS_2, "TWP_NO", "LONG", "#", "#", "#", "#", "NULLABLE", "NON_REQUIRED", "#") arcpy.AddField_management(PLSS_2, "RNG_NO", "LONG", "#", "#", "#", "#", "NULLABLE", "NON_REQUIRED", "#")