Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated grid implementation #84

Merged
merged 4 commits into from
Oct 24, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 31 additions & 16 deletions tests/test_grid.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,6 @@
"""Test module for grid.py.

NAME
test_grid.py

DESCRIPTION
This module tests the following functions from grid.py:

- grid.make_square_grid
Create a square grid.

- grid.make_hex_grid
Create a hexagonal grid.

- TODO The grid.Grid class.

- TODO grid.Grid.dump and grid.Grid.dumps for0 geojson

This module tests the functionality of grid.py
"""

import json
Expand Down Expand Up @@ -88,6 +73,36 @@ def test_make_hex_grid(cell_id):
assert np.rad2deg(rad) == pytest.approx(60)


@pytest.mark.parametrize(
argnames=["grid_type", "excep_type", "message"],
argvalues=[
("penrose", ValueError, "The grid_type penrose is not defined."),
(
"square",
ValueError,
"The square creator function generated ids and polygons of unequal length.",
),
],
)
def test_grid_exceptions(mocker, grid_type, excep_type, message):
"""Test Grid init exceptions."""

from virtual_rainforest.core.grid import Grid

# Mock the registered 'square' creator with something that returns unequal length
# ids and polygons tuples.
mocker.patch.dict(
"virtual_rainforest.core.grid.GRID_REGISTRY",
{"square": lambda *args, **kwargs: ((1, 2, 3, 4), ("poly", "poly", "poly"))},
)

with pytest.raises(excep_type) as err:

Grid(grid_type=grid_type)

assert str(err.value) == message


@pytest.mark.parametrize(argnames=["preset_distances"], argvalues=[(True,), (False,)])
@pytest.mark.parametrize(
argnames=["grid_type", "cfrom", "cto"],
Expand Down
41 changes: 19 additions & 22 deletions virtual_rainforest/core/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"""

import json
from typing import Any, Callable, NamedTuple, Optional, Sequence, Union
from typing import Any, Callable, Optional, Sequence, Union

import numpy as np
import numpy.typing as npt
Expand All @@ -31,23 +31,16 @@
decorator.
"""


class GridStructure(NamedTuple):
"""Data structure to be returned from grid creator functions.

The contents should be two equal length lists giving unique integer ID values
and corresponding shapely.geometry.Polygon objects.
"""

ids: list[int]
polygons: list[Polygon]
GRID_STRUCTURE_SIG = tuple[tuple[int, ...], tuple[Polygon, ...]]
"""Signature of the data structure to be returned from grid creator functions."""


def register_grid(grid_type: str) -> Callable:
"""Add a grid type and creator function to the grid registry.

This decorator is used to add a function creating a grid layout to the registry of
accepted grids and returning an object of class GridStructure.
accepted grids. The function must return equal-length tuples of integer polygon ids
and Polygon objects, following the GRID_STRUCTURE_SIG signature.

The grid_type argument is used to identify the grid creation function to be used by
the Grid class and in configuration files.
Expand Down Expand Up @@ -77,7 +70,7 @@ def make_square_grid(
cell_ny: int,
xoff: float = 0,
davidorme marked this conversation as resolved.
Show resolved Hide resolved
yoff: float = 0,
) -> GridStructure:
) -> GRID_STRUCTURE_SIG:
"""Create a square grid.

Args:
Expand All @@ -88,7 +81,7 @@ def make_square_grid(
yoff: An offset to use for the grid origin in the Y direction.

Returns:
A GridStructure instance
Equal-length tuples of integer polygon ids and Polygon objects
"""

# Create the polygon prototype object, with origin at 0,0 and area 1
Expand All @@ -113,7 +106,7 @@ def make_square_grid(
prototype, xoff=scale_factor * x_idx, yoff=scale_factor * y_idx
)

return GridStructure(ids=list(range(len(cell_list))), polygons=cell_list)
return (tuple(range(len(cell_list))), tuple(cell_list))
davidorme marked this conversation as resolved.
Show resolved Hide resolved


@register_grid(grid_type="hexagon")
Expand All @@ -123,7 +116,7 @@ def make_hex_grid(
cell_ny: int,
xoff: float = 0,
yoff: float = 0,
) -> GridStructure:
) -> GRID_STRUCTURE_SIG:
"""Create a hexagonal grid.

Args:
Expand All @@ -134,7 +127,7 @@ def make_hex_grid(
yoff: An offset to use for the grid origin in the Y direction.

Returns:
A GridStructure instance
Equal-length tuples of integer polygon ids and Polygon objects
"""

# TODO - implement grid orientation and kwargs passing
Expand Down Expand Up @@ -179,7 +172,7 @@ def make_hex_grid(
yoff=1.5 * side_length * y_idx,
)

return GridStructure(ids=list(range(len(cell_list))), polygons=cell_list)
return (tuple(range(len(cell_list))), tuple(cell_list))
davidorme marked this conversation as resolved.
Show resolved Hide resolved


@register_grid(grid_type="triangle")
Expand All @@ -189,7 +182,7 @@ def make_triangular_grid(
cell_ny: int,
xoff: float = 0,
yoff: float = 0,
) -> GridStructure:
) -> GRID_STRUCTURE_SIG:
"""Create a equilateral triangular grid.

Args:
Expand Down Expand Up @@ -258,16 +251,20 @@ def __init__(
raise ValueError(f"The grid_type {self.grid_type} is not defined.")

# Run the grid creation
grid_structure = creator(
self.cell_id, self.polygons = creator(
cell_area=self.cell_area,
cell_nx=self.cell_nx,
cell_ny=self.cell_ny,
xoff=self.xoff,
yoff=self.yoff,
)

self.cell_id = grid_structure.ids
self.polygons = grid_structure.polygons
if len(self.cell_id) != len(self.polygons):
raise ValueError(
f"The {self.grid_type} creator function generated ids and polygons of "
"unequal length."
)

self.n_cells = len(self.cell_id)

# Get the centroids as a numpy array
Expand Down