Make grids from bounds

class Gridlooper(gridsize, mask, gridbuffer=0, parallelizer=None, concat=False, clip=True, keep_geom_type=True, verbose=False)[source]

Bases: object

Run functions in a loop cellwise based on a grid.

Parameters:
  • gridsize (int) – Size of the grid cells in units of the crs (meters, degrees).

  • mask (GeoDataFrame | GeoSeries | Geometry) – Geometry object to create a grid around.

  • gridbuffer (int) – Units to buffer each gridcell by. For edge cases. Defaults to 0.

  • clip (bool) – If True (default) geometries are clipped by the grid cells. If False, all geometries that intersect will be selected in each iteration.

  • verbose (bool) – Whether to print progress. Defaults to False.

  • keep_geom_type (bool) – Whether to keep only the input geometry types after clipping. Defaults to True.

  • concat (bool) – Whether to use pd.concat on the results after each ‘run’ call.

  • parallelizer (Parallel | None)

Examples:

Get some points and some polygons.

>>> import sgis as sg
>>> points = sg.read_parquet_url("https://media.githubusercontent.com/media/statisticsnorway/ssb-sgis/main/tests/testdata/points_oslo.parquet")
>>> points["idx"] = points.index
>>> buffered = sg.buff(points, 100)
>>> print(buffered.to_string(max_rows=10, max_colwidth=50, show_dimensions=True))
     idx                                           geometry
0      0  POLYGON ((263222.7 6651184.9, 263222.563 66511...
1      1  POLYGON ((272556.1 6653369.5, 272555.963 66533...
2      2  POLYGON ((270182.3 6653032.7, 270182.163 66530...
3      3  POLYGON ((259904.8 6650339.7, 259904.663 66503...
4      4  POLYGON ((272976.2 6652889.1, 272976.063 66528...
..   ...                                                ...
995  995  POLYGON ((266901.7 6647844.5, 266901.563 66478...
996  996  POLYGON ((261374 6653593.4, 261373.863 6653588...
997  997  POLYGON ((263642.9 6645427, 263642.763 6645421...
998  998  POLYGON ((269326.7 6650628, 269326.563 6650622...
999  999  POLYGON ((264670.3 6644239.5, 264670.163 66442...

[1000 rows x 2 columns]

Instantiate a gridlooper.

>>> looper = sg.Gridlooper(gridsize=200, mask=buffered, concat=True, parallelizer=sg.Parallel(1, backend="multiprocessing"))

Run the function clean_overlay in a gridloop.

>>> results = looper.run(
...     sg.clean_overlay,
...     points,
...     buffered,
... )
>>> print(results.to_string(max_rows=10, max_colwidth=50, show_dimensions=True))
     idx_1 idx_2                    geometry
0      220   220  POINT (254575.2 6661631.5)
1      299   299  POINT (255727.9 6651036.8)
2      514   514  POINT (255862.1 6651178.8)
3      289   289  POINT (255812.8 6651631.4)
4      765   765  POINT (255929.7 6650851.1)
...    ...   ...                         ...
1481   425   802  POINT (273316.8 6653248.9)
1482   425   425  POINT (273316.8 6653248.9)
1483   757   757  POINT (273507.6 6652806.6)
1484   457   457  POINT (273524.4 6652979.9)
1485   284   284  POINT (273650.8 6653000.5)

[1486 rows x 3 columns]
run(func, *args, **kwargs)[source]

Run a function for each grid cell in a loop.

Returns a list of the return values from the function, or a (Geo)DataFrame if self.concat is True.

Return type:

Any | list[Any]

Parameters:

func (Callable)

add_grid_id(gdf, gridsize, out_column='ssb_rute_id')[source]

Adds an SSB grid ID column to a GeoDataFrame of points.

The GeoDataFrame must have 25833 as crs (UTM 33 N).

Parameters:
  • gdf (GeoDataFrame) – A GeoDataFrame.

  • gridsize (int) – Size of the grid in meters.

  • out_column (str) – Name of column for the grid id.

Return type:

GeoDataFrame

Returns:

The input GeoDataFrame with a new grid id column.

Raises:

ValueError – If the GeoDataFrame does not have 25833 as crs.

bounds_to_points(gdf, copy=True)[source]

Creates a 4-noded multipoint around the geometry in each row of a GeoDataFrame.

Parameters:
  • gdf (GeoDataFrame | GeoSeries) – The GeoDataFrame.

  • copy (bool) – Defaults to True.

Return type:

GeoDataFrame | GeoSeries

Returns:

GeoDataFrame of multipoints with same length and index as ‘gdf’.

Examples:

>>> import sgis as sg
>>> from shapely.geometry import MultiPoint, Point
>>> gdf = sg.to_gdf([MultiPoint([(0, 0), (1, 1)]), Point(0, 0)])
>>> gdf
                    geometry
0  MULTIPOINT ((0 0), (1 1))
1                POINT (0 0)
>>> sg.bounds_to_points(gdf)
                                  geometry
0  MULTIPOINT ((1 0), (1 1), (0 1), (0 0))
1                       MULTIPOINT ((0 0))
bounds_to_polygon(gdf, copy=True)[source]

Creates a box around the geometry in each row of a GeoDataFrame.

Parameters:
  • gdf (GeoDataFrame | GeoSeries) – The GeoDataFrame.

  • copy (bool) – Defaults to True.

Return type:

GeoDataFrame | GeoSeries

Returns:

GeoDataFrame of box polygons with length and index of ‘gdf’.

Examples:

>>> import sgis as sg
>>> from shapely.geometry import MultiPoint, Point
>>> gdf = sg.to_gdf([MultiPoint([(0, 0), (1, 1)]), Point(0, 0)])
>>> gdf
                    geometry
0  MULTIPOINT ((0 0), (1 1))
1                POINT (0 0)
>>> sg.bounds_to_polygon(gdf)
                              geometry
0  POLYGON ((1 0, 1 1, 0 1, 0 0, 1 0))
1  POLYGON ((0 0, 0 0, 0 0, 0 0, 0 0))
get_total_bounds(*geometries, strict=False)[source]

Get a combined total bounds of multiple geometry objects.

Return type:

tuple[float, float, float, float]

Parameters:
  • geometries (GeoDataFrame | GeoSeries | Geometry)

  • strict (bool)

gridloop(func, gridsize, mask, gridbuffer=0, clip=True, keep_geom_type=True, verbose=False, args=None, kwargs=None, parallelizer=None)[source]

Runs a function in a loop cellwise based on a grid.

Creates grid from a mask, and runs the function for each cell with all GeoDataFrame keyword arguments clipped to the cell extent.

Parameters:
  • func (Callable) – Function to run cellwise.

  • mask (GeoDataFrame | GeoSeries | Geometry) – Geometry object to create a grid around.

  • gridsize (int) – Size of the grid cells in units of the crs (meters, degrees).

  • gridbuffer (int) – Units to buffer each gridcell by. For edge cases. Defaults to 0.

  • clip (bool) – If True (default) geometries are clipped by the grid cells. If False, all geometries that intersect will be selected in each iteration.

  • verbose (bool) – Whether to print progress. Defaults to False.

  • keep_geom_type (bool) – Whether to keep only the input geometry types after clipping. Defaults to True.

  • args (tuple | None) – Positional arguments to pass to the function. Arguments of type GeoDataFrame or GeoSeries will be clipped by the grid cells in a loop.

  • kwargs (dict | None) – Keyword arguments to pass to the function. Arguments of type GeoDataFrame or GeoSeries will be clipped by the grid cells in a loop.

  • parallelizer (Parallel | None) – Optional instance of sgis.Parallel, to run the function in parallel.

Return type:

list[Any]

Returns:

List of results with the same length as number of grid cells.

Raises:

TypeError – If args or kwargs has a wrong type

Examples:

Get some points and some polygons.

>>> import sgis as sg
>>> points = sg.read_parquet_url("https://media.githubusercontent.com/media/statisticsnorway/ssb-sgis/main/tests/testdata/points_oslo.parquet")
>>> points["idx"] = points.index
>>> buffered = sg.buff(points, 100)
>>> print(buffered.to_string(max_rows=10, max_colwidth=50, show_dimensions=True))
     idx                                           geometry
0      0  POLYGON ((263222.7 6651184.9, 263222.563 66511...
1      1  POLYGON ((272556.1 6653369.5, 272555.963 66533...
2      2  POLYGON ((270182.3 6653032.7, 270182.163 66530...
3      3  POLYGON ((259904.8 6650339.7, 259904.663 66503...
4      4  POLYGON ((272976.2 6652889.1, 272976.063 66528...
..   ...                                                ...
995  995  POLYGON ((266901.7 6647844.5, 266901.563 66478...
996  996  POLYGON ((261374 6653593.4, 261373.863 6653588...
997  997  POLYGON ((263642.9 6645427, 263642.763 6645421...
998  998  POLYGON ((269326.7 6650628, 269326.563 6650622...
999  999  POLYGON ((264670.3 6644239.5, 264670.163 66442...

[1000 rows x 2 columns]

Run the function clean_overlay where the data is clipped to a grid of 1000x1000 meters. Args are the first two arguments of clean_overlay, kwargs are additional keyword arguments.

>>> resultslist = sg.gridloop(
...     func=sg.clean_overlay,
...     mask=buffered,
...     gridsize=1000,
...     args=(points, buffered),
...     kwargs={"how": "intersection"}
... )
>>> type(resultslist)
<class 'list'>
>>> results = pd.concat(resultslist, ignore_index=True)
>>> print(results.to_string(max_rows=10, max_colwidth=50, show_dimensions=True))
     idx_1 idx_2                    geometry
0      220   220  POINT (254575.2 6661631.5)
1      735   735  POINT (256337.4 6649931.7)
2      575   575  POINT (256369.2 6650413.3)
3       39    39  POINT (256142.3 6650526.3)
4      235   235  POINT (256231.3 6650720.2)
...    ...   ...                         ...
1481   711   795  POINT (272845.5 6655048.8)
1482   711   711  POINT (272845.5 6655048.8)
1483   757   757  POINT (273507.6 6652806.6)
1484   457   457  POINT (273524.4 6652979.9)
1485   284   284  POINT (273650.8 6653000.5)

[1486 rows x 3 columns]
make_grid(obj, gridsize, *, crs=None, clip_to_bounds=False)[source]

Create a polygon grid around geometries.

Creates a GeoDataFrame of grid cells of a given size around the bounds of a given GeoDataFrame. The corners are rounded to the nearest integer.

Parameters:
  • obj (GeoDataFrame | GeoSeries | Geometry | tuple) – GeoDataFrame, GeoSeries, shapely geometry or bounding box (an iterable with four values (minx, miny, maxx, maxy)).

  • gridsize (int | float) – Length of the grid cell walls.

  • crs (CRS | None) – Coordinate reference system if ‘obj’ is not GeoDataFrame or GeoSeries.

  • clip_to_bounds (bool) – Whether to clip the grid to the total bounds of the geometries. Defaults to False.

Return type:

GeoDataFrame

Returns:

GeoDataFrame with grid polygons.

Raises:

ValueError – crs can only be None if obj is GeoDataFrame/GeoSeries.

make_grid_from_bbox(minx, miny, maxx, maxy, *_, gridsize, crs)[source]

Creates a polygon grid from a bounding box.

Creates a GeoDataFrame of grid cells of a given size within the given maxumum and mimimum x and y values.

Parameters:
  • minx (int | float) – Minumum x coordinate.

  • miny (int | float) – Minumum y coordinate.

  • maxx (int | float) – Maximum x coordinate.

  • maxy (int | float) – Maximum y coordinate.

  • gridsize (int | float) – Length of the grid walls.

  • crs (CRS | int | str) – Coordinate reference system.

Return type:

GeoDataFrame

Returns:

GeoDataFrame with grid geometries.

make_ssb_grid(gdf, gridsize=1000, add=1)[source]

Creates a polygon grid around a GeoDataFrame with an SSB id column.

Creates a grid that follows the grids produced by Statistics Norway. The GeoDataFrame must have 25833 as crs (UTM 33 N).

Courtesy https://gis.stackexchange.com/questions/269243/creating-polygon-grid-using-geopandas

Parameters:
  • gdf (GeoDataFrame | GeoSeries) – A GeoDataFrame.

  • gridsize (int) – Size of the grid in meters.

  • add (int | float) – Number of grid cells to add on each side, to make sure all data is covered by the grid.

Return type:

GeoDataFrame

Returns:

GeoDataFrame with grid geometries and a column ‘ssb_rute_id’.

Raises:
  • ValueError – If the GeoDataFrame does not have 25833 as crs.

  • TypeError – if gdf has wrong type.