def Secant(building): array = arcpy.Array([arcpy.Point(*coords) for coords in building]) build = arcpy.Geometry("POLYGON", array) secants = [] k=2 for pnt in building[2:-2]: d = Distance(building[0][0],pnt[0],building[0][1],pnt[1]) num = k+1 geom = arcpy.Geometry("POLYLINE", arcpy.Array([arcpy.Point(building[0][0],building[0][1]), arcpy.Point(pnt[0],pnt[1])])) if geom.within(build): in_out = 1 else: in_out = 0 diction = {'id':(str(0)+str(k)), 'lenght':d, 'vert_num':num, 'id_from':0, 'id_to':k, "in_out":in_out} if not geom.crosses(build): secants.append(diction) k+=1 i=1 for pnt in building[1:]: j=i+2 for oth in building[i+2:-1]: d = Distance(pnt[0],oth[0],pnt[1],oth[1]) num = j-i+1 geom = arcpy.Geometry("POLYLINE", arcpy.Array([arcpy.Point(pnt[0],pnt[1]), arcpy.Point(oth[0],oth[1])])) if geom.within(build): in_out = 1 else: in_out = 0 diction = {'id':str(i)+str(j), 'lenght':d, 'vert_num':num, 'id_from':i, 'id_to':j, "in_out":in_out} if not geom.crosses(build): secants.append(diction) j+=1 i+=1 secants = sorted(secants, key=lambda k: k['lenght']) return secants
def external_edge_buffer(in_edges, edge_buffer, out_fc=None): g_edges = arcpy.Buffer_analysis(in_edges, arcpy.Geometry(), 0.1, "FULL", "ROUND", "ALL") g_edge_to_polys = arcpy.FeatureToPolygon_management(g_edges, arcpy.Geometry()) g_buffer_polys = arcpy.Buffer_analysis(g_edge_to_polys, arcpy.Geometry(), edge_buffer, "FULL", "ROUND", "ALL") if out_fc: arcpy.CopyFeatures_management(g_buffer_polys, out_fc,) return g_buffer_polys
def thing(fc_stream, fc_contour): g_wtc = arcpy.CopyFeatures_management(fc_stream, arcpy.Geometry()) g_ctr = arcpy.CopyFeatures_management(fc_contour, arcpy.Geometry()) for g in g_ctr: print g.firstPoint, g.lastPoint for v in g_wtc[0]: print v.X, v.Y, v.Z
def execute(self, parameters, messages): """The source code of the tool.""" in_layer = parameters[0].valueAsText erase_layer = parameters[1].valueAsText output_layer = parameters[2].valueAsText in_geometries = arcpy.CopyFeatures_management(in_layer, arcpy.Geometry()) dissolve_erase_geometry = arcpy.Dissolve_management( erase_layer, arcpy.Geometry())[0] erase_result_geometry = [ polygon.difference(dissolve_erase_geometry) for polygon in in_geometries ] return arcpy.SpatialJoin_analysis(erase_result_geometry, in_layer, output_layer)
def execute(self, parameters, messages): """The source code of the tool.""" in_layer = parameters[0].valueAsText out_layer = parameters[1].valueAsText method = parameters[2].valueAsText in_geometries = arcpy.CopyFeatures_management(in_layer, arcpy.Geometry()) if method == 'ALL': in_geometries = arcpy.Dissolve_management(in_geometries, arcpy.Geometry()) result_geometry = [ line.convexHull() for line in in_geometries if line.convexHull().type == 'polygon' ] return arcpy.CopyFeatures_management(result_geometry, out_layer)
def parseCORRIDOR(record,height): utils.common.OutputMessage(logging.DEBUG, "{0} parseCORRIDOR()".format(time.ctime())) line = [] items = record.split('/') (distance, units) = parseDistance(items[1]) for i in items: if i.startswith('LATS') == True or i.startswith('LATM') == True or i.startswith('DMPIT') == True: line.append(parseLatLong(i,height)) pass newline = arcpy.Polyline(arcpy.Array([arcpy.Point(*coords) for coords in line]),arcpy.SpatialReference(4326), False, False) arcpy.Buffer_analysis(arcpy.Polyline(arcpy.Array([arcpy.Point(*coords) for coords in line]),arcpy.SpatialReference(4326), False, False), r'in_memory\tempBuffer', '%s %s' % (distance/2, units), 'FULL', 'FLAT', 'ALL') geometries = arcpy.CopyFeatures_management(r'in_memory\tempBuffer', arcpy.Geometry()) objJson = json.loads(geometries[0].JSON) objJson['hasZ'] = True for i in range(0, len(objJson['rings'])): for j in range(0, len(objJson['rings'][i])): objJson['rings'][i][j].append(height) arcpy.Delete_management(r'in_memory\tempBuffer') del geometries return objJson
def get_unique_point(line_layer, start_of_drainages="p_o_start"): global start_of_drainages_fullpath arcpy.CreateFeatureclass_management(workspace, start_of_drainages, "Multipoint", "", "DISABLED", "DISABLED", line_layer) geometries = arcpy.CopyFeatures_management(line_layer, arcpy.Geometry()) #arcpy.AddMessage("-"*22) startlist = [] lastlist = [] for geometry in geometries: startlist.append( [round(geometry.firstPoint.X, 2), round(geometry.firstPoint.Y, 2)]) lastlist.append( [round(geometry.lastPoint.X, 2), round(geometry.lastPoint.Y, 2)]) unique_list = [] for x in startlist: if x not in lastlist: unique_list.append(x) for zz in unique_list: array = arcpy.Array(arcpy.Point(zz[0], zz[1])) Multipoint = arcpy.Multipoint(array) cursor = arcpy.da.InsertCursor(start_of_drainages_fullpath, "SHAPE@") cursor.insertRow((Multipoint, )) del cursor
def generateCurves(fc): desc = arcpy.Describe(fc) fc_name = desc.name fc_gdb = desc.path Curves = fc_gdb + "\\" + fc_name + "_curves_polygon" if arcpy.Exists(Curves): arcpy.Delete_management(Curves) arcpy.CreateFeatureclass_management(fc_gdb, fc_name + "_curves_polygon", "POLYGON", "", "", "", fc) for row in arcpy.da.SearchCursor(fc, ['SHAPE@']): pts = arcpy.Array() j = json.loads(row[0].JSON) if 'curve' in str(j): #print "You have true curves!" try: exe = [ pts.add(arcpy.Point(f[0], f[1])) for i in row[0] if i for f in i if f ] except: exe = [pts.add(f) for i in row[0] if i for f in i if f] if pts: pts.add(pts.getObject(0)) polygon = arcpy.Polygon(pts, arcpy.SpatialReference("Israel TM Grid")) diff = polygon.symmetricDifference(row[0]) diff_sp = arcpy.MultipartToSinglepart_management( diff, arcpy.Geometry()) if len(diff_sp) > 0: arcpy.Append_management(diff_sp, Curves, "NO_TEST") return Curves
def generateCurves(fc): desc = arcpy.Describe(fc) fc_name = desc.name fc_gdb = desc.path Curves = fc_gdb + "\\" + fc_name + "_curves_polygon" #print "generateCurves("+fc_name+")..." arcpy.CreateFeatureclass_management(fc_gdb, fc_name + "_curves_polygon", "POLYGON", "", "", "", fc) curveFeatureList = [] for row in arcpy.SearchCursor(fc): pts = [] geom = row.Shape j = json.loads(geom.JSON) if 'curve' in str(j): #print "You have true curves!" coords = geom.__geo_interface__['coordinates'] for i in coords: if i: for f in i: if f: pts.append(arcpy.Point(f[0], f[1])) if pts: polygon = PtsToPolygon(pts) diff = polygon.symmetricDifference(geom) diff_sp = arcpy.MultipartToSinglepart_management( diff, arcpy.Geometry()) if len(diff_sp) > 0: arcpy.Append_management(diff_sp, Curves, "NO_TEST") return Curves
def __init__(self, center, inputRangeList, distanceUnits, sr): ''' initialize rings ''' self.deleteme = [] # project center to sr, and keep it as a list of PointGeometries object originalGeom = arcpy.CopyFeatures_management(center, arcpy.Geometry()) newGeom = [] for g in originalGeom: newGeom.append(g.projectAs(sr)) self.center = newGeom self.rangeList = self._sortList(inputRangeList) if distanceUnits == None or distanceUnits == "#" or distanceUnits == "": self.distanceUnits = sr.linearUnitName else: self.distanceUnits = distanceUnits if not sr == None or not sr == "#" or not sr == "": self.sr = sr else: self.sr = srDefault self.ringFeatures = None self.radialFeatures = None self.ringCount = len(self.rangeList) self.ringMin = min(self.rangeList) self.ringMax = max(self.rangeList)
def sobreposicao_poligono_camada(poligono, camada, dissolve=True): log(id_imovel, 'Classificando tema {0}'.format(camada)) clipped = arcpy.Clip_analysis(camada, poligono, arcpy.Geometry()) if not clipped: return None if not dissolve: return clipped return dissolve_poligonos(clipped)
def execute(self, parameters, messages): """The source code of the tool.""" in_layer = parameters[0].valueAsText out_layer = parameters[1].valueAsText geometries_list = arcpy.CopyFeatures_management(in_layer, arcpy.Geometry()) result_geometry = [polygon.extent.polygon for polygon in geometries_list] return arcpy.SpatialJoin_analysis(result_geometry, in_layer, out_layer)
def buffer_poligno(poligono, distance): if not poligono: return None if distance == 0: return poligono buf = arcpy.Buffer_analysis(poligono, arcpy.Geometry(), buffer_distance_or_field="{0} Meters".format(distance), line_side="FULL", line_end_type="ROUND", dissolve_option="ALL", dissolve_field="", method="PLANAR") return buf[0] if len(buf) > 0 else None
def dissolve_poligonos(lista_poligonos): if not lista_poligonos: return None lista = filter(lambda item: item, lista_poligonos) if len(lista) == 0: return None if len(lista) == 1: return lista[0] dissolved = arcpy.Dissolve_management(lista, arcpy.Geometry()) return dissolved[0] if len(dissolved) > 0 else None
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 create_aoi_mask_layer(aoi_features, output_feature_class, style_layer=None): """Create a visibility mask to focus on an Area of Interest in a map.""" assert has_arcpy, 'ArcPy is required (environment with arcpy referencing ArcGIS Pro functionality) to create an AOI mask.' # get a describe object to work with desc = arcpy.Describe(aoi_features) # ensure aoi is polygon assert desc.shapeType == 'Polygon', 'The area of interest must be a polygon.' # if multiple polygons, dissolve into one if int(arcpy.management.GetCount(aoi_features)[0]) > 1: aoi_features = arcpy.analysis.PairwiseDissolve(aoi_features, arcpy.Geometry()) # simplify the geometry for rendering efficiency later tol_val = (desc.extent.width + desc.extent.height) / 2 * 0.0001 smpl_feat = arcpy.cartography.SimplifyPolygon(aoi_features, out_feature_class=arcpy.Geometry(), algorithm='POINT_REMOVE', tolerance=tol_val, collapsed_point_option='NO_KEEP').split(';')[0] # create polygon covering the entire globe to cut out from coord_lst = [[-180.0, -90.0], [-180.0, 90.0], [180.0, 90.0], [180.0, -90.0], [-180.0, -90.0]] coord_arr = arcpy.Array((arcpy.Point(x, y) for x, y in coord_lst)) mask_geom = [arcpy.Polygon(coord_arr, arcpy.SpatialReference(4326))] # erase the simplified area of interest from the global extent polygon mask_fc = arcpy.analysis.Erase(mask_geom, smpl_feat, output_feature_class) # get the style layer if one is not provided styl_lyr = Paths.dir_arcgis_lyrs / 'aoi_mask.lyrx' if style_layer is None else style_layer # create a layer and make it pretty strt_lyr = arcpy.management.MakeFeatureLayer(mask_fc)[0] styl_lyr = str(styl_lyr) if isinstance(styl_lyr, Path) else styl_lyr lyr = arcpy.management.ApplySymbologyFromLayer(strt_lyr, styl_lyr)[0] return lyr
def execute(self, parameters, messages): """The source code of the tool.""" in_layer = parameters[0].valueAsText out_layer = parameters[1].valueAsText tolerance = float(parameters[2].valueAsText) # Using the "arcpy.Geometry" object's generalize method, # which simplify the geometry by a distance tolerance between vertices in_geometries = arcpy.CopyFeatures_management(in_layer, arcpy.Geometry()) result_geometry = [ feature.generalize(tolerance) for feature in in_geometries ] return arcpy.CopyFeatures_management(result_geometry, out_layer)
def execute(self, parameters, messages): """The source code of the tool.""" in_layer = parameters[0].valueAsText symmetric_layer = parameters[1].valueAsText output_layer = parameters[2].valueAsText # Dissolve input and symmetric layers to two single polygons, to # avoid collisions between input polygons' symmetric differences in_geometry = arcpy.Dissolve_management(in_layer, arcpy.Geometry())[0] symmetric_difference_geometry = arcpy.Dissolve_management( symmetric_layer, arcpy.Geometry())[0] # Perform symmetric difference between the two above geometries symmetric_difference_geometry = [ in_geometry.symmetricDifference(symmetric_difference_geometry) ] # Break apart the symmetric difference to separated polygons symmetric_difference_geometry = arcpy.Dissolve_management( symmetric_difference_geometry, arcpy.Geometry(), multi_part="SINGLE_PART") # Retrieve the polygons data from input layer return arcpy.SpatialJoin_analysis(symmetric_difference_geometry, in_layer, output_layer)
def findbiggestgeometry(houses_around): find_flag = 0 max_square = 0 max_geometry = arcpy.Geometry() for geometry in houses_around: square = geometry.area if square >= max_square: max_square = square max_geometry = geometry find_flag = 1 return max_geometry, find_flag
def checkGeometry(polygon, point, tableField="Name"): """ polygon has to be either a layer object or a shp file / gdb feature file without a Raster-field. point has to be a either a layer object or a shp/gdb feature file. NOTE: Only the last row will be taken into consideration. Returns: A str-list of polygons which contain the point. """ try: #result=[] string = "" print type(string) polygonGeometries = arcpy.CopyFeatures_management( polygon, arcpy.Geometry()) try: pointGeometry = arcpy.CopyFeatures_management( point, arcpy.Geometry())[-1] except: arcpy.AddWarning("Die Point-Datei ist leer!") print("Die Point-Datei ist leer!") polygonNames = [ row[0] for row in arcpy.da.SearchCursor(polygon, (tableField)) ] for index, polygonGeometry in enumerate(polygonGeometries): if polygonGeometry.contains(pointGeometry): print "Die Geometrie enthaelt:" + polygonNames[index] #result.append(polygonNames[index]) string += polygonNames[index] + "\n" return string except: arcpy.AddMessage( "Fehler in Funktion checkGeometry (checkGeometry -> point2map-library)." ) print( "Fehler in Funktion checkGeometry (checkGeometry -> point2map-library)." ) string = "Kartengrundlage: Keine Karte gefunden!" return string
def changeStartingVertex(fcInputPoints, fcInputPolygons): ## Create Geometry Object for Processing input points. g = arcpy.Geometry() geomPoints = arcpy.CopyFeatures_management(fcInputPoints, g) listPointCoords = [] for point in geomPoints: listPointCoords.append([point.centroid.X, point.centroid.Y]) #arcpy.AddMessage(str(point.centroid.X) + ","+ str(point.centroid.Y)) with arcpy.da.UpdateCursor(fcInputPolygons, ["OID@", "SHAPE@"]) as ucPolygons: for featPolygon in ucPolygons: vertexList = [] #arcpy.AddMessage("Feature: " + str(featPolygon[0])) i = 0 iStart = 0 for polygonVertex in featPolygon[1].getPart(0): # shape,firstpart if polygonVertex: #arcpy.AddMessage(' Vertex:' + str(i)) vertexList.append([polygonVertex.X, polygonVertex.Y]) if [polygonVertex.X, polygonVertex.Y] in listPointCoords: #arcpy.AddMessage(" Point-Vertex Match!") iStart = i else: pass #arcpy.AddMessage(" No Match") i = i + 1 if iStart == 0: newVertexList = vertexList #arcpy.AddMessage("No Change for: " + str(featPolygon[0])) else: #arcpy.AddMessage("Changing Vertex List for: " + str(featPolygon[0])) newVertexList = vertexList[iStart:i] + vertexList[0:iStart] for v in newVertexList: arcpy.AddMessage(str(v[0]) + "," + str(v[1])) #listVertexPointObjects = [] newShapeArray = arcpy.Array() for newVertex in newVertexList: #arcpy.AddMessage("Changing Vertex: " + str(newVertex[0]) + ',' + str(newVertex[1])) newShapeArray.add(arcpy.Point(newVertex[0], newVertex[1])) #listVertexPointObjects.append(arcpy.Point(newVertex[0],newVertex[1])) #newShapeArray = arcpy.Array(listVertexPointObjects) newPolygonArray = arcpy.Polygon(newShapeArray) ucPolygons.updateRow([featPolygon[0], newPolygonArray]) return
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 find_nearest_distance(self, row, col, layer): point = self.get_geo_point_from_raster(row, col) if layer not in self.feature_class_dict: # so the whole layer does not have to be loaded at a time self.feature_class_dict[layer] = arcpy.CopyFeatures_management( layer, arcpy.Geometry()) geometries = self.feature_class_dict[layer] closeted = None for geometry in geometries: possible_closest = geometry.distanceTo(point) if closeted is None: closeted = possible_closest elif possible_closest < closeted: closeted = possible_closest return closeted
def execute(self, parameters, messages): """The source code of the tool.""" in_layer = parameters[0].valueAsText out_layer = parameters[1].valueAsText tolerance = float(parameters[2].valueAsText) in_geometries = arcpy.CopyFeatures_management(in_layer, arcpy.Geometry()) out_geometries = [] for polygon in in_geometries: # Get all features in tolerance distance from current iterated polygon polygons_in_range = [ feature for feature in in_geometries if polygon.distanceTo(feature) <= tolerance ] # Union said features with a dissolve, in case that the features does not overlap union_polygon = arcpy.Dissolve_management(polygons_in_range, arcpy.Geometry()) # Convex hull aggregates the features together convex_polygon = union_polygon[0].convexHull() out_geometries.append(convex_polygon) arcpy.Dissolve_management(out_geometries, out_layer, multi_part="SINGLE_PART")
def createCropBoxTopo(infeature, orderNumber, scale=24000): """creates a polygon based off of the order layer with presets for topo. scale is parameter to make it more usable for other shit.""" # grab the centroid from the order table # note that this is flawed because we can have orders that have many rows # makes me think that we should do a dissolve on order number or something centroid = arcpy.Select_analysis( infeature, arcpy.Geometry(), """ "Orders"= '{}' """.format(orderNumber))[0].centroid # flip the f*****g point because of f*****g arc centroid = (centroid.Y, centroid.X) # create a MapDocument class mapDoc = MapDocument(scale=scale, centroid=centroid) # which allows us to create a polygon poly = mapDoc.createArcPolygon() return poly
def createGeometry(pntCoords, geometry_type): geometry = arcpy.Geometry() spatialRef = arcpy.SpatialReference(4326) if geometry_type.lower() == 'point': geometry = arcpy.Multipoint( arcpy.Array([arcpy.Point(*coords) for coords in pntCoords]), spatialRef) elif geometry_type.lower() == 'polyline': geometry = arcpy.Polyline( arcpy.Array([arcpy.Point(*coords) for coords in pntCoords]), spatialRef) elif geometry_type.lower() == 'polygon': geometry = arcpy.Polygon( arcpy.Array([arcpy.Point(*coords) for coords in pntCoords]), spatialRef) return geometry
def execute(self, parameters, messages): """The source code of the tool.""" in_layer = parameters[0].valueAsText out_layer = parameters[1].valueAsText geometries_list = arcpy.CopyFeatures_management( in_layer, arcpy.Geometry()) points = [] for geometry in geometries_list: parts = geometry.getPart() for part in parts: points += [ arcpy.PointGeometry(part.getObject(i)) for i in range(len(part)) ] return arcpy.SpatialJoin_analysis(points, in_layer, out_layer)
def sobreposicao_camadas(camada1, camada2, dissolve=True, keep_atributes=False): log(id_imovel, 'Classificando tema {0}'.format(camada2)) if (not arcpy.Exists(camada2)): log(id_imovel, 'Tema {} nao encontrado na base de insumos'.format(camada2)) return None if keep_atributes: join_attributes = 'NO_FID' output = arcpy.CreateUniqueName('INTERSECT', '%scratchGDB%') else: join_attributes = 'ONLY_FID' output = arcpy.Geometry() intersect = arcpy.Intersect_analysis([camada1, camada2], output, output_type='INPUT', join_attributes=join_attributes) if not intersect: return None if not dissolve: return intersect return dissolve_poligonos(intersect)
def addAreaPerimeter(dbfPath, areaName, perimeterName): # This function adds fields to the specified dbf and calculates area and # perimeter for each row based on the shapfile accompanying the dbf # first make sure we have the fields we want try: arcpy.DeleteField_management(dbfPath, areaName) arcpy.DeleteField_management(dbfPath, perimeterName) except: print "one or more fields not found. Creating..." try: arcpy.AddField_management(dbfPath, areaName, "FLOAT", 6) arcpy.AddField_management(dbfPath, perimeterName, "FLOAT", 6) except: print "WARNING! was not able to add pp_area or pp_perimeter fields" # this is the geometries from the .shp that comes with the dbf geometries = arcpy.CopyFeatures_management(dbfPath[0:-3] + "shp", arcpy.Geometry()) # setup lists areas = [] perimeters = [] # fill lists with data from geometries for geometry in geometries: areas.append(geometry.getArea("GEODESIC")) perimeters.append(geometry.getLength("GEODESIC")) print "Area:", geometry.getArea( "GEODESIC"), "Length:", geometry.getLength("GEODESIC") # put the data from the geometries into the dbf in the new fields we just made i = 0 updateCursor = arcpy.da.UpdateCursor(dbfPath, (areaName, perimeterName)) for row in updateCursor: row[0] = areas[i] row[1] = perimeters[i] updateCursor.updateRow(row) i += 1 # clear references del row del updateCursor del geometries
def line_extend_within_polygon(boundary_polygon, lines_to_extend): """ This python function can extend the lines within a boundary polygon upto the border line. Here, boundary_polygon is the polygon shapefile and the lines_to_extend is the line shapefile which will be extended upto the border using the function. """ arcpy.PolygonToLine_management(in_features=boundary_polygon, out_feature_class="boundary_line", neighbor_option="IDENTIFY_NEIGHBORS") arcpy.RepairGeometry_management(in_features=lines_to_extend, delete_null="DELETE_NULL") coastline = "boundary_line" directions = lines_to_extend g = arcpy.Geometry() bank = arcpy.CopyFeatures_management(coastline, g)[0] for i in range(2): with arcpy.da.UpdateCursor(directions, "Shape@") as cursor: for row in cursor: line = row[0] pStart = line.firstPoint pEnd = line.lastPoint L = line.length dX = (pEnd.X - pStart.X) / L dY = (pEnd.Y - pStart.Y) / L p = pEnd m = 0 while True: l = bank.distanceTo(p) L += l p.X = pStart.X + dX * L p.Y = pStart.Y + dY * L m += 1 if m > 100: break if l < 0.001: break if m > 100: continue row[0] = arcpy.Polyline(arcpy.Array([pStart, p])) cursor.updateRow(row) if i == 0: arcpy.FlipLine_edit(in_features=directions) # deleting the boundary_line layer arcpy.Delete_management(coastline) return