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

Add numpy interface #210

Merged
merged 3 commits into from
Jun 11, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 3 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ repos:

# Format the code aggressively using black
- repo: https://github.com/psf/black
rev: 20.8b1
rev: 21.5b2
hooks:
- id: black
args: [--line-length=120]
Expand All @@ -40,7 +40,6 @@ repos:
additional_dependencies:
- flake8-comprehensions==3.1.0
- flake8-bugbear==21.3.2
- pandas-dev-flaker==0.2.0
files: ^(geoutils|tests)
# Lint the code using mypy
- repo: https://github.com/pre-commit/mirrors-mypy
Expand Down Expand Up @@ -69,7 +68,7 @@ repos:

# Automatically upgrade syntax to a minimum version
- repo: https://github.com/asottile/pyupgrade
rev: v2.18.3
rev: v2.19.1
hooks:
- id: pyupgrade
args: [--py37-plus]
Expand All @@ -95,6 +94,6 @@ repos:

# Add custom regex lints (see .relint.yml)
- repo: https://github.com/codingjoe/relint
rev: 1.2.0
rev: 1.2.1
hooks:
- id: relint
7 changes: 7 additions & 0 deletions geoutils/georaster.py
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,13 @@ def copy(self: RasterType, new_array: np.ndarray | None = None) -> RasterType:

return cp

@property
def __array_interface__(self) -> dict[str, Any]:
if self._data is None:
self.load()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we really load it? Maybe it's not wanted by the user (some cropping or loading only a single band might be needed instead). I would rather raise an error.


return self._data.__array_interface__ # type: ignore

def load(self, bands: int | list[int] | None = None, **kwargs: Any) -> None:
r"""
Load specific bands of the dataset, using rasterio.read().
Expand Down
2 changes: 1 addition & 1 deletion geoutils/geovector.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def __repr__(self) -> str:
return str(self.ds.__repr__())

def __str__(self) -> str:
""" Provide string of information about Raster. """
"""Provide string of information about Raster."""
return self.info()

def info(self) -> str:
Expand Down
36 changes: 36 additions & 0 deletions tests/test_georaster.py
Original file line number Diff line number Diff line change
Expand Up @@ -875,3 +875,39 @@ def test_resampling_str(self) -> None:
img3a = img1.reproject(img2, resampling="q1")
img3b = img1.reproject(img2, resampling=rio.warp.Resampling.q1)
assert img3a == img3b


@pytest.mark.parametrize("dtype", ["float32", "uint8", "int32"]) # type: ignore
def test_numpy_functions(dtype: str) -> None:
"""Test how rasters can be used as/with numpy arrays."""
warnings.simplefilter("error")

# Create an array of unique values starting at 0 and ending at 24
array = np.arange(25, dtype=dtype).reshape((1, 5, 5))
# Create an associated dummy transform
transform = rio.transform.from_origin(0, 5, 1, 1)

# Create a raster from the array
raster = gu.Raster.from_array(array, transform=transform, crs=4326)

# Test some ufuncs
assert np.median(raster) == 12.0
assert np.mean(raster) == 12.0

# Check that rasters don't become arrays when using simple arithmetic.
assert isinstance(raster + 1, gr.Raster)

# Test that array_equal works
assert np.array_equal(array, raster)

# Test the data setter method by creating a new array
raster.data = array + 2

# Check that the median updated accordingly.
assert np.median(raster) == 14.0

# Test
raster += array

assert isinstance(raster, gr.Raster)
assert np.median(raster) == 26.0