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

Process typing #626

Merged
merged 30 commits into from
May 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
e2ecd33
add examples for typed processes
ungarj Feb 25, 2024
cf3b977
use ABC for input base classes
ungarj Feb 26, 2024
01de955
deprecate mapchete.commons module
ungarj Feb 26, 2024
30350bd
add test to verify that all process config parameters can be set from…
ungarj Feb 27, 2024
8eaeca0
fine tune processes; adapt tests
ungarj Feb 27, 2024
89725ac
remove deprecated tests
ungarj Feb 27, 2024
71f8326
rely on protocols rather than ABC for driver classes
ungarj Feb 29, 2024
bf5a34c
update tests
ungarj Mar 27, 2024
ddae46c
Merge branch 'main' into process_typing
ungarj Mar 27, 2024
9828af8
add Empty exception as alias for MapcheteNodataTile; fix typing conce…
ungarj Mar 27, 2024
186c39c
run 'ruff check . --fix'
ungarj Mar 27, 2024
5f95838
remove breakpoint
ungarj Mar 27, 2024
68daeea
add examples
ungarj Mar 28, 2024
3d2a457
remove deprecated fs kwargs for clip command; add typing
ungarj Mar 29, 2024
7143347
add clip example
ungarj Mar 29, 2024
7c0ef03
add numpy array protocol to ReferencedRaster
ungarj Mar 29, 2024
4ae5f30
add CRS check
ungarj Apr 2, 2024
7883cdd
don't use __array_interface__ as it cannot handle array masks
ungarj Apr 25, 2024
be3513d
make typing compatible for python 3.8
ungarj Apr 25, 2024
46982b0
increase test coverage; add more tests for contour process
ungarj Apr 25, 2024
8a8204c
streamline contour generation
ungarj Apr 29, 2024
a70cf35
increase test coverage
ungarj Apr 29, 2024
b050e46
dev commit
ungarj May 13, 2024
712869f
add more tests for ReferencedRaster and disregard deprecated tile kwarg
ungarj May 14, 2024
71903b9
increase test coverage
ungarj May 14, 2024
eea4250
mapchete.cli: collect all tests in test submodule
ungarj May 14, 2024
e25a8bc
mapchete.commands: collect all tests in test submodule
ungarj May 14, 2024
9dc9a6b
Merge branch 'main' into process_typing
ungarj May 15, 2024
e8b8672
rename modules
ungarj May 15, 2024
6646e3d
fix module import
ungarj May 15, 2024
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
16 changes: 16 additions & 0 deletions examples/clip/clip.mapchete
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
process: mapchete.processes.clip
zoom_levels:
min: 0
max: 8
pyramid:
grid: geodetic
metatiling: 1
input:
inp: ../../test/testdata/cleantopo_br.tif
clip: ../../test/testdata/aoi_br.geojson

output:
path: output
format: GTiff
dtype: uint8
bands: 1
19 changes: 19 additions & 0 deletions examples/contours/contours.mapchete
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
process: mapchete.processes.contours
zoom_levels:
min: 0
max: 8
pyramid:
grid: geodetic
metatiling: 1
input:
dem: ../../test/testdata/cleantopo_tl.tif
output:
format: GeoJSON
path: output
schema:
properties:
elevation: float
geometry: LineString
process_parameters:
field: "elevation"
interval: 100
29 changes: 29 additions & 0 deletions examples/custom_grid/custom_grid.mapchete
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
process: mapchete.processes.convert
input:
inp: ../../test/testdata/custom_grid_points.geojson
output:
format: GeoJSON
path: output
schema:
properties:
name: str
geometry: Unknown
pyramid:
grid:
shape:
- 1525
- 125
bounds:
- 166020
- 0
- 934020
- 9369600
is_global: false
proj: +proj=utm +zone=32 +datum=WGS84 +units=m +no_defs
metatiling: 4
zoom_levels: 3
bounds:
- 166020
- 0
- 934020
- 9369600
20 changes: 20 additions & 0 deletions examples/file_groups/file_groups.mapchete
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
process: file_groups.py
zoom_levels:
min: 0
max: 5
pyramid:
grid: geodetic
pixelbuffer: 10
metatiling: 8
input:
group1:
file1: ../../test/testdata/cleantopo_tl.tif
file2: ../../test/testdata/cleantopo_br.tif
group2:
file1: ../../test/testdata/dummy1.tif
file2: ../../test/testdata/dummy2.tif
output:
dtype: uint16
bands: 1
format: GTiff
path: output
21 changes: 21 additions & 0 deletions examples/file_groups/file_groups.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""Example process file."""

import numpy.ma as ma

from mapchete import RasterInputGroup


def execute(group1: RasterInputGroup, group2: RasterInputGroup) -> ma.MaskedArray:
"""User defined process."""

# read band 1 and get mean of group1
group1 = ma.mean(
ma.stack([raster_input.read(1) for _, raster_input in group1]), axis=0
)

# read band 1 and get mean of group1
group2 = ma.mean(
ma.stack([raster_input.read(1) for _, raster_input in group2]), axis=0
)

return ma.mean(ma.stack([group1, group2]), axis=0)
21 changes: 21 additions & 0 deletions examples/hillshade/hillshade.mapchete
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
process: mapchete.processes.hillshade
zoom_levels:
min: 0
max: 8
pyramid:
grid: geodetic
metatiling: 1
pixelbuffer: 2
input:
dem: ../../test/testdata/cleantopo_tl.tif
output:
path: output
format: GTiff
dtype: uint8
bands: 1
process_parameters:
resampling: "nearest"
azimuth: 315.0
altitude: 45.0
z: 1.0
scale: 1.0
25 changes: 16 additions & 9 deletions mapchete/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import logging
import os
from typing import Optional, Union
from typing import Union

from fsspec import AbstractFileSystem

from mapchete.config import MapcheteConfig
from mapchete.errors import Empty, MapcheteNodataTile
from mapchete.executor import Executor, MFuture
from mapchete.formats import read_output_metadata
from mapchete.formats.protocols import (
RasterInput,
RasterInputGroup,
VectorInput,
VectorInputGroup,
)
from mapchete.path import MPath, fs_from_path
from mapchete.processing import Mapchete, MapcheteProcess
from mapchete.tile import count_tiles
Expand All @@ -19,7 +26,13 @@
"MapcheteProcess",
"Timer",
"Executor",
"Empty",
"MapcheteNodataTile",
"MFuture",
"RasterInput",
"RasterInputGroup",
"VectorInput",
"VectorInputGroup",
]
__version__ = "2024.5.0"

Expand All @@ -30,8 +43,6 @@
def open(
some_input: Union[MPathLike, dict, MapcheteConfig],
with_cache: bool = False,
fs: Optional[AbstractFileSystem] = None,
fs_kwargs: Optional[dict] = None,
**kwargs,
) -> Mapchete:
"""
Expand Down Expand Up @@ -72,11 +83,9 @@ def open(
# for TileDirectory inputs
if isinstance(some_input, MPath) and some_input.suffix == "":
logger.debug("assuming TileDirectory")
metadata_json = MPath.from_inp(some_input).joinpath("metadata.json")
fs_kwargs = fs_kwargs or {}
fs = fs or fs_from_path(metadata_json, **fs_kwargs)
metadata_json = MPath.from_inp(some_input) / "metadata.json"
logger.debug("read metadata.json")
metadata = read_output_metadata(metadata_json, fs=fs)
metadata = read_output_metadata(metadata_json)
config = dict(
process=None,
input=None,
Expand All @@ -88,8 +97,6 @@ def open(
if k not in ["delimiters", "mode"]
},
path=some_input,
fs=fs,
fs_kwargs=fs_kwargs,
**kwargs,
),
config_dir=os.getcwd(),
Expand Down
1 change: 0 additions & 1 deletion mapchete/cli/default/cp.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import click
import tqdm

from mapchete import commands
from mapchete.cli import options
Expand Down
2 changes: 1 addition & 1 deletion mapchete/cli/default/rm.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from mapchete import commands
from mapchete.cli import options
from mapchete.cli.progress_bar import PBar
from mapchete.commands._rm import existing_paths
from mapchete.commands.rm import existing_paths


@click.command(help="Remove tiles from TileDirectory.")
Expand Down
4 changes: 2 additions & 2 deletions mapchete/cli/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ def _validate_zoom(ctx, param, zoom):
if len(zoom_levels) > 2:
raise ValueError("zooms can be maximum two items")
return ZoomLevels.from_inp(zoom_levels)
except Exception as e:
raise click.BadParameter(e)
except Exception as exc:
raise click.BadParameter(str(exc))


def _validate_bounds(ctx, param, bounds):
Expand Down
11 changes: 6 additions & 5 deletions mapchete/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
This package contains easy to access functions which otherwise would have to be called via the CLI.
This should make the use from within other scripts, notebooks, etc. easier.
"""
from mapchete.commands._convert import convert
from mapchete.commands._cp import cp
from mapchete.commands._execute import execute
from mapchete.commands._index import index
from mapchete.commands._rm import rm

from mapchete.commands.convert import convert
from mapchete.commands.cp import cp
from mapchete.commands.execute import execute
from mapchete.commands.index import index
from mapchete.commands.rm import rm

__all__ = ["convert", "cp", "execute", "index", "rm"]
24 changes: 14 additions & 10 deletions mapchete/commands/_convert.py → mapchete/commands/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
from contextlib import AbstractContextManager
from multiprocessing import cpu_count
from pprint import pformat
from typing import List, NoReturn, Optional, Tuple, Type, Union
from typing import List, Optional, Tuple, Type, Union

import tilematrix
from rasterio.crs import CRS
from rasterio.enums import Resampling
from shapely.geometry import box
from shapely.geometry.base import BaseGeometry

from mapchete.commands._execute import execute
from mapchete.commands.execute import execute
from mapchete.commands.observer import ObserverProtocol, Observers
from mapchete.commands.parser import InputInfo, OutputInfo
from mapchete.config import DaskSettings
Expand Down Expand Up @@ -43,7 +43,7 @@ def convert(
dask_settings: DaskSettings = DaskSettings(),
workers: Optional[int] = None,
clip_geometry: Optional[str] = None,
bidx: Optional[List[int]] = None,
bidx: Optional[Union[List[int], int]] = None,
output_pyramid: Optional[Union[str, dict, MPathLike]] = None,
output_metatiling: Optional[int] = None,
output_format: Optional[str] = None,
Expand All @@ -63,7 +63,7 @@ def convert(
retry_on_exception: Tuple[Type[Exception], Type[Exception]] = Exception,
cancel_on_exception: Type[Exception] = JobCancelledError,
retries: int = 0,
) -> NoReturn:
) -> None:
"""
Convert mapchete outputs or other geodata.

Expand Down Expand Up @@ -121,9 +121,11 @@ def convert(
),
)
if output_pyramid
else input_info.output_pyramid.to_dict()
if input_info.output_pyramid
else None
else (
input_info.output_pyramid.to_dict()
if input_info.output_pyramid
else None
)
),
output=dict(
{
Expand All @@ -139,9 +141,11 @@ def convert(
),
dtype=output_dtype or input_info.output_params.get("dtype"),
**creation_options,
**dict(overviews=True, overviews_resampling=overviews_resampling_method)
if overviews
else dict(),
**(
dict(overviews=True, overviews_resampling=overviews_resampling_method)
if overviews
else dict()
),
),
config_dir=os.getcwd(),
zoom_levels=zoom or input_info.zoom_levels,
Expand Down
Loading
Loading