Skip to content

Commit

Permalink
Provide example data (TopoToolbox#29)
Browse files Browse the repository at this point in the history
Resolves TopoToolbox#9 

Adds a mechanism for downloading example DEMs from the TopoToolbox/DEMs repository.
  • Loading branch information
Teschl authored May 30, 2024
1 parent d505bf2 commit 3eb8997
Show file tree
Hide file tree
Showing 7 changed files with 263 additions and 30 deletions.
72 changes: 72 additions & 0 deletions examples/test_load_dem.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import topotoolbox as topo"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(topo.get_dem_names())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"dem = topo.load_dem(\"taiwan\")\n",
"dem.info()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(topo.get_cache_contents())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"topo.clear_cache()\n",
"print(topo.get_cache_contents())"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
1 change: 1 addition & 0 deletions src/topotoolbox/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from .grid_object import GridObject
from .utils import *
44 changes: 23 additions & 21 deletions src/topotoolbox/grid_object.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
"""This module contains the GridObject class.
"""

import random
from typing import Union

import numpy as np
import rasterio

from .gridmixins.fillsinks import FillsinksMixin
from .gridmixins.info import InfoMixin
from .gridmixins.magic import MagicMixin
from .gridmixins.identifyflats import IdentifyflatsMixin
from .gridmixins import * # pylint: disable=W0401

__all__ = ['GridObject']


class GridObject(
Expand All @@ -19,23 +19,21 @@ class GridObject(
MagicMixin
):
"""A class containing all information of a Digital Elevation Model (DEM).
This class combines mixins to provide various functionalities for working with DEMs.
Args:
InfoMixin: A mixin class providing methods to retrieve information about the DEM.
FillsinksMixin: A mixin class providing a method to fill sinks in the DEM.
MagicMixin: A mixin class providing magical methods for the DEM.
This class combines mixins to provide various functionalities
for working with DEMs.
"""

def __init__(self, path: Union[str, None] = None) -> None:
"""Initialize a GridObject instance.
Args:
path (str, optional): The path to the raster file. Defaults to None.
path (str, optional): The path to the raster file.
Defaults to None.
Raises:
TypeError: If an invalid type is passed as the `path`.
ValueError: If an error occurs while processing the `path` argument.
ValueError: If an error occurs while processing
the `path` argument.
"""

if path is not None:
Expand Down Expand Up @@ -66,7 +64,8 @@ def __init__(self, path: Union[str, None] = None) -> None:
def gen_random(
cls, hillsize: int = 24, rows: int = 128, columns: int = 128,
cellsize: float = 10.0) -> 'GridObject':
"""Generate a GridObject instance that is generated with OpenSimplex noise.
"""Generate a GridObject instance that is generated with
OpenSimplex noise.
Args:
hillsize (int, optional): Controls the "smoothness" of the
Expand All @@ -80,16 +79,17 @@ def gen_random(
ImportError: If OpenSimplex has not been installed.
Returns:
GridObject: An instance of GridObject with randomly generated values.
GridObject: An instance of GridObject with randomly
generated values.
"""

try:
import opensimplex as simplex
import opensimplex as simplex # pylint: disable=C0415

except ImportError:
raise ImportError(
"""For gen_random to work, use \"pip install topotoolbox[opensimplex]\"
or \"pip install .[opensimplex]\"""") from None
err = ("For gen_random to work, use \"pip install topotool" +
"box[opensimplex]\" or \"pip install .[opensimplex]\"")
raise ImportError(err) from None

noise_array = np.empty((rows, columns), dtype=np.float32)
for y in range(0, rows):
Expand All @@ -116,14 +116,16 @@ def gen_empty(cls) -> None:

@classmethod
def gen_random_bool(
cls, rows: int = 32, columns: int = 32, cellsize: float = 10.0) -> 'GridObject':
"""Generate a GridObject instance that caontains only randomly
cls, rows: int = 32, columns: int = 32, cellsize: float = 10.0
) -> 'GridObject':
"""Generate a GridObject instance that contains only randomly
generated Boolean values.
Args:
rows (int, optional): Number of rows. Defaults to 32.
columns (int, optional): Number of columns. Defaults to 32.
cellsize (float, optional): size of each cell in the grid. Defaults to 10.
cellsize (float, optional): size of each cell in the grid.
Defaults to 10.
Returns:
GridObject: _description_
Expand Down
6 changes: 6 additions & 0 deletions src/topotoolbox/gridmixins/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from .fillsinks import FillsinksMixin
from .info import InfoMixin
from .magic import MagicMixin
from .identifyflats import IdentifyflatsMixin

__all__ = ['FillsinksMixin', 'InfoMixin', 'MagicMixin', 'IdentifyflatsMixin']
22 changes: 16 additions & 6 deletions src/topotoolbox/gridmixins/identifyflats.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""This module contains the Mixin class IdentifyflatsMixin for the GridObject.
"""
import copy

import numpy as np
Expand All @@ -6,24 +8,32 @@


class IdentifyflatsMixin():
"""Mixin class containing Identifyflats.
"""

def identifyflats(self, raw=False, output=['sills', 'flats']) -> tuple:
def identifyflats(
self, raw: bool = False, output: list[str] = None) -> tuple:
"""
Identifies flats and sills in a digital elevation model (DEM).
Args:
raw (bool): If True, returns the raw output grid as np.ndarray.
Defaults to False.
Defaults to False.
output (list): List of strings indicating desired output types.
Possible values are 'sills', 'flats'. Defaults to ['sills', 'flats'].
Possible values are 'sills', 'flats'.
Defaults to ['sills', 'flats'].
Returns:
tuple: A tuple containing copies of the DEM with identified flats and/or sills.
tuple: A tuple containing copies of the DEM with identified
flats and/or sills.
Note:
Flats are identified as 1s, sills as 2s and presills as 5s (since they are also flats)
in the output grid. Only relevant when using raw=True.
Flats are identified as 1s, sills as 2s and presills as 5s
(since they are also flats) in the output grid.
Only relevant when using raw=True.
"""
if output is None:
output = ['sills', 'flats']

dem = self.z.astype(np.float32)
output_grid = np.zeros_like(dem).astype(np.int32)
Expand Down
9 changes: 6 additions & 3 deletions src/topotoolbox/gridmixins/magic.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,8 @@ def __and__(self, other):
or other.z[x][y] not in [0, 1]):

raise ValueError(
"Invalid cell value. 'and' can only compare True (1) and False (0) values.")
"Invalid cell value. 'and' can only compare " +
"True (1) and False (0) values.")

dem.z[x][y] = (int(self.z[x][y]) & int(other.z[x][y]))

Expand All @@ -183,7 +184,8 @@ def __or__(self, other):
or other.z[x][y] not in [0, 1]):

raise ValueError(
"Invalid cell value. 'or' can only compare True (1) and False (0) values.")
"Invalid cell value. 'or' can only compare True (1)" +
" and False (0) values.")

dem.z[x][y] = (int(self.z[x][y]) | int(other.z[x][y]))

Expand All @@ -205,7 +207,8 @@ def __xor__(self, other):
or other.z[x][y] not in [0, 1]):

raise ValueError(
"Invalid cell value. 'xor' can only compare True (1) and False (0) values.")
"Invalid cell value. 'xor' can only compare True (1)" +
" and False (0) values.")

dem.z[x][y] = (int(self.z[x][y]) ^ int(other.z[x][y]))

Expand Down
Loading

0 comments on commit 3eb8997

Please sign in to comment.