Class: QgsGeos¶
Does vector analysis using the GEOS library and handles import, export, and exception handling.
Note
Available in Python bindings since QGIS 3.42
Class Hierarchy¶
Base classes¶
A geometry engine is a low-level representation of a |
Abstract Methods
Returns |
|
Methods
Performs a fast, non-robust intersection between the geometry and a rectangle. |
|
Returns the closest point on the geometry to the other geometry. |
|
Returns a possibly concave geometry that encloses the input geometry. |
|
Returns a constrained Delaunay triangulation for the vertices of the geometry. |
|
Returns the Delaunay triangulation for the vertices of the geometry. |
|
Returns the Fréchet distance between this geometry and another geometry, restricted to discrete points for both geometries. |
|
Returns the Fréchet distance between this geometry and another geometry, restricted to discrete points for both geometries. |
|
Returns the Hausdorff distance between this geometry and another geometry. |
|
Returns the Hausdorff distance between this geometry and another geometry. |
|
Constructs the Largest Empty Circle for a set of obstacle geometries, up to a specified tolerance. |
|
Returns a distance representing the location along this linestring of the closest point on this linestring geometry to the specified point. |
|
Repairs the geometry using GEOS make valid routine. |
|
Returns the maximum inscribed circle. |
|
Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line strings. |
|
Computes the minimum clearance of a geometry. |
|
Returns a LineString whose endpoints define the minimum clearance of a geometry. |
|
Returns a linestring geometry which represents the minimum diameter of the geometry. |
|
Returns a (Multi)LineString representing the fully noded version of a collection of linestrings. |
|
Find paths shared between the two given lineal geometries (this and other). |
|
Returns the shortest line joining this geometry to the other geometry. |
|
Operates on a coverage (represented as a list of polygonal geometry with exactly matching edge geometry) to apply a Visvalingam–Whyatt simplification to the edges, reducing complexity in proportion with the provided tolerance, while retaining a valid coverage (no edges will cross or touch after the simplification). |
|
Returns a single sided buffer for a geometry. |
|
Subdivides the geometry. |
|
Optimized union algorithm for polygonal inputs that are correctly noded and do not overlap. |
|
Creates a Voronoi diagram for the nodes contained within the geometry. |
- class qgis.core.QgsGeos[source]¶
Bases:
QgsGeometryEngine
- __init__(geometry: QgsAbstractGeometry | None, precision: float = 0, flags: Qgis.GeosCreationFlags | Qgis.GeosCreationFlag = Qgis.GeosCreationFlag.SkipEmptyInteriorRings)
GEOS geometry engine constructor
- Parameters:
geometry (Optional[QgsAbstractGeometry]) – The geometry
precision (float = 0) – The precision of the grid to which to snap the geometry vertices. If 0, no snapping is performed.
flags (Union[Qgis.GeosCreationFlags, Qgis.GeosCreationFlag] = Qgis.GeosCreationFlag.SkipEmptyInteriorRings) – GEOS creation flags (since QGIS 3.40)
Note
The third parameter was prior to QGIS 3.40 a boolean which has been incorporated into the flag
- clip(self, rectangle: QgsRectangle)¶
Performs a fast, non-robust intersection between the geometry and a
rectangle
. The returned geometry may be invalid.- Parameters:
rectangle (
QgsRectangle
) -> (Optional[QgsAbstractGeometry]) – clipping rectangle- Returns:
clipped geometry
errorMsg: descriptive error string if the operation fails
- closestPoint(self, other: QgsGeometry)¶
Returns the closest point on the geometry to the other geometry.
- Parameters:
other (
QgsGeometry
) -> (Optional[QgsAbstractGeometry]) – geometry to compare against- Returns:
closest point
errorMsg: descriptive error string if the operation fails
See also
- concaveHull(self, targetPercent: float, allowHoles: bool = False)¶
Returns a possibly concave geometry that encloses the input geometry.
The result is a single polygon, line or point.
It will not contain holes unless the optional
allowHoles
argument is specified as true.One can think of a concave hull as a geometry obtained by “shrink-wrapping” a set of geometries. This is different to the convex hull, which is more like wrapping a rubber band around the geometries. It is slower to compute than the convex hull but generally has a smaller area and represents a more natural boundary for the input geometry. The
target_percent
is the percentage of area of the convex hull the solution tries to approach.A
target_percent
of 1 gives the same result as the convex hull. Atarget_percent
between 0 and 0.99 produces a result that should have a smaller area than the convex hull.This method requires a QGIS build based on GEOS 3.11 or later.
- Parameters:
targetPercent (float)
allowHoles (bool = False) -> (Optional[QgsAbstractGeometry])
- Returns:
concave geometry that encloses the input geometry
errorMsg: descriptive error string if the operation fails
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.10 or earlier.
See also
convexHull()
Added in version 3.28.
- constrainedDelaunayTriangulation(self)¶
Returns a constrained Delaunay triangulation for the vertices of the geometry.
An empty geometry will be returned if the triangulation could not be calculated.
This method requires a QGIS build based on GEOS 3.11 or later.
- Returns:
constrained Delaunay triangulation
errorMsg: descriptive error string if the operation fails
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.10 or earlier.
See also
Added in version 3.36.
- abstract contains(self, x: float, y: float)[source]¶
Returns
True
if the geometry contains the point at (x
,y
).This method is more efficient than creating a temporary
QgsPoint
object to test for containment.- Parameters:
x (float) – x-coordinate of point to test
y (float) -> (bool) – y-coordinate of point to test
- Returns:
True
if the geometry contains the pointerrorMsg: descriptive error string if the operation fails
Added in version 3.26.
- abstract contains(self, geom: QgsAbstractGeometry | None, errorMsg: str | None | None = '') bool [source]
- Parameters:
geom (Optional[QgsAbstractGeometry])
errorMsg (Optional[Optional[str]] = '')
- Return type:
bool
- delaunayTriangulation(self, tolerance: float = 0, edgesOnly: bool = False)¶
Returns the Delaunay triangulation for the vertices of the geometry. The
tolerance
parameter specifies an optional snapping tolerance which can be used to improve the robustness of the triangulation. IfedgesOnly
isTrue
than line string boundary geometries will be returned instead of polygons. An empty geometry will be returned if the diagram could not be calculated.- Parameters:
tolerance (float = 0)
edgesOnly (bool = False) -> (Optional[QgsAbstractGeometry])
- Returns:
Delaunay triangulation
errorMsg: descriptive error string if the operation fails
See also
- abstract distance(self, geom: QgsAbstractGeometry | None, errorMsg: str | None | None = '') float [source]¶
- Parameters:
geom (Optional[QgsAbstractGeometry])
errorMsg (Optional[Optional[str]] = '')
- Return type:
float
- abstract distance(self, x: float, y: float)[source]
Returns the minimum distance from the geometry to the point at (
x
,y
).This method is more efficient than creating a temporary
QgsPoint
object to test distance.- Parameters:
x (float) – x-coordinate of point to test
y (float) -> (float) – y-coordinate of point to test
- Returns:
minimum distance
errorMsg: descriptive error string if the operation fails
Added in version 3.26.
- frechetDistance(self, geometry: QgsAbstractGeometry | None)[source]¶
Returns the Fréchet distance between this geometry and another
geometry
, restricted to discrete points for both geometries.The Fréchet distance is a measure of similarity between curves that takes into account the location and ordering of the points along the curves. Therefore it is often better than the Hausdorff distance.
This method requires a QGIS build based on GEOS 3.7 or later.
- Parameters:
geometry (Optional[QgsAbstractGeometry]) -> (float) – geometry to compare to
- Returns:
calculated Fréchet distance
errorMsg: descriptive error string if the operation fails
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.6 or earlier.
See also
Added in version 3.20.
- frechetDistanceDensify(self, geometry: QgsAbstractGeometry | None, densifyFraction: float)[source]¶
Returns the Fréchet distance between this geometry and another
geometry
, restricted to discrete points for both geometries.The Fréchet distance is a measure of similarity between curves that takes into account the location and ordering of the points along the curves. Therefore it is often better than the Hausdorff distance.
This function accepts a
densifyFraction
argument. The function performs a segment densification before computing the discrete Fréchet distance. ThedensifyFraction
parameter sets the fraction by which to densify each segment. Each segment will be split into a number of equal-length subsegments, whose fraction of the total length is closest to the given fraction.This method can be used when the default approximation provided by
frechetDistance()
is not sufficient. Decreasing thedensifyFraction
parameter will make the distance returned approach the true Fréchet distance for the geometries.This method requires a QGIS build based on GEOS 3.7 or later.
- Parameters:
geometry (Optional[QgsAbstractGeometry]) – geometry to compare to
densifyFraction (float) -> (float) – fraction by which to densify each segment
- Returns:
calculated densified Fréchet distance
errorMsg: descriptive error string if the operation fails
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.6 or earlier.
See also
Added in version 3.20.
- hausdorffDistance(self, geometry: QgsAbstractGeometry | None)[source]¶
Returns the Hausdorff distance between this geometry and another
geometry
. This is basically a measure of how similar or dissimilar 2 geometries are.This algorithm is an approximation to the standard Hausdorff distance. This approximation is exact or close enough for a large subset of useful cases. Examples of these are:
computing distance between Linestrings that are roughly parallel to each other, and roughly equal in length. This occurs in matching linear networks.
Testing similarity of geometries.
If the default approximate provided by this method is insufficient, use
hausdorffDistanceDensify()
instead.- Parameters:
geometry (Optional[QgsAbstractGeometry]) -> (float) – geometry to compare to
- Returns:
calculated Hausdorff distance
errorMsg: descriptive error string if the operation fails
See also
- hausdorffDistanceDensify(self, geometry: QgsAbstractGeometry | None, densifyFraction: float)[source]¶
Returns the Hausdorff distance between this geometry and another
geometry
. This is basically a measure of how similar or dissimilar 2 geometries are.This function accepts a
densifyFraction
argument. The function performs a segment densification before computing the discrete Hausdorff distance. ThedensifyFraction
parameter sets the fraction by which to densify each segment. Each segment will be split into a number of equal-length subsegments, whose fraction of the total length is closest to the given fraction.This method can be used when the default approximation provided by
hausdorffDistance()
is not sufficient. Decreasing thedensifyFraction
parameter will make the distance returned approach the true Hausdorff distance for the geometries.- Parameters:
geometry (Optional[QgsAbstractGeometry]) – geometry to compare to
densifyFraction (float) -> (float) – fraction by which to densify each segment
- Returns:
calculated densified Hausdorff distance
errorMsg: descriptive error string if the operation fails
See also
- largestEmptyCircle(self, tolerance: float, boundary: QgsAbstractGeometry | None = None)¶
Constructs the Largest Empty Circle for a set of obstacle geometries, up to a specified tolerance.
The Largest Empty Circle is the largest circle which has its center in the convex hull of the obstacles (the boundary), and whose interior does not intersect with any obstacle. The circle center is the point in the interior of the boundary which has the farthest distance from the obstacles (up to tolerance). The circle is determined by the center point and a point lying on an obstacle indicating the circle radius. The implementation uses a successive-approximation technique over a grid of square cells covering the obstacles and boundary. The grid is refined using a branch-and-bound algorithm. Point containment and distance are computed in a performant way by using spatial indexes. Returns a two-point linestring, with one point at the center of the inscribed circle and the other on the boundary of the inscribed circle.
This method requires a QGIS build based on GEOS 3.9 or later.
- Parameters:
tolerance (float) – tolerance to determine when iteration should end
boundary (Optional[QgsAbstractGeometry] = None) -> (Optional[QgsAbstractGeometry]) – optional set of boundary obstacles
- Returns:
largest empty circle geometry
errorMsg: descriptive error string if the operation fails
Warning
the
tolerance
value must be a value greater than 0, or the algorithm may never converge on a solution- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.8 or earlier.
Added in version 3.20.
- lineLocatePoint(self, point: QgsPoint)[source]¶
Returns a distance representing the location along this linestring of the closest point on this linestring geometry to the specified point. Ie, the returned value indicates how far along this linestring you need to traverse to get to the closest location where this linestring comes to the specified point.
- Parameters:
point (
QgsPoint
) -> (float) – point to seek proximity to- Returns:
distance along line, or -1 on error
errorMsg: descriptive error string if the operation fails
Note
only valid for linestring geometries
- lineLocatePoint(self, x: float, y: float)[source]
Returns a distance representing the location along this linestring of the closest point on this linestring geometry to the point at (
x
,y
). Ie, the returned value indicates how far along this linestring you need to traverse to get to the closest location where this linestring comes to the specified point.This method is more efficient than creating a temporary
QgsPoint
object to locate.- Parameters:
x (float) – x-coordinate of point to locate
y (float) -> (float) – y-coordinate of point to locate
- Returns:
distance along line, or -1 on error
errorMsg: descriptive error string if the operation fails
Note
only valid for linestring geometries
Added in version 3.26.
- makeValid(self, method: Qgis.MakeValidMethod = Qgis.MakeValidMethod.Linework, keepCollapsed: bool = False, errorMsg: str | None | None = '') QgsAbstractGeometry | None ¶
Repairs the geometry using GEOS make valid routine.
The
method
andkeepCollapsed
arguments require builds based on GEOS 3.10 or later.- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.9 or earlier when the
method
is not Qgis.MakeValidMethod.Linework or thekeepCollapsed
option is set.
Added in version 3.20.
- Parameters:
method (Qgis.MakeValidMethod = Qgis.MakeValidMethod.Linework)
keepCollapsed (bool = False)
errorMsg (Optional[Optional[str]] = '')
- Return type:
Optional[QgsAbstractGeometry]
- maximumInscribedCircle(self, tolerance: float)¶
Returns the maximum inscribed circle.
Constructs the Maximum Inscribed Circle for a polygonal geometry, up to a specified tolerance. The Maximum Inscribed Circle is determined by a point in the interior of the area which has the farthest distance from the area boundary, along with a boundary point at that distance. In the context of geography the center of the Maximum Inscribed Circle is known as the Pole of Inaccessibility. A cartographic use case is to determine a suitable point to place a map label within a polygon. The radius length of the Maximum Inscribed Circle is a measure of how “narrow” a polygon is. It is the distance at which the negative buffer becomes empty. The class supports polygons with holes and multipolygons. The implementation uses a successive-approximation technique over a grid of square cells covering the area geometry. The grid is refined using a branch-and-bound algorithm. Point containment and distance are computed in a performant way by using spatial indexes. Returns a two-point linestring, with one point at the center of the inscribed circle and the other on the boundary of the inscribed circle.
This method requires a QGIS build based on GEOS 3.9 or later.
- Parameters:
tolerance (float) -> (Optional[QgsAbstractGeometry]) – tolerance to determine when iteration should end
- Returns:
maximum inscribed circle geometry
errorMsg: descriptive error string if the operation fails
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.8 or earlier.
Added in version 3.20.
- mergeLines(self, parameters: QgsGeometryParameters = QgsGeometryParameters())¶
Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line strings.
- Returns:
a LineString or MultiLineString geometry, with any connected lines joined. An empty geometry will be returned if the input geometry was not a LineString/MultiLineString geometry.
errorMsg: descriptive error string if the operation fails
- minimumClearance(self)[source]¶
Computes the minimum clearance of a geometry.
The minimum clearance is the smallest amount by which a vertex could be moved to produce an invalid polygon, a non-simple linestring, or a multipoint with repeated points. If a geometry has a minimum clearance of ‘eps’, it can be said that:
No two distinct vertices in the geometry are separated by less than ‘eps’
No vertex is closer than ‘eps’ to a line segment of which it is not an endpoint.
If the minimum clearance cannot be defined for a geometry (such as with a single point, or a multipoint whose points are identical) a value of infinity will be returned.
If an error occurs while calculating the clearance NaN will be returned.
This method requires a QGIS build based on GEOS 3.6 or later.
- Returns:
calculated minimum clearance of the geometry
errorMsg: descriptive error string if the operation fails
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.5 or earlier.
Added in version 3.20.
- minimumClearanceLine(self)¶
Returns a LineString whose endpoints define the minimum clearance of a geometry.
If the geometry has no minimum clearance, an empty LineString will be returned.
This method requires a QGIS build based on GEOS 3.6 or later.
- Returns:
linestring geometry representing the minimum clearance of the geometry
errorMsg: descriptive error string if the operation fails
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.5 or earlier.
Added in version 3.20.
- minimumWidth(self)¶
Returns a linestring geometry which represents the minimum diameter of the geometry.
The minimum diameter is defined to be the width of the smallest band that contains the geometry, where a band is a strip of the plane defined by two parallel lines. This can be thought of as the smallest hole that the geometry can be moved through, with a single rotation.
This method requires a QGIS build based on GEOS 3.6 or later.
- Returns:
linestring representing the minimum diameter of the geometry
errorMsg: descriptive error string if the operation fails
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.5 or earlier.
Added in version 3.20.
- node(self)¶
Returns a (Multi)LineString representing the fully noded version of a collection of linestrings.
The noding preserves all of the input nodes, and introduces the least possible number of new nodes. The resulting linework is dissolved (duplicate lines are removed).
The input geometry type should be a (Multi)LineString.
- Returns:
(multi)linestring geometry representing the fully noded version of the collection of linestrings
errorMsg: descriptive error string if the operation fails
Added in version 3.20.
Find paths shared between the two given lineal geometries (this and
other
).Returns a GeometryCollection having two elements:
first element is a MultiLineString containing shared paths having the same direction on both inputs
second element is a MultiLineString containing shared paths having the opposite direction on the two inputs
- Parameters:
other (Optional[QgsAbstractGeometry]) -> (Optional[QgsAbstractGeometry]) – geometry to compare against
- Returns:
shared paths, or
None
on exceptionerrorMsg: descriptive error string if the operation fails
Added in version 3.20.
- shortestLine(self, other: QgsGeometry)¶
Returns the shortest line joining this geometry to the other geometry.
- Parameters:
other (
QgsGeometry
) -> (Optional[QgsAbstractGeometry]) – geometry to compare against- Returns:
shortest line joining this geometry to the other geometry
errorMsg: descriptive error string if the operation fails
See also
- shortestLine(self, other: QgsAbstractGeometry | None)
Returns the shortest line joining this geometry to the other geometry.
- Parameters:
other (Optional[QgsAbstractGeometry]) -> (Optional[QgsAbstractGeometry]) – geometry to compare against
- Returns:
shortest line joining this geometry to the other geometry
errorMsg: descriptive error string if the operation fails
See also
Added in version 3.20.
- simplifyCoverageVW(self, tolerance: float, preserveBoundary: bool)¶
Operates on a coverage (represented as a list of polygonal geometry with exactly matching edge geometry) to apply a Visvalingam–Whyatt simplification to the edges, reducing complexity in proportion with the provided tolerance, while retaining a valid coverage (no edges will cross or touch after the simplification).
Geometries never disappear, but they may be simplified down to just a triangle. Also, some invalid geoms (such as Polygons which have too few non-repeated points) will be returned unchanged.
If the input dataset is not a valid coverage due to overlaps, it will still be simplified, but invalid topology such as crossing edges will still be invalid.
- Parameters:
tolerance (float) – A tolerance parameter in linear units.
preserveBoundary (bool) -> (Optional[QgsAbstractGeometry]) – Set to
True
to preserve the outside edges of the coverage without simplification, orFalse
to allow them to be simplified.
- Returns:
simplified coverage
errorMsg: descriptive error string if the operation fails
This method requires a QGIS build based on GEOS 3.12 or later.
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.11 or earlier.
See also
validateCoverage()
Added in version 3.36.
- singleSidedBuffer(self, distance: float, segments: int, side: Qgis.BufferSide, joinStyle: Qgis.JoinStyle, miterLimit: float)¶
Returns a single sided buffer for a geometry. The buffer is only applied to one side of the geometry.
- Parameters:
distance (float) – buffer distance
segments (int) – for round joins, number of segments to approximate quarter-circle
side (Qgis.BufferSide) – side of geometry to buffer (0 = left, 1 = right)
joinStyle (Qgis.JoinStyle) – join style for corners ( Round (1) / Miter (2) / Bevel (3) )
miterLimit (float) -> (Optional[QgsAbstractGeometry]) – limit on the miter ratio used for very sharp corners
- Returns:
buffered geometry, or
None
if buffer could not be calculatederrorMsg: descriptive error string if the operation fails
- subdivide(self, maxNodes: int, parameters: QgsGeometryParameters = QgsGeometryParameters())¶
Subdivides the geometry. The returned geometry will be a collection containing subdivided parts from the original geometry, where no part has more then the specified maximum number of nodes (
maxNodes
).This is useful for dividing a complex geometry into less complex parts, which are better able to be spatially indexed and faster to perform further operations such as intersects on. The returned geometry parts may not be valid and may contain self-intersections.
The minimum allowed value for
maxNodes
is 8.Curved geometries are not supported.
- Parameters:
maxNodes (int) – Maximum nodes used
parameters (
QgsGeometryParameters
= QgsGeometryParameters()) -> (Optional[QgsAbstractGeometry]) – can be used to specify parameters which control the subdivision results (since QGIS 3.28)
- Returns:
subdivided geometry
errorMsg: descriptive error string if the operation fails
- unionCoverage(self)¶
Optimized union algorithm for polygonal inputs that are correctly noded and do not overlap. It may generate an error (returns
None
) for inputs that do not satisfy this constraint, however this is not guaranteed.The input geometry is the polygonal coverage to union, stored in a geometry collection. All members must be POLYGON or MULTIPOLYGON.
- Returns:
unioned coverage
errorMsg: descriptive error string if the operation fails
See also
validateCoverage()
Added in version 3.36.
- voronoiDiagram(self, extent: QgsAbstractGeometry | None = None, tolerance: float = 0, edgesOnly: bool = False)¶
Creates a Voronoi diagram for the nodes contained within the geometry.
Returns the Voronoi polygons for the nodes contained within the geometry. If
extent
is specified then it will be used as a clipping envelope for the diagram. If no extent is set then the clipping envelope will be automatically calculated. In either case the diagram will be clipped to the larger of the provided envelope OR the envelope surrounding all input nodes. Thetolerance
parameter specifies an optional snapping tolerance which can be used to improve the robustness of the diagram calculation. IfedgesOnly
isTrue
than line string boundary geometries will be returned instead of polygons. An empty geometry will be returned if the diagram could not be calculated.- Parameters:
extent (Optional[QgsAbstractGeometry] = None) – optional clipping envelope for the diagram
tolerance (float = 0)
edgesOnly (bool = False) -> (Optional[QgsAbstractGeometry])
- Returns:
Voronoi diagram
errorMsg: descriptive error string if the operation fails