Skip to content

set_geom_precision

Set the precision of a Shapely geometry.

Note

Typically six decimals is sufficient for most applications.

Parameters:

Name Type Description Default
geom BaseGeometry

Input Shapely geometry.

required
precision int

The number of decimal places to round the coordinates to.

6

Returns:

Name Type Description
BaseGeometry BaseGeometry

The input geometry with coordinates rounded to the specified precision.

Examples:

>>> from histolytics.utils.gdf import gdf_apply, set_geom_precision
>>> from histolytics.data import hgsc_cancer_nuclei
>>> from functools import partial
>>> # Set precision to 3 decimal places
>>> prec = partial(set_geom_precision, precision=3)
>>> gdf = hgsc_cancer_nuclei()
>>> gdf = gdf_apply(gdf, prec, columns=["geometry"])
>>> print(gdf.head(3))
    0    POLYGON ((1394.01 0, 1395.01 1.99, 1398 3.99, ...
    1    POLYGON ((1391 2.01, 1387 2.01, 1384.01 3.01, ...
    2    POLYGON ((1382.99 156.01, 1380 156.01, 1376.01...
    dtype: geometry
Source code in src/histolytics/utils/gdf.py
def set_geom_precision(geom: BaseGeometry, precision: int = 6) -> BaseGeometry:
    """Set the precision of a Shapely geometry.

    Note:
        Typically six decimals is sufficient for most applications.

    Parameters:
        geom (BaseGeometry):
            Input Shapely geometry.
        precision (int):
            The number of decimal places to round the coordinates to.

    Returns:
        BaseGeometry:
            The input geometry with coordinates rounded to the specified precision.

    Examples:
        >>> from histolytics.utils.gdf import gdf_apply, set_geom_precision
        >>> from histolytics.data import hgsc_cancer_nuclei
        >>> from functools import partial
        >>> # Set precision to 3 decimal places
        >>> prec = partial(set_geom_precision, precision=3)
        >>> gdf = hgsc_cancer_nuclei()
        >>> gdf = gdf_apply(gdf, prec, columns=["geometry"])
        >>> print(gdf.head(3))
            0    POLYGON ((1394.01 0, 1395.01 1.99, 1398 3.99, ...
            1    POLYGON ((1391 2.01, 1387 2.01, 1384.01 3.01, ...
            2    POLYGON ((1382.99 156.01, 1380 156.01, 1376.01...
            dtype: geometry
    """
    wkt_str = dumps(geom, rounding_precision=precision)
    return wkt.loads(wkt_str)