diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..c6721e3 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,91 @@ +name: Docs + +# Builds every docs site in strict mode: the frame site (docs/mkdocs.yml) and one site per module +# (beratools/modules//docs/mkdocs.yml), and puts them together as one GitHub Pages site: the +# frame site at the root and each module's site under // (tests/test_docs_sites.py keeps the +# site URLs in line). Only the public BERATool/beratools repository deploys it, on pushes to main and +# by hand; elsewhere, and on pull requests, the sites are only built. + +on: + workflow_dispatch: + pull_request: + branches: + - main + paths: + - 'docs/**' + - 'beratools/**' + - 'pyproject.toml' + - 'pixi.toml' + - 'pixi.lock' + - '.github/workflows/docs.yml' + push: + branches: + - main + paths: + - 'docs/**' + - 'beratools/**' + - 'pyproject.toml' + - 'pixi.toml' + - 'pixi.lock' + - '.github/workflows/docs.yml' + +concurrency: + group: docs-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + build-docs: + # a push to main only matters where the sites are deployed + if: github.event_name != 'push' || github.repository == 'BERATool/beratools' + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + fetch-depth: 0 + - name: Set up Pixi environment + uses: prefix-dev/setup-pixi@v0.8.1 + with: + cache: false + - name: Build every docs site (strict) + run: | + status=0 + for site in docs/mkdocs.yml beratools/modules/*/docs/mkdocs.yml; do + echo "::group::$site" + pixi run zensical build --strict --clean -f "$site" || { echo "::error file=$site::docs build failed"; status=1; } + echo "::endgroup::" + done + exit $status + - name: Put the sites together + run: | + mkdir _site + cp -r docs/site/. _site/ + for docs in beratools/modules/*/docs; do + module=$(basename "$(dirname "$docs")") + cp -r "$docs/site" "_site/$module" + done + - name: Upload Pages artifact + if: github.repository == 'BERATool/beratools' && github.event_name != 'pull_request' + uses: actions/upload-pages-artifact@v3 + with: + path: _site + + deploy: + if: github.repository == 'BERATool/beratools' && github.event_name != 'pull_request' + needs: build-docs + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/.github/workflows/mkdocs-gh-pages.yml b/.github/workflows/mkdocs-gh-pages.yml deleted file mode 100644 index c7693a7..0000000 --- a/.github/workflows/mkdocs-gh-pages.yml +++ /dev/null @@ -1,66 +0,0 @@ -name: Deploy Docs to GitHub Pages - -on: - workflow_dispatch: - pull_request: - branches: - - main - paths: - - 'docs/**' - - 'pyproject.toml' - - 'pixi.toml' - - 'pixi.lock' - - '.github/workflows/mkdocs-gh-pages.yml' - push: - branches: - - main - paths: - - 'docs/**' - - 'pyproject.toml' - - 'pixi.toml' - - 'pixi.lock' - - '.github/workflows/mkdocs-gh-pages.yml' - -concurrency: - group: docs-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true - -jobs: - test-docs: - runs-on: ubuntu-latest - timeout-minutes: 20 - permissions: - contents: read - steps: - - uses: actions/checkout@v7 - with: - persist-credentials: false - fetch-depth: 0 - - name: Set up Pixi environment - uses: prefix-dev/setup-pixi@v0.8.1 - with: - cache: false - - name: Build docs site - run: pixi run zensical build -f docs/mkdocs.yml - - name: Upload Pages artifact - if: github.event_name != 'pull_request' - uses: actions/upload-pages-artifact@v3 - with: - path: docs/site - - deploy: - if: github.event_name != 'pull_request' - needs: test-docs - runs-on: ubuntu-latest - timeout-minutes: 10 - permissions: - contents: read - pages: write - id-token: write - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - steps: - - name: Deploy to GitHub Pages - id: deployment - uses: actions/deploy-pages@v4 diff --git a/.github/workflows/publish_to_anaconda.yml b/.github/workflows/publish_to_anaconda.yml index 3518520..e047c9d 100644 --- a/.github/workflows/publish_to_anaconda.yml +++ b/.github/workflows/publish_to_anaconda.yml @@ -80,10 +80,11 @@ jobs: RELEASE_TAG: ${{ steps.source.outputs.release_tag }} run: | set -euo pipefail - if [[ "$PUBLISH" == "true" ]]; then - version="$RELEASE_TAG" - else - version="$(pixi run python -c "from setuptools_scm import get_version; print(get_version(root='.'))")" + # the version is set in beratools/__init__.py; a release tag must match it + version="$(pixi run python -c "import beratools; print(beratools.__version__)")" + if [[ "$PUBLISH" == "true" && "$version" != "$RELEASE_TAG" ]]; then + echo "Release tag $RELEASE_TAG does not match __version__ $version in beratools/__init__.py." >&2 + exit 1 fi if [[ ! "$version" =~ ^[0-9][0-9A-Za-z.+_-]*$ ]]; then @@ -93,14 +94,12 @@ jobs: echo "version=$version" >> "$GITHUB_OUTPUT" echo "VERSION=$version" >> "$GITHUB_ENV" - echo "SETUPTOOLS_SCM_PRETEND_VERSION=$version" >> "$GITHUB_ENV" echo "Package version: $version" - name: Build Conda package working-directory: packaging env: VERSION: ${{ steps.package.outputs.version }} - SETUPTOOLS_SCM_PRETEND_VERSION: ${{ steps.package.outputs.version }} run: | set -euo pipefail echo "🏗️ Building version: $VERSION" @@ -167,7 +166,7 @@ jobs: micromamba run -n bera-conda-smoke beratools --help echo "🧪 Running package integration test" - micromamba run -n bera-conda-smoke pytest tests/test_workflow.py --maxfail=1 -q + micromamba run -n bera-conda-smoke pytest beratools/modules/mapping/tests/test_workflow.py --maxfail=1 -q - name: Upload to Anaconda.org (binstar) if: steps.source.outputs.publish == 'true' diff --git a/.github/workflows/publish_to_pypi.yml b/.github/workflows/publish_to_pypi.yml index d351645..c5cf23b 100644 --- a/.github/workflows/publish_to_pypi.yml +++ b/.github/workflows/publish_to_pypi.yml @@ -55,17 +55,13 @@ jobs: printf 'release_tag=%s\npublish=%s\n' "$tag" "$publish" >> "$GITHUB_OUTPUT" printf '### Publishing source\n\n- Mode: `%s`\n- Tag: `%s`\n- Source commit: `%s`\n- Workflow commit: `%s`\n' \ "$mode" "${tag:-none}" "$source_sha" "$GITHUB_SHA" >> "$GITHUB_STEP_SUMMARY" - - name: Set release version - if: steps.source.outputs.publish == 'true' - env: - RELEASE_TAG: ${{ steps.source.outputs.release_tag }} - run: echo "SETUPTOOLS_SCM_PRETEND_VERSION=$RELEASE_TAG" >> "$GITHUB_ENV" - name: Install build tools - run: pip install build twine hatch-vcs + run: pip install build twine - name: Build package run: python -m build - name: Check package metadata run: python -m twine check --strict dist/* + # the version comes from beratools/__init__.py; a tag that doesn't match it stops the release - name: Verify release package version if: steps.source.outputs.publish == 'true' env: diff --git a/.github/workflows/python-compatibility-tests.yml b/.github/workflows/python-compatibility-tests.yml index 9c3bdd0..53d8698 100644 --- a/.github/workflows/python-compatibility-tests.yml +++ b/.github/workflows/python-compatibility-tests.yml @@ -7,7 +7,7 @@ jobs: compatibility: name: Tox / Python ${{ matrix.python-version }} runs-on: ubuntu-latest - timeout-minutes: 20 + timeout-minutes: 8 permissions: contents: read strategy: @@ -54,13 +54,18 @@ jobs: scikit-image>=0.24 tqdm xarray-spatial + numba python-igraph tabulate + jsonschema + psutil + laspy + lazrs-python + scipy pip pytest pytest-qt tox - psutil condarc: | channel_priority: strict channels: diff --git a/.github/workflows/python-integration-tests.yml b/.github/workflows/python-integration-tests.yml index 4cb7185..eff38fe 100644 --- a/.github/workflows/python-integration-tests.yml +++ b/.github/workflows/python-integration-tests.yml @@ -30,7 +30,8 @@ concurrency: jobs: integration: name: Pixi integration - timeout-minutes: 30 + # R packages for the PC2Products tools come prebuilt from conda-forge on linux-64 (see pixi.toml) + timeout-minutes: 60 runs-on: ubuntu-latest permissions: contents: read @@ -47,5 +48,15 @@ jobs: cache: false - name: Run integration tests - run: pixi run pytest --cov=beratools --cov-report=term tests/test_workflow.py --maxfail=1 --disable-warnings -s -v --log-cli-level=INFO + run: pixi run pytest --cov=beratools --cov-report=term beratools/modules/mapping/tests/test_workflow.py --maxfail=1 --disable-warnings -s -v --log-cli-level=INFO + - name: Install Ubuntu dependencies for R + run: | + sudo apt-get update + sudo apt-get install -y libudunits2-dev libgdal-dev libgeos-dev libproj-dev libgl1-mesa-dev libglu1-mesa-dev + + - name: Run R environment test (installs missing R packages into the pixi R) + run: pixi run pytest beratools/modules/pc2products/tests/test_r_environment.py --maxfail=1 --disable-warnings -v --log-cli-level=INFO + + - name: Run PC2Products workflow test + run: pixi run pytest --cov=beratools --cov-report=term beratools/modules/pc2products/tests/test_r_workflow.py --maxfail=1 --disable-warnings -v --log-cli-level=INFO diff --git a/.gitignore b/.gitignore index 94f4ff5..aee911c 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,15 @@ _build .aider.* .ignore /docs/site +/beratools/modules/*/docs/site +# PC2Products tool outputs from the LiDAR tests +beratools/modules/pc2products/tests/data/LiDAR/Classified_PC +beratools/modules/pc2products/tests/data/LiDAR/Normalized_PC +beratools/modules/pc2products/tests/data/LiDAR/Raster_Output +# Spatial indexes the LiDAR tools build next to their inputs, and the local large-file test data +**/tests/data/**/*.lax +**/tests/data/LiDAR/Large_PC +**/tests/data/LiDAR/Real_Lidar # Hydra run logs from examples/full_workflow.py outputs/ diff --git a/README.md b/README.md index 223c88c..69c93c5 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,158 @@ Install with Anaconda works on Windows, macOS, and Linux. For more information about installation, check the [BERA Tools Installation](https://beratool.github.io/beratools/user/installation/). +#### Troubleshooting: `CondaEnvException: Pip failed` + +`environment.yml` installs `rpy2` with pip at the end of `conda env create`. If that step fails +(e.g. `Pip subprocess error`), create the environment without pip first, then install `rpy2` yourself: + +1. Open `environment.yml` and comment out the pip section: + + ```yaml + # - pip: + # - rpy2 + ``` + +2. Create and activate the environment: + + ```bash + $ conda env create -n bera -f environment.yml + $ conda activate bera + ``` + +3. Set the R paths (Windows **Anaconda Prompt**): + + ```bat + set "R_HOME=%CONDA_PREFIX%\Lib\R" + set "PATH=%R_HOME%\bin\x64;%PATH%" + ``` + +4. Install `rpy2` with pip: + + ```bash + $ python -m pip install rpy2 + ``` + +If pip still fails, check that the environment's Python starts with `python -c "print('ok')"`. A +Python that does not start (e.g. "The file or directory is corrupted and unreadable") is the real +cause. Rebuild the environment with a different Python version. + +## PC2Products (LiDAR) Tools + +The **PC2Products** (Point Cloud to Products) category turns LiDAR point clouds (`.las` / `.laz`) into +rasters such as a DTM, DSM, CHM and hummock/hollow maps. The tools run R and +[lidR](https://r-lidar.github.io/lidRbook/) through [rpy2](https://rpy2.github.io/); `environment.yml` +and `pixi.toml` include R, and the tools install the R packages they need the first time they run +(see [R for the PC2Products tools](https://beratool.github.io/beratools/user/installation/#r-for-the-pc2products-lidar-tools)). + +| Tool | `bt` subcommand | +|------|-----------------| +| [LiDAR data info](https://beratool.github.io/beratools/pc2products/user/las_info/) | `las_info` | +| [Raster Cell size from LiDAR data](https://beratool.github.io/beratools/pc2products/user/cellsize/) | `cellsize` | +| [Build LiDAR Spatial Index](https://beratool.github.io/beratools/pc2products/user/lidar_index/) | `lidar_index` | +| [Tile LiDAR Data](https://beratool.github.io/beratools/pc2products/user/lidar_tile/) | `tile` | +| [Ground Classify Using CSF](https://beratool.github.io/beratools/pc2products/user/gnd_csf/) | `gnd_csf` | +| [Generate DTM from LiDAR Data](https://beratool.github.io/beratools/pc2products/user/dtm/) | `dtm` | +| [Normalize LiDAR Data](https://beratool.github.io/beratools/pc2products/user/normalize/) | `normalize` | +| [Generate CHM or DSM from LiDAR Data](https://beratool.github.io/beratools/pc2products/user/chm_dsm/) | `chm_dsm` | +| [Detect Hummock and Hollow from LiDAR Data](https://beratool.github.io/beratools/pc2products/user/hummock_hollow/) | `hh` | +| [Surface Water Mapping](https://beratool.github.io/beratools/pc2products/user/surface_water/) | `surface_water` | +| [Depth-to-Water from Surface Water](https://beratool.github.io/beratools/pc2products/user/dtw/) | `dtw` | +| [Seismic Line Disturbance Analysis](https://beratool.github.io/beratools/pc2products/user/seismic_line_analysis/) | `line_analysis` | + +```bash +$ beratools dtm --in_las_folder tests/data/LiDAR --out_folder tests/data/LiDAR/Raster_Output --style tin +``` + +Sample tiles are in `tests/data/LiDAR/`, and `examples/` has two scripts that run the LiDAR tools in +sequence (see [examples/README.md](examples/README.md)). + +### Things to consider for running the R tools in parallel + +Ground classification, DTM, normalization, CHM/DSM and hummock/hollow split the point cloud into +tiles and process them with several R workers. How many workers a computer runs depends mostly on +its **free memory** and the **point density**, as each worker must hold the densest tile it gets. +A few files or tiles much denser than the rest don't hold the whole run back: they are processed +after the others with fewer workers. + +- **Memory per worker**: about (1.6 GB + bytes per point × the points in a tile with its buffer) + ÷ 0.6 of free memory, as the tools share 60% of the memory free when they start. The bytes per + point were measured for each tool: 260 for ground classification and IDW normalization, 160 for + the IDW DTM, up to 670 for the tools that triangulate the ground points (TIN DTM, TIN + normalization and hummock/hollow; less for data with less ground, which they sample before + planning; the table below is for all ground), 850 for the pit-free CHM/DSM, and about 120 plus 450 per raster cell for + the TIN CHM/DSM (see + [How all the tools behave](https://beratool.github.io/beratools/pc2products/technical/tool_behaviour/)). + Tiles are 100 to 500 m, chosen for each 500 m block from the density, so dense areas get small + tiles. Free memory needed per worker at the smallest tile (100 m, read with a 20 m buffer for + ground classification and 30 m for the other tools), with one thread: + + | Point density | Typical data | Ground classification | IDW normalization | TIN tools | Pit-free CHM/DSM | + |---|---|---|---|---|---| + | 20 pts/m² | airborne LiDAR | 2.8 GB | 2.9 GB | 3.2 GB | 3.4 GB | + | 100 pts/m² | dense airborne LiDAR | 3.5 GB | 3.8 GB | 5.5 GB | 6.3 GB | + | 300 pts/m² | drone LiDAR | 5.2 GB | 6.0 GB | 11.2 GB | 13.5 GB | + | 700 pts/m² | photogrammetry point clouds | 8.6 GB | 10.4 GB | 22.7 GB | 28.1 GB | + +- **RAM**: installed RAM ≈ workers × memory per worker + 5 to 6 GB for Windows and other + programs. For example, airborne LiDAR runs 2 to 4 workers with 16 GB; a 700 pts/m² point cloud + needs 32 GB for 2 workers with little else open, and 48 to 64 GB for 4 (for ground + classification; a TIN DTM of it needs about 32 GB for 1 worker). Close other programs + before a long run, as the tools plan for the memory free when they start. +- **CPU**: the `processes` allowed (all cores by default) are shared between the workers, so + when memory allows fewer workers than cores, each worker gets the spare cores as lidR threads + (about 0.2 GB more each). A worker is started only for every 20 million points of input, so + small jobs use one worker. +- **Disk**: a hard disk works; an SSD helps when several workers read LAZ files at once. Each + input file gets a `.lax` spatial index next to it (built once, see + [Build LiDAR Spatial Index](https://beratool.github.io/beratools/pc2products/user/lidar_index/)), so the + input folder must be writable for the fastest reading. +- **Memory limit**: each tool and its workers are limited to 80% of the free memory, so a tile + that needs more stops the tool with an error (`std::bad_alloc` or "cannot allocate") instead of + running the computer out of memory. +- **Resuming**: a run stops at the first tile that fails, or when you cancel it. Free memory, then + run the tool again with `skip_existing` set to `true` and the same parameters: the tiles whose + outputs are complete are skipped (each output is written as `.partial.` and renamed + when complete, so a tile cut off while writing is made again), and the 500 m blocks that have outputs keep the tile sizes of the plan the run + saved next to its outputs (`tiles_.csv`); the other blocks are tiled again for the + memory free now. +- **Kriging**: the memory figures were measured for ground classification. Kriging (DTM and + normalization) needs far more, over 7.8 GB for 14 million points, so use TIN or IDW on large + or dense data. +- **Uniform tiles**: tiled point cloud outputs (ground classification, normalization) vary in size + with the density, from 500 m down to 100 m, and the next tool processes them best as they are, + since each one fits in memory. To deliver them as uniform tiles, for example for GIS or to match + a tile index, run [Tile LiDAR Data](https://beratool.github.io/beratools/pc2products/user/lidar_tile/) on the + output folder once the chain of tools is done. Every tile size divides the 500 m blocks, so the + outputs combine into exact 500 m (or 1 km) tiles; the points are streamed, using little memory, + but each is read and written once more: + + ```bash + bt tile --in_las_folder Classified_PC --out_folder Classified_PC_500m --tile_size 500 --buffer 0 + ``` + + The raster tools don't need this: they also write one merged `Merged_*.tif`. + +[How the LiDAR tools tile a point cloud](docs/files/technical/lidar_density_tiling.md) +explains the tiling with diagrams, and +[How all the tools behave](https://beratool.github.io/beratools/pc2products/technical/tool_behaviour/) has the +details of tiling, workers and progress. + +## Raster2Products Tools + +The **Raster2Products** category makes rasters from other rasters, such as a DTM from +[Generate DTM from LiDAR Data](https://beratool.github.io/beratools/pc2products/user/dtm/). The tools run in +Python and need no R; they read large rasters in tiles and process each tile in parallel. + +| Tool | `bt` subcommand | +|------|-----------------| +| [Normalized DTM from DTM Raster](https://beratool.github.io/beratools/raster2products/user/ndtm_fr_dtmraster/) | `ndtm_fr_dtmraster` | + +```bash +$ bt ndtm_fr_dtmraster --in_dtm Raster_Output/Merged_TIN_DTM.tif --out_folder NDTM --Smooth_by median --Min_ws 3 +$ bt ndtm_fr_dtmraster --in_dtm Raster_Output --out_folder NDTM --Smooth_by median --Min_ws 3 # its DTM tiles, one output each +``` + ## Pipelines The **Pipeline** tab, next to **Tool history** in the GUI, chains tools into steps that run one after diff --git a/beratools/__init__.py b/beratools/__init__.py index 4bf58e8..694a250 100644 --- a/beratools/__init__.py +++ b/beratools/__init__.py @@ -1,6 +1,9 @@ __author__ = """Applied Geospatial Research Group""" __email__ = 'appliedgrg@gmail.com' -__version__ = '0.5.3' +# The one place the version is set: the packages, the GUI's About box and each module's +# requires_frame check read it. Bump it for each release (see the maintainer guide), and set +# "version" in every module's tools.json to the same (tests/test_registry.py checks it). +__version__ = "0.7.0" __license__ = "GPL-3.0-or-later" __copyright__ = "Copyright (c) AppliedGRG" __status__ = "Pre-Alpha" diff --git a/beratools/cli/entry.py b/beratools/cli/entry.py index 31dd3d4..6205e94 100644 --- a/beratools/cli/entry.py +++ b/beratools/cli/entry.py @@ -3,38 +3,26 @@ from __future__ import annotations import argparse -import json from pathlib import Path from typing import Any -from beratools.utility.tool_args import CallMode +from beratools.utility.env_checks import put_conda_dlls_on_path +# Before any tool imports numpy: the environment's DLL folders go first on PATH, for a start +# without activating it (e.g. from an IDE) +put_conda_dlls_on_path() -TOOL_ALIASES = { - "check_line": "check_seed_line", - "vertex_opt": "vertex_optimization", - "centerline": "centerline", - "footprint_abs": "canopy_footprint_absolute", - "footprint_rel": "line_footprint_relative", - "footprint_grd": "ground_footprint", -} +from beratools.core.registry import get_registry, tool_function # noqa: E402 +from beratools.utility.tool_args import CallMode, to_bool # noqa: E402 -def _assets_json_path() -> Path: - return Path(__file__).resolve().parents[1] / "gui" / "assets" / "beratools.json" +def tool_aliases() -> dict[str, str]: + """{cli_name: tool_api} for every tool of the loaded modules.""" + return get_registry().cli_names() def _load_tools_config() -> dict[str, dict[str, Any]]: - with open(_assets_json_path(), "r", encoding="utf-8") as f: - data = json.load(f) - - by_api: dict[str, dict[str, Any]] = {} - for toolbox in data.get("toolbox", []): - for tool in toolbox.get("tools", []): - api = tool.get("tool_api") - if api: - by_api[api] = tool - return by_api + return get_registry().by_api() def _parse_subtype(value: Any) -> list[str]: @@ -46,15 +34,10 @@ def _parse_subtype(value: Any) -> list[str]: def _to_bool(value: Any) -> bool: - if isinstance(value, bool): - return value - if isinstance(value, str): - lowered = value.strip().lower() - if lowered in {"true", "1", "yes", "y", "on"}: - return True - if lowered in {"false", "0", "no", "n", "off"}: - return False - raise argparse.ArgumentTypeError(f"Invalid boolean value: {value!r}") + try: + return to_bool(value, strict=True) + except ValueError as exc: + raise argparse.ArgumentTypeError(str(exc)) from exc def _coerce_value(value: Any, subtype: str) -> Any: @@ -157,7 +140,7 @@ def _build_parser(prog: str, tools_cfg: dict[str, dict[str, Any]]) -> argparse.A list_parser = subparsers.add_parser("list-tools", help="List available short tool commands") list_parser.set_defaults(handler=lambda _args: print_tool_list()) - for short_name, tool_api in TOOL_ALIASES.items(): + for short_name, tool_api in tool_aliases().items(): tool_cfg = tools_cfg.get(tool_api) if tool_cfg is None: continue @@ -171,31 +154,7 @@ def _build_parser(prog: str, tools_cfg: dict[str, dict[str, Any]]) -> argparse.A def _resolve_tool_function(tool_api: str): - if tool_api == "check_seed_line": - from beratools.tools.check_seed_line import check_seed_line - - return check_seed_line - if tool_api == "vertex_optimization": - from beratools.tools.vertex_optimization import vertex_optimization - - return vertex_optimization - if tool_api == "centerline": - from beratools.tools.centerline import centerline - - return centerline - if tool_api == "canopy_footprint_absolute": - from beratools.tools.canopy_footprint_absolute import canopy_footprint_abs - - return canopy_footprint_abs - if tool_api == "line_footprint_relative": - from beratools.tools.line_footprint_relative import line_footprint_relative - - return line_footprint_relative - if tool_api == "ground_footprint": - from beratools.tools.ground_footprint import ground_footprint - - return ground_footprint - raise ValueError(f"Unsupported tool_api: {tool_api}") + return tool_function(tool_api) def run_tool_command(args: argparse.Namespace) -> int: @@ -223,7 +182,7 @@ def launch_gui() -> int: def print_tool_list() -> int: print("Available tools:") - for short_name, tool_api in TOOL_ALIASES.items(): + for short_name, tool_api in tool_aliases().items(): print(f"- {short_name} ({tool_api})") return 0 @@ -250,7 +209,7 @@ def run(argv: list[str] | None = None, prog_name: str | None = None) -> int: if not argv: return print_basic_info(prog) - if len(argv) == 1 and argv[0] in TOOL_ALIASES: + if len(argv) == 1 and argv[0] in tool_aliases(): subparser = _get_subparser(parser, argv[0]) if subparser is not None: subparser.print_help() diff --git a/beratools/core/algo_astar.py b/beratools/core/algo_astar.py index 93595dc..5531551 100644 --- a/beratools/core/algo_astar.py +++ b/beratools/core/algo_astar.py @@ -1,541 +1,20 @@ -"""Reusable A* path and corridor algorithms for centerline workflows.""" +""" +Deprecated: moved to beratools.modules.mapping. -from __future__ import annotations +Kept so old imports keep working, with a DeprecationWarning, until it is removed. +""" -import heapq -import math -from dataclasses import dataclass -from itertools import count -from typing import Iterable +import sys +import warnings -import numpy as np -import rasterio -import logging +from beratools.modules.mapping import algo_astar as _moved -from rasterio.features import geometry_mask -from scipy import ndimage -from shapely.geometry import LineString -import shapely.ops as sh_ops -import shapely.geometry as sh_geom -import beratools.core.algo_common as algo_common - -LOGGER_NAME = "centerline" -logger = logging.getLogger(LOGGER_NAME) - - - -SQRT2 = math.sqrt(2.0) -ASTAR_LINE_BIAS = 0.001 -DEFAULT_CORRIDOR_LINE_BIAS_WEIGHT = 0.1 -DEFAULT_CORRIDOR_DISTANCE_PENALTY_WEIGHT = 0.2 - -NEIGHBORS: tuple[tuple[int, int], ...] = ( - (1, 0), - (0, -1), - (-1, 0), - (0, 1), - (1, -1), - (1, 1), - (-1, -1), - (-1, 1), +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" LineString | None: - """Find an 8-neighbor A* LCP, tie-broken toward the seed-line direction.""" - - if input_line is None or input_line.is_empty or len(input_line.coords) < 2: - logger.info(cid+f"Input line is empty or too short: {input_line}") - return None - - x1, y1 = input_line.coords[0] - x2, y2 = input_line.coords[-1] - costs, walkable = _prepare_lcp_costs(cost_arr, meta.get("nodata")) - rows, cols = costs.shape - transformer = rasterio.transform.AffineTransformer(meta["transform"]) - start_rc = rasterio.transform.rowcol(meta["transform"], x1, y1) - end_rc = rasterio.transform.rowcol(meta["transform"], x2, y2) - if not walkable[start_rc]: - start_xy_pt,start_rc_fixed=nearest_valid_location_on_line(cost_arr, meta["transform"], input_line, - from_start=True,step=meta["transform"].a, - max_search=10.0) - if start_rc_fixed is None: - start_rc_fixed = nearest_valid_cell(cost_arr, start_rc) - if start_rc_fixed is None: - logger.info(cid+f"Start point is not traversable: {start_rc}") - return None - else: - sx,sy=rasterio.transform.xy(meta["transform"], start_rc_fixed[0], start_rc_fixed[-1]) - start_xy_pt =sh_geom.Point(sx,sy) - - ds=input_line.project(start_xy_pt) - start_connector=sh_ops.substring(input_line,0,ds) - logger.warning( - cid + - f" start_connector_type={type(start_connector).__name__ if start_connector is not None else None}" - ) - start_xy=start_xy_pt.coords[0] - logger.warning( - cid + - f" moved start {start_rc}->{start_rc_fixed}" - ) - else: - start_rc_fixed = start_rc - start_connector=None - start_xy = (x1, y1) - if not walkable[end_rc]: - end_xy_pt,end_rc_fixed=nearest_valid_location_on_line(cost_arr, meta["transform"], input_line, - from_start=False,step=meta["transform"].a, - max_search=10.0) - if end_rc_fixed is None: - end_rc_fixed= nearest_valid_cell(cost_arr, end_rc) - if end_rc_fixed is None: - logger.info(cid+f"End point is not traversable: {end_rc}") - return None - else: - ex,ey=rasterio.transform.xy(meta["transform"], end_rc_fixed[0], end_rc_fixed[-1]) - end_xy_pt =sh_geom.Point(ex,ey) - de = input_line.project(end_xy_pt) - end_connector = sh_ops.substring(input_line, de, input_line.length) - logger.warning( - cid + - f" end_connector_type={type(end_connector).__name__ if end_connector is not None else None}" - ) - end_xy = end_xy_pt.coords[0] - logger.warning( - cid + - f" moved end {end_rc}->{end_rc_fixed}" - ) - else: - end_rc_fixed = end_rc - end_xy = (x2, y2) - end_connector = None - - start = _clamp_row_col(start_rc_fixed, rows, cols) - end = _clamp_row_col(end_rc_fixed, rows, cols) - if not walkable[start] or not walkable[end]: - logger.info(cid+ - f"Start or end point is not traversable: {start_rc_fixed} or {end_rc_fixed}") - return None - - min_cost = float(costs[walkable].min()) if np.any(walkable) else 0.0 - tie_scores = np.full((rows, cols), math.inf, dtype="float64") - g_scores = np.full((rows, cols), math.inf, dtype="float64") - came_from: dict[tuple[int, int], tuple[int, int] | None] = {start: None} - closed: set[tuple[int, int]] = set() - sequence = count() - heap: list[tuple] = [] - - g_scores[start] = 0.0 - tie_scores[start] = 0.0 - heapq.heappush(heap, _lcp_queue_entry(start, end, start, 0.0, 0.0, min_cost, next(sequence))) - - while heap: - *_, current = heapq.heappop(heap) - if current in closed: - continue - if current == end: - lcp = _path_to_linestring(_reconstruct_path(came_from, end), transformer, start_xy, end_xy) - segments = [] - if start_connector is not None: - segments.append(start_connector) - - segments.append(lcp) - - if end_connector is not None: - segments.append(end_connector) - if len(segments) == 1: - return segments[0] - return algo_common._safe_linemerge(sh_geom.MultiLineString(segments)) - - closed.add(current) - - for neighbor in _neighbors(current, rows, cols, walkable): - if neighbor in closed: - continue - new_g = g_scores[current] + _lcp_edge_cost(costs, current, neighbor) - new_tie = _line_bias_score(neighbor, start, end) - current_g = g_scores[neighbor] - current_tie = tie_scores[neighbor] - improved = new_g < current_g - 1e-6 - tied_better = abs(new_g - current_g) <= 1e-6 and new_tie < current_tie - if not improved and not tied_better: - continue - g_scores[neighbor] = new_g - tie_scores[neighbor] = new_tie - came_from[neighbor] = current - heapq.heappush( - heap, - _lcp_queue_entry(neighbor, end, start, new_g, new_tie, min_cost, next(sequence)), - ) - logger.info(cid+f'No path found between {start_rc_fixed} and {end_rc_fixed} using A* LCP.') - return None - - -def astar_accumulation_corridor_raster( - cost_arr, - meta: dict, - lc_path: LineString, - *, - corridor_threshold: float, - line_bias_weight: float = DEFAULT_CORRIDOR_LINE_BIAS_WEIGHT, - distance_penalty_weight: float = DEFAULT_CORRIDOR_DISTANCE_PENALTY_WEIGHT, -) -> tuple[np.ma.MaskedArray, dict[str, object]]: - """Build an A* accumulation corridor raster using BERA's 0-inside/1-outside convention.""" - - if lc_path is None or lc_path.is_empty or len(lc_path.coords) < 2: - raise RuntimeError("A* corridor requires a valid least-cost path") - - cost = _prepare_corridor_cost_surface(cost_arr, meta) - rows, cols = cost.shape - transform = meta["transform"] - transformer = rasterio.transform.AffineTransformer(transform) - start_xy = lc_path.coords[0] - end_xy = lc_path.coords[-1] - source = _clamp_row_col(transformer.rowcol(*start_xy), rows, cols) - destination = _clamp_row_col(transformer.rowcol(*end_xy), rows, cols) - if not np.isfinite(cost[source]): - _, source = nearest_valid_location_on_line(cost_arr, meta["transform"], lc_path, from_start=True,step=meta['transform'].a) - - if not np.isfinite(cost[destination]): - _, destination = nearest_valid_location_on_line(cost_arr, meta["transform"], lc_path, from_start=False,step=meta['transform'].a) - sampling = _raster_sampling(transform) - - forward = _astar_mcp_geometric_accumulation( - cost, - source, - destination, - sampling=sampling, - line_bias_weight=line_bias_weight, - ) - reverse = _astar_mcp_geometric_accumulation( - cost, - destination, - source, - sampling=sampling, - line_bias_weight=line_bias_weight, - ) - - valid = forward.closed & reverse.closed - score_data = forward.g_scores + reverse.g_scores - forward.best_cost - if distance_penalty_weight > 0.0: - astar_path = _path_to_linestring(forward.path, transformer, start_xy, end_xy) - distance_to_path = _distance_raster_to_line(astar_path, meta, cost.shape) - score_data = score_data + distance_to_path * distance_penalty_weight - - score = np.ma.masked_invalid(score_data) - score = np.ma.array(score, mask=np.ma.getmaskarray(score) | ~valid) - inside = (~np.ma.getmaskarray(score)) & np.asarray(score.filled(np.inf) < corridor_threshold, dtype=bool) - corridor = np.ma.where(inside, 0.0, 1.0) - corridor = np.ma.array(corridor, mask=np.ma.getmaskarray(score)) - - details = { - "corridor_threshold": float(corridor_threshold), - "astar_line_bias_weight": float(line_bias_weight), - "astar_distance_penalty_weight": float(distance_penalty_weight), - "astar_best_cost": float(forward.best_cost), - "inside_cells": int(np.count_nonzero(inside)), - "inside_area": float(np.count_nonzero(inside) * _cell_area(transform)), - "forward_closed_cells": int(np.count_nonzero(forward.closed)), - "reverse_closed_cells": int(np.count_nonzero(reverse.closed)), - "both_closed_cells": int(np.count_nonzero(valid)), - "astar_path_vertices": int(len(forward.path)), - } - return corridor, details - - -def _prepare_lcp_costs(cost_arr, nodata) -> tuple[np.ndarray, np.ndarray]: - array = np.ma.asarray(cost_arr) - if array.ndim > 2: - array = np.ma.squeeze(array, axis=0) - costs = np.asarray(array.filled(np.nan), dtype="float64") - walkable = np.isfinite(costs) & (costs > 0.0) - if nodata is not None: - walkable &= costs != float(nodata) - return costs, walkable - - -def _prepare_corridor_cost_surface(cost_arr, meta: dict) -> np.ndarray: - arr = np.ma.asarray(cost_arr) - if arr.ndim > 2: - arr = np.ma.squeeze(arr, axis=0) - cost = np.asarray(arr.filled(np.inf), dtype="float64") - nodata = meta.get("nodata") - if nodata is not None: - cost[cost == float(nodata)] = np.inf - cost[~np.isfinite(cost)] = np.inf - cost[cost <= 0.0] = np.inf - return cost - - -def _astar_mcp_geometric_accumulation( - cost: np.ndarray, - source: tuple[int, int], - destination: tuple[int, int], - *, - sampling: tuple[float, float], - line_bias_weight: float, -) -> AStarAccumulation: - if not np.isfinite(cost[source]) or not np.isfinite(cost[destination]): - raise RuntimeError("A* source or destination is not traversable") - - rows, cols = cost.shape - walkable = np.isfinite(cost) & (cost > 0.0) - min_cost = float(cost[walkable].min()) if np.any(walkable) else 0.0 - g_scores = np.full(cost.shape, math.inf, dtype="float64") - tie_scores = np.full(cost.shape, math.inf, dtype="float64") - came_from: dict[tuple[int, int], tuple[int, int] | None] = {source: None} - closed_nodes: set[tuple[int, int]] = set() - closed = np.zeros(cost.shape, dtype=bool) - sequence = count() - heap: list[tuple[float, float, float, int, tuple[int, int]]] = [] - - g_scores[source] = 0.0 - tie_scores[source] = 0.0 - destination_path = None - destination_cost = None - heapq.heappush( - heap, - _corridor_queue_entry( - source, - destination, - source, - 0.0, - 0.0, - min_cost, - sampling, - line_bias_weight, - next(sequence), - ), - ) - - while heap: - *_, current = heapq.heappop(heap) - if current in closed_nodes: - continue - if current == destination and destination_path is None: - destination_path = _reconstruct_path(came_from, destination) - destination_cost = float(g_scores[destination]) - closed_nodes.add(current) - closed[current] = True - - for neighbor in _neighbors(current, rows, cols, walkable): - if neighbor in closed_nodes: - continue - new_g = g_scores[current] + _geometric_edge_cost(cost, current, neighbor, sampling) - new_tie = _line_bias_score(neighbor, source, destination) - improved = new_g < g_scores[neighbor] - 1e-9 - tied_better = abs(new_g - g_scores[neighbor]) <= 1e-9 and new_tie < tie_scores[neighbor] - if not improved and not tied_better: - continue - g_scores[neighbor] = new_g - tie_scores[neighbor] = new_tie - came_from[neighbor] = current - heapq.heappush( - heap, - _corridor_queue_entry( - neighbor, - destination, - source, - new_g, - new_tie, - min_cost, - sampling, - line_bias_weight, - next(sequence), - ), - ) - - if destination_path is None or destination_cost is None: - raise RuntimeError("A* path did not reach destination") - - return AStarAccumulation( - path=destination_path, - best_cost=destination_cost, - g_scores=g_scores, - closed=closed, - ) - - -def _neighbors(node: tuple[int, int], rows: int, cols: int, walkable: np.ndarray) -> Iterable[tuple[int, int]]: - row, col = node - for d_row, d_col in NEIGHBORS: - neighbor = row + d_row, col + d_col - if 0 <= neighbor[0] < rows and 0 <= neighbor[1] < cols and walkable[neighbor]: - yield neighbor - - -def _lcp_edge_cost(costs: np.ndarray, current: tuple[int, int], neighbor: tuple[int, int]) -> float: - base = (float(costs[current]) + float(costs[neighbor])) / 2.0 - return base * (SQRT2 if current[0] != neighbor[0] and current[1] != neighbor[1] else 1.0) - - -def _geometric_edge_cost( - cost: np.ndarray, - current: tuple[int, int], - neighbor: tuple[int, int], - sampling: tuple[float, float], -) -> float: - d_row = neighbor[0] - current[0] - d_col = neighbor[1] - current[1] - offset_length = math.hypot(d_row * sampling[0], d_col * sampling[1]) - return offset_length * 0.5 * (float(cost[current]) + float(cost[neighbor])) - - -def _lcp_queue_entry( - node: tuple[int, int], - end: tuple[int, int], - start: tuple[int, int], - g_score: float, - tie_score: float, - min_cost: float, - sequence: int, -) -> tuple: - heuristic = _octile(node, end) * min_cost - priority = g_score + heuristic + tie_score * ASTAR_LINE_BIAS - return priority, g_score + heuristic, tie_score, heuristic, sequence, node - - -def _corridor_queue_entry( - node: tuple[int, int], - destination: tuple[int, int], - source: tuple[int, int], - g_score: float, - tie_score: float, - min_cost: float, - sampling: tuple[float, float], - line_bias_weight: float, - sequence: int, -) -> tuple[float, float, float, int, tuple[int, int]]: - heuristic = _euclidean_grid_distance(node, destination, sampling) * min_cost - priority = g_score + heuristic + tie_score * line_bias_weight - return priority, heuristic, _line_bias_score(node, source, destination), sequence, node - - -def _octile(a: tuple[int, int], b: tuple[int, int]) -> float: - d_row = abs(a[0] - b[0]) - d_col = abs(a[1] - b[1]) - return d_row + d_col + (SQRT2 - 2.0) * min(d_row, d_col) - - -def _euclidean_grid_distance(a: tuple[int, int], b: tuple[int, int], sampling: tuple[float, float]) -> float: - return math.hypot((a[0] - b[0]) * sampling[0], (a[1] - b[1]) * sampling[1]) - - -def _line_bias_score(node: tuple[int, int], start: tuple[int, int], end: tuple[int, int]) -> float: - dx1 = node[1] - end[1] - dy1 = node[0] - end[0] - dx2 = start[1] - end[1] - dy2 = start[0] - end[0] - return abs(dx1 * dy2 - dx2 * dy1) / max(1.0, math.hypot(dx2, dy2)) - - -def _reconstruct_path( - came_from: dict[tuple[int, int], tuple[int, int] | None], end: tuple[int, int] -) -> list[tuple[int, int]]: - path = [end] - current = end - while came_from[current] is not None: - current = came_from[current] - path.append(current) - path.reverse() - return path - - -def _path_to_linestring(path: list[tuple[int, int]], transformer, start_xy, end_xy) -> LineString | None: - if len(path) < 2: - return None - points = [transformer.xy(row, col) for row, col in path] - points[0] = (start_xy[0], start_xy[1]) - points[-1] = (end_xy[0], end_xy[1]) - return LineString(points) - - -def _distance_raster_to_line(line: LineString, meta: dict, shape: tuple[int, int]) -> np.ndarray: - transform = meta["transform"] - cell_size = max(abs(float(transform.a)), abs(float(transform.e))) - path_mask = geometry_mask( - [line.buffer(cell_size * 0.5)], - out_shape=shape, - transform=transform, - invert=True, - all_touched=True, - ) - return ndimage.distance_transform_edt(~path_mask, sampling=_raster_sampling(transform)) - - -def _raster_sampling(transform) -> tuple[float, float]: - return (abs(float(transform.e)), abs(float(transform.a))) - - -def _cell_area(transform) -> float: - return abs(float(transform.a) * float(transform.e)) - - -def _clamp_row_col(row_col: tuple[int, int], rows: int, cols: int) -> tuple[int, int]: - return max(0, min(int(row_col[0]), rows - 1)), max(0, min(int(row_col[1]), cols - 1)) +sys.modules[__name__] = _moved diff --git a/beratools/core/algo_canopy_footprint_absolute.py b/beratools/core/algo_canopy_footprint_absolute.py index 5b51294..8a3159d 100644 --- a/beratools/core/algo_canopy_footprint_absolute.py +++ b/beratools/core/algo_canopy_footprint_absolute.py @@ -1,1008 +1,20 @@ """ -Copyright (C) 2025 Applied Geospatial Research Group. +Deprecated: moved to beratools.modules.mapping. -This script is licensed under the GNU General Public License v3.0. -See for full license details. - -Author: Richard Zeng, Maverick Fong - -Description: - This script is part of the BERA Tools. - Webpage: https://github.com/BERATool/beratools - - The purpose of this script is to provide main interface for adaptive relative canopy footprint tool. - The tool is used to generate the canopy footprint of a line based on adaptive relative threshold. +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -import math -from dataclasses import dataclass, field -from enum import Enum - -import geopandas as gpd -import numpy as np -import pandas as pd -import rasterio.features as ras_feat -from rasterio.transform import rowcol -import shapely -import shapely.geometry as sh_geom -import shapely.ops as sh_ops -from skimage.graph import MCP_Flexible - -import beratools.core.algo_common as algo_common -import beratools.core.algo_cost as algo_cost -import beratools.core.algo_geometry as algo_geometry -import beratools.core.constants as bt_const -import beratools.core.tool_base as bt_base -import beratools.utility.spatial_common as sp_common -from beratools.utility.tool_args import CallMode - - -@dataclass -class CanopyFootprintRequest: - """Common request contract for canopy footprint runs.""" - - in_line: str - in_chm: str - out_footprint: str - max_ln_width: float = 32.0 - processes: int = 0 - call_mode: CallMode | str = CallMode.CLI - log_level: str = "INFO" - corridor_thresh: float | None = None - exp_shk_cell: int | None = None - tree_radius: float | None = None - max_line_dist: float | None = None - canopy_avoidance: float | None = None - exponent: float | None = None - canopy_thresh_percentage: float | None = None - simplify_footprint_polygon: bool = True - footprint_simplify_length: float = 0.5 - smooth_footprint_polygon: bool = False - footprint_polygon_smooth_iterations: int = 1 - merge_by_original_line: bool = False - - -@dataclass -class CanopyFootprintResult: - """Common result contract for canopy footprint runs.""" - - footprints_gdf: gpd.GeoDataFrame | None = None - aux_layers: dict[str, gpd.GeoDataFrame] = field(default_factory=dict) - stats: dict[str, int] = field(default_factory=dict) - messages: list[str] = field(default_factory=list) - - -def cast_request_types(request: CanopyFootprintRequest) -> CanopyFootprintRequest: - """Cast optional numeric values to expected types.""" - - request.max_ln_width = float(request.max_ln_width) - request.processes = int(request.processes) - - if request.corridor_thresh is not None: - request.corridor_thresh = float(request.corridor_thresh) - if request.exp_shk_cell is not None: - request.exp_shk_cell = int(request.exp_shk_cell) - if request.tree_radius is not None: - request.tree_radius = float(request.tree_radius) - if request.max_line_dist is not None: - request.max_line_dist = float(request.max_line_dist) - if request.canopy_avoidance is not None: - request.canopy_avoidance = float(request.canopy_avoidance) - if request.exponent is not None: - request.exponent = float(request.exponent) - if request.canopy_thresh_percentage is not None: - request.canopy_thresh_percentage = float(request.canopy_thresh_percentage) - request.simplify_footprint_polygon = _to_bool(request.simplify_footprint_polygon) - request.footprint_simplify_length = float(request.footprint_simplify_length) - request.smooth_footprint_polygon = _to_bool(request.smooth_footprint_polygon) - request.footprint_polygon_smooth_iterations = int(request.footprint_polygon_smooth_iterations) - request.merge_by_original_line = _to_bool(request.merge_by_original_line) - - return request - - -def _to_bool(value): - if isinstance(value, bool): - return value - if isinstance(value, str): - lowered = value.strip().lower() - if lowered in {"true", "1", "yes", "y", "on"}: - return True - if lowered in {"false", "0", "no", "n", "off"}: - return False - return bool(value) - - -def copy_line_ids(footprint, line): - """Carry the source line's OLnFID/OLnSEG onto its footprint, so footprints can be merged per line.""" - if footprint is None or line is None: - return footprint - for field in ("OLnFID", "OLnSEG"): - if field in line.columns: - footprint[field] = line[field].iloc[0] - return footprint - - -def merge_footprints_by_original_line(footprints_gdf, printer=print): - """Dissolve footprints sharing an OLnFID into one, as the centerline tool merges lines.""" - if footprints_gdf is None or footprints_gdf.empty: - return footprints_gdf - if "OLnFID" not in footprints_gdf.columns: - printer("[Warning]: OLnFID not found in input lines; footprints are not merged.") - return footprints_gdf - merged = footprints_gdf.dissolve(by="OLnFID", as_index=False) - merged["OLnSEG"] = -1 - return merged - - -def process_footprint_polygon_gdf( - footprint_gdf, - *, - simplify_footprint_polygon=True, - footprint_simplify_length=0.5, - smooth_footprint_polygon=False, - footprint_polygon_smooth_iterations=1, -): - if footprint_gdf is None or footprint_gdf.empty: - return footprint_gdf - - processed = footprint_gdf.copy() - processed.geometry = processed.geometry.apply( - lambda geom: algo_geometry.process_corridor_polygon( - geom, - simplify=simplify_footprint_polygon, - simplify_length=footprint_simplify_length, - smooth=smooth_footprint_polygon, - smooth_iterations=footprint_polygon_smooth_iterations, - ) - ) - return processed - - -def save_main_footprint( - result: CanopyFootprintResult, - out_footprint: str, - rejected_layer_name: str, - default_layer_name: str = "canopy_footprint", - printer=print, -) -> bool: - """Save main footprint output and return whether save succeeded.""" - - if result.footprints_gdf is None or result.footprints_gdf.empty: - printer("Warning: No footprints generated. Output file not written.") - return False - - out_file, out_layer = sp_common.decode_file_layer(out_footprint) - layer_name = out_layer if out_layer else default_layer_name - - results = gpd.GeoDataFrame(result.footprints_gdf).reset_index(drop=True) - results = algo_common.clean_geometries( - results, - stage="output", - out_file=out_file, - layer=rejected_layer_name, - ) - - if results is None or results.empty: - printer("Warning: No valid footprints generated after cleaning. Output file not written.") - return False - - results.to_file(out_file, layer=layer_name) - printer(f"Saved footprint to {out_file}, layer: {layer_name}") - return True - - -def save_aux_layers(result: CanopyFootprintResult, out_footprint: str, printer=print) -> list[str]: - """Save optional auxiliary layers and return saved layer names.""" - - saved_layers = [] - if not result.aux_layers: - return saved_layers - - out_file, _ = sp_common.decode_file_layer(out_footprint) - out_file_aux = algo_common.get_aux_path(out_file) - - for layer_name, gdf in result.aux_layers.items(): - if gdf is None or not hasattr(gdf, "empty") or gdf.empty: - continue - gdf.to_file(out_file_aux, layer=layer_name) - saved_layers.append(layer_name) - printer(f"Saved auxiliary layer '{layer_name}' to {out_file_aux}") - - return saved_layers - - -class Side(Enum): - """Constants for left and right side.""" - - left = "left" - right = "right" - - -@dataclass(frozen=True) -class CutParams: - """Cut distance and cut height for one side.""" - - cut_dist: float - cut_height: float - - -@dataclass(frozen=True) -class SideRasterInputs: - """Inputs required to compute side-specific canopy cost raster.""" - - line_buffer: object - cut_dist: float - canopy_height_thresh: float - - -@dataclass(frozen=True) -class SideFootprintResult: - """Result wrapper for side footprint generation.""" - - footprint_gdf: gpd.GeoDataFrame | None - reason: str | None = None - - -class FootprintCanopyAdaptive: - """Adaptive relative canopy footprint class.""" - - def __init__( - self, - in_geom, - in_chm, - max_line_width=32.0, - tree_radius=1.5, - max_line_dist=1.5, - canopy_avoidance=0.0, - exponent=1.0, - canopy_thresh_percentage=50.0, - exp_shk_cell=0, - simplify_footprint_polygon=True, - footprint_simplify_length=0.5, - smooth_footprint_polygon=False, - footprint_polygon_smooth_iterations=1, - ): - in_file, in_layer = sp_common.decode_file_layer(in_geom) - data = algo_common.read_geospatial_file(in_file, layer=in_layer) - if data is None: - data = gpd.GeoDataFrame() - self.lines = [] - self.cut_params = [] - - for idx in data.index: - line = LineInfo( - data.loc[[idx]].copy(), - in_chm, - max_line_width=max_line_width, - tree_radius=tree_radius, - max_line_dist=max_line_dist, - canopy_avoidance=canopy_avoidance, - exponent=exponent, - canopy_thresh_percentage=canopy_thresh_percentage, - exp_shk_cell=exp_shk_cell, - simplify_footprint_polygon=simplify_footprint_polygon, - footprint_simplify_length=footprint_simplify_length, - smooth_footprint_polygon=smooth_footprint_polygon, - footprint_polygon_smooth_iterations=footprint_polygon_smooth_iterations, - ) - self.lines.append(line) - - def compute(self, processes, call_mode=CallMode.CLI): - result = bt_base.execute_multiprocessing( - algo_common.process_single_item, - self.lines, - "Canopy Footprint", - processes, - call_mode, - ) - - footprint_list = [] - percentile = [] - cut_params = [] - try: - for item in result: - if item.footprint is not None: - footprint_list.append(item.footprint) - else: - print("Footprint is None for one of the lines.") - - if item.lines_percentile is not None: - percentile.append(item.lines_percentile) - else: - print("lines_percentile is None for one of the lines.") - - cut_params.append( - { - "left_cut_dist": float(item.left_cut_dist), - "left_cut_height": float(item.left_cut_height), - "right_cut_dist": float(item.right_cut_dist), - "right_cut_height": float(item.right_cut_height), - } - ) - - self.footprints = pd.concat(footprint_list, ignore_index=True) if footprint_list else None - self.lines_percentile = pd.concat(percentile, ignore_index=True) if percentile else None - self.cut_params = cut_params - - if self.footprints is None: - print("No valid footprints to save.") - if self.lines_percentile is None: - print("No valid lines_percentile to save.") - except Exception as e: - print(f"Error during processing: {e}") - - def save_footprint(self, out_footprint, layer=None): - if self.footprints is not None and isinstance(self.footprints, gpd.GeoDataFrame): - self.footprints = algo_common.clean_geometries( - self.footprints, - stage="output", - out_file=out_footprint, - layer="rejected_output_canopy_footprint_adaptive", - ) - self.footprints.to_file(out_footprint, layer=layer) - else: - print("No footprints to save (None or not a GeoDataFrame).") - - def save_line_percentile(self, out_percentile): - if self.lines_percentile is not None and isinstance(self.lines_percentile, gpd.GeoDataFrame): - self.lines_percentile.to_file(out_percentile) - else: - print("No lines_percentile to save (None or not a GeoDataFrame).") - - -class BufferRing: - """Buffer ring class.""" - - def __init__(self, ring_poly, side): - self.geometry = ring_poly - self.side = side - self.percentile = 0.5 - - -class LineInfo: - """Class to store line information.""" - - def __init__( - self, - line_gdf, - in_chm, - max_line_width=32.0, - tree_radius=1.5, - max_line_dist=1.5, - canopy_avoidance=0.0, - exponent=1.0, - canopy_thresh_percentage=50.0, - exp_shk_cell=0, - simplify_footprint_polygon=True, - footprint_simplify_length=0.5, - smooth_footprint_polygon=False, - footprint_polygon_smooth_iterations=1, - ): - self.line = line_gdf - self.in_chm = in_chm - self.line_simplified = self.line.geometry.simplify(tolerance=0.5, preserve_topology=True) - - self.buffer_rings = [] - - self.left_cut_height = np.nan - self.right_cut_height = np.nan - self.right_cut_dist = np.nan - self.left_cut_dist = np.nan - - self.canopy_thresh_percentage = canopy_thresh_percentage - self.canopy_avoidance = canopy_avoidance - self.exponent = exponent - self.exp_shk_cell = exp_shk_cell - self.simplify_footprint_polygon = _to_bool(simplify_footprint_polygon) - self.footprint_simplify_length = float(footprint_simplify_length) - self.smooth_footprint_polygon = _to_bool(smooth_footprint_polygon) - self.footprint_polygon_smooth_iterations = int(footprint_polygon_smooth_iterations) - self.max_line_width = max_line_width - self.max_line_dist = max_line_dist - self.tree_radius = tree_radius - - self.buffer_left = None - self.buffer_right = None - self.footprint = None - - self.lines_percentile = None - - def compute(self): - self.buffer_rings = self._build_rings_with_percentiles() - self.lines_percentile = self._build_lines_percentile() - - self.rate_of_change(self.get_percentile_array(Side.left), Side.left) - self.rate_of_change(self.get_percentile_array(Side.right), Side.right) - - self.prepare_line_buffer() - - fp_left = self.process_single_footprint(Side.left) - fp_right = self.process_single_footprint(Side.right) - - merged = self.merge_side_footprints(fp_left, fp_right) - if merged is None: - self.footprint = None - return - self.footprint = merged - self.footprint = process_footprint_polygon_gdf( - self.footprint, - simplify_footprint_polygon=self.simplify_footprint_polygon, - footprint_simplify_length=self.footprint_simplify_length, - smooth_footprint_polygon=self.smooth_footprint_polygon, - footprint_polygon_smooth_iterations=self.footprint_polygon_smooth_iterations, - ) - - # Transfer group value to footprint if present - if bt_const.BT_GROUP in self.line.columns: - self.footprint[bt_const.BT_GROUP] = self.line[bt_const.BT_GROUP].iloc[0] - copy_line_ids(self.footprint, self.line) - - def _build_rings_with_percentiles(self): - self.prepare_ring_buffer() - ring_list = [] - for item in self.buffer_rings: - ring = self.calc_ring_percentile(item) - if ring is not None: - ring_list.append(ring) - return ring_list - - def _build_lines_percentile(self): - percentile_records = [ - {"geometry": ring.geometry, "percentile": ring.percentile, "side": ring.side.value} - for ring in self.buffer_rings - ] - if not percentile_records: - return None - - lines_percentile = gpd.GeoDataFrame(percentile_records, geometry="geometry") - if self.line.crs: - lines_percentile = lines_percentile.set_crs(self.line.crs, allow_override=True) - return lines_percentile - - def merge_side_footprints(self, fp_left, fp_right): - if fp_left is None or fp_right is None: - print("One or both footprints are None in LineInfo.") - return None - - try: - fp_left.geometry = fp_left.geometry.buffer(0) - fp_right.geometry = fp_right.geometry.buffer(0) - - fp_combined = pd.concat([fp_left, fp_right], ignore_index=True) - if fp_combined.empty or not isinstance(fp_combined, gpd.GeoDataFrame): - print("Combined footprint is invalid or empty.") - return None - - fp_combined = fp_combined.dissolve() - fp_combined.geometry = fp_combined.geometry.buffer(-0.005) - return fp_combined - except Exception as e: - print(f"Error combining footprints: {e}") - return None - - def prepare_ring_buffer(self): - for ring_step, ring_max_dist, side in [(1, 15, Side.left), (-1, -15, Side.right)]: - ring_list = self.multi_ring_buffer(self.line_simplified, ring_step, ring_max_dist) - for ring_poly in ring_list: - self.buffer_rings.append(BufferRing(ring_poly, side)) - - def calc_ring_percentile(self, ring): - try: - line_buffer = ring.geometry - if line_buffer.is_empty or shapely.is_missing(line_buffer): - return None - if line_buffer.has_z: - line_buffer = sh_ops.transform(lambda x, y, z=None: (x, y), line_buffer) - - except Exception as e: - print(f"calc_ring_percentile: {e}") - return None - - try: - clipped_raster, _ = sp_common.clip_raster(self.in_chm, line_buffer, 0) - clipped_raster = np.squeeze(clipped_raster, axis=0) - - # mask all -9999 (nodata) value cells - masked_raster = np.ma.masked_where(clipped_raster == bt_const.BT_NODATA, clipped_raster) - filled_raster = np.ma.filled(masked_raster, np.nan) - - # Calculate the percentile - ring.percentile = np.nanpercentile(filled_raster, 50) - except Exception as e: - print(e) - print("Default values are used.") - - return ring - - def get_percentile_array(self, side): - return [ring.percentile for ring in self.buffer_rings if ring.side == side] - - def derive_cut_params(self, percentile_array): - # Since the x interval is 1 unit, the array 'diff' is the rate of change (slope) - diff = np.ediff1d(percentile_array) - cut_dist = len(percentile_array) / 5 - - median_percentile = np.nanmedian(percentile_array) - if not np.isnan(median_percentile): - cut_percentile = float(math.floor(median_percentile)) - else: - cut_percentile = 0.5 - - found = False - changes = 1.50 - rate_change = np.insert(diff, 0, 0) - # test the rate of change is > than 150% (1.5), if it is - # no result found then lower to 140% (1.4) until 110% (1.1) - while not found and changes >= 1.1: - for idx in range(0, len(rate_change) - 1): - if percentile_array[idx] >= 0.5: - if rate_change[idx] >= changes: - cut_dist = idx + 1 - cut_percentile = math.floor(percentile_array[idx]) - - if 0.5 >= cut_percentile: - if cut_dist > 5: - cut_percentile = 2 - # @<0.5 found and modified - elif 15 < cut_percentile: - if cut_dist > 4: - cut_percentile = 15.5 - found = True - # rate of change found - break - changes = changes - 0.1 - - # if still no result found, lower to 10% (1.1), - # if no result found then default is used - if not found: - if 0.5 >= median_percentile: - cut_dist = 4 - cut_percentile = 0.5 - elif 0.5 < median_percentile <= 5.0: - cut_dist = 4.5 - cut_percentile = math.floor(median_percentile) - elif 5.0 < median_percentile <= 10.0: - cut_dist = 5.5 - cut_percentile = math.floor(median_percentile) - elif 10.0 < median_percentile <= 15: - cut_dist = 6 - cut_percentile = math.floor(median_percentile) - elif 15 < median_percentile: - cut_dist = 5 - cut_percentile = 15.5 - - return CutParams(cut_dist=cut_dist, cut_height=float(cut_percentile)) - - def rate_of_change(self, percentile_array, side): - cut_params = self.derive_cut_params(percentile_array) - - if side == Side.right: - self.right_cut_dist = cut_params.cut_dist - self.right_cut_height = cut_params.cut_height - elif side == Side.left: - self.left_cut_dist = cut_params.cut_dist - self.left_cut_height = cut_params.cut_height - - def multi_ring_buffer(self, df, ring_step, ring_max_dist): - """ - Buffers an input DataFrames geometry with concentric rings. - - Compute with a distance between rings of ring_step and returns - a list of non overlapping buffers - """ - rings = [] - line = df.geometry.iloc[0] - for ring in np.arange(0, ring_max_dist, ring_step): - big_ring = line.buffer(ring_step + ring, single_sided=True, cap_style="flat") - small_ring = line.buffer(ring, single_sided=True, cap_style="flat") - the_ring = big_ring.difference(small_ring) - if not shapely.is_empty(the_ring) and not shapely.is_missing(the_ring) and the_ring.area > 0: - if isinstance(the_ring, (sh_geom.MultiPolygon, shapely.Polygon)): - rings.append(the_ring) - elif isinstance(the_ring, shapely.GeometryCollection): - for geom in the_ring.geoms: - if not isinstance(geom, shapely.LineString): - rings.append(geom) - - return rings - - def prepare_line_buffer(self): - self.buffer_left, self.buffer_right = self.build_line_side_buffers( - self.line.geometry.iloc[0], self.max_line_width - ) - - def build_line_side_buffers(self, line, max_line_width): - buffer_left_1 = line.buffer( - distance=max_line_width + 1, - cap_style=3, - single_sided=True, - ) - - buffer_left_2 = line.buffer( - distance=-1, - cap_style=3, - single_sided=True, - ) - - buffer_left = sh_ops.unary_union([buffer_left_1, buffer_left_2]) - - buffer_right_1 = line.buffer( - distance=-max_line_width - 1, - cap_style=3, - single_sided=True, - ) - buffer_right_2 = line.buffer(distance=1, cap_style=3, single_sided=True) - - buffer_right = sh_ops.unary_union([buffer_right_1, buffer_right_2]) - return buffer_left, buffer_right - - def _get_side_raster_inputs(self, side): - canopy_thresh_ratio = self.canopy_thresh_percentage / 100 - - if side == Side.left: - return SideRasterInputs( - line_buffer=self.buffer_left, - cut_dist=self.left_cut_dist, - canopy_height_thresh=float(self.left_cut_height * canopy_thresh_ratio), - ) - if side == Side.right: - return SideRasterInputs( - line_buffer=self.buffer_right, - cut_dist=self.right_cut_dist, - canopy_height_thresh=float(self.right_cut_height * canopy_thresh_ratio), - ) - raise ValueError(f"Unsupported side: {side}") - - def dyn_canopy_cost_raster(self, side): - side_inputs = self._get_side_raster_inputs(side) - canopy_height_thresh = side_inputs.canopy_height_thresh - if canopy_height_thresh <= 0: - canopy_height_thresh = 0.5 - - try: - clipped_raster, out_meta = sp_common.clip_raster(self.in_chm, side_inputs.line_buffer, 0) - negative_cost_clip, dyn_canopy_ndarray = algo_cost.cost_raster( - clipped_raster, - out_meta, - self.tree_radius, - canopy_height_thresh, - self.max_line_dist, - self.canopy_avoidance, - self.exponent, - ) - - return dyn_canopy_ndarray, negative_cost_clip, out_meta, side_inputs.cut_dist - - except Exception as e: - print(f"dyn_canopy_cost_raster: {e}") - return None - - def _extract_coords(self, feat): - """Extract coordinate list from a geometry (single or multi).""" - coords = [] - if hasattr(feat, "geoms"): - for geom in feat.geoms: - coords.extend(geom.coords) - else: - coords.extend(feat.coords) - return coords - - def process_single_footprint(self, side): - result = self.dyn_canopy_cost_raster(side) - if result is None: - return None - canopy_raster, cost_raster, in_meta, cut_dist = result - - if canopy_raster is None or cost_raster is None or in_meta is None or cut_dist is None: - return None - - if np.isnan(canopy_raster).all(): - print("Canopy raster empty") - return None - - if np.isnan(cost_raster).all(): - print("Cost raster empty") - return None - - in_transform = in_meta["transform"] - feat = self.line.geometry.iloc[0] - segment_list = self._extract_coords(feat) - - result = self.build_corridor_polygon( - canopy_raster, cost_raster, in_transform, cut_dist, feat, segment_list - ) - if result.reason is not None: - print(result.reason) - return result.footprint_gdf - - def build_corridor_polygon(self, canopy_raster, cost_raster, in_transform, cut_dist, feat, segment_list): - cell_size_x = in_transform[0] - cell_size_y = -in_transform[4] - - # Work out the corridor from both end of the centerline - try: - if len(cost_raster.shape) > 2: - cost_raster = np.squeeze(cost_raster, axis=0) - - algo_cost.remove_nan_from_array_refactor(cost_raster) - cost_raster[cost_raster == bt_const.BT_NODATA] = np.inf - - # generate 1m interval points along line - distances = np.arange(0, feat.length, 1) - multipoint_along_line = [feat.interpolate(d) for d in distances] - multipoint_along_line.append(sh_geom.Point(segment_list[-1])) - - # Rasterize points along line - rasterized_points = ras_feat.rasterize( - multipoint_along_line, - out_shape=cost_raster.shape, - transform=in_transform, - fill=0, - all_touched=True, - default_value=1, - ) - points_along_line = np.transpose(np.nonzero(rasterized_points)) - - # Find minimum cost paths through an N-d costs array. - mcp = MCP_Flexible(cost_raster, sampling=(cell_size_x, cell_size_y), fully_connected=True) - mcp_cost_surface, _ = mcp.find_costs(starts=points_along_line) - - # Generate corridor - corridor = np.ma.masked_invalid(mcp_cost_surface) - - # Calculate minimum value of corridor raster - corridor_min = float(np.ma.min(corridor)) if np.ma.min(corridor) is not None else 0.5 - - # normalize corridor raster by deducting corridor_min - corridor_norm = corridor - corridor_min - - # Set minimum as zero and save minimum file - corridor_threshold = cut_dist / cell_size_x - if corridor_threshold < 0: # if no threshold found, use default value - corridor_threshold = bt_const.FP_CORRIDOR_THRESHOLD / cell_size_x - - corridor_thresh = np.ma.where(corridor_norm >= corridor_threshold, 1.0, 0.0) - clean_raster = algo_common.morph_raster( - corridor_thresh, canopy_raster, self.exp_shk_cell, cell_size_x - ) - - # create mask for non-polygon area - mask = np.where(clean_raster == 1, True, False) - if clean_raster.dtype == np.int64: - clean_raster = clean_raster.astype(np.int32) - - # Process: ndarray to shapely Polygon - out_polygon = ras_feat.shapes(clean_raster, mask=mask, transform=in_transform) - - # create a shapely MultiPolygon - multi_polygon = [] - if out_polygon is not None: - try: - for poly, value in out_polygon: - multi_polygon.append(sh_geom.shape(poly)) - except TypeError as e: - return SideFootprintResult(None, f"Invalid polygon output: {e}") - - if not multi_polygon: - return SideFootprintResult(None, "No polygons generated from raster. Returning None.") - - poly = sh_geom.MultiPolygon(multi_polygon) - - # create GeoDataFrame directly from dictionary - footprint_gdf = gpd.GeoDataFrame( - {"corridor_thresh": [corridor_threshold], "geometry": [poly]}, - geometry="geometry", - ) - if self.line.crs: - footprint_gdf = footprint_gdf.set_crs(self.line.crs, allow_override=True) - - if footprint_gdf.empty or footprint_gdf.geometry.isnull().all(): - return SideFootprintResult(None, "Empty GeoDataFrame from process_single_footprint.") - - return SideFootprintResult(footprint_gdf) - - except Exception as e: - return SideFootprintResult(None, "Exception: {}".format(e)) - - -class FootprintCanopyAbsolute: - """Class to compute the footprint of a line based on absolute threshold.""" - - def __init__( - self, - line_seg, - in_chm, - corridor_thresh, - max_ln_width, - exp_shk_cell, - simplify_footprint_polygon=True, - footprint_simplify_length=0.5, - smooth_footprint_polygon=False, - footprint_polygon_smooth_iterations=1, - ): - self.line_seg = line_seg - self.in_chm = in_chm - self.corridor_thresh = corridor_thresh - self.max_ln_width = max_ln_width - self.exp_shk_cell = exp_shk_cell - self.simplify_footprint_polygon = _to_bool(simplify_footprint_polygon) - self.footprint_simplify_length = float(footprint_simplify_length) - self.smooth_footprint_polygon = _to_bool(smooth_footprint_polygon) - self.footprint_polygon_smooth_iterations = int(footprint_polygon_smooth_iterations) - - self.footprint = None - self.corridor_poly_gpd = None - self.centerline = None - - def compute(self): - """Generate line footprint.""" - - prep = self.prepare_inputs() - raster = self.compute_cost_surface(prep["feat"]) - - corridor_thresh = algo_common.corridor_raster( - raster["clip_cost"], - raster["out_meta"], - raster["source"], - raster["destination"], - (raster["cell_size_x"], raster["cell_size_y"]), - prep["corridor_thresh"], - ) - - clean_raster = algo_common.morph_raster( - corridor_thresh, - raster["clip_canopy"], - self.exp_shk_cell, - raster["cell_size_x"], - ) - self.footprint = self.build_candidate_polygon(clean_raster, raster["out_transform"]) - self.footprint = process_footprint_polygon_gdf( - self.footprint, - simplify_footprint_polygon=self.simplify_footprint_polygon, - footprint_simplify_length=self.footprint_simplify_length, - smooth_footprint_polygon=self.smooth_footprint_polygon, - footprint_polygon_smooth_iterations=self.footprint_polygon_smooth_iterations, - ) - copy_line_ids(self.footprint, self.line_seg) - self.postprocess_output( - corridor_thresh, - raster["out_transform"], - prep["line_gpd"], - prep["feat"], - self.exp_shk_cell, - ) - - def prepare_inputs(self): - corridor_thresh = self.corridor_thresh - try: - corridor_thresh = float(corridor_thresh) - if corridor_thresh < 0.0: - corridor_thresh = 3.0 - except ValueError: - corridor_thresh = 3.0 - except Exception: - corridor_thresh = 3.0 - - feat = self.line_seg.geometry[0] - return { - "line_gpd": self.line_seg, - "corridor_thresh": corridor_thresh, - "feat": feat, - } - - def compute_cost_surface(self, feat): - clip_cost, out_meta = sp_common.clip_raster(self.in_chm, feat, self.max_ln_width) - out_transform = out_meta["transform"] - cell_size_x = out_transform[0] - cell_size_y = -out_transform[4] - - clip_cost, clip_canopy = algo_cost.cost_raster(clip_cost, out_meta) - if len(clip_canopy.shape) > 2: - clip_canopy = np.squeeze(clip_canopy, axis=0) - - source = [rowcol(out_transform, feat.coords[0][0], feat.coords[0][1])] - destination = [rowcol(out_transform, feat.coords[-1][0], feat.coords[-1][1])] - - return { - "clip_cost": clip_cost, - "clip_canopy": clip_canopy, - "out_meta": out_meta, - "out_transform": out_transform, - "cell_size_x": cell_size_x, - "cell_size_y": cell_size_y, - "source": source, - "destination": destination, - } - - def build_candidate_polygon(self, clean_raster, out_transform): - mask = np.where(clean_raster == 1, True, False) - if clean_raster.dtype == np.int64: - clean_raster = clean_raster.astype(np.int32) - - out_polygon = ras_feat.shapes(clean_raster, mask=mask, transform=out_transform) - - multi_polygon = [] - for shp, _value in out_polygon: - multi_polygon.append(sh_geom.shape(shp)) - poly = sh_geom.MultiPolygon(multi_polygon) - - crs_str = None - if hasattr(self.line_seg, "crs") and self.line_seg.crs: - if hasattr(self.line_seg.crs, "to_string"): - crs_str = self.line_seg.crs.to_string() - else: - crs_str = str(self.line_seg.crs) - else: - crs_str = "EPSG:4326" - - if not isinstance(poly, (sh_geom.Polygon, sh_geom.MultiPolygon)): - poly = sh_geom.MultiPolygon([poly]) if poly else None - - if not crs_str or not isinstance(crs_str, str) or not crs_str.startswith("EPSG"): - crs_str = "EPSG:4326" - - if poly is not None and isinstance(poly, (sh_geom.Polygon, sh_geom.MultiPolygon)): - geometry_list = [poly] - else: - geometry_list = [] - - footprint = gpd.GeoDataFrame({"geometry": geometry_list}) - footprint.set_crs(crs_str, inplace=True) - return footprint - - def postprocess_output(self, corridor_thresh, out_transform, line_gpd, feat, exp_shk_cell=0): - import beratools.core.algo_centerline as algo_cl - - corridor_poly_gpd = algo_cl.find_corridor_polygon( - corridor_thresh, out_transform, line_gpd, exp_shk_cell=exp_shk_cell - ) - centerline, _status = algo_cl.find_centerline(corridor_poly_gpd.geometry.iloc[0], feat) - - self.corridor_poly_gpd = corridor_poly_gpd - self.centerline = centerline - - -def process_single_absolute_line(line_footprint): - """Compute one absolute line footprint.""" - - try: - line_footprint.compute() - except Exception as err: - print(f"process_single_absolute_line: exception {err}") - return line_footprint - - -def generate_absolute_line_class_list( - in_line, - in_chm, - corridor_thresh, - max_ln_width, - exp_shk_cell, - simplify_footprint_polygon=True, - footprint_simplify_length=0.5, - smooth_footprint_polygon=False, - footprint_polygon_smooth_iterations=1, - in_layer=None, -): - """Build absolute footprint work list.""" - - line_classes = [] - line_list = algo_common.prepare_lines_gdf(in_line, in_layer, proc_segments=False) +import sys +import warnings - for line in line_list: - line_classes.append( - FootprintCanopyAbsolute( - line, - in_chm, - corridor_thresh, - max_ln_width, - exp_shk_cell, - simplify_footprint_polygon=simplify_footprint_polygon, - footprint_simplify_length=footprint_simplify_length, - smooth_footprint_polygon=smooth_footprint_polygon, - footprint_polygon_smooth_iterations=footprint_polygon_smooth_iterations, - ) - ) +from beratools.modules.mapping import algo_canopy_footprint_absolute as _moved - return line_classes +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" for full license details. - -Author: Richard Zeng - -Description: - This script is part of the BERA Tools. - Webpage: https://github.com/BERATool/beratools - - This file is intended to be hosting algorithms and utility functions/classes - for centerline tool. +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -import enum -from dataclasses import dataclass -from itertools import compress - -import geopandas as gpd -import numpy as np -import pandas as pd -import rasterio -import shapely -import shapely.geometry as sh_geom -import shapely.ops as sh_ops -import logging -from scipy import ndimage - -# Lazy-imported in find_centerline() to avoid ~5s startup cost -# from beratools.external.polygon_centerline import get_centerline - -import beratools.core.algo_common as algo_common -import beratools.core.algo_cost as algo_cost -import beratools.core.algo_astar as algo_astar -import beratools.core.algo_geometry as algo_geometry -import beratools.core.alt_spatial_common as alt_sp_common -import beratools.core.algo_dijkstra as bt_dijkstra -import beratools.core.constants as bt_const -import beratools.core.tool_base as bt_base -import beratools.core.tool_geo_simplify as tool_geo_simplify -import beratools.utility.spatial_common as sp_common - -LOGGER_NAME = "centerline" -logger = logging.getLogger(LOGGER_NAME) - - - -class CenterlineParams(float, enum.Enum): - """ - Parameters for centerline generation. - - These parameters are used to control the behavior of centerline generation - and should be adjusted based on the specific requirements of the application. - """ - - BUFFER_CLIP = 5.0 - SEGMENTIZE_LENGTH = 1.0 - SIMPLIFY_LENGTH = 0.5 - SMOOTH_SIGMA = 0.8 - CLEANUP_POLYGON_BY_AREA = 1.0 - ENDPOINT_ANCHOR_TOL = 1e-9 - GUIDED_FALLBACK_MAX_SNAP = 2.0 - GUIDE_SAMPLE_INTERVAL = 10.0 - MIN_GUIDE_LENGTH_RATIO = 0.94 - MAX_SHORTCUT_MEDIAN_DISTANCE = 2.0 - - -@enum.unique -class CenterlineStatus(enum.IntEnum): - """ - Status of centerline generation. - - This enum is used to indicate the status of centerline generation. - It can be used to track the success or failure of the centerline generation process. - - """ - - SUCCESS = 1 - FAILED = 2 - REGENERATE_SUCCESS = 3 - REGENERATE_FAILED = 4 - CENTERLINE_FAILED_LCP_FALLBACK = 5 - LCP_FAILED_SEED_FALLBACK = 6 - THIN_POLYGON_STABILIZED_SUCCESS = 7 - ABSOLUTE_FOOTPRINT_SUCCESS = 8 - -@dataclass(frozen=True) -class EndPointAnchorResult: - anchored: bool - reversed_match: bool - start_dist: float - end_dist: float - - -def centerline_is_valid(centerline, input_line,cid=None): - """ - Check if centerline is valid. - - Args: - centerline (_type_): _description_ - input_line (sh_geom.LineString): Seed line or least cost path. - Only two end points are used. - - Returns: - bool: True if line is valid - - """ - if not centerline: - if cid: - logger.info(f"{cid} validation failed: centerline is None") - return False - - length_check = centerline.length < input_line.length / 2 - anchor_result = _is_endpoint_anchored( - centerline, - input_line, - tol=bt_const.BT_EPSILON,) - - endpoint_check = not anchor_result.anchored - - if length_check or endpoint_check: - # logger.info( - # f"{cid} validation failed:" - # f" anchored={anchor_result.anchored}, " - # f" reversed={anchor_result.reversed_match}, " - # f" start_dist={anchor_result.start_dist:.6f}, " - # f" end_dist={anchor_result.end_dist:.6f}") - return False - - if _looks_like_shortcut(centerline, input_line, cid=cid): - return False - - return True - - -def _looks_like_shortcut(centerline, input_line, cid=None): - if not centerline or not input_line or input_line.length <= 0: - return False - - length_ratio = centerline.length / input_line.length - - if length_ratio >= CenterlineParams.MIN_GUIDE_LENGTH_RATIO: - return False - - distances = _sampled_line_distances( - input_line, - centerline, - CenterlineParams.GUIDE_SAMPLE_INTERVAL, - ) - - if not distances: - return False - - median_distance = float(np.median(distances)) - - shortcut = ( - median_distance > - CenterlineParams.MAX_SHORTCUT_MEDIAN_DISTANCE - ) - - # if cid: - # logger.file_only( - # f"{cid} shortcut check:" - # f" ratio={length_ratio:.3f}, " - # f" median_dist={median_distance:.3f}, " - # f" threshold_ratio={CenterlineParams.MIN_GUIDE_LENGTH_RATIO.value}, " - # f" threshold_dist={CenterlineParams.MAX_SHORTCUT_MEDIAN_DISTANCE.value}, " - # f" shortcut={shortcut}" - # ) - - return shortcut - -def _sampled_line_distances(source_line, target_line, interval): - if interval <= 0: - interval = 10.0 - sample_count = max(int(np.ceil(source_line.length / interval)), 1) - distances = [] - for i in range(sample_count + 1): - distance_along = min(i * interval, source_line.length) - distances.append(source_line.interpolate(distance_along).distance(target_line)) - return distances - - -def snap_end_to_end(in_line, line_reference, max_snap_dist=None,cid=None): - """ - Snap centerline ends to opposite seedline endpoints. - - Prevents: - start -> seed_start - end -> seed_start - - which creates a ring. - """ - - if in_line is None or in_line.is_empty: - return line_reference - - coords = list(in_line.coords) - - if len(coords) < 2: - return line_reference - - cl_start = sh_geom.Point(coords[0]) - cl_end = sh_geom.Point(coords[-1]) - - seed_coords = list(line_reference.coords) - - seed_start = sh_geom.Point(seed_coords[0]) - seed_end = sh_geom.Point(seed_coords[-1]) - - # - # Evaluate both possible assignments - # - cost_forward = (cl_start.distance(seed_start) - + cl_end.distance(seed_end)) - - cost_reverse = (cl_start.distance(seed_end) - + cl_end.distance(seed_start)) - - if abs(cost_forward - cost_reverse) < 1.0: - - seed_dir = np.array([seed_end.x - seed_start.x, - seed_end.y - seed_start.y,]) - - center_dir = np.array([cl_end.x - cl_start.x, - cl_end.y - cl_start.y,]) - - forward = np.dot(seed_dir, center_dir) >= 0 - - elif cost_forward < cost_reverse: - - forward = True - - else: - - forward = False - - if forward: - snap_start, snap_end = seed_start, seed_end - else: - snap_start, snap_end = seed_end, seed_start - - # Only snap ends within max_snap_dist of their target - if max_snap_dist is None or cl_start.distance(snap_start) <= max_snap_dist: - coords[0] = snap_start.coords[0] - if max_snap_dist is None or cl_end.distance(snap_end) <= max_snap_dist: - coords[-1] = snap_end.coords[0] - # - # Safety check - # - if coords[0] == coords[-1]: - # keep original geometry rather than - # creating a ring - return in_line - - return sh_geom.LineString(coords) - -def _is_endpoint_anchored( - centerline, - seed_line, - tol=CenterlineParams.ENDPOINT_ANCHOR_TOL, -) -> EndPointAnchorResult: - """ - Check whether centerline endpoints match seed endpoints. - - Returns - ------- - EndPointAnchorResult - anchored : endpoints match - reversed_match : centerline orientation is reversed - start_dist : endpoint distance used for evaluation - end_dist : endpoint distance used for evaluation - """ - default_return = EndPointAnchorResult( - False, - False, - float("inf"), - float("inf"), - ) - if centerline is None or seed_line is None: - return default_return - - if not isinstance(centerline, sh_geom.LineString): - return default_return - - if not isinstance(seed_line, sh_geom.LineString): - return default_return - - cl_coords = list(centerline.coords) - seed_coords = list(seed_line.coords) - - if len(cl_coords) <=1 or len(seed_coords) <=1: - return default_return - - cl_start = sh_geom.Point(cl_coords[0]) - cl_end = sh_geom.Point(cl_coords[-1]) - - seed_start = sh_geom.Point(seed_coords[0]) - seed_end = sh_geom.Point(seed_coords[-1]) - - direct_start = cl_start.distance(seed_start) - direct_end = cl_end.distance(seed_end) - - reverse_start = cl_start.distance(seed_end) - reverse_end = cl_end.distance(seed_start) - - direct = (direct_start <= tol and direct_end <= tol) - - reversed_match = (reverse_start <= tol and reverse_end <= tol) - - if direct: - return EndPointAnchorResult( - anchored=True, - reversed_match=False, - start_dist=direct_start, - end_dist=direct_end,) - - if reversed_match: - return EndPointAnchorResult( - anchored=True, - reversed_match=True, - start_dist=reverse_start, - end_dist=reverse_end,) - - if (direct_start + direct_end) <= ( - reverse_start + reverse_end): - return EndPointAnchorResult( - anchored=False, - reversed_match=False, - start_dist=direct_start, - end_dist=direct_end, - ) - - return EndPointAnchorResult( - anchored=False, - reversed_match=True, - start_dist=reverse_start, - end_dist=reverse_end, - ) - - -def _trim_and_snap_centerline(centerline, input_line, max_snap_dist=None): - cl_coords = list(centerline.coords) - - head_buffer = sh_geom.Point(cl_coords[0]).buffer(CenterlineParams.BUFFER_CLIP) - centerline = centerline.difference(head_buffer) - - end_buffer = sh_geom.Point(cl_coords[-1]).buffer(CenterlineParams.BUFFER_CLIP) - centerline = centerline.difference(end_buffer) - - if not centerline: - return None - - try: - if centerline.is_empty: - return None - except Exception as e: - logger.info(f"find_centerline: {e}") - - return snap_end_to_end(centerline, input_line, max_snap_dist=max_snap_dist) - - -def _extract_centerline_from_polygon( - poly, - src_geom, - dst_geom, - guided_strategy, - endpoint_mode='strict', - endpoint_candidate_k=5, - cell_size=1.0, - corridor_id="UNKNOWN", - guide_line=None, -): - from beratools.external.polygon_centerline import get_centerline - from beratools.external.polygon_centerline._src import get_last_centerline_info - - _extract_centerline_from_polygon.last_info = {} - centerline = get_centerline( - poly, - segmentize_maxlen=1, - max_points=3000, - simplification=0.05, - smooth_sigma=CenterlineParams.SMOOTH_SIGMA, - max_paths=1, - src_geom=src_geom, - dst_geom=dst_geom, - guided_strategy=guided_strategy, - endpoint_mode=endpoint_mode, - endpoint_candidate_k=endpoint_candidate_k, - cell_size=cell_size, - corridor_id=corridor_id, - input_line=guide_line, - ) - _extract_centerline_from_polygon.last_info = get_last_centerline_info() - return centerline - - -_extract_centerline_from_polygon.last_info = {} - - -def _last_extraction_used_stabilized_voronoi(): - info = getattr(_extract_centerline_from_polygon, "last_info", {}) or {} - return info.get("qhull_retry") not in {None, "none"} or bool(info.get("polygon_stabilized")) - - -def find_centerline(poly, input_line, - guided_strategy="main_route", - endpoint_mode=None, - endpoint_candidate_k=8, - allow_regeneration=True, - cell_size=1.0, - corridor_id="UNKNOWN", - ): - """ - Find centerline from polygon and input line. - - Args: - poly : sh_geom.Polygon - input_line ( sh_geom.LineString): Least cost path or seed line - - Returns: - centerline (sh_geom.LineString): Centerline - status (CenterlineStatus): Status of centerline generation - - """ - cid = f"[CID={corridor_id}] " if corridor_id else "[CID=UNKNOWN] " - default_return = input_line, CenterlineStatus.FAILED - valid_guided_strategies = {"main_route", "pairwise", "virtual_nodes", "direct_insert"} - ordered_valid_guided_strategies = ["pairwise", "virtual_nodes", "direct_insert", "main_route"] - if guided_strategy not in valid_guided_strategies: - raise ValueError("guided_strategy must be one of {}".format(sorted(valid_guided_strategies))) - effective_strategy = guided_strategy - - if not poly: - logger.info(cid+ - f"find_centerline: No polygon found") - return default_return - - poly = shapely.segmentize(poly, max_segment_length=CenterlineParams.SEGMENTIZE_LENGTH) - - # buffer to reduce MultiPolygons - poly = poly.buffer(bt_const.SMALL_BUFFER) - if type(poly) is sh_geom.MultiPolygon: - logger.info("sh_geom.MultiPolygon encountered, skip.") - return default_return - - exterior_pts = list(poly.exterior.coords) - - if bt_const.CenterlineFlags.DELETE_HOLES: - poly = sh_geom.Polygon(exterior_pts) - if bt_const.CenterlineFlags.SIMPLIFY_POLYGON: - poly = poly.simplify(CenterlineParams.SIMPLIFY_LENGTH) - - line_coords = list(input_line.coords) - - src_geom = None - dst_geom = None - if guided_strategy in {"pairwise", "virtual_nodes", "direct_insert"}: - src_geom = sh_geom.Point(line_coords[0]) - dst_geom = sh_geom.Point(line_coords[-1]) - start_covered = poly.buffer(0.5).covers(src_geom) - end_covered = poly.buffer(0.5).covers(dst_geom) - buffer_dist=-0.5 - inner_poly=poly - # to prevent buffering from shrinking the polygon but use min buffer - for buffer_dist in np.arange(-0.5,0.00,0.05): - try_buffer = poly.buffer(buffer_dist) - if try_buffer.is_empty: - break - if try_buffer.area 1: - logger.info(" Multiple centerline segments detected, no further processing.") - return centerline, status # TODO: inspect - elif len(centerline.geoms) == 1: - centerline = centerline.geoms[0] - else: - return default_return - - needs_trim_snap = effective_strategy == "main_route" - if effective_strategy in {"pairwise", "virtual_nodes"}: - result = _is_endpoint_anchored( - centerline, - input_line, - tol=CenterlineParams.ENDPOINT_ANCHOR_TOL, - ) - needs_trim_snap = not result.anchored - if needs_trim_snap: - max_snap_dist = None - if effective_strategy in {"pairwise", "virtual_nodes"}: - max_snap_dist = CenterlineParams.GUIDED_FALLBACK_MAX_SNAP - centerline = _trim_and_snap_centerline( - centerline, - input_line, - max_snap_dist=max_snap_dist, - ) - if not centerline: - return default_return - - # Check centerline. If valid, regenerate by splitting polygon into two halves. - if allow_regeneration and not centerline_is_valid(centerline, input_line,cid=cid): - try: - logger.info(f"{cid} " - f"Regenerating line ...") - centerline = regenerate_centerline(poly, input_line,corridor_id) - logger.info( - f"{cid}" - f" COMPUTE_RESULT regenerate_centerline " - f"status={status.name} " - f"has_centerline={centerline is not None}" - ) - if not centerline: - return input_line, CenterlineStatus.REGENERATE_FAILED - try: - if centerline.is_empty: - return input_line, CenterlineStatus.REGENERATE_FAILED - except Exception as e: - logger.info(f"find_centerline: {e}") - return input_line, CenterlineStatus.REGENERATE_FAILED - return centerline, CenterlineStatus.REGENERATE_SUCCESS - except Exception as e: - logger.info(f"find_centerline: {e}") - return input_line, CenterlineStatus.REGENERATE_FAILED - logger.info( - f"{cid}" - f" FIND_CENTERLINE_RETURN " - f"status={status.name} " - f"length={centerline.length:.2f}" - ) - - return centerline, status - - -def find_corridor_polygon(corridor_thresh, in_transform, - line_gpd, exp_shk_cell=0.,cid=None): - # Threshold corridor raster used for generating centerline - corridor_thresh_cl = algo_common.corridor_threshold_to_mask(corridor_thresh) - labels_before, n_before = ndimage.label(corridor_thresh_cl) - corridor_thresh_cl = algo_common.generalize_binary_mask(corridor_thresh_cl, exp_shk_cell) - labels_after, n_after = ndimage.label(corridor_thresh_cl) - - sizes = np.bincount(labels_after.ravel())[1:] - - logger.info( - f"{cid} " - f"mask_components before-after: " - f"{n_before}->{n_after}" - f" raster_cc={n_after} " - f"largest={sizes.max() if len(sizes) else 0}" - ) - if corridor_thresh_cl.dtype == np.int64: - corridor_thresh_cl = corridor_thresh_cl.astype(np.int32) - - corridor_mask = np.where(1 == corridor_thresh_cl, True, False) - poly_generator = rasterio.features.shapes(corridor_thresh_cl, mask=corridor_mask, transform=in_transform) - corridor_polygon = [] - - try: - for poly, value in poly_generator: - if sh_geom.shape(poly).area > 1: - corridor_polygon.append(sh_geom.shape(poly)) - except Exception as e: - logger.info(f"find_corridor_polygon: {e}") - - if corridor_polygon: - corridor_polygon = sh_ops.unary_union(corridor_polygon) - if type(corridor_polygon) is sh_geom.MultiPolygon: - largest_area=max([geom.area for geom in corridor_polygon.geoms]) - parts = [ - p for p in corridor_polygon.geoms - if p.area >=largest_area*0.01 - ] - if len(parts)>=1: - # poly_list = shapely.get_parts(corridor_polygon) - merge_poly = parts[0] - for i in range(1, len(parts)): - p1, p2 = sh_ops.nearest_points( - merge_poly, - parts[i]) - bridge = sh_geom.LineString([p1, p2]).buffer(3 if exp_shk_cell==0 else exp_shk_cell*3) - merged = shapely.union(merge_poly, bridge) - merge_poly = shapely.union(merged, parts[i]) - corridor_polygon = merge_poly - elif len(parts) == 1: - corridor_polygon = sh_ops.unary_union(parts) - else: - corridor_polygon = None - - else: - corridor_polygon = None - - # create GeoDataFrame for centerline - corridor_poly_gpd = gpd.GeoDataFrame.copy(line_gpd) - corridor_poly_gpd.geometry = [corridor_polygon] - - return corridor_poly_gpd - - -def _to_bool(value): - if isinstance(value, bool): - return value - if isinstance(value, str): - lowered = value.strip().lower() - if lowered in {"true", "1", "yes", "y", "on"}: - return True - if lowered in {"false", "0", "no", "n", "off"}: - return False - return bool(value) - - -def process_single_centerline(row_and_path): - """ - Find centerline. - - Args: - row_and_path (list of row (gdf and lc_path)): and least cost path - first is GeoPandas row, second is input line, (least cost path) - - Returns: - row: GeoPandas row with centerline - - """ - row = row_and_path[0] - lc_path = row_and_path[1] - corridor_id = f"{row['OLnFID'].iloc[0]}_{row['OLnSEG'].iloc[0]}" - - poly = row.geometry.iloc[0] - centerline, status = find_centerline(poly, lc_path, - guided_strategy="pairwise", - corridor_id=corridor_id,) - row["centerline"] = centerline - - return row - - -def find_centerlines(poly_gpd, line_seg, processes): - centerline_gpd = [] - rows_and_paths = [] - - try: - for i in poly_gpd.index: - row = poly_gpd.loc[[i]] - if "OLnSEG" in line_seg.columns: - line_id, Seg_id = row["OLnFID"].iloc[0], row["OLnSEG"].iloc[0] - lc_path = line_seg.loc[(line_seg.OLnFID == line_id) & (line_seg.OLnSEG == Seg_id)][ - "geometry" - ].iloc[0] - else: - line_id = row["OLnFID"].iloc[0] - lc_path = line_seg.loc[(line_seg.OLnFID == line_id)]["geometry"].iloc[0] - - rows_and_paths.append((row, lc_path)) - except Exception as e: - logger.info(f"find_centerlines: {e}") - - centerline_gpd = bt_base.execute_multiprocessing( - process_single_centerline, rows_and_paths, "find_centerlines", processes, 1 - ) - return pd.concat(centerline_gpd) - - -def regenerate_centerline(poly, input_line,corridor_id="UNKNOWN", - cell_size=1.0, - guided_strategy="pairwise", - endpoint_mode="strict", - endpoint_candidate_k=8, - ): - """ - Regenerates centerline when initial poly is not valid. - Split the corridor polygon, extract each half independently, - and merge the two centerlines. - - Args: - input_line (sh_geom.LineString): Seed line or least cost path. - Only two end points will be used - - Returns: - sh_geom.MultiLineString - - """ - cid = (f"[CID={corridor_id}] "if corridor_id else "[CID=UNKNOWN] ") - half_line_length = input_line.length / 2 - split_pt=input_line.interpolate(half_line_length) - line_1 = sh_ops.substring(input_line, start_dist=0.0, end_dist=half_line_length) - line_2 = sh_ops.substring(input_line, start_dist=half_line_length, end_dist=input_line.length) - - pts = shapely.force_2d( - [ - sh_geom.Point(list(input_line.coords)[0]), - split_pt, - sh_geom.Point(list(input_line.coords)[-1]), - ] - ) - perp = algo_common.generate_perpendicular_line_precise(pts) - - # sh_geom.MultiPolygon is rare, but need to be dealt with - # remove polygon of area less than CenterlineParams.CLEANUP_POLYGON_BY_AREA - poly = poly.buffer(bt_const.SMALL_BUFFER) - if type(poly) is sh_geom.MultiPolygon: - poly_geoms = list(poly.geoms) - poly_valid = [True] * len(poly_geoms) - for i, item in enumerate(poly_geoms): - if item.area < CenterlineParams.CLEANUP_POLYGON_BY_AREA: - poly_valid[i] = False - - poly_geoms = list(compress(poly_geoms, poly_valid)) - if len(poly_geoms) != 1: # still multi polygon - logger.info("regenerate_centerline: Multi or none polygon found, pass.") - - poly = sh_geom.Polygon(poly_geoms[0]) - - poly_exterior = sh_geom.Polygon(poly.buffer(bt_const.SMALL_BUFFER).exterior) - - poly_split = sh_ops.split(poly_exterior, perp) - - if len(poly_split.geoms) < 2: - logger.file_only(cid+ - f"regenerate_centerline: polygon sh_ops.split failed, pass.") - return None - - poly_1 = poly_split.geoms[0] - poly_2 = poly_split.geoms[1] - - # find polygon and line pairs - pair_line_1 = line_1 - pair_line_2 = line_2 - if not poly_1.intersects(line_1): - pair_line_1 = line_2 - pair_line_2 = line_1 - elif poly_1.intersection(line_1).length < line_1.length / 3: - pair_line_1 = line_2 - pair_line_2 = line_1 - - - center_line_1 = find_centerline(poly_1, pair_line_1,corridor_id=corridor_id,allow_regeneration=False,) - center_line_2 = find_centerline(poly_2, pair_line_2,corridor_id=corridor_id,allow_regeneration=False,) - - center_line_1 = center_line_1[0] - center_line_2 = center_line_2[0] - - if not center_line_1 or not center_line_2: - logger.info("Regenerate line: centerline is None") - return None - - try: - if center_line_1.is_empty or center_line_2.is_empty: - logger.info("Regenerate line: centerline is empty") - return None - except Exception as e: - logger.info(f"regenerate_centerline: {e}") - - center_line_1 = orient_to_split(center_line_1, - split_pt,want_end_at_split=True) - - center_line_2 = orient_to_split(center_line_2, - split_pt,want_end_at_split=False) - - result=algo_common._safe_linemerge(sh_geom.MultiLineString([center_line_1, center_line_2])) - - if isinstance(result, sh_geom.MultiLineString): - return None - return result - -class SeedLine: - """Class to store seed line and least cost path.""" - - def __init__( - self, - line_gdf, - ras_file, - proc_segments, - line_radius, - guided_strategy="main_route", - centerline_method=bt_const.CENTERLINE_METHOD.value, - lcp_simplify_enabled=False, - lcp_simplify_diameter=10.0, - lcp_smooth_enabled=False, - lcp_smooth_iterations=1, - chm_mode=bt_const.CENTERLINE_CHM_MODE.value, - chm_buffer_width=5.0, - chm_buffer_multiplier=0.5, - astar_corridor_line_bias_weight=0.1, - astar_corridor_distance_penalty_weight=0.2, - corridor_simplify_polygon=False, - corridor_simplify_length=0.5, - corridor_smooth_polygon=False, - corridor_polygon_smooth_iterations=1, - ): - self.line = line_gdf - self.raster = ras_file - self.line_radius = line_radius - self.guided_strategy = guided_strategy - self.centerline_method = centerline_method - self.lcp_simplify_enabled = _to_bool(lcp_simplify_enabled) - self.lcp_simplify_diameter = float(lcp_simplify_diameter) - self.lcp_smooth_enabled = _to_bool(lcp_smooth_enabled) - self.lcp_smooth_iterations = max(int(lcp_smooth_iterations), 0) - if isinstance(chm_mode, bt_const.CenterlineChmMode): - chm_mode = chm_mode.value - if chm_mode not in {mode.value for mode in bt_const.CenterlineChmMode}: - valid_modes = [mode.value for mode in bt_const.CenterlineChmMode] - raise ValueError("chm_mode must be one of {}".format(valid_modes)) - self.chm_mode = chm_mode - self.chm_buffer_width = float(chm_buffer_width) - self.chm_buffer_multiplier = float(chm_buffer_multiplier) - if self.chm_buffer_width < 0.0: - raise ValueError("chm_buffer_width must be greater than or equal to zero") - if not 0.0 <= self.chm_buffer_multiplier <= 1.0: - raise ValueError("chm_buffer_multiplier must be between zero and one") - self.astar_corridor_line_bias_weight = max(float(astar_corridor_line_bias_weight), 0.0) - self.astar_corridor_distance_penalty_weight = max(float(astar_corridor_distance_penalty_weight), 0.0) - self.corridor_simplify_polygon = _to_bool(corridor_simplify_polygon) - self.corridor_simplify_length = max(float(corridor_simplify_length), 0.0) - self.corridor_smooth_polygon = _to_bool(corridor_smooth_polygon) - self.corridor_polygon_smooth_iterations = max(int(corridor_polygon_smooth_iterations), 0) - self.lc_path = None - self.centerline = None - self.corridor_poly_gpd = None - self.endpoint_mode="strict" - self.endpoint_candidate_k=5 - self.cell_size=1.0 - self.cid = "UNKNOWN" - self.tree_radius = 2.5 - - def compute(self): - line = self.line.geometry[0] - line_radius = self.line_radius - in_raster = self.raster - seed_line = line # LineString - chm_mode = self.chm_mode - ## corridor_id is used to identify features in the log file. - corridor_id = ( - f"{self.line['OLnFID'].iloc[0]}_" - f"{self.line['OLnSEG'].iloc[0]}" - ) - cid=f"[CID:{corridor_id}] " - self.cid=cid - try: - ras_clip, out_meta,*tree_gaps = self._clip_chm(in_raster, seed_line, line_radius) - if self.chm_mode == bt_const.CenterlineChmMode.BUFFER.value: - ras_clip = algo_cost.reduce_chm_in_line_buffer( - ras_clip, - out_meta, - seed_line, - self.chm_buffer_width, - self.chm_buffer_multiplier, - ) - if self.chm_mode==bt_const.CenterlineChmMode.ALT.value: - cost_clip, _ = algo_cost.alt_cost_raster(ras_clip, out_meta,tree_gaps[0]) - else: - cost_clip, _ = algo_cost.cost_raster(ras_clip, out_meta) - # rest CHM mode to current mode for the rest of the code. - self.chm_mode = bt_const.CenterlineChmMode.CURRENT.value - except Exception as e: - logger.info(f"{self.cid}:{e}") - self._set_fallback_outputs( - seed_line, - seed_line, - CenterlineStatus.LCP_FAILED_SEED_FALLBACK, - corridor_geometry=seed_line.buffer(line_radius), - ) - return - - lc_path = line - - try: - if self.centerline_method == bt_const.CenterlineMethod.ASTAR.value: - lc_path = algo_astar.find_least_cost_path_astar_closest_line(cost_clip, out_meta, seed_line,cid=self.cid) - if lc_path is None: - logger.warning( - f"{self.cid} A* returned None" - ) - else: - logger.warning( - f"{self.cid} " - f"A* vertices={len(list(lc_path.coords))} " - f"length={lc_path.length:.2f}" - ) - elif bt_const.CenterlineFlags.USE_SKIMAGE_GRAPH: - lc_path = bt_dijkstra.find_least_cost_path_skimage(cost_clip, out_meta, seed_line) - else: - lc_path = bt_dijkstra.find_least_cost_path(cost_clip, out_meta, seed_line) - except Exception as e: - logger.info(f"{self.cid}:{e}") - self._set_fallback_outputs( - seed_line, - seed_line, - CenterlineStatus.LCP_FAILED_SEED_FALLBACK, - corridor_geometry=seed_line.buffer(line_radius), - ) - return - - if lc_path: - lc_path_coords = lc_path.coords - else: - lc_path_coords = [] - - # search for centerline - if len(lc_path_coords) < 2: - logger.info(self.cid+"No least cost path detected, use input line.") - self._set_fallback_outputs( - seed_line, - seed_line, - CenterlineStatus.LCP_FAILED_SEED_FALLBACK, - corridor_geometry=seed_line.buffer(line_radius), - ) - return - - # get corridor raster - lc_path = sh_geom.LineString(lc_path_coords) - lc_path = self._postprocess_lcp(lc_path, out_meta.get("crs")) - lc_path_coords = list(lc_path.coords) - try: - ras_clip, out_meta = self._clip_chm(in_raster, lc_path, line_radius * 0.9) - cost_clip, _ = algo_cost.cost_raster(ras_clip, out_meta) - - out_transform = out_meta["transform"] - transformer = rasterio.transform.AffineTransformer(out_transform) - cell_size = (out_transform[0], -out_transform[4]) - - x1, y1 = lc_path_coords[0] - x2, y2 = lc_path_coords[-1] - source = [transformer.rowcol(x1, y1)] - destination = [transformer.rowcol(x2, y2)] - if self.centerline_method == bt_const.CenterlineMethod.ASTAR.value: - corridor_thresh_cl, _details = algo_astar.astar_accumulation_corridor_raster( - cost_clip, - out_meta, - lc_path, - corridor_threshold=bt_const.FP_CORRIDOR_THRESHOLD, - line_bias_weight=self.astar_corridor_line_bias_weight, - distance_penalty_weight=self.astar_corridor_distance_penalty_weight, - ) - else: - corridor_thresh_cl = algo_common.corridor_raster( - cost_clip, - out_meta, - source, - destination, - cell_size, - bt_const.FP_CORRIDOR_THRESHOLD, - ) - except Exception as e: - logger.info(f"Corridor error {cid}:{e}, fall back lcp buffer line_radius") - self._set_fallback_outputs( - lc_path, - lc_path, - CenterlineStatus.CENTERLINE_FAILED_LCP_FALLBACK, - corridor_geometry=lc_path.buffer(line_radius), - ) - return - - # find contiguous corridor polygon and extract centerline - try: - df = gpd.GeoDataFrame(geometry=[seed_line], crs=out_meta["crs"]) - corridor_poly_gpd = find_corridor_polygon(corridor_thresh_cl, out_transform, df,exp_shk_cell=self.cell_size, - cid=cid) - corridor_poly_gpd = self._postprocess_corridor_polygon(corridor_poly_gpd) - center_line, status = find_centerline( - corridor_poly_gpd.geometry.iloc[0], - lc_path, - guided_strategy=self.guided_strategy, - corridor_id=corridor_id - ) - logger.warning( - f"{cid}" - f" COMPUTE_RESULT " - f"status={status.name} " - f"has_centerline={center_line is not None}" - ) - except Exception as e: - logger.info(f"{cid}:{e}") - corridor_poly_gpd = self.line.copy() - corridor_poly_gpd.geometry = [lc_path.buffer(line_radius)] - center_line = lc_path - status = CenterlineStatus.CENTERLINE_FAILED_LCP_FALLBACK - - status = CenterlineStatus(status) - if status in {CenterlineStatus.FAILED, CenterlineStatus.REGENERATE_FAILED}: - corridor_geom = corridor_poly_gpd.geometry.iloc[0] - if pd.notna(corridor_geom) and not corridor_geom.is_empty: - estimated_width = corridor_poly_gpd.geometry.iloc[0].area / max(lc_path.length, 1e-6) - else: - estimated_width = line_radius/2 - buffer_width = min(line_radius,estimated_width / 2.0) - absolute_footprint = lc_path.buffer(buffer_width) - try: - absolute_centerline, absolute_status = find_centerline( - absolute_footprint, - lc_path, - guided_strategy=self.guided_strategy, - corridor_id=corridor_id, - allow_regeneration=False,) - logger.info( - f"{cid}" - f" COMPUTE_RESULT absolute_footprint " - f"status={status.name} " - f"has_centerline={center_line is not None}" - ) - absolute_status = CenterlineStatus(absolute_status) - if absolute_status not in {CenterlineStatus.FAILED, CenterlineStatus.REGENERATE_FAILED}: - center_line = absolute_centerline - status = CenterlineStatus.ABSOLUTE_FOOTPRINT_SUCCESS - corridor_poly_gpd = self.line.copy() - corridor_poly_gpd.geometry = [absolute_footprint] - - else: - status = CenterlineStatus.CENTERLINE_FAILED_LCP_FALLBACK - center_line = lc_path - except Exception as e: - logger.info(f"{cid}:{e}") - status = CenterlineStatus.CENTERLINE_FAILED_LCP_FALLBACK - center_line = lc_path - - self.line["cl_status"] = status.value - self.line["cl_status_name"] = status.name - - self.lc_path = self.line.copy() - self.lc_path.geometry = [lc_path] - self.lc_path["centerline_method"] = self.centerline_method - self.lc_path["lcp_simplified"] = bool(self.lcp_simplify_enabled and self.lcp_simplify_diameter > 0) - self.lc_path["lcp_smoothed"] = bool(self.lcp_smooth_enabled and self.lcp_smooth_iterations > 0) - - self.centerline = self.line.copy() - self.centerline.geometry = [center_line] - self.centerline["centerline_method"] = self.centerline_method - self.centerline["OLnFID"] = self.lc_path["OLnFID"] - self.centerline["OLnSEG"] = self.lc_path["OLnSEG"] - - self.corridor_poly_gpd = corridor_poly_gpd - self.corridor_poly_gpd["centerline_method"] = self.centerline_method - self.corridor_poly_gpd["cl_status"] = status.value - self.corridor_poly_gpd["cl_status_name"] = status.name - self.corridor_poly_gpd["OLnFID"] = self.lc_path["OLnFID"] - self.corridor_poly_gpd["OLnSEG"] = self.lc_path["OLnSEG"] - for field in (algo_common.SOURCE_ROW_FIELD, algo_common.SOURCE_SEG_FIELD): - if field in self.lc_path.columns: - self.corridor_poly_gpd[field] = self.lc_path[field] - - def _set_fallback_outputs(self, lc_path, centerline, status, corridor_geometry=None): - status = CenterlineStatus(status) - self.line["cl_status"] = status.value - self.line["cl_status_name"] = status.name - - self.lc_path = self.line.copy() - self.lc_path.geometry = [lc_path] - self.lc_path["centerline_method"] = self.centerline_method - self.lc_path["lcp_simplified"] = False - self.lc_path["lcp_smoothed"] = False - - self.centerline = self.line.copy() - self.centerline.geometry = [centerline] - self.centerline["centerline_method"] = self.centerline_method - self.centerline["OLnFID"] = self.lc_path["OLnFID"] - self.centerline["OLnSEG"] = self.lc_path["OLnSEG"] - - self.corridor_poly_gpd = self.line.copy() - self.corridor_poly_gpd.geometry = [corridor_geometry] - self.corridor_poly_gpd["centerline_method"] = self.centerline_method - self.corridor_poly_gpd["OLnFID"] = self.lc_path["OLnFID"] - self.corridor_poly_gpd["OLnSEG"] = self.lc_path["OLnSEG"] - - def _clip_chm(self, in_raster, clip_geometry, buffer): - tree_gaps=[] - if self.chm_mode == bt_const.CenterlineChmMode.ALT.value: - ras_clip, out_meta,tree_gaps = alt_sp_common.alt_clip_and_filter_regional_maxima_wgap( - self, - in_raster, - clip_geometry, - buffer, - ) - return ras_clip, out_meta,tree_gaps - return sp_common.clip_raster(in_raster, clip_geometry, buffer) - - def _postprocess_lcp(self, lc_path, crs): - processed = lc_path - if self.lcp_simplify_enabled and self.lcp_simplify_diameter > 0: - processed = tool_geo_simplify.simplify_line_reduce_bend( - processed, - crs=crs, - diameter=self.lcp_simplify_diameter, - smooth_line=True, - ) - if self.lcp_smooth_enabled and self.lcp_smooth_iterations > 0: - processed = algo_geometry.chaikin_smooth_line( - processed, - iterations=self.lcp_smooth_iterations, - ) - return processed - - def _postprocess_corridor_polygon(self, corridor_poly_gpd): - polygon = corridor_poly_gpd.geometry.iloc[0] - processed = algo_geometry.process_corridor_polygon( - polygon,cid=self.cid, - delete_holes=bool(bt_const.CenterlineFlags.DELETE_HOLES), - simplify=self.corridor_simplify_polygon, - simplify_length=self.corridor_simplify_length, - smooth=self.corridor_smooth_polygon, - smooth_iterations=self.corridor_polygon_smooth_iterations, - ) - corridor_poly_gpd = corridor_poly_gpd.copy() - corridor_poly_gpd.geometry = [processed] - return corridor_poly_gpd - -def orient_to_split(line, split_pt, want_end_at_split=True): - - start_gap = sh_geom.Point(line.coords[0]).distance(split_pt) - - end_gap = sh_geom.Point(line.coords[-1]).distance(split_pt) +import sys +import warnings - if want_end_at_split: - if start_gap < end_gap: - return algo_common._reverse_line(line) - else: - if end_gap < start_gap: - return algo_common._reverse_line(line) +from beratools.modules.mapping import algo_centerline as _moved - return line +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=("= 0 else None - curr_coord = work_coords[remove_index] - next_coord = work_coords[remove_index + 1] if remove_index + 1 < len(work_coords) else None - - old_scores = [] - if prev_coord is not None and remove_index - 2 >= 0: - old_scores.append(self._bend_score(work_coords[remove_index - 2], prev_coord, curr_coord)) - if next_coord is not None and remove_index + 2 < len(work_coords): - old_scores.append(self._bend_score(curr_coord, next_coord, work_coords[remove_index + 2])) - if prev_coord is not None and next_coord is not None: - old_scores.append(self._bend_score(prev_coord, curr_coord, next_coord)) - - new_scores = [] - if prev_coord is not None and next_coord is not None: - if remove_index - 2 >= 0: - new_scores.append(self._bend_score(work_coords[remove_index - 2], prev_coord, next_coord)) - if remove_index + 2 < len(work_coords): - new_scores.append(self._bend_score(prev_coord, next_coord, work_coords[remove_index + 2])) - - old_peak = max(old_scores) if old_scores else 0.0 - new_peak = max(new_scores) if new_scores else 0.0 - significant_penalty = 50.0 if old_peak > self.angle_tol and new_peak <= self.angle_tol else 0.0 - return abs(old_peak - new_peak) + significant_penalty - - def _dedupe_consecutive_coords(self, coords): - if not coords: - return [] - - work_coords = [coords[0]] - for coord in coords[1:]: - if self._point_distance(work_coords[-1], coord) > bt_const.SMALL_BUFFER: - work_coords.append(coord) - - return work_coords - - def _finalize_line(self, coords, original_line): - if len(coords) < 2: - return None - - if self._point_distance(coords[0], coords[-1]) <= bt_const.SMALL_BUFFER: - return None - - if len(coords) == len(original_line.coords): - return original_line - - return sh_geom.LineString(coords) - - def _cleanup_endpoint_only(self, coords): - while len(coords) > 2 and self._point_distance(coords[0], coords[1]) < self.close_distance: - coords.pop(1) - - while len(coords) > 2 and self._point_distance(coords[-2], coords[-1]) < self.close_distance: - coords.pop(-2) - - return coords - - def cleanup_line(self, line, mode="full"): - if mode not in self.VALID_MODES: - raise ValueError(f"Unsupported vertex cleanup mode: {mode}") - - coords = [tuple(coord) for coord in line.coords] - if len(coords) <= 2: - return line - - work_coords = self._dedupe_consecutive_coords(coords) - if len(work_coords) <= 2: - return self._finalize_line(work_coords, line) - - work_coords = self._cleanup_endpoint_only(work_coords) - if mode == "endpoint_only": - return self._finalize_line(work_coords, line) - - i = 1 - while i < len(work_coords) - 2: - left_coord = work_coords[i] - right_coord = work_coords[i + 1] - if self._point_distance(left_coord, right_coord) >= self.close_distance: - i += 1 - continue - - left_score = self._bend_score(work_coords[i - 1], left_coord, right_coord) - right_score = self._bend_score(left_coord, right_coord, work_coords[i + 2]) - - if left_score > self.angle_tol and right_score <= self.angle_tol: - remove_index = i + 1 - elif right_score > self.angle_tol and left_score <= self.angle_tol: - remove_index = i - else: - remove_left_loss = self._shape_loss(work_coords, i) - remove_right_loss = self._shape_loss(work_coords, i + 1) - remove_index = i if remove_left_loss <= remove_right_loss else i + 1 - - work_coords.pop(remove_index) - if i > 1: - i -= 1 - - return self._finalize_line(work_coords, line) - - def remove_close_vertices(self, gdf, mode="full"): - if mode not in self.VALID_MODES: - raise ValueError(f"Unsupported vertex cleanup mode: {mode}") - - if gdf is None or gdf.empty: - return gdf - - if isinstance(gdf, gpd.GeoSeries): - gdf = gpd.GeoDataFrame(geometry=gdf) - - out_gdf = gdf.copy() - - if any(getattr(geom, "geom_type", None) == "MultiLineString" for geom in out_gdf.geometry): - out_gdf = out_gdf.explode(index_parts=False) - - cleaned_geoms = [] - for geom in out_gdf.geometry: - if geom is None or geom.is_empty: - cleaned_geoms.append(None) - continue - - if geom.geom_type != "LineString": - cleaned_geoms.append(geom) - continue - - cleaned_geoms.append(self.cleanup_line(geom, mode=mode)) - - geom_series = gpd.GeoSeries(cleaned_geoms, index=out_gdf.index, crs=out_gdf.crs) - valid_mask = geom_series.notna() & ~geom_series.is_empty - out_gdf = out_gdf.loc[valid_mask].copy() - out_gdf.set_geometry(geom_series.loc[valid_mask], inplace=True) - out_gdf = out_gdf[out_gdf.geometry.length > bt_const.SMALL_BUFFER] - out_gdf = gpd.GeoDataFrame(out_gdf, crs=gdf.crs) - out_gdf.reset_index(drop=True, inplace=True) - - return out_gdf - - -def _iter_line_parts(geom): - if geom is None or geom.is_empty: - return [] - - if geom.geom_type == "LineString": - return [geom] - - if geom.geom_type == "MultiLineString": - return [part for part in geom.geoms if part and not part.is_empty and part.geom_type == "LineString"] - - if geom.geom_type == "GeometryCollection": - parts = [] - for item in geom.geoms: - parts.extend(_iter_line_parts(item)) - return parts - - return [] - - -def _normalize_to_lines(gdf): - if gdf is None: - return gdf - - if gdf.empty: - return gdf - - exploded = gdf.explode(index_parts=False).reset_index(drop=True) - records = [] - - for _, row in exploded.iterrows(): - line_parts = _iter_line_parts(row.geometry) - if not line_parts: - continue - - row_dict = row.to_dict() - for line_geom in line_parts: - rec = row_dict.copy() - rec["geometry"] = line_geom - records.append(rec) - - return gpd.GeoDataFrame(records, columns=gdf.columns, crs=gdf.crs) - - -def _require_crs(gdf, parameter_label): - return unit_conversion.require_crs(gdf, parameter_label) - - -def _build_linear_unit_context(crs, reference_geom): - return unit_conversion.build_linear_unit_context(crs, reference_geom) - - -def _meters_to_native_units(distance_m, unit_ctx): - return unit_conversion.meters_to_native_units(distance_m, unit_ctx) - - -def _geometry_length_meters(geom, unit_ctx): - return unit_conversion.geometry_length_meters(geom, unit_ctx) - - -def _geographic_raster_cell_size_m(src, crs, x_res, y_res): - geod = crs.get_geod() - if geod is None: - raise ValueError("Unable to build geodesic calculator for geographic CRS.") - - bounds = src.bounds - center_x = float((bounds.left + bounds.right) / 2.0) - center_y = float((bounds.bottom + bounds.top) / 2.0) - max_lat = 89.999999 - min_lat = -89.999999 - y_for_dx = min(max(center_y, min_lat), max_lat) - y_start = min(max(center_y, min_lat), max_lat) - y_for_dy = min(max(center_y + float(y_res), min_lat), max_lat) - dist_x = abs(geod.inv(center_x, y_for_dx, center_x + float(x_res), y_for_dx)[2]) - dist_y = abs(geod.inv(center_x, y_start, center_x, y_for_dy)[2]) - return min(dist_x, dist_y) - - -def _default_close_distance_m(in_raster): - fallback = 2.0 - max_auto_default = 30.0 - - def _fallback(reason, exc=None): - if exc is None: - logger.warning( - "Using fallback preclean distance %.2f m: %s (raster=%s)", - fallback, - reason, - in_raster, - ) - else: - logger.warning( - "Using fallback preclean distance %.2f m: %s (raster=%s, error=%s)", - fallback, - reason, - in_raster, - exc, - ) - return fallback - - if not in_raster or rasterio is None: - reason = "missing input raster" - if rasterio is None: - reason = "rasterio unavailable" - return _fallback(reason) - - try: - with rasterio.open(in_raster) as src: - crs = pyproj.CRS.from_user_input(src.crs) if src.crs else None - if crs is None: - return _fallback("raster CRS missing or unreadable") - - x_res, y_res = src.res - cell_size_native = min(abs(float(x_res)), abs(float(y_res))) - if math.isclose(cell_size_native, 0.0): - return _fallback("raster resolution is zero") - - if crs.is_geographic: - try: - cell_size_m = _geographic_raster_cell_size_m(src, crs, x_res, y_res) - except ValueError as exc: - return _fallback(str(exc)) - else: - unit_factor = crs.axis_info[0].unit_conversion_factor if crs.axis_info else None - if unit_factor is None or unit_factor <= 0: - return _fallback("unable to determine projected CRS linear unit factor") - cell_size_m = cell_size_native * float(unit_factor) - - if math.isclose(cell_size_m, 0.0): - return _fallback("computed metric cell size is zero") - inferred_default = 1.5 * float(cell_size_m) - return float(min(max_auto_default, max(fallback, inferred_default))) - except Exception as exc: - return _fallback("failed to derive raster-based default", exc=exc) - - -def _preclean_lines_full(gdf, close_distance_m, angle_tol_deg): - if gdf.empty: - return gdf, gdf.iloc[0:0].copy() - - valid_mask = ~gdf.geometry.isna() & ~gdf.geometry.is_empty - out = gdf[valid_mask].copy() - rejected = gdf[~valid_mask].copy() - if out.empty: - return out.reset_index(drop=True), rejected.reset_index(drop=True) - - crs = _require_crs(out, "Preclean close distance (m)") - precleaner = VertexPrecleaner(close_distance=close_distance_m, angle_tol=angle_tol_deg) - cleaned_records = [] - removed_records = [] - - if crs.is_geographic: - reference_geom = out.unary_union.envelope - unit_ctx = _build_linear_unit_context(crs, reference_geom) - for _, row in out.iterrows(): - geom = row.geometry - if geom is None or geom.is_empty or geom.geom_type != "LineString": - rec = row.to_dict() - if geom is None or geom.is_empty: - removed_records.append(rec) - else: - cleaned_records.append(rec) - continue - - geom_metric = sh_ops.transform(unit_ctx["to_metric"].transform, geom) - cleaned_metric = precleaner.cleanup_line(geom_metric, mode="full") - if cleaned_metric is None or cleaned_metric.is_empty: - removed_records.append(row.to_dict()) - continue - - rec = row.to_dict() - rec["geometry"] = sh_ops.transform(unit_ctx["to_source"].transform, cleaned_metric) - cleaned_records.append(rec) - else: - unit_ctx = _build_linear_unit_context(crs, out.unary_union.envelope) - close_distance_native = max( - _meters_to_native_units(close_distance_m, unit_ctx), bt_const.SMALL_BUFFER - ) - precleaner_native = VertexPrecleaner(close_distance=close_distance_native, angle_tol=angle_tol_deg) - for _, row in out.iterrows(): - geom = row.geometry - if geom is None or geom.is_empty or geom.geom_type != "LineString": - rec = row.to_dict() - if geom is None or geom.is_empty: - removed_records.append(rec) - else: - cleaned_records.append(rec) - continue - - cleaned = precleaner_native.cleanup_line(geom, mode="full") - if cleaned is None or cleaned.is_empty: - removed_records.append(row.to_dict()) - continue - - rec = row.to_dict() - rec["geometry"] = cleaned - cleaned_records.append(rec) - - cleaned_gdf = gpd.GeoDataFrame(cleaned_records, columns=gdf.columns, crs=gdf.crs) - removed_gdf = gpd.GeoDataFrame( - [*rejected.to_dict("records"), *removed_records], columns=gdf.columns, crs=gdf.crs - ) - return cleaned_gdf.reset_index(drop=True), removed_gdf.reset_index(drop=True) - - -def _clean_line_geometries_min_length_m(line_gdf, min_length_m): - if line_gdf is None: - return line_gdf, None - if line_gdf.empty: - return line_gdf.copy(), line_gdf.copy() - - valid_mask = ~line_gdf.geometry.isna() & ~line_gdf.geometry.is_empty - out = line_gdf[valid_mask] - rejected = line_gdf[~valid_mask].copy() - - if out.empty: - return out.reset_index(drop=True), rejected.reset_index(drop=True) - - crs = _require_crs(out, "Minimum line length (m)") - - reference_geom = out.unary_union.envelope - unit_ctx = _build_linear_unit_context(crs, reference_geom) - min_len_m = max(float(min_length_m), bt_const.SMALL_BUFFER) - - if unit_ctx["is_geographic"]: - mask = out.geometry.apply(lambda geom: _geometry_length_meters(geom, unit_ctx) > min_len_m) - kept = out[mask] - removed_short = out[~mask] - else: - min_len_native = max(_meters_to_native_units(min_len_m, unit_ctx), bt_const.SMALL_BUFFER) - kept = out[out.geometry.length > min_len_native] - removed_short = out[~(out.geometry.length > min_len_native)] - - if rejected.empty: - rejected = removed_short.copy() - elif not removed_short.empty: - rejected = gpd.GeoDataFrame( - [*rejected.to_dict("records"), *removed_short.to_dict("records")], - columns=line_gdf.columns, - crs=line_gdf.crs, - ) - - return kept.reset_index(drop=True), rejected.reset_index(drop=True) - - -def _clip_to_chm_footprint(gdf, in_raster, shrink_m): - footprint = algo_common.generate_raster_footprint(in_raster, latlon=False) - if footprint is None or footprint.is_empty: - raise ValueError("Unable to build CHM footprint from input raster.") - - shrink_dist_m = abs(float(shrink_m)) - crs = _require_crs(gdf, "CHM footprint shrink (m)") - unit_ctx = _build_linear_unit_context(crs, footprint) - - if unit_ctx["is_geographic"]: - footprint_metric = sh_ops.transform(unit_ctx["to_metric"].transform, footprint) - shrunken_metric = footprint_metric.buffer(-shrink_dist_m) - shrunken = sh_ops.transform(unit_ctx["to_source"].transform, shrunken_metric) - else: - shrink_dist_units = _meters_to_native_units(shrink_dist_m, unit_ctx) - shrunken = footprint.buffer(-shrink_dist_units) - - if shrunken is None or shrunken.is_empty: - raise ValueError("CHM footprint became empty after inward shrink; reduce 'CHM footprint shrink (m)'.") - - clipped_records = [] - rejected_records = [] - for _, row in gdf.iterrows(): - geom = row.geometry - if geom is None or geom.is_empty: - rejected_records.append(row.to_dict()) - continue - - clipped = geom.intersection(shrunken) - if clipped is None or clipped.is_empty: - rejected_records.append(row.to_dict()) - continue - - rec = row.to_dict() - rec["geometry"] = clipped - clipped_records.append(rec) - - clipped_gdf = gpd.GeoDataFrame(clipped_records, columns=gdf.columns, crs=gdf.crs) - rejected_gdf = gpd.GeoDataFrame(rejected_records, columns=gdf.columns, crs=gdf.crs) - return clipped_gdf, rejected_gdf, shrunken - - -def _parse_line_id(raw_id): - if isinstance(raw_id, bool): - return None - try: - val = int(raw_id) - return val - except (TypeError, ValueError): - return None - - -def _choose_anchor(endpoint_a, endpoint_b): - line_id_a = _parse_line_id(endpoint_a.get("line_id")) - line_id_b = _parse_line_id(endpoint_b.get("line_id")) - - score_a = ( - -int(endpoint_a.get("degree", 0)), - -endpoint_a["line_length"], - 0 if line_id_a is not None else 1, - line_id_a if line_id_a is not None else float("inf"), - endpoint_a["discovery_order"], - ) - score_b = ( - -int(endpoint_b.get("degree", 0)), - -endpoint_b["line_length"], - 0 if line_id_b is not None else 1, - line_id_b if line_id_b is not None else float("inf"), - endpoint_b["discovery_order"], - ) - - if score_a <= score_b: - return endpoint_a, endpoint_b - return endpoint_b, endpoint_a - - -def _snap_close_endpoints(gdf, tolerance): - if gdf.empty: - return gdf - - tol_m = float(tolerance) - if tol_m <= bt_const.SMALL_BUFFER: - return gdf - - crs = _require_crs(gdf, "Snap tolerance (m)") - reference_geom = gdf.unary_union.envelope - unit_ctx = _build_linear_unit_context(crs, reference_geom) - tol_native = _meters_to_native_units(tol_m, unit_ctx) - - endpoints = [] - discovery_order = 0 - for row_index, row in gdf.iterrows(): - geom = row.geometry - if geom is None or geom.is_empty or geom.geom_type != "LineString": - continue - - coords = list(geom.coords) - if len(coords) < 2: - continue - - line_length = _geometry_length_meters(geom, unit_ctx) - line_id = row.get("line_id") - for endpoint_idx, coord in ((0, coords[0]), (-1, coords[-1])): - metric_point = None - if unit_ctx["is_geographic"]: - metric_point = sh_ops.transform(unit_ctx["to_metric"].transform, Point(coord)) - endpoints.append( - { - "gdf_index": row_index, - "endpoint_idx": endpoint_idx, - "point": Point(coord), - "metric_point": metric_point, - "line_length": line_length, - "line_id": line_id, - "discovery_order": discovery_order, - } - ) - discovery_order += 1 - - if len(endpoints) < 2: - return gdf - - neighbor_graph = {idx: set() for idx in range(len(endpoints))} - for i in range(len(endpoints)): - for j in range(i + 1, len(endpoints)): - ep_i = endpoints[i] - ep_j = endpoints[j] - - if ep_i["gdf_index"] == ep_j["gdf_index"]: - continue - - if unit_ctx["is_geographic"]: - dist = ep_i["metric_point"].distance(ep_j["metric_point"]) - close_threshold = bt_const.SMALL_BUFFER - snap_threshold = tol_m - else: - dist = ep_i["point"].distance(ep_j["point"]) - close_threshold = bt_const.SMALL_BUFFER - snap_threshold = tol_native - - if dist <= close_threshold: - continue - if dist <= snap_threshold: - neighbor_graph[i].add(j) - neighbor_graph[j].add(i) - - if not any(neighbor_graph.values()): - return gdf - - for idx, endpoint in enumerate(endpoints): - endpoint["degree"] = len(neighbor_graph[idx]) - - visited = set() - components = [] - active_nodes = [idx for idx, neighbors in neighbor_graph.items() if neighbors] - for node in active_nodes: - if node in visited: - continue - stack = [node] - component = [] - while stack: - curr = stack.pop() - if curr in visited: - continue - visited.add(curr) - component.append(curr) - for neighbor in neighbor_graph[curr]: - if neighbor not in visited: - stack.append(neighbor) - - if len(component) > 1: - components.append(component) - - if not components: - return gdf - - updates = {} - for component in components: - anchor_endpoint = endpoints[component[0]] - for idx in component[1:]: - candidate = endpoints[idx] - anchor_endpoint, _ = _choose_anchor(anchor_endpoint, candidate) - - anchor_coord = tuple(anchor_endpoint["point"].coords[0]) - anchor_key = (anchor_endpoint["gdf_index"], anchor_endpoint["endpoint_idx"]) - - for idx in component: - endpoint = endpoints[idx] - endpoint_key = (endpoint["gdf_index"], endpoint["endpoint_idx"]) - if endpoint_key == anchor_key: - continue - updates[endpoint_key] = anchor_coord - - if not updates: - return gdf - - out = gdf.copy() - for row_index, row in out.iterrows(): - geom = row.geometry - if geom is None or geom.is_empty or geom.geom_type != "LineString": - continue - - coords = list(geom.coords) - changed = False - for endpoint_idx in (0, -1): - key = (row_index, endpoint_idx) - if key in updates: - target_coord = updates[key] - if endpoint_idx == 0: - coords[0] = target_coord - else: - coords[-1] = target_coord - changed = True - - if changed: - out.at[row_index, "geometry"] = LineString(coords) - - return out - - -def _interp_coord(start, end, ratio): - n_dims = min(len(start), len(end)) - return tuple(start[i] + (end[i] - start[i]) * ratio for i in range(n_dims)) - - -def _densify_linestring(line, max_segment_length): - if line is None or line.is_empty or line.geom_type != "LineString": - return line - - max_seg = float(max_segment_length) - if max_seg <= bt_const.SMALL_BUFFER: - raise ValueError("Max segment length must be greater than zero.") - - total_len = float(line.length) - if total_len <= max_seg: - return line - - n_parts = int(math.ceil(total_len / max_seg)) - spacing = total_len / n_parts - split_distances = [spacing * i for i in range(1, n_parts)] - - coords = list(line.coords) - if len(coords) < 2: - return line - - out_coords = [coords[0]] - curr_dist = 0.0 - split_idx = 0 - - for seg_idx in range(len(coords) - 1): - start = coords[seg_idx] - end = coords[seg_idx + 1] - seg_len = Point(start).distance(Point(end)) - if seg_len <= bt_const.SMALL_BUFFER: - continue - - seg_end_dist = curr_dist + seg_len - while split_idx < len(split_distances) and split_distances[split_idx] < seg_end_dist: - ratio = (split_distances[split_idx] - curr_dist) / seg_len - interp = _interp_coord(start, end, ratio) - if Point(out_coords[-1]).distance(Point(interp)) > bt_const.SMALL_BUFFER: - out_coords.append(interp) - split_idx += 1 - - if Point(out_coords[-1]).distance(Point(end)) > bt_const.SMALL_BUFFER: - out_coords.append(end) - curr_dist = seg_end_dist - - if len(out_coords) < 2: - return line - return LineString(out_coords) - - -def _densify_long_lines(gdf, max_segment_length): - if gdf.empty: - return gdf - - max_seg_m = float(max_segment_length) - if max_seg_m <= bt_const.SMALL_BUFFER: - raise ValueError("Max segment length must be greater than zero.") - - valid = gdf[~gdf.geometry.isna() & ~gdf.geometry.is_empty] - if valid.empty: - return gdf - - crs = _require_crs(valid, "Max segment length (m)") - reference_geom = valid.unary_union.envelope - unit_ctx = _build_linear_unit_context(crs, reference_geom) - - out = gdf.copy() - - if unit_ctx["is_geographic"]: - for idx, row in out.iterrows(): - geom = row.geometry - if geom is None or geom.is_empty or geom.geom_type != "LineString": - continue - - geom_metric = sh_ops.transform(unit_ctx["to_metric"].transform, geom) - if geom_metric.length <= max_seg_m: - continue - - densified_metric = _densify_linestring(geom_metric, max_seg_m) - out.at[idx, "geometry"] = sh_ops.transform(unit_ctx["to_source"].transform, densified_metric) - - return out - - max_seg_native = max(_meters_to_native_units(max_seg_m, unit_ctx), bt_const.SMALL_BUFFER) - for idx, row in out.iterrows(): - geom = row.geometry - if geom is None or geom.is_empty or geom.geom_type != "LineString": - continue - if geom.length <= max_seg_native: - continue - out.at[idx, "geometry"] = _densify_linestring(geom, max_seg_native) - return out - - -def qc_merge_multilinestring(gdf): - """ - QC step: Merge MultiLineStrings if possible, else split into LineStrings. - - Args: - gdf (GeoDataFrame): Input GeoDataFrame. - - Returns: - GeoDataFrame: Cleaned GeoDataFrame with only LineStrings. - """ - from shapely.geometry.base import BaseGeometry - - from beratools.core.algo_merge_lines import custom_line_merge - - records = [] - for _, row in gdf.iterrows(): - geom = row.geometry - if geom is None: - continue - row_dict = row.to_dict() - if geom.geom_type == "MultiLineString": - merged = custom_line_merge(geom) - if merged.geom_type == "MultiLineString": - for part in getattr(merged, "geoms", []): - new_row = row_dict.copy() - new_row["geometry"] = part - if part.geom_type == "LineString": - records.append(new_row) - elif merged.geom_type == "LineString": - new_row = row_dict.copy() - new_row["geometry"] = merged - records.append(new_row) - else: - new_row = row_dict.copy() - new_row["geometry"] = merged - if hasattr(merged, "geom_type") and merged.geom_type == "LineString": - records.append(new_row) - elif geom.geom_type == "LineString": - records.append(row_dict) - - valid_records = [rec for rec in records if isinstance(rec.get("geometry", None), BaseGeometry)] - out_gdf = gpd.GeoDataFrame.from_records(valid_records, columns=gdf.columns) - out_gdf.set_crs(gdf.crs, inplace=True) - out_gdf = out_gdf.reset_index(drop=True) - out_gdf, _ = algo_common.chk_df_multipart(out_gdf, 'LineString') - return out_gdf - - -def qc_split_lines_at_intersections(gdf): - """ - QC step: Split lines at intersections so each segment becomes a separate line object. - - Args: - gdf (GeoDataFrame): Input GeoDataFrame of LineStrings. - - Returns: - GeoDataFrame: New GeoDataFrame with lines split at all intersection points. - """ - from beratools.core.algo_split_with_lines import LineSplitter - - splitter = LineSplitter(gdf) - splitter.process() - if splitter.split_lines_gdf is not None: - if isinstance(splitter.split_lines_gdf, gpd.GeoDataFrame): - return splitter.split_lines_gdf.reset_index(drop=True) - return splitter.split_lines_gdf - return gdf.reset_index(drop=True) - - - -def _bend_angle(a, b, c): - """ - Return deviation from straight line in degrees. - - 0° = perfectly straight - 90° = right angle - """ - - v1 = np.array([ - a[0] - b[0], - a[1] - b[1], - ]) - - v2 = np.array([ - c[0] - b[0], - c[1] - b[1], - ]) - - n1 = np.linalg.norm(v1) - n2 = np.linalg.norm(v2) - - if n1 == 0 or n2 == 0: - return 0.0 - - cosang = np.dot(v1, v2) / (n1 * n2) - cosang = np.clip(cosang, -1.0, 1.0) - - angle = np.degrees( - np.arccos(cosang) - ) - - return min( - angle, - 180.0 - angle - ) - - -def _trim_short_terminal_segments( - line, - min_segment_length=5.0, - max_bend_angle=5.0, -): - coords = list(line.coords) - - # - # remove short tail - # - while len(coords) > 2: - - tail_len = ( - sh_geom.Point(coords[-2]) - .distance( - sh_geom.Point(coords[-1]) - ) - ) - - if tail_len >= min_segment_length: - break - - # - # check if last vertex is essentially inline - # - if len(coords) >= 3: - - angle = _bend_angle( - coords[-3], - coords[-2], - coords[-1] - ) - - if angle > max_bend_angle: - break - - coords.pop(-1) - - # - # remove short head - # - while len(coords) > 2: - - head_len = ( - sh_geom.Point(coords[0]) - .distance( - sh_geom.Point(coords[1]) - ) - ) - - if head_len >= min_segment_length: - break - - # - # check if first vertex is essentially inline - # - if len(coords) >= 3: - - angle = _bend_angle( - coords[0], - coords[1], - coords[2] - ) - - if angle > max_bend_angle: - break - - coords.pop(0) - - return sh_geom.LineString(coords) \ No newline at end of file +""" +Deprecated: moved to beratools.modules.mapping. + +Kept so old imports keep working, with a DeprecationWarning, until it is removed. +""" + +import sys +import warnings + +from beratools.modules.mapping import algo_check_seed_line as _moved + +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" 0: - samples.append(Point(src.xy(row, col - 1))) - if row > 0: - samples.append(Point(src.xy(row - 1, col))) - - distances = [_point_distance_m(center, sample, unit_ctx) for sample in samples] - distances = [dist for dist in distances if dist > bt_const.SMALL_BUFFER] - if distances: - return min(distances) - - return max(abs(float(src.transform.a)), abs(float(src.transform.e)), bt_const.SMALL_BUFFER) - - -def _raster_valid_mask(data, nodata): - values = np.ma.getdata(data) - invalid = np.ma.getmaskarray(data).copy() - - if nodata is not None: - try: - invalid |= np.isclose(values, nodata) - except TypeError: - invalid |= values == nodata - - if np.issubdtype(values.dtype, np.floating): - invalid |= np.isnan(values) - - return ~invalid - - -def _nearest_valid_distance_m(src, valid_mask, row_offset, col_offset, point, unit_ctx, exclude_cell=None): - valid_rows, valid_cols = np.nonzero(valid_mask) - best_distance = None - - for local_row, local_col in zip(valid_rows, valid_cols): - global_row = int(row_offset + local_row) - global_col = int(col_offset + local_col) - if exclude_cell is not None and (global_row, global_col) == exclude_cell: - continue - - candidate = Point(src.xy(global_row, global_col)) - distance_m = _point_distance_m(point, candidate, unit_ctx) - if best_distance is None or distance_m < best_distance: - best_distance = float(distance_m) - - return best_distance - - -def _check_chm_point(src, point, search_radius_m, unit_ctx): - try: - row, col = src.index(point.x, point.y) - except Exception: - return {"reason": "outside_raster", "nearest_valid_m": None} - - in_bounds = 0 <= row < src.height and 0 <= col < src.width - if not in_bounds: - return {"reason": "outside_raster", "nearest_valid_m": None} - - center_row = min(max(int(row), 0), src.height - 1) - center_col = min(max(int(col), 0), src.width - 1) - cell_size_m = _raster_cell_size_m(src, center_row, center_col, unit_ctx) - radius_px = max(1, int(math.ceil(float(search_radius_m) / max(cell_size_m, bt_const.SMALL_BUFFER)))) - - row_start = max(center_row - radius_px, 0) - row_stop = min(center_row + radius_px + 1, src.height) - col_start = max(center_col - radius_px, 0) - col_stop = min(center_col + radius_px + 1, src.width) - - if row_stop <= row_start or col_stop <= col_start: - return {"reason": "outside_raster", "nearest_valid_m": None} - - window = Window(col_start, row_start, col_stop - col_start, row_stop - row_start) - data = src.read(1, window=window, masked=True) - valid_mask = _raster_valid_mask(data, src.nodata) - - center_valid = False - if in_bounds: - local_row = int(row - row_start) - local_col = int(col - col_start) - center_valid = bool(valid_mask[local_row, local_col]) - - if center_valid: - local_row = int(row - row_start) - local_col = int(col - col_start) - neighbor_row_start = max(local_row - 1, 0) - neighbor_row_stop = min(local_row + 2, valid_mask.shape[0]) - neighbor_col_start = max(local_col - 1, 0) - neighbor_col_stop = min(local_col + 2, valid_mask.shape[1]) - neighbors = valid_mask[neighbor_row_start:neighbor_row_stop, neighbor_col_start:neighbor_col_stop].copy() - neighbors[local_row - neighbor_row_start, local_col - neighbor_col_start] = False - if np.any(neighbors): - return None - - nearest_valid_m = _nearest_valid_distance_m( - src, - valid_mask, - row_start, - col_start, - point, - unit_ctx, - exclude_cell=(int(row), int(col)), - ) - return {"reason": "surrounded_by_nodata", "nearest_valid_m": nearest_valid_m} - - nearest_valid_m = _nearest_valid_distance_m(src, valid_mask, row_start, col_start, point, unit_ctx) - return {"reason": "on_nodata", "nearest_valid_m": nearest_valid_m} - - -def _segment_length_m(coord_a, coord_b, unit_ctx): - seg = LineString([coord_a, coord_b]) - return unit_conversion.geometry_length_meters(seg, unit_ctx) - - -def _intersection_points(geom): - if geom is None or geom.is_empty: - return [] - if isinstance(geom, Point): - return [geom] - if isinstance(geom, MultiPoint): - return [pt for pt in geom.geoms if pt is not None and not pt.is_empty] - if isinstance(geom, LineString): - if geom.length <= bt_const.SMALL_BUFFER: - return [] - return [geom.interpolate(0.5, normalized=True)] - if isinstance(geom, MultiLineString): - points = [] - for part in geom.geoms: - points.extend(_intersection_points(part)) - return points - if isinstance(geom, GeometryCollection): - points = [] - for part in geom.geoms: - points.extend(_intersection_points(part)) - return points - if hasattr(geom, "representative_point"): - return [geom.representative_point()] - return [] - - -def _overlap_midpoints_and_lengths(geom, unit_ctx): - if geom is None or geom.is_empty: - return [] - - items = [] - if isinstance(geom, LineString): - length_m = unit_conversion.geometry_length_meters(geom, unit_ctx) - if length_m > bt_const.SMALL_BUFFER: - items.append((geom.interpolate(0.5, normalized=True), float(length_m))) - return items - - if isinstance(geom, MultiLineString): - for part in geom.geoms: - items.extend(_overlap_midpoints_and_lengths(part, unit_ctx)) - return items - - if isinstance(geom, GeometryCollection): - for part in geom.geoms: - items.extend(_overlap_midpoints_and_lengths(part, unit_ctx)) - return items - - return items - - -def _dedupe_records(records, precision=9): - deduped = [] - seen = set() - for rec in records: - pt = rec["geometry"] - key = ( - rec["issue_type"], - int(rec["line_id"]), - -1 if rec["line_id_2"] is None else int(rec["line_id_2"]), - round(float(pt.x), precision), - round(float(pt.y), precision), - round(float(rec["value"]), 6), - round(float(rec["threshold"]), 6), - ) - if key in seen: - continue - seen.add(key) - deduped.append(rec) - return deduped - - -def check_short_lines(gdf, min_length_m, unit_ctx): - threshold = float(min_length_m) - records = [] - for line_id, geom in enumerate(gdf.geometry): - for part in _iter_line_parts(geom): - length_m = unit_conversion.geometry_length_meters(part, unit_ctx) - if length_m < threshold: - records.append( - { - "issue_type": "short_line", - "description": f"Line length {length_m:.3f}m is below minimum {threshold:.3f}m", - "line_id": int(line_id), - "line_id_2": None, - "value": float(length_m), - "threshold": threshold, - "geometry": part.interpolate(0.5, normalized=True), - } - ) - return _dedupe_records(records) - - -def check_close_vertices(gdf, close_distance_m, unit_ctx): - threshold = float(close_distance_m) - records = [] - for line_id, geom in enumerate(gdf.geometry): - for part in _iter_line_parts(geom): - coords = list(part.coords) - if len(coords) < 2: - continue - for i in range(1, len(coords)): - dist_m = _segment_length_m(coords[i - 1], coords[i], unit_ctx) - if bt_const.SMALL_BUFFER < dist_m <= threshold: - records.append( - { - "issue_type": "close_vertices", - "description": ( - f"Consecutive vertices are {dist_m:.3f}m apart; threshold {threshold:.3f}m" - ), - "line_id": int(line_id), - "line_id_2": None, - "value": float(dist_m), - "threshold": threshold, - "geometry": Point(coords[i]), - } - ) - return _dedupe_records(records) - - -def check_unsnapped_endpoints(gdf, snap_tolerance_m, unit_ctx): - threshold = float(snap_tolerance_m) - records = [] - - endpoints = [] - for line_id, geom in enumerate(gdf.geometry): - for part in _iter_line_parts(geom): - coords = list(part.coords) - if len(coords) < 2: - continue - endpoints.append({"line_id": int(line_id), "point": Point(coords[0])}) - endpoints.append({"line_id": int(line_id), "point": Point(coords[-1])}) - - if len(endpoints) < 2: - return records - - if unit_ctx["is_geographic"]: - candidates = [ - (i, j) - for i in range(len(endpoints)) - for j in range(i + 1, len(endpoints)) - if endpoints[i]["line_id"] != endpoints[j]["line_id"] - ] - else: - threshold_native = unit_conversion.meters_to_native_units(threshold, unit_ctx) - points = gpd.GeoSeries([ep["point"] for ep in endpoints], crs=gdf.crs) - sindex = points.sindex - candidates = [] - for i, ep in enumerate(endpoints): - bounds = ep["point"].buffer(threshold_native).bounds - for j in sindex.intersection(bounds): - if j <= i: - continue - if ep["line_id"] == endpoints[j]["line_id"]: - continue - candidates.append((i, int(j))) - - for i, j in candidates: - ep_a = endpoints[i] - ep_b = endpoints[j] - dist_m = _point_distance_m(ep_a["point"], ep_b["point"], unit_ctx) - if dist_m <= bt_const.SMALL_BUFFER or dist_m > threshold: - continue - - line_id_a = min(ep_a["line_id"], ep_b["line_id"]) - line_id_b = max(ep_a["line_id"], ep_b["line_id"]) - records.append( - { - "issue_type": "unsnapped_endpoint", - "description": ( - f"Endpoints are close ({dist_m:.3f}m) but not snapped (threshold {threshold:.3f}m)" - ), - "line_id": int(line_id_a), - "line_id_2": int(line_id_b), - "value": float(dist_m), - "threshold": threshold, - "geometry": ep_a["point"], - } - ) - - return _dedupe_records(records) - - -def check_self_crossing(gdf): - records = [] - threshold = 0.0 - for line_id, geom in enumerate(gdf.geometry): - for part in _iter_line_parts(geom): - if part.is_simple: - continue - - coords = list(part.coords) - if len(coords) < 4: - continue - - segments = [] - for i in range(len(coords) - 1): - seg = LineString([coords[i], coords[i + 1]]) - if seg.length > bt_const.SMALL_BUFFER: - segments.append((i, seg)) - - seg_count = len(segments) - for i in range(seg_count): - idx_a, seg_a = segments[i] - for j in range(i + 1, seg_count): - idx_b, seg_b = segments[j] - - if abs(idx_a - idx_b) <= 1: - continue - if idx_a == 0 and idx_b == len(coords) - 2 and Point(coords[0]).equals(Point(coords[-1])): - continue - - inter = seg_a.intersection(seg_b) - if inter is None or inter.is_empty: - continue - - for pt in _intersection_points(inter): - records.append( - { - "issue_type": "self_crossing", - "description": "Line has self-crossing or self-touching segments", - "line_id": int(line_id), - "line_id_2": None, - "value": 0.0, - "threshold": threshold, - "geometry": pt, - } - ) - - return _dedupe_records(records) - - -def check_overlapping_lines(gdf): - records = [] - threshold = 0.0 - - lines = [] - for line_id, geom in enumerate(gdf.geometry): - for part in _iter_line_parts(geom): - lines.append({"line_id": int(line_id), "geometry": part}) - - if len(lines) < 2: - return records - - unit_ctx = _build_unit_ctx(gdf) - - line_gdf = gpd.GeoDataFrame(lines, geometry="geometry", crs=gdf.crs) - sindex = line_gdf.sindex - - for i, row in line_gdf.iterrows(): - geom_i = row.geometry - for j in sindex.intersection(geom_i.bounds): - j = int(j) - if j <= i: - continue - other = line_gdf.iloc[j] - if int(other["line_id"]) == int(row["line_id"]): - continue - - inter = geom_i.intersection(other.geometry) - if inter is None or inter.is_empty: - continue - - for pt, overlap_len_m in _overlap_midpoints_and_lengths(inter, unit_ctx): - line_id_a = min(int(row["line_id"]), int(other["line_id"])) - line_id_b = max(int(row["line_id"]), int(other["line_id"])) - records.append( - { - "issue_type": "overlap", - "description": f"Lines share an overlapping segment ({overlap_len_m:.3f}m)", - "line_id": line_id_a, - "line_id_2": line_id_b, - "value": float(overlap_len_m), - "threshold": threshold, - "geometry": pt, - } - ) - - return _dedupe_records(records) - - -def check_chm_nodata_vertices( - gdf, - in_raster, - search_radius_m, - unit_ctx, - check_internal_vertices=False, -): - records = [] - if not in_raster or rasterio is None or Window is None: - return records - if not Path(in_raster).exists(): - return records - - threshold = float(search_radius_m) - include_internal = bool(check_internal_vertices) - - with rasterio.open(in_raster) as src: - for line_id, row in gdf.reset_index(drop=True).iterrows(): - bt_uid = row.get(bt_const.BT_UID) - for part in _iter_line_parts(row.geometry): - coords = list(part.coords) - if len(coords) < 2: - continue - - candidates = [(0, coords[0], "start_endpoint"), (len(coords) - 1, coords[-1], "end_endpoint")] - if include_internal and len(coords) > 2: - candidates.extend( - (idx, coord, "internal_vertex") for idx, coord in enumerate(coords[1:-1], start=1) - ) - - for vertex_index, coord, vertex_type in candidates: - point = Point(coord) - result = _check_chm_point(src, point, threshold, unit_ctx) - if result is None: - continue - - nearest_valid_m = result["nearest_valid_m"] - nearest_text = ( - f"nearest valid CHM cell is {nearest_valid_m:.3f}m away" - if nearest_valid_m is not None - else f"no valid CHM cell found within {threshold:.3f}m" - ) - uid_text = f"; BT_UID={bt_uid}" if bt_uid is not None else "" - reason_text = ( - "falls on CHM NoData" - if result["reason"] == "on_nodata" - else "is surrounded by CHM NoData" - if result["reason"] == "surrounded_by_nodata" - else "falls outside the CHM raster" - ) - - records.append( - { - "issue_type": "chm_nodata_vertex", - "description": ( - f"{vertex_type} {reason_text}; vertex_index={vertex_index}{uid_text}; " - f"coordinate=({point.x:.3f}, {point.y:.3f}); {nearest_text}" - ), - "line_id": int(line_id), - "line_id_2": None, - "value": -1.0 if nearest_valid_m is None else float(nearest_valid_m), - "threshold": threshold, - "geometry": point, - } - ) - - return _dedupe_records(records) - - -def generate_qc_report( - gdf, - min_length_m, - close_distance_m, - snap_tolerance_m, - in_raster=None, - warn_nodata_vertices=False, - nodata_vertex_search_radius_m=10.0, - check_internal_vertices=False, -): - if gdf is None: - gdf = gpd.GeoDataFrame(geometry=[]) - - gdf = gdf.reset_index(drop=True) - if gdf.empty: - issues_gdf = gpd.GeoDataFrame( - {col: [] for col in ISSUE_COLUMNS if col != "geometry"}, - geometry=gpd.GeoSeries([], crs=gdf.crs), - crs=gdf.crs, - ) - summary = { - "short_line": 0, - "close_vertices": 0, - "unsnapped_endpoint": 0, - "self_crossing": 0, - "overlap": 0, - "chm_nodata_vertex": 0, - "total": 0, - } - return issues_gdf, summary - - unit_ctx = _build_unit_ctx(gdf) - - short_line = check_short_lines(gdf, min_length_m=min_length_m, unit_ctx=unit_ctx) - close_vertices = check_close_vertices(gdf, close_distance_m=close_distance_m, unit_ctx=unit_ctx) - unsnapped_endpoint = check_unsnapped_endpoints( - gdf, - snap_tolerance_m=snap_tolerance_m, - unit_ctx=unit_ctx, - ) - self_crossing = check_self_crossing(gdf) - overlap = check_overlapping_lines(gdf) - chm_nodata_vertex = [] - if warn_nodata_vertices: - chm_nodata_vertex = check_chm_nodata_vertices( - gdf, - in_raster=in_raster, - search_radius_m=nodata_vertex_search_radius_m, - unit_ctx=unit_ctx, - check_internal_vertices=check_internal_vertices, - ) - - all_issues = short_line + close_vertices + unsnapped_endpoint + self_crossing + overlap + chm_nodata_vertex - - if all_issues: - issues_gdf = gpd.GeoDataFrame(all_issues, columns=ISSUE_COLUMNS, geometry="geometry", crs=gdf.crs) - else: - issues_gdf = gpd.GeoDataFrame( - {col: [] for col in ISSUE_COLUMNS if col != "geometry"}, - geometry=gpd.GeoSeries([], crs=gdf.crs), - crs=gdf.crs, - ) - - summary = { - "short_line": len(short_line), - "close_vertices": len(close_vertices), - "unsnapped_endpoint": len(unsnapped_endpoint), - "self_crossing": len(self_crossing), - "overlap": len(overlap), - "chm_nodata_vertex": len(chm_nodata_vertex), - } - summary["total"] = int(sum(summary.values())) - - return issues_gdf, summary +""" +Deprecated: moved to beratools.modules.mapping. + +Kept so old imports keep working, with a DeprecationWarning, until it is removed. +""" + +import sys +import warnings + +from beratools.modules.mapping import algo_check_seed_line_validate as _moved + +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" for full license details. - -Author: Richard Zeng - -Description: - This script is part of the BERA Tools. - Webpage: https://github.com/BERATool/beratools - - The purpose of this script is to provide common algorithms - and utility functions/classes. +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -import math -import tempfile -import logging -import json -from pathlib import Path - -import sqlite3 -import pyogrio -import geopandas as gpd -import numpy as np -import pyproj -from osgeo import gdal, ogr -import rasterio -import shapely -import shapely.affinity as sh_aff -import shapely.geometry as sh_geom -import shapely.ops as sh_ops -import shapely.validation as sh_val -import skimage.graph as sk_graph -from scipy import ndimage - -import beratools.core.algo_cost as algo_cost -import beratools.core.constants as bt_const - -gpd.options.io_engine = "pyogrio" -DISTANCE_THRESHOLD = 2 # 1 meter for intersection neighborhood - -LOGGER_NAME = "algo_common" -logger = logging.getLogger(LOGGER_NAME) - -def log_file_only(message, level=logging.INFO, logger_name=None): - """Log a message to file handlers only, skipping console/gui handlers.""" - target_logger = logging.getLogger(logger_name) if logger_name else logging.getLogger(__name__) - record = target_logger.makeRecord( - name=target_logger.name, - level=level, - fn="", - lno=0, - msg=message, - args=(), - exc_info=None, - ) - - root_logger = logging.getLogger() - wrote_to_file = False - for handler in root_logger.handlers: - if isinstance(handler, logging.FileHandler): - handler.handle(record) - wrote_to_file = True - - if not wrote_to_file: - target_logger.log(level, message) - -def process_single_item(cls_obj): - """ - Process a class object for universal multiprocessing. - - Args: - cls_obj: Class object to be processed - - Returns: - cls_obj: Class object after processing - - """ - try: - cls_obj.compute() - return cls_obj - except Exception as e: - import traceback - - print(f"❌ Exception during compute() for object: {e}") - traceback.print_exc() - return None - - -def read_geospatial_file(file_path, layer=None): - """ - Read a geospatial file, clean the geometries and return a GeoDataFrame. - - Args: - file_path (str): The path to the geospatial file (e.g., .shp, .gpkg). - layer (str, optional): The specific layer to read if the file is - multi-layered (e.g., GeoPackage). - - Returns: - GeoDataFrame: The cleaned GeoDataFrame containing the data from the file - with valid geometries only. - None: If there is an error reading the file or layer. - - """ - try: - kwargs = {} - if layer is not None: - kwargs["layer"] = layer - - gdf = gpd.read_file(file_path, **kwargs) - - # Rename 'fid' column to avoid conflict with GeoPackage's reserved - # FID field on write. - if "fid" in gdf.columns: - gdf = gdf.rename(columns={"fid": "orig_fid"}) - - # Clean the geometries in the GeoDataFrame - gdf = clean_geometries(gdf, stage="input") - gdf = gdf.reset_index(drop=True) - gdf["BT_UID"] = range(len(gdf)) # assign temporary UID - return gdf - - except Exception as e: - print(f"Error reading file {file_path}: {e}") - return None - - -def has_multilinestring(gdf): - """Check if any geometry is a MultiLineString.""" - # Filter out None values (invalid geometries) from the GeoDataFrame - valid_geometries = gdf.geometry - return any(isinstance(geom, sh_geom.MultiLineString) for geom in valid_geometries) - - -def get_aux_path(out_file): - out_path = Path(out_file) - return out_path.with_stem(out_path.stem + "_aux").with_suffix(".gpkg").as_posix() - - -def save_aux_layer(gdf, out_file, layer): - if gdf is None or gdf.empty or out_file is None or layer is None: - return - - aux_file = get_aux_path(out_file) - try: - gdf.to_file(aux_file, layer=layer) - except Exception as exc: - logger.warning("Failed saving aux layer '%s' to %s: %s", layer, aux_file, exc) - - -def _infer_ogr_field_type(value): - if isinstance(value, bool): - return ogr.OFTInteger - if isinstance(value, int): - return ogr.OFTInteger64 - if isinstance(value, float): - return ogr.OFTReal - return ogr.OFTString - - -def save_aux_table(rows, out_file, table, overwrite=True): - if out_file is None or table is None: - return - - if rows is None: - rows = [] - - if isinstance(rows, dict): - rows = [rows] - - if not isinstance(rows, list): - logger.warning("Skipping aux table '%s': rows must be a list of dicts.", table) - return - - normalized_rows = [] - columns = [] - for row in rows: - if not isinstance(row, dict): - logger.warning("Skipping aux table row for '%s': expected dict, got %s.", table, type(row)) - continue - normalized_rows.append(row) - for key in row.keys(): - if key not in columns: - columns.append(key) - - aux_file = get_aux_path(out_file) - try: - driver = ogr.GetDriverByName("GPKG") - if driver is None: - raise RuntimeError("OGR GeoPackage driver is unavailable.") - - ds = driver.Open(aux_file, 1) - if ds is None: - ds = driver.CreateDataSource(aux_file) - if ds is None: - raise RuntimeError(f"Unable to open or create GeoPackage: {aux_file}") - - if overwrite: - layer_index = -1 - for idx in range(ds.GetLayerCount()): - layer_obj = ds.GetLayer(idx) - if layer_obj is not None and layer_obj.GetName() == table: - layer_index = idx - break - - if layer_index >= 0: - ds.DeleteLayer(layer_index) - - layer = ds.GetLayerByName(table) - if layer is None: - layer = ds.CreateLayer(table, geom_type=ogr.wkbNone) - - layer_defn = layer.GetLayerDefn() - existing_fields = [layer_defn.GetFieldDefn(i).GetName() for i in range(layer_defn.GetFieldCount())] - - for col in columns: - if col in existing_fields: - continue - - sample_value = None - for row in normalized_rows: - if row.get(col) is not None: - sample_value = row[col] - break - - field_type = _infer_ogr_field_type(sample_value) - field_defn = ogr.FieldDefn(col, field_type) - layer.CreateField(field_defn) - - layer_defn = layer.GetLayerDefn() - for row in normalized_rows: - feature = ogr.Feature(layer_defn) - for col in columns: - value = row.get(col) - if isinstance(value, bool): - value = int(value) - if value is None: - continue - feature.SetField(col, value) - layer.CreateFeature(feature) - feature = None - - ds = None - except Exception as exc: - logger.warning("Failed saving aux table '%s' to %s: %s", table, aux_file, exc) - - -def clean_geometries(gdf, stage=None, out_file=None, layer=None): - """ - Remove rows with invalid, None, or empty geometries from the GeoDataFrame. - - Args: - gdf (GeoDataFrame): The GeoDataFrame to clean. - - Returns: - GeoDataFrame: The cleaned GeoDataFrame with valid, non-null, - and non-empty geometries. - - """ - if gdf is None: - return gdf - - if gdf.empty: - return gdf - - m_null = gdf.geometry.isna() - - m_empty = m_null.copy() - m_empty[:] = False - non_null_mask = ~m_null - if non_null_mask.any(): - m_empty.loc[non_null_mask] = gdf.geometry.loc[non_null_mask].is_empty - - m_invalid = m_null.copy() - m_invalid[:] = False - valid_candidate_mask = non_null_mask & ~m_empty - if valid_candidate_mask.any(): - m_invalid.loc[valid_candidate_mask] = ~gdf.geometry.loc[valid_candidate_mask].is_valid - - rejected_mask = m_invalid | m_null | m_empty - if not rejected_mask.any(): - return gdf - - rejected_gdf = gdf[rejected_mask].copy() - rejected_gdf["BT_REJECT_REASON"] = np.where( - m_invalid[rejected_mask], - "invalid", - np.where(m_null[rejected_mask], "null", "empty"), - ) - - kept_gdf = gdf[~rejected_mask] - - n_invalid = int((rejected_gdf["BT_REJECT_REASON"] == "invalid").sum()) - n_null = int((rejected_gdf["BT_REJECT_REASON"] == "null").sum()) - n_empty = int((rejected_gdf["BT_REJECT_REASON"] == "empty").sum()) - total_removed = int(rejected_mask.sum()) - original_count = len(gdf) - - stage_prefix = f"[{stage}] " if stage else "" - logger.info( - "%sRemoved %s invalid, %s null, %s empty geometries (%s of %s rows)", - stage_prefix, - n_invalid, - n_null, - n_empty, - total_removed, - original_count, - ) - - layer_name = layer - if layer_name is None: - layer_name = f"rejected_{stage}" if stage else "rejected" - - if out_file is not None: - save_aux_layer(rejected_gdf, out_file, layer_name) - - return kept_gdf - - -def clean_line_geometries(line_gdf, min_length=bt_const.SMALL_BUFFER): - """Clean line geometries in the GeoDataFrame.""" - if line_gdf is None: - return line_gdf - - if line_gdf.empty: - return line_gdf - - line_gdf = line_gdf[~line_gdf.geometry.isna() & ~line_gdf.geometry.is_empty] - line_gdf = line_gdf[line_gdf.geometry.length > float(min_length)] - return line_gdf - - -def split_lines_to_segments(gdf): - """Split input lines to single-segment rows while preserving attributes.""" - if gdf is None: - return [] - - gdf, _ = chk_df_multipart(gdf, 'LineString') - - split_gdf_list = [] - for row in gdf.itertuples(index=False): - line = row.geometry - coords = list(line.coords) - - for i in range(len(coords) - 1): - segment = sh_geom.LineString([coords[i], coords[i + 1]]) - attributes = {col: getattr(row, col) for col in gdf.columns if col != "geometry"} - attributes["OLnSEG"] = i - single_row_gdf = gpd.GeoDataFrame([attributes], geometry=[segment], crs=gdf.crs) - split_gdf_list.append(single_row_gdf) - - return split_gdf_list - - -def lines_gdf_to_list(gdf): - """Convert lines GeoDataFrame rows to list of single-row GeoDataFrames.""" - if gdf is None: - return [] - - if has_multilinestring(gdf): - gdf = gdf.explode(index_parts=False) - - out_list = [] - for row in gdf.itertuples(index=False): - line = row.geometry - attributes = {col: getattr(row, col) for col in gdf.columns if col != "geometry"} - single_row_gdf = gpd.GeoDataFrame([attributes], geometry=[line], crs=gdf.crs) - out_list.append(single_row_gdf) - - return out_list - - -# remember which input row (and its OLnSEG) each processed piece came from -SOURCE_ROW_FIELD = "BT_SRC_ROW" -SOURCE_SEG_FIELD = "BT_SRC_SEG" - - -def keep_source_seg(gdf): - """Remember each row's OLnSEG before split_lines_to_segments renumbers it per vertex.""" - if gdf is not None and "OLnSEG" in gdf.columns: - gdf = gdf.copy() - gdf[SOURCE_SEG_FIELD] = gdf["OLnSEG"] - return gdf - - -def restore_source_seg(gdf): - """Put back the OLnSEG saved by keep_source_seg once the segments are merged into their rows.""" - if gdf is not None and SOURCE_SEG_FIELD in gdf.columns: - gdf = gdf.copy() - gdf["OLnSEG"] = gdf[SOURCE_SEG_FIELD] - gdf = gdf.drop(columns=SOURCE_SEG_FIELD) - return gdf - - -def prepare_lines_gdf(file_path, layer=None, proc_segments=True, tag_source_rows=False): - """ - Split lines at vertices or return original rows. - - It handles for MultiLineString. With tag_source_rows, OLnFID/OLnSEG are added if missing - and each row records its input row and OLnSEG, so pieces can be merged back to it. - - """ - gdf = read_geospatial_file(file_path, layer=layer) - if gdf is None: - return [] - - if tag_source_rows: - gdf, _ = chk_df_multipart(gdf, "LineString") - gdf = gdf.reset_index(drop=True) - gdf[SOURCE_ROW_FIELD] = gdf.index - gdf[SOURCE_SEG_FIELD] = gdf["OLnSEG"] - - if proc_segments: - return split_lines_to_segments(gdf) - - return lines_gdf_to_list(gdf) - - -def corridor_threshold_to_mask(corridor_thresh): - """Convert BERA corridor threshold raster to a binary inside-corridor mask. - - Corridor rasters use 0 for inside the selected corridor and 1 for outside. - Polygonization and morphology helpers use 1 for selected cells. - """ - - return np.ma.where(corridor_thresh == 0.0, 1, 0).filled(0).astype(np.int32) - - -def apply_canopy_mask(corridor_mask, canopy_raster): - """Gate corridor cells by canopy raster where canopy value 0 means keep.""" - - canopy = np.ma.asarray(canopy_raster).filled(1) - return np.where((np.asarray(corridor_mask) == 1) & (canopy == 0), 1, 0).astype(np.int32) - - -def generalize_binary_mask(binary_mask, exp_shk_cell, boundary_clean=True): - """Apply FLM-style cell-based expand/shrink and boundary clean.""" - - clean_raster = np.asarray(binary_mask, dtype=np.int32) - exp_shk_cell = int(float(exp_shk_cell or 0)) - - if exp_shk_cell > 0: - # FLM original Expand/Shrink equivalent. The range is cell-based. - cell_size = int(exp_shk_cell * 2 + 1) - clean_raster = ndimage.grey_dilation(clean_raster, size=(cell_size, cell_size)) - clean_raster = ndimage.grey_erosion(clean_raster, size=(cell_size, cell_size)) - elif bt_const.BT_DEBUGGING: - print("No Expand And Shrink cell performed.") - - if boundary_clean: - # Pragmatic open-source approximation of ArcGIS BoundaryClean_sa. - clean_raster = ndimage.median_filter(clean_raster, size=3) - - return clean_raster.astype(np.int32) - - -def morph_raster(corridor_thresh, canopy_raster, exp_shk_cell, cell_size_x): - corridor_mask = corridor_threshold_to_mask(corridor_thresh) - raster_class = apply_canopy_mask(corridor_mask, canopy_raster) - return generalize_binary_mask(raster_class, exp_shk_cell) - - -def closest_point_to_line(point, line): - if not line: - return None - - pt = line.interpolate(line.project(sh_geom.Point(point))) - return pt - - -def line_coord_list(line): - point_list = [] - try: - for point in list(line.coords): # loops through every point in a line - # loops through every vertex of every segment - if point: # adds all the vertices to segment_list, which creates an array - point_list.append(sh_geom.Point(point[0], point[1])) - except Exception as e: - print(e) - - return point_list - - -def intersection_of_lines(line_1, line_2): - """ - Only LINESTRING is dealt with for now. - - Args: - line_1 : - line_2 : - - Returns: - sh_geom.Point: intersection point - - """ - # intersection collection, may contain points and lines - inter = None - if line_1 and line_2: - inter = line_1.intersection(line_2) - - # TODO: intersection may return GeometryCollection, LineString or MultiLineString - if inter: - if ( - type(inter) is sh_geom.GeometryCollection - or type(inter) is sh_geom.LineString - or type(inter) is sh_geom.MultiLineString - ): - return inter.centroid - - return inter - - -def get_angle(line, vertex_index): - """ - Calculate the angle of the first or last segment. - - # TODO: use np.arctan2 instead of np.arctan - - Args: - line: LineString - end_index: 0 or -1 of the line vertices. Consider the multipart. - - """ - pts = line_coord_list(line) - - if vertex_index == 0: - pt_1 = pts[0] - pt_2 = pts[1] - elif vertex_index == -1: - pt_1 = pts[-1] - pt_2 = pts[-2] - - delta_x = pt_2.x - pt_1.x - delta_y = pt_2.y - pt_1.y - if np.isclose(pt_1.x, pt_2.x): - angle = np.pi / 2 - if delta_y > 0: - angle = np.pi / 2 - elif delta_y < 0: - angle = -np.pi / 2 - else: - angle = np.arctan(delta_y / delta_x) - - # arctan is in range [-pi/2, pi/2], regulate all angles to [[-pi/2, 3*pi/2]] - if delta_x < 0: - angle += np.pi # the second or fourth quadrant - - return angle - - -def points_are_close(pt1, pt2): - if abs(pt1.x - pt2.x) < DISTANCE_THRESHOLD and abs(pt1.y - pt2.y) < DISTANCE_THRESHOLD: - return True - else: - return False - - -def generate_raster_footprint(in_raster, latlon=True): - inter_img = "image_overview.tif" - - src_ds = gdal.Open(in_raster) - width, height = src_ds.RasterXSize, src_ds.RasterYSize - src_crs = src_ds.GetSpatialRef().ExportToWkt() - - geom = None - with tempfile.TemporaryDirectory() as tmp_folder: - if bt_const.BT_DEBUGGING: - print("Temporary folder: {}".format(tmp_folder)) - - if max(width, height) <= 1024: - inter_img = in_raster - else: - if width >= height: - options = gdal.TranslateOptions(width=1024, height=0) - else: - options = gdal.TranslateOptions(width=0, height=1024) - - inter_img = Path(tmp_folder).joinpath(inter_img).as_posix() - gdal.Translate(inter_img, src_ds, options=options) - - shapes = gdal.Footprint("", inter_img, dstSRS=src_crs, format="MEM") - target_feat = shapes.GetLayer(0).GetNextFeature() - geom = sh_geom.shape(json.loads(target_feat.GetGeometryRef().ExportToJson())) - - if geom is not None and latlon: - out_crs = pyproj.CRS("EPSG:4326") - transformer = pyproj.Transformer.from_crs(pyproj.CRS(src_crs), out_crs) - - geom = sh_ops.transform(transformer.transform, geom) - - return geom - - -def save_raster_to_file(in_raster_mem, in_meta, out_raster_file): - """ - Save raster matrix in memory to file. - - Args: - in_raster_mem: numpy raster - in_meta: input meta - out_raster_file: output raster file - - """ - with rasterio.open(out_raster_file, "w", **in_meta) as dest: - dest.write(in_raster_mem, indexes=1) - - -def generate_perpendicular_line_precise(points, offset=20): - """ - Generate a perpendicular line to the input line at the given point. - - Args: - points (list[Point]): The points where to generate the perpendicular lines. - offset (float): The length of the perpendicular line. - - Returns: - shapely.geometry.LineString: The generated perpendicular line. - - """ - # Compute the angle of the line - if len(points) not in [2, 3]: - return None - - center = points[1] - perp_line = None - - if len(points) == 2: - head = points[0] - tail = points[1] - - delta_x = head.x - tail.x - delta_y = head.y - tail.y - angle = 0.0 - - if math.isclose(delta_x, 0.0): - angle = math.pi / 2 - else: - angle = math.atan(delta_y / delta_x) - - start = [center.x + offset / 2.0, center.y] - end = [center.x - offset / 2.0, center.y] - line = sh_geom.LineString([start, end]) - perp_line = sh_aff.rotate(line, angle + math.pi / 2.0, origin=center, use_radians=True) - elif len(points) == 3: - head = points[0] - tail = points[2] - - angle_1 = _line_angle(center, head) - angle_2 = _line_angle(center, tail) - angle_diff = (angle_2 - angle_1) / 2.0 - head_new = sh_geom.Point( - center.x + offset / 2.0 * math.cos(angle_1), - center.y + offset / 2.0 * math.sin(angle_1), - ) - if head.has_z: - head_new = shapely.force_3d(head_new) - try: - perp_seg_1 = sh_geom.LineString([center, head_new]) - perp_seg_1 = sh_aff.rotate(perp_seg_1, angle_diff, origin=center, use_radians=True) - perp_seg_2 = sh_aff.rotate(perp_seg_1, math.pi, origin=center, use_radians=True) - perp_line = sh_geom.LineString([list(perp_seg_1.coords)[1], list(perp_seg_2.coords)[1]]) - except Exception as e: - print(e) - - return perp_line - - -def _line_angle(point_1, point_2): - """ - Calculate the angle of the line. - - Args: - point_1, point_2: start and end points of shapely line - - """ - delta_y = point_2.y - point_1.y - delta_x = point_2.x - point_1.x - - angle = math.atan2(delta_y, delta_x) - return angle - - -def corridor_raster(raster_clip, out_meta, source, destination, cell_size, corridor_threshold): - """ - Calculate corridor raster. - - Args: - raster_clip (raster): - out_meta : raster file meta - source (list of point tuple(s)): start point in row/col - destination (list of point tuple(s)): end point in row/col - cell_size (tuple): (cell_size_x, cell_size_y) - corridor_threshold (double) - - Returns: - corridor raster - - """ - try: - # change all nan to BT_NODATA_COST for workaround - if len(raster_clip.shape) > 2: - raster_clip = np.squeeze(raster_clip, axis=0) - - algo_cost.remove_nan_from_array_refactor(raster_clip) - - # generate the cost raster to source point - mcp_source = sk_graph.MCP_Geometric(raster_clip, sampling=cell_size) - source_cost_acc = mcp_source.find_costs(source)[0] - del mcp_source - - # # # generate the cost raster to destination point - mcp_dest = sk_graph.MCP_Geometric(raster_clip, sampling=cell_size) - dest_cost_acc = mcp_dest.find_costs(destination)[0] - - # Generate corridor - corridor = source_cost_acc + dest_cost_acc - corridor = np.ma.masked_invalid(corridor) - - # Calculate minimum value of corridor raster - if np.ma.min(corridor) is not None: - corr_min = float(np.ma.min(corridor)) - else: - corr_min = 0.5 - - # normalize corridor raster by deducting corr_min - corridor_norm = corridor - corr_min - corridor_thresh_cl = np.ma.where(corridor_norm >= corridor_threshold, 1.0, 0.0) - - except Exception as e: - print(e) - print("corridor_raster: Exception occurred.") - return None - - return corridor_thresh_cl - - -def remove_holes(geom): - if geom.geom_type == "Polygon": - if geom.interiors: - return sh_geom.Polygon(geom.exterior) - return geom - elif geom.geom_type == "MultiPolygon": - new_polygons = [] - for polygon in geom.geoms: # Iterate through MultiPolygon - if polygon.interiors: - new_polygons.append(sh_geom.Polygon(polygon.exterior)) - else: - new_polygons.append(polygon) - return sh_geom.MultiPolygon(new_polygons) - return geom # Return other geometry types as is - -def _reverse_line(line): - """Reverse a LineString coordinate sequence.""" - return sh_geom.LineString( - list(line.coords)[::-1] - ) - -def _safe_linemerge(geometry): - """ - Safely merge line geometry. - - Returns - ------- - LineString - When all input parts form one connected line. - - MultiLineString - When multiple disconnected line components remain. - - None - When the input contains no usable line geometry. - """ - def _usable_line(line): - - if line is None: - return False - - if line.is_empty: - return False - - if line.length <= 0: - return False - - if line.is_ring: - return False - - return True - - if geometry is None: - return None - - try: - if geometry.is_empty: - return geometry - except Exception: - return None - - # Already one usable line. - if isinstance(geometry, sh_geom.LineString): - if _usable_line(geometry): - return geometry - else: - valid_geom=sh_val.make_valid(geometry) - - if isinstance(valid_geom, sh_geom.LineString): - return valid_geom if _usable_line(valid_geom) else None - - elif isinstance(valid_geom, sh_geom.MultiLineString): - try: - cleaned_parts = [] - for part in valid_geom.geoms: - if not _usable_line(part): - continue - else: - cleaned_parts.append(part) - - if len(cleaned_parts) == 0: - return None - else: - return sh_ops.linemerge(cleaned_parts) - except (TypeError, ValueError): - return None - elif isinstance(valid_geom, sh_geom.GeometryCollection): - lines = [] - for part in valid_geom.geoms: - if isinstance(part, sh_geom.LineString): - if _usable_line(part): - lines.append(part) - elif isinstance(part, sh_geom.MultiLineString): - lines.extend( - line - for line in part.geoms - if _usable_line(line)) - - if not lines: - return None - - if len(lines) == 1: - return lines[0] - - return sh_ops.linemerge(lines) - - # linemerge is valid for a MultiLineString. - if isinstance(geometry, sh_geom.MultiLineString): - try: - cleaned_parts = [] - for part in geometry.geoms: - if not _usable_line(part): - continue - else: - cleaned_parts.append(part) - - if len(cleaned_parts) == 0: - return None - else: - return sh_ops.linemerge(cleaned_parts) - except (TypeError, ValueError): - return None - - # Extract line components from a mixed collection. - if isinstance(geometry, sh_geom.GeometryCollection): - lines = [] - - for part in geometry.geoms: - if part is None or part.is_empty: - continue - - if isinstance(part, sh_geom.LineString): - if _usable_line(part): - lines.append(part) - - elif isinstance(part, sh_geom.MultiLineString): - lines.extend(line - for line in part.geoms - if _usable_line(line)) - - if not lines: - return None - - if len(lines) == 1: - return lines[0] - - unioned = sh_ops.unary_union(lines) - - if isinstance(unioned, sh_geom.LineString): - return unioned - - if isinstance(unioned, sh_geom.MultiLineString): - try: - return sh_ops.linemerge(unioned) - except (TypeError, ValueError): - return unioned - - return None - - return None - -def merge_lines_by_original_id( - line_gdf, - group_field="OLnFID", - order_field="OLnSEG", - max_bridge_gap=0.5, - output_segment_value=-1, - geometry_count_field="merged_part_count", -): - """ - Reconstruct ordered LineString features by original ID. - - Works for centerlines and least-cost paths. - """ - if line_gdf is None or line_gdf.empty: - return line_gdf - - if group_field not in line_gdf.columns: - raise KeyError( - f"Missing grouping field: {group_field}" - ) - - if order_field not in line_gdf.columns: - raise KeyError( - f"Missing ordering field: {order_field}" - ) - - output_rows = [] - crs = line_gdf.crs - - for original_id, group in line_gdf.groupby( - group_field, - sort=False, - ): - group = group.sort_values( - order_field, - kind="stable", - ) - - ordered_lines = [] - - for geometry in group.geometry: - if geometry is None: - continue - - try: - if geometry.is_empty: - continue - except Exception: - continue - - if isinstance(geometry, sh_geom.LineString): - if geometry.length > 0: - ordered_lines.append(geometry) - - elif isinstance( - geometry, - sh_geom.MultiLineString, - ): - parts = [ - part - for part in geometry.geoms - if not part.is_empty - and part.length > 0 - ] - - if not parts: - continue - - locally_merged = _safe_linemerge( - sh_ops.unary_union(parts) - ) - - if isinstance( - locally_merged, - sh_geom.LineString, - ): - if locally_merged.length > 0: - ordered_lines.append(locally_merged) - - elif isinstance( - locally_merged, - sh_geom.MultiLineString, - ): - ordered_lines.extend( - part - for part in locally_merged.geoms - if not part.is_empty - and part.length > 0 - ) - - if not ordered_lines: - logger.warning( - "OLnFID=%s has no usable line parts", - original_id, - ) - continue - - oriented = [ordered_lines[0]] - - for current in ordered_lines[1:]: - - previous = oriented[-1] - - previous_end = sh_geom.Point( - previous.coords[-1] - ) - - start_gap = previous_end.distance( - sh_geom.Point(current.coords[0]) - ) - - end_gap = previous_end.distance( - sh_geom.Point(current.coords[-1]) - ) - - if end_gap < start_gap: - current = _reverse_line(current) - - oriented.append(current) - coords = list(oriented[0].coords) - - max_gap = 0.0 - - for i, line in enumerate(oriented[1:], start=1): - - line_coords = list(line.coords) - - gap = ( - sh_geom.Point(coords[-1]) - .distance( - sh_geom.Point(line_coords[0]) - ) - ) - - max_gap = max(max_gap, gap) - - if gap > max_bridge_gap: - coords.append(line_coords[0]) - coords.extend(line_coords[1:]) - - merged = sh_geom.LineString(coords) - - if merged is None or merged.is_empty: - logger.warning( - "OLnFID=%s produced no geometry during merge", - original_id, - ) - continue - - row = group.iloc[0].copy() - row.geometry = merged - row[group_field] = original_id - row[order_field] = output_segment_value - row[geometry_count_field] = len(ordered_lines) - row["merge_max_gap"] = max_gap - row["merge_status"] = ("merged" if max_gap <= max_bridge_gap else "bridged") - output_rows.append(row) - - return gpd.GeoDataFrame( - output_rows, - geometry="geometry", - crs=crs, - ).reset_index(drop=True) - -def merge_corridors_by_original_id( - corridor_gdf, - group_field="OLnFID", - order_field="OLnSEG", - repair_invalid=True, -): - """ - Union corridor polygons back to one record per - original seedline ID. - """ - if corridor_gdf is None or corridor_gdf.empty: - return corridor_gdf - - if group_field not in corridor_gdf.columns: - raise KeyError( - f"Missing grouping field: {group_field}" - ) - - output_rows = [] - crs = corridor_gdf.crs - - for original_id, group in corridor_gdf.groupby( - group_field, - sort=False, - ): - polygon_parts = [] - - for geometry in group.geometry: - if geometry is None or geometry.is_empty: - continue - - if repair_invalid and not geometry.is_valid: - geometry = geometry.buffer(0) - - if geometry is None or geometry.is_empty: - continue - - if isinstance(geometry, sh_geom.Polygon): - polygon_parts.append(geometry) - - elif isinstance( - geometry, - sh_geom.MultiPolygon, - ): - polygon_parts.extend( - list(geometry.geoms) - ) - - if not polygon_parts: - continue - - merged = sh_ops.unary_union( - polygon_parts - ) - - if repair_invalid and not merged.is_valid: - merged = merged.buffer(0) - - row = group.iloc[0].copy() - row.geometry = merged - row[group_field] = original_id - - if order_field in row.index: - row[order_field] = -1 - - row["merged_corridor_part_count"] = len( - polygon_parts - ) - - row["merge_status"] = ( - "merged" - if isinstance(merged, sh_geom.Polygon) - else "disconnected" - ) - - output_rows.append(row) - - return gpd.GeoDataFrame( - output_rows, - geometry="geometry", - crs=crs, - ).reset_index(drop=True) - -def chk_df_multipart(df:gpd.GeoDataFrame, - chk_shp_in_string:str)-> tuple[gpd.GeoDataFrame , bool]: - """ - This function is check the input geopandas.GeoDataFrame object contains multipart geometry. - If multipart geometry is found, function will try to explode and return single geometry and - a boolean of multipart is found or not. - Args: - df: Any geopandas.GeoDataFrame like - chk_shp_in_string: String that the input GeoDataFrame geometry type expected to contain, i.e. 'Point', 'Polygon', 'LineString' - - Returns: Expected geometry type and boolean of multipart geometry - - """ - - try: - found = False - # Check the OLnFID column in data. If it is not, column will be created - if "OLnFID" not in df.columns.array: - print("New column created: {}".format("OLnFID")) - df["OLnFID"] = df.index - - # Check the OLnSEG column in data. If it is not, column will be created - if "OLnSEG" not in df.columns.array: - print("New column created: {}".format("OLnSEG")) - df["OLnSEG"] = 0 - - if has_multilinestring(df): - found = True - df = df.explode() - if type(df) is gpd.geodataframe.GeoDataFrame: - df["OLnSEG"] = df.groupby("OLnFID").cumcount() - df = df.sort_values(by=["OLnFID", "OLnSEG"]) - df = df.reset_index(drop=True) - else: - found = False - - return df, found - except Exception as e: - print(e) - return df, True - - -def _is_degenerate_line( - line, - min_length=1.0, - endpoint_tolerance=1e-6, - min_straightness=0.10, - stage="final",): - """ - Return True when a line is unusable. - - Parameters - ---------- - line : shapely geometry - LineString or mergeable MultiLineString. - - min_length : float - Minimum length used primarily for final merged output. - - endpoint_tolerance : float - Absolute tolerance for coincident endpoints. - - min_straightness : float - Minimum endpoint-gap / line-length ratio. - - stage : {"segment", "regeneration", "final"} - Controls how strictly the line is validated. - """ - - if line is None: - return True - - try: - if line.is_empty: - return True - except Exception: - return True - - if isinstance(line, sh_geom.MultiLineString): - try: - merged = _safe_linemerge(line) - except Exception: - return True - - if isinstance(merged, sh_geom.MultiLineString): - # Individual centerline should normally be connected. - # Final merge may handle components separately. - return True - - line = merged - - if not isinstance(line, sh_geom.LineString): - return True - - try: - length = float(line.length) - except (TypeError, ValueError, OverflowError): - return True - - if not np.isfinite(length): - return True - - if length <= endpoint_tolerance: - return True - - try: - coords = list(line.coords) - except Exception: - return True - - if len(coords) < 2: - return True - - xy_coords = [] - - for coord in coords: - if len(coord) < 2: - return True - - x = float(coord[0]) - y = float(coord[1]) - - if not np.isfinite(x) or not np.isfinite(y): - return True - - xy_coords.append((x, y)) - - if len(set(xy_coords)) < 2: - return True - - endpoint_gap = sh_geom.Point(xy_coords[0]).distance( - sh_geom.Point(xy_coords[-1]) - ) - - if endpoint_gap <= endpoint_tolerance: - return True - - straightness = endpoint_gap / max(length, 1e-9) - - if stage == "segment": - # Be permissive. Short segments are expected when - # proc_segments=True. - # - # Reject only an extreme loop or retracing collapse. - if length >= max(2.0 * min_length, endpoint_tolerance): - if straightness < 0.05: - return True - - return False - - if stage == "regeneration": - # Regenerated pieces need some meaningful endpoint extent, - # but can still be short. - if length < max(0.25 * min_length, endpoint_tolerance): - return True - - if straightness < 0.08: - return True - - return False - - if stage == "final": - # Strong checks apply only after restoring the original ID. - if length < min_length: - logger.info( - f"DEGENERATE length={length:.2f}" - ) - return True - - if straightness < min_straightness: - logger.info( - f"DEGENERATE straightness={straightness:.4f}" - ) - return True - - return False - - raise ValueError( - "stage must be 'segment', 'regeneration', or 'final'" - ) - - -def prepare_gpkg_layer( - gpkg, - layer): - - gpkg = Path(gpkg) - - if not gpkg.exists(): - return - - layers = pyogrio.list_layers(gpkg) - - layer_names = [ - row[0] - for row in layers - ] - - if layer not in layer_names: - return - - conn = sqlite3.connect(gpkg) - - try: - - conn.execute( - f'DROP TABLE "{layer}"' - ) - - conn.execute( - "DELETE FROM gpkg_contents " - "WHERE table_name=?", - (layer,) - ) - - conn.execute( - "DELETE FROM gpkg_geometry_columns " - "WHERE table_name=?", - (layer,) - ) - - conn.commit() - - finally: - - conn.close() - -def drop_layer_if_exists( - gpkg, - layer): - - if not Path(gpkg).exists(): - return - - layers = pyogrio.list_layers(gpkg) - - layer_names = [ - row[0] - for row in layers - ] - - if layer not in layer_names: - return - - conn = sqlite3.connect(gpkg) - - try: - - conn.execute( - f'DROP TABLE "{layer}"' - ) - - conn.execute( - "DELETE FROM gpkg_contents " - "WHERE table_name=?", - (layer,) - ) - - conn.execute( - "DELETE FROM gpkg_geometry_columns " - "WHERE table_name=?", - (layer,) - ) - - conn.commit() +import sys +import warnings - finally: +from beratools.modules.mapping import algo_common as _moved - conn.close() +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" for full license details. - -Author: Richard Zeng - -Description: - This script is part of the BERA Tools. - Webpage: https://github.com/BERATool/beratools - - This file hosts cost raster related functions. +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -import numpy as np -import scipy -from rasterio.features import geometry_mask - -import beratools.core.constants as bt_const - - -def reduce_chm_in_line_buffer( - in_chm, - meta, - line, - buffer_width, - multiplier=0.5, -): - """Return a CHM copy with valid values reduced inside a line buffer.""" - buffer_width = float(buffer_width) - multiplier = float(multiplier) - if buffer_width < 0.0: - raise ValueError("buffer_width must be greater than or equal to zero") - if not 0.0 <= multiplier <= 1.0: - raise ValueError("multiplier must be between zero and one") - if line is None or line.is_empty: - raise ValueError("line must be a non-empty geometry") - - source = np.ma.asarray(in_chm) - if source.ndim == 2: - raster_shape = source.shape - elif source.ndim == 3 and source.shape[0] == 1: - raster_shape = source.shape[1:] - else: - raise ValueError("in_chm must be a 2D or single-band 3D raster") - - reduced = np.ma.array(source, dtype=float, copy=True) - if buffer_width == 0.0 or multiplier == 1.0: - return reduced - - inside_buffer = geometry_mask( - [line.buffer(buffer_width)], - out_shape=raster_shape, - transform=meta["transform"], - invert=True, - ) - if reduced.ndim == 3: - inside_buffer = inside_buffer[np.newaxis, ...] - - data = reduced.data - valid = inside_buffer & ~np.ma.getmaskarray(reduced) & np.isfinite(data) - nodata = meta.get("nodata") - if nodata is not None and np.isfinite(nodata): - valid &= data != nodata - data[valid] *= multiplier - return reduced - - -def cost_raster( - in_raster, - meta, - tree_radius=2.5, - canopy_ht_threshold=2.5, - max_line_dist=2.5, - canopy_avoid=0.4, - cost_raster_exponent=1.5, -): - """ - General version of cost_raster. - - To be merged later: variables and consistent nodata solution - - """ - if len(in_raster.shape) > 2: - in_raster = np.squeeze(in_raster, axis=0) - - # regulate canopy_avoid between 0 and 1 - avoidance = max(0, min(1, canopy_avoid)) - cell_x, cell_y = meta["transform"][0], -meta["transform"][4] - - kernel_radius = int(tree_radius / cell_x) - kernel = circle_kernel_refactor(2 * kernel_radius + 1, kernel_radius) - dyn_canopy_ndarray = dyn_np_cc_map(in_raster, canopy_ht_threshold) - - cc_std, cc_mean = cost_focal_stats(dyn_canopy_ndarray, kernel) - cc_smooth = cost_norm_dist_transform(dyn_canopy_ndarray, max_line_dist, [cell_x, cell_y]) - - cost_clip = dyn_np_cost_raster_refactor( - dyn_canopy_ndarray, cc_mean, cc_std, cc_smooth, avoidance, cost_raster_exponent - ) - - # TODO use nan or BT_DATA? - cost_clip[in_raster == bt_const.BT_NODATA] = np.nan - dyn_canopy_ndarray[in_raster == bt_const.BT_NODATA] = np.nan - - return cost_clip, dyn_canopy_ndarray - - -def remove_nan_from_array_refactor(matrix, replacement_value=bt_const.BT_NODATA_COST): - # Use boolean indexing to replace nan values - matrix[np.isnan(matrix)] = replacement_value - - -def dyn_np_cc_map(in_chm, canopy_ht_threshold): - """ - Create a new canopy raster. - - MaskedArray based on the threshold comparison of in_chm (canopy height model) - with canopy_ht_threshold. It assigns 1.0 where the condition is True (canopy) - and 0.0 where the condition is False (non-canopy). - - """ - canopy_ndarray = np.ma.where(in_chm >= canopy_ht_threshold, 1.0, 0.0).astype(float) - return canopy_ndarray - - -def cost_focal_stats(canopy_ndarray, kernel): - mask = canopy_ndarray.mask if np.ma.is_masked(canopy_ndarray) else np.zeros(canopy_ndarray.shape, dtype=bool) - # Replace masked/nan values with 0 for convolution; track valid pixel counts - data = np.where(mask, 0.0, np.asarray(canopy_ndarray, dtype=float)) - valid = (~mask).astype(float) - - # Use fast C-level convolution instead of generic_filter with Python callbacks - kernel_f = kernel.astype(float) - sum_vals = scipy.ndimage.convolve(data, kernel_f, mode="nearest") - count = scipy.ndimage.convolve(valid, kernel_f, mode="nearest") - count = np.maximum(count, 1.0) # avoid division by zero - - mean_array = sum_vals / count - - # Var = E[X^2] - E[X]^2 - sum_sq = scipy.ndimage.convolve(data * data, kernel_f, mode="nearest") - variance = sum_sq / count - mean_array * mean_array - variance = np.maximum(variance, 0.0) # clamp numerical noise - std_array = np.sqrt(variance) - - return std_array, mean_array - - -def cost_norm_dist_transform(canopy_ndarray, max_line_dist, sampling): - """Compute a distance-based cost map based on the proximity of valid data points.""" - # Convert masked array to a regular array and fill the masked areas with np.nan - in_ndarray = canopy_ndarray.filled(np.nan) - - # Compute the Euclidean distance transform (edt) where the valid values are - euc_dist_array = scipy.ndimage.distance_transform_edt( - np.logical_not(np.isnan(in_ndarray)), sampling=sampling - ) - - # Apply the mask back to set the distances to np.nan - euc_dist_array[canopy_ndarray.mask] = np.nan - - # Calculate the smoothness (cost) array - normalized_cost = float(max_line_dist) - euc_dist_array - normalized_cost[normalized_cost <= 0.0] = 0.0 - smooth_cost_array = normalized_cost / float(max_line_dist) - - return smooth_cost_array - - -def dyn_np_cost_raster_refactor(canopy_ndarray, cc_mean, cc_std, cc_smooth, avoidance, cost_raster_exponent): - # Calculate the lower and upper bounds for canopy cover (mean ± std deviation) - lower_bound = cc_mean - cc_std - upper_bound = cc_mean + cc_std - - # Calculate the ratio between the lower and upper bounds - ratio_lower_upper = np.divide( - lower_bound, - upper_bound, - where=upper_bound != 0, - out=np.zeros(lower_bound.shape, dtype=float), - ) - - # Normalize the ratio to a scale between 0 and 1 - normalized_ratio = (1 + ratio_lower_upper) / 2 - - # Adjust where the sum of mean and std deviation is less than or equal to zero - adjusted_cover = cc_mean + cc_std - adjusted_ratio = np.where(adjusted_cover <= 0, 0, normalized_ratio) - - # Combine canopy cover ratio with smoothing, weighted by avoidance factor - weighted_cover = adjusted_ratio * (1 - avoidance) + (cc_smooth * avoidance) - - # Final cost modification based on canopy presence (masked by canopy_ndarray) - final_cost = np.where(canopy_ndarray.data == 1, 1, weighted_cover) - - # Apply the exponential transformation to the cost values - exponent_cost = np.exp(final_cost) - - # Raise the cost to the specified exponent - result_cost_raster = np.power(exponent_cost, float(cost_raster_exponent)) - - return result_cost_raster - - -def circle_kernel_refactor(size, radius): - """ - Create a circular kernel using Scipy. - - Args: - size : kernel size - radius : radius of the circle - - Returns: - kernel (ndarray): A circular kernel. - - Examples: - kernel_scipy = create_circle_kernel_scipy(17, 8) - will replicate xarray-spatial kernel - cell_x = 0.3 - cell_y = 0.3 - tree_radius = 2.5 - convolution.circle_kernel(cell_x, cell_y, tree_radius) - - """ - # Create grid points (mesh) - y, x = np.ogrid[:size, :size] - - # Center of the kernel - center_x, center_y = (size - 1) / 2, (size - 1) / 2 - - # Calculate the distance from the center - distance = np.sqrt((x - center_x) ** 2 + (y - center_y) ** 2) - - # Create a circular kernel - kernel = distance <= radius - return kernel.astype(float) - - -def alt_cost_raster( - in_raster, - meta, - tree_gaps, - tree_radius=2.5, - canopy_ht_threshold=2.5, - max_line_dist=2.5, - canopy_avoid=0.4, - cost_raster_exponent=1.5, -): - """ - Alternative version of cost_raster. - - """ - - def alt_dyn_np_cc_map(in_chm, canopy_ht_threshold, tree_gaps=None): - """ - Create a new canopy raster. - - MaskedArray based on the threshold comparison of in_chm (canopy height model) - with canopy_ht_threshold. It assigns 1.0 where the condition is True (canopy) - and 0.0 where the condition is False (non-canopy). - - """ - - canopy_ndarray = np.ma.where(in_chm >= canopy_ht_threshold, 1.0, 0.0).astype(float) - canopy_ndarray = np.ma.where(tree_gaps.astype(bool), 0.0, canopy_ndarray) - - return canopy_ndarray - - def alt_cost_focal_stats(canopy_ndarray, kernel, tree_gaps=None): - mask = canopy_ndarray.mask if np.ma.is_masked(canopy_ndarray) else np.zeros(canopy_ndarray.shape, dtype=bool) - # Replace masked/nan values with 0 for convolution; track valid pixel counts - data = np.where(mask, 0.0, np.asarray(canopy_ndarray, dtype=float)) - data[tree_gaps.astype(bool)] = 0.0 - valid = (~mask).astype(float) - - # Use fast C-level convolution instead of generic_filter with Python callbacks - kernel_f = kernel.astype(float) - sum_vals = scipy.ndimage.convolve(data, kernel_f, mode="nearest") - count = scipy.ndimage.convolve(valid, kernel_f, mode="nearest") - count = np.maximum(count, 1.0) # avoid division by zero - - mean_array = sum_vals / count - - # Var = E[X^2] - E[X]^2 - sum_sq = scipy.ndimage.convolve(data * data, kernel_f, mode="nearest") - variance = sum_sq / count - mean_array * mean_array - variance = np.maximum(variance, 0.0) # clamp numerical noise - std_array = np.sqrt(variance) - - return std_array, mean_array - - def alt_cost_norm_dist_transform(canopy_ndarray, max_line_dist, sampling, tree_gaps=None): - """Compute a distance-based cost map based on the proximity of valid data points.""" - # Convert masked array to a regular array and fill the masked areas with np.nan - in_ndarray = canopy_ndarray.filled(np.nan) - in_ndarray[tree_gaps.astype(bool)] = 0.0 - # Compute the Euclidean distance transform (edt) where the valid values are - dist_transform_array = scipy.ndimage.distance_transform_edt(np.logical_not(np.isnan(in_ndarray)), - sampling=sampling - ) - - # Apply the mask back to set the distances to np.nan - dist_transform_array[canopy_ndarray.mask] = np.nan - # dist_transform_crown_array[canopy_ndarray.mask] = np.nan - - # Calculate the smoothness (cost) array - normalized_cost = float(max_line_dist) - dist_transform_array # *dist_transform_crown_array) - normalized_cost[normalized_cost <= 0.0] = 0.0 - smooth_cost_array = normalized_cost / float(max_line_dist) - - return smooth_cost_array - - def alt_dyn_np_cost_raster_refactor(canopy_ndarray, cc_mean, cc_std, cc_smooth, avoidance, cost_raster_exponent, - tree_gaps=None): - # Calculate the lower and upper bounds for canopy cover (mean ± std deviation) - lower_bound = cc_mean - cc_std - upper_bound = cc_mean + cc_std - - # Calculate the ratio between the lower and upper bounds - ratio_lower_upper = np.divide( - lower_bound, - upper_bound, - where=upper_bound != 0, - out=np.zeros(lower_bound.shape, dtype=float), - ) - - # Normalize the ratio to a scale between 0 and 1 - normalized_ratio = (1 + ratio_lower_upper) / 2 - - # Adjust where the sum of mean and std deviation is less than or equal to zero - adjusted_cover = cc_mean + cc_std - adjusted_ratio = np.where(adjusted_cover <= 0, 0, normalized_ratio) - - # Combine canopy cover ratio with smoothing, weighted by avoidance factor - weighted_cover = adjusted_ratio * (1 - avoidance) + (cc_smooth * avoidance) - - # Final cost modification based on canopy presence (masked by canopy_ndarray) - final_cost = np.where(canopy_ndarray.data == 1, 1, weighted_cover) - - # Apply the exponential transformation to the cost values - exponent_cost = np.exp(final_cost) - - # Raise the cost to the specified exponent - result_cost_raster = np.power(exponent_cost, float(cost_raster_exponent)) - result_cost_raster[tree_gaps == 1] = 1.0 - - return result_cost_raster - - if len(in_raster.shape) > 2: - in_raster = np.squeeze(in_raster, axis=0) - - # regulate canopy_avoid between 0 and 1 - avoidance = max(0, min(1, int(canopy_avoid))) - cell_x, cell_y = meta["transform"][0], -meta["transform"][4] - tree_gaps_=tree_gaps.copy() - tree_gaps_[tree_gaps<=canopy_ht_threshold]=0 - kernel_radius = int(tree_radius / cell_x) - kernel = circle_kernel_refactor(2 * kernel_radius + 1, kernel_radius) - dyn_canopy_ndarray = alt_dyn_np_cc_map(in_raster, canopy_ht_threshold, tree_gaps_) - - cc_std, cc_mean = alt_cost_focal_stats(dyn_canopy_ndarray, kernel, tree_gaps_) - cc_smooth = alt_cost_norm_dist_transform(dyn_canopy_ndarray, max_line_dist, [cell_x, cell_y],tree_gaps_) - - cost_clip = alt_dyn_np_cost_raster_refactor( - dyn_canopy_ndarray, cc_mean, cc_std, cc_smooth, avoidance, cost_raster_exponent,tree_gaps_ - ) +import sys +import warnings - # TODO use nan or BT_DATA? - cost_clip[in_raster == bt_const.BT_NODATA] = np.nan - dyn_canopy_ndarray[in_raster == bt_const.BT_NODATA] = np.nan +from beratools.modules.mapping import algo_cost as _moved - return cost_clip, dyn_canopy_ndarray +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=("= size_of_grid: - return False - if node[1] < 0 or node[1] >= size_of_grid: - return False - return True - - -def up(node): - return node[0] - 1, node[1] - - -def down(node): - return node[0] + 1, node[1] - - -def left(node): - return node[0], node[1] - 1 - - -def right(node): - return node[0], node[1] + 1 - - -def backtrack(initial_node, desired_node, distances): - # idea start at the last node then choose the least number of steps to go back - # last node - path = [desired_node] - - size_of_grid = distances.shape[0] - - while True: - # check up down left right - choose the direction that has the least distance - potential_distances = [] - potential_nodes = [] - - directions = [up, down, left, right] - - for direction in directions: - node = direction(path[-1]) - if valid_node(node, size_of_grid): - potential_nodes.append(node) - potential_distances.append(distances[node[0], node[1]]) - - print(potential_nodes) - - least_distance_index = np.argsort(potential_distances) - - pt_added = False - for index in least_distance_index: - p_point = potential_nodes[index] - if p_point == (1, 6): - pass - if p_point not in path: - path.append(p_point) - pt_added = True - break - - if index >= len(potential_distances) - 1 and not pt_added: - print("No best path found.") - return - - if path[-1][0] == initial_node[0] and path[-1][1] == initial_node[1]: - break - - if len(path) == 0 or path[-1][0] != initial_node[0] or path[-1][1] != initial_node[1]: - return None - - return list(reversed(path)) - - -def dijkstra_np(start_tuple, end_tuple, matrix): - """ - Dijkstra's algorithm for finding the shortest path between two nodes in a graph. - - Args: - start_node (list): [row,col] coordinates of the initial node - end_node (list): [row,col] coordinates of the desired node - matrix (array 2d): numpy array that contains matrix as 1s and free space as 0s - - Returns: - list[list]: list of list of nodes that form the shortest path - - """ - # source and destination are free - start_node = start_tuple[0] - end_node = end_tuple[0] - path = None - costs = None - - try: - matrix[start_node[0], start_node[1]] = 0 - matrix[end_node[0], end_node[1]] = 0 - - path, cost = sk_graph.route_through_array(matrix, start_node, end_node) - costs = [0.0 for i in range(len(path))] - except Exception as e: - print(f"dijkstra_np: {e}") - return None - - return [(path, costs, end_tuple)] - - -def find_least_cost_path(out_image, in_meta, line, find_nearest=True, output_linear_reference=False): - default_return = None - ras_nodata = in_meta["nodata"] - - pt_start = line.coords[0] - pt_end = line.coords[-1] - - out_image = np.where(out_image < 0, np.nan, out_image) # set negative value to nan - if len(out_image.shape) > 2: - out_image = np.squeeze(out_image, axis=0) - - if USE_NUMPY_FOR_DIJKSTRA: - matrix, contains_negative = MinCostPathHelper.block2matrix_numpy(out_image, ras_nodata) - else: - matrix, contains_negative = MinCostPathHelper.block2matrix(out_image, ras_nodata) - - if contains_negative: - print("ERROR: Raster has negative values.") - return default_return - - transformer = rasterio.transform.AffineTransformer(in_meta["transform"]) - - if ( - type(pt_start[0]) is tuple - or type(pt_start[1]) is tuple - or type(pt_end[0]) is tuple - or type(pt_end[1]) is tuple - ): - print("Point initialization error. Input is tuple.") - return default_return - - start_tuples = [] - end_tuples = [] - start_tuple = [] - try: - start_tuples = [ - ( - transformer.rowcol(pt_start[0], pt_start[1]), - sh_geom.Point(pt_start[0], pt_start[1]), - 0, - ) - ] - end_tuples = [ - ( - transformer.rowcol(pt_end[0], pt_end[1]), - sh_geom.Point(pt_end[0], pt_end[1]), - 1, - ) - ] - start_tuple = start_tuples[0] - end_tuple = end_tuples[0] - - # clamp row/col to valid matrix bounds - rows, cols = matrix.shape - - def _clamp_row_col(row_col): - row = max(0, min(int(row_col[0]), rows - 1)) - col = max(0, min(int(row_col[1]), cols - 1)) - return row, col - - start_tuple = (_clamp_row_col(start_tuple[0]), start_tuple[1], start_tuple[2]) - end_tuple = (_clamp_row_col(end_tuple[0]), end_tuple[1], end_tuple[2]) - - except Exception as e: - print(f"find_least_cost_path: {e}") - - if USE_NUMPY_FOR_DIJKSTRA: - result = dijkstra_np(start_tuple, end_tuple, matrix) - else: - # TODO: change end_tuples to end_tuple - result = dijkstra(start_tuple, end_tuples, matrix, find_nearest) - - if result is None: - return default_return - - if len(result) == 0: - print("No result returned.") - return default_return - - path_points = None - for path, costs, end_tuple in result: - path_points = MinCostPathHelper.create_points_from_path( - transformer, path, start_tuple[1], end_tuple[1] - ) - if output_linear_reference: - # TODO: code not reached - # add linear reference - for point, cost in zip(path_points, costs): - point.addMValue(cost) - - # feat_attr = (start_tuple[2], end_tuple[2], total_cost) - lc_path = None - if len(path_points) >= 2: - lc_path = sh_geom.LineString(path_points) - - return lc_path - - -def find_least_cost_path_skimage(cost_clip, in_meta, seed_line): - lc_path_new = [] - if len(cost_clip.shape) > 2: - cost_clip = np.squeeze(cost_clip, axis=0) - - out_transform = in_meta["transform"] - transformer = rasterio.transform.AffineTransformer(out_transform) - - x1, y1 = list(seed_line.coords)[0][:2] - x2, y2 = list(seed_line.coords)[-1][:2] - row1, col1 = transformer.rowcol(x1, y1) - row2, col2 = transformer.rowcol(x2, y2) - - try: - path_new = sk_graph.route_through_array(cost_clip[0], [row1, col1], [row2, col2]) - except Exception as e: - print(f"find_least_cost_path_skimage: {e}") - return None - - if path_new[0]: - for row, col in path_new[0]: - x, y = transformer.xy(row, col) - lc_path_new.append((x, y)) +import sys +import warnings - if len(lc_path_new) < 2: - print("No least cost path detected, pass.") - return None - else: - lc_path_new = sh_geom.LineString(lc_path_new) +from beratools.modules.mapping import algo_dijkstra as _moved - return lc_path_new +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" LineString: - if line is None or line.is_empty or iterations <= 0 or len(line.coords) < 3: - return line - - points = [(float(x), float(y)) for x, y, *_ in line.coords] - for _ in range(iterations): - smoothed = [points[0]] - for point, next_point in zip(points, points[1:]): - smoothed.append((0.75 * point[0] + 0.25 * next_point[0], 0.75 * point[1] + 0.25 * next_point[1])) - smoothed.append((0.25 * point[0] + 0.75 * next_point[0], 0.25 * point[1] + 0.75 * next_point[1])) - smoothed.append(points[-1]) - points = smoothed - return LineString(points) - - -def chaikin_smooth_polygon(geometry, *, iterations: int): - if geometry is None or geometry.is_empty or iterations <= 0: - return geometry - if geometry.geom_type == "Polygon": - exterior = _chaikin_smooth_ring(geometry.exterior.coords, iterations=iterations) - interiors = [_chaikin_smooth_ring(interior.coords, iterations=iterations) for interior in geometry.interiors] - return Polygon(exterior, interiors) - if geometry.geom_type == "MultiPolygon": - return MultiPolygon([chaikin_smooth_polygon(part, iterations=iterations) for part in geometry.geoms]) - return geometry - - -def process_corridor_polygon( - polygon, - cid=None, - *, - delete_holes=False, - simplify=False, - simplify_length=0.0, - smooth=False, - smooth_iterations=0, -): - """Apply stage-8 style polygon cleanup, simplification, and smoothing.""" - - if polygon is None or polygon.is_empty: - return polygon - - processed = polygon - if delete_holes: - processed = _delete_polygon_holes(processed) - processed = processed.buffer(0.5) - processed = processed.buffer(-0.5) - if simplify and float(simplify_length) > 0: - area_before = processed.area - processed = processed.simplify(float(simplify_length), preserve_topology=True) - logger.debug( - f"{cid} simplify " - f"area_change=" - f"{100 * (processed.area - area_before) / area_before:.2f}%") - if smooth and int(smooth_iterations) > 0: - processed = chaikin_smooth_polygon(processed, iterations=int(smooth_iterations)) - if processed is not None and not processed.is_valid: - processed = processed.buffer(0) - return processed - - -def _delete_polygon_holes(geometry): - if geometry.geom_type == "Polygon": - return Polygon(geometry.exterior) - if geometry.geom_type == "MultiPolygon": - return MultiPolygon([Polygon(poly.exterior) for poly in geometry.geoms]) - return geometry - - -def _chaikin_smooth_ring(coords, *, iterations: int) -> list[tuple[float, float]]: - points = [(float(x), float(y)) for x, y, *_ in coords] - if len(points) > 1 and points[0] == points[-1]: - points = points[:-1] - if len(points) < 3 or iterations <= 0: - return points + points[:1] - - for _ in range(iterations): - smoothed = [] - for index, point in enumerate(points): - next_point = points[(index + 1) % len(points)] - smoothed.append((0.75 * point[0] + 0.25 * next_point[0], 0.75 * point[1] + 0.25 * next_point[1])) - smoothed.append((0.25 * point[0] + 0.75 * next_point[0], 0.25 * point[1] + 0.75 * next_point[1])) - points = smoothed - return points + points[:1] +""" +Deprecated: moved to beratools.modules.mapping. + +Kept so old imports keep working, with a DeprecationWarning, until it is removed. +""" + +import sys +import warnings + +from beratools.modules.mapping import algo_geometry as _moved + +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" for full license details. - -Author: Richard Zeng, Maverick Fong - -Description: - This script is part of the BERA Tools. - Webpage: https://github.com/BERATool/beratools - - This file hosts code to deal with line grouping and merging, cleanups. +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -import enum -from collections import defaultdict -from dataclasses import dataclass, field -from itertools import chain -from typing import Optional, Union - -import networkit as nk -import numpy as np -import shapely -import shapely.geometry as sh_geom - -import beratools.core.algo_common as algo_common -import beratools.core.algo_merge_lines as algo_merge_lines -import beratools.core.constants as bt_const - -TRIMMING_DISTANCE = 75 # meters -SMALL_BUFFER = 1 - +import sys +import warnings -@enum.unique -class VertexClass(enum.IntEnum): - """Enum class for vertex class.""" +from beratools.modules.mapping import algo_line_grouping as _moved - TWO_WAY_ZERO_PRIMARY_LINE = 1 - THREE_WAY_ZERO_PRIMARY_LINE = 2 - THREE_WAY_ONE_PRIMARY_LINE = 3 - FOUR_WAY_ZERO_PRIMARY_LINE = 4 - FOUR_WAY_ONE_PRIMARY_LINE = 5 - FOUR_WAY_TWO_PRIMARY_LINE = 6 - FIVE_WAY_ZERO_PRIMARY_LINE = 7 - FIVE_WAY_ONE_PRIMARY_LINE = 8 - FIVE_WAY_TWO_PRIMARY_LINE = 9 - SINGLE_WAY = 10 - - -CONCERN_CLASSES = ( - VertexClass.FIVE_WAY_ZERO_PRIMARY_LINE, - VertexClass.FIVE_WAY_ONE_PRIMARY_LINE, - VertexClass.FIVE_WAY_TWO_PRIMARY_LINE, - VertexClass.FOUR_WAY_ZERO_PRIMARY_LINE, - VertexClass.FOUR_WAY_ONE_PRIMARY_LINE, - VertexClass.FOUR_WAY_TWO_PRIMARY_LINE, - VertexClass.THREE_WAY_ZERO_PRIMARY_LINE, - VertexClass.THREE_WAY_ONE_PRIMARY_LINE, - VertexClass.TWO_WAY_ZERO_PRIMARY_LINE, - VertexClass.SINGLE_WAY, +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" None: - self.vertex = None - self.line_list = [] - self.line_connected = [] # pairs of lines connected - self.line_not_connected = [] - self.vertex_class = None - - if line: - self.add_line(SingleLine(line_id, line, sim_line, vertex_index, group)) - - def set_vertex(self, line, vertex_index): - """Set vertex coordinates.""" - if line is None: - self.vertex = None - return - - if line.is_empty: - self.vertex = None - return - - try: - self.vertex = shapely.force_2d( - shapely.get_point(line, vertex_index) - ) - except Exception: - self.vertex = None - - def add_line(self, line_class): - """Add line when creating or merging other VertexNode.""" - self.line_list.append(line_class) - self.set_vertex(line_class.line, line_class.vertex_index) - - def get_line(self, line_id): - for line in self.line_list: - if line.line_id == line_id: - return line.line - - def get_line_obj(self, line_id): - for line in self.line_list: - if line.line_id == line_id: - return line - - def get_line_geom(self, line_id): - return self.get_line_obj(line_id).line - - def get_all_line_ids(self): - all_line_ids = {i.line_id for i in self.line_list} - return all_line_ids - - def update_line(self, line_id, line): - for i in self.line_list: - if i.line_id == line_id: - i.update_line(line) - - def merge(self, vertex): - """Merge other VertexNode if they have same vertex coords.""" - self.add_line(vertex.line_list[0]) - - def get_trim_transect(self, poly, line_indices): - if not poly: - return None - - internal_line = None - for line_idx in line_indices: - line = self.get_line_obj(line_idx) - if poly.contains(line.midpoint()): - internal_line = line - - if not internal_line: - # print("No line is retrieved") - return None - return internal_line.end_transect() - - def _trim_polygon(self, poly, trim_transect): - if not poly or not trim_transect: - return None - - split_poly = shapely.ops.split(poly, trim_transect) - - if len(split_poly.geoms) != 2: - return - - # check geom_type - none_poly = False - for geom in split_poly.geoms: - if geom.geom_type != "Polygon": - none_poly = True - - if none_poly: - return None - - # only two polygons in split_poly - if split_poly.geoms[0].area > split_poly.geoms[1].area: - poly = split_poly.geoms[0] - else: - poly = split_poly.geoms[1] - - return poly - - def trim_end_all(self, polys): - """ - Trim all unconnected lines in the vertex. - - Args: - polys: list of polygons returned by sindex.query - - """ - polys = polys.geometry - new_polys = [] - for idx, poly in polys.items(): - out_poly = self.trim_end(poly) - if out_poly: - new_polys.append((idx, out_poly)) - - return new_polys - - def trim_end(self, poly): - transect = self.get_trim_transect(poly, self.line_not_connected) - if not transect: - return None - - poly = self._trim_polygon(poly, transect) - return poly - # Helper to get the neighbor coordinate based on vertex_index. - - @staticmethod - def get_vertex(line_obj, index): - coords = list(line_obj.sim_line.coords) - # Normalize negative indices. - if index < 0: - index += len(coords) - if 0 <= index < len(coords): - return sh_geom.Point(coords[index]) - return None - - @staticmethod - def get_neighbor(line_obj): - index = 0 - - if line_obj.vertex_index == 0: - index = 1 - elif line_obj.vertex_index == -1: - index = -2 - - return VertexNode.get_vertex(line_obj, index) - - @staticmethod - def parallel_line_centered(p1, p2, center, length): - """Generate a parallel line.""" - # Compute the direction vector. - dx = p2.x - p1.x - dy = p2.y - p1.y - - # Normalize the direction vector. - magnitude = (dx**2 + dy**2) ** 0.5 - if magnitude == 0: - return None - dx /= magnitude - dy /= magnitude - - # Compute half-length shifts. - half_dx = (dx * length) / 2 - half_dy = (dy * length) / 2 - - # Compute the endpoints of the new parallel line. - new_p1 = sh_geom.Point(center.x - half_dx, center.y - half_dy) - new_p2 = sh_geom.Point(center.x + half_dx, center.y + half_dy) - - return sh_geom.LineString([new_p1, new_p2]) - - def get_transect_for_primary(self): - """ - Get a transect line from two primary connected lines. - - This method calculates a transect line that is perpendicular to the line segment - formed by the next vertex neighbors of these two lines and the current vertex. - - Return: - A transect line object if the conditions are met, otherwise None. - - """ - if not self.line_connected or len(self.line_connected[0]) != 2: - return None - - # Retrieve the two connected line objects from the first connectivity group. - line_ids = self.line_connected[0] - pt1 = None - pt1 = None - if line_ids[0] == line_ids[1]: # line ring - # TODO: check line ring when merging vertex nodes. - # TODO: change one end index to -1 - line_id = line_ids[0] - pt1 = self.get_vertex(self.get_line_obj(line_id), 1) - pt2 = self.get_vertex(self.get_line_obj(line_id), -2) - else: # two different lines - line_obj1 = self.get_line_obj(line_ids[0]) - line_obj2 = self.get_line_obj(line_ids[1]) - - pt1 = self.get_neighbor(line_obj1) - pt2 = self.get_neighbor(line_obj2) - - if pt1 is None or pt2 is None: - return None - - transect = algo_common.generate_perpendicular_line_precise([pt1, self.vertex, pt2], offset=40) - return transect - - def get_transect_for_primary_second(self): - """ - Get a transect line from the second primary connected line. - - For the second primary line, this method retrieves the neighbor point from - two lines in the second connectivity group, creates a reference line through the - vertex by mirroring the neighbor point about the vertex, and then generates a - parallel line centered at the vertex. - - Returns: - A LineString representing the transect if available, otherwise None. - - """ - # Ensure there is a second connectivity group. - if not self.line_connected or len(self.line_connected) < 2: - return None - - # Use the first line of the second connectivity group. - second_primary = self.line_connected[1] - line_obj1 = self.get_line_obj(second_primary[0]) - line_obj2 = self.get_line_obj(second_primary[1]) - if not line_obj1 or not line_obj2: - return None - - pt1 = self.get_neighbor(line_obj1) - pt2 = self.get_neighbor(line_obj2) - - if pt1 is None or pt2 is None: - return None - - center = self.vertex - transect = self.parallel_line_centered(pt1, pt2, center, TRANSECT_LENGTH) - return transect - - def trim_primary_end(self, polys): - """ - Trim first primary line in the vertex. - - Args: - polys: list of polygons returned by sindex.query - - """ - if len(self.line_connected) == 0: - return None - - new_polys = [] - line = self.line_connected[0] - - # use the first line to get transect - # transect = self.get_line_obj(line[0]).end_transect() - # if len(self.line_connected) == 1: - transect = self.get_transect_for_primary() - # elif len(self.line_connected) > 1: - # transect = self.get_transect_for_primary_second() - - idx_1 = line[0] - poly_1 = None - idx_1 = line[1] - poly_2 = None - - for idx, poly in polys.items(): - # TODO: no polygons - if not poly: - continue - - if poly.buffer(SMALL_BUFFER).contains(self.get_line_geom(line[0])): - poly_1 = poly - idx_1 = idx - elif poly.buffer(SMALL_BUFFER).contains(self.get_line_geom(line[1])): - poly_2 = poly - idx_2 = idx - - if poly_1: - poly_1 = self._trim_polygon(poly_1, transect) - new_polys.append([idx_1, poly_1]) - if poly_2: - poly_2 = self._trim_polygon(poly_2, transect) - new_polys.append([idx_2, poly_2]) - - return new_polys - - def trim_intersection(self, polys, merge_group=True): - """ - Trim intersection of lines and polygons. - - TODO: there are polygons of 0 zero. - - """ - - def get_poly_with_info(line, polys): - if polys.empty: - return None, None, None - - for idx, row in polys.iterrows(): - poly = row.geometry - if not poly: # TODO: no polygon - continue - - if poly.buffer(SMALL_BUFFER).contains(line): - return idx, poly, row["max_width"] - - return None, None, None - - poly_trim_list = [] - primary_lines = [] - p_primary_list = [] - - # retrieve primary lines - if len(self.line_connected) > 0: - for idx in self.line_connected[0]: # only one connected line is used - primary_lines.append(self.get_line(idx)) - _, poly, _ = get_poly_with_info(self.get_line(idx), polys) - - if poly: - p_primary_list.append(poly.buffer(bt_const.SMALL_BUFFER)) - else: - print("trim_intersection: No primary polygon found.") - - line_idx_to_trim = self.line_not_connected - poly_list = [] - if not merge_group: # add all remaining primary lines for trimming - if len(self.line_connected) > 1: - for line in self.line_connected[1:]: - line_idx_to_trim.extend(line) - - # sort line index to by footprint area - for line_idx in line_idx_to_trim: - line = self.get_line_geom(line_idx) - poly_idx, poly, max_width = get_poly_with_info(line, polys) - if poly_idx: - poly_list.append((line_idx, poly_idx, max_width)) - - poly_list = sorted(poly_list, key=lambda x: x[2]) - - # create PolygonTrimming object and trim all by primary line - for i, indices in enumerate(poly_list): - line_idx = indices[0] - poly_idx = indices[1] - line_cleanup = self.get_line(line_idx) - poly_cleanup = polys.loc[poly_idx].geometry - poly_trim = PolygonTrimming( - line_index=line_idx, - line_cleanup=line_cleanup, - poly_index=poly_idx, - poly_cleanup=poly_cleanup, - ) - - poly_trim_list.append(poly_trim) - if p_primary_list: - poly_trim.process(p_primary_list, self.vertex) - - # use poly_trim.poly_cleanup to update polys gdf's geometry - polys.at[poly_trim.poly_index, "geometry"] = poly_trim.poly_cleanup - - # further trimming overlaps by non-primary lines - # poly_list and poly_trim_list have same index - for i, indices in enumerate(poly_list): - p_list = [] - for p in poly_list[i + 1 :]: - p_list.append(polys.loc[p[1]].geometry) - - poly_trim = poly_trim_list[i] - poly_trim.process(p_list, self.vertex) - - return poly_trim_list - - def assign_vertex_class(self): - if len(self.line_list) == 5: - if len(self.line_connected) == 0: - self.vertex_class = VertexClass.FIVE_WAY_ZERO_PRIMARY_LINE - if len(self.line_connected) == 1: - self.vertex_class = VertexClass.FIVE_WAY_ONE_PRIMARY_LINE - if len(self.line_connected) == 2: - self.vertex_class = VertexClass.FIVE_WAY_TWO_PRIMARY_LINE - elif len(self.line_list) == 4: - if len(self.line_connected) == 0: - self.vertex_class = VertexClass.FOUR_WAY_ZERO_PRIMARY_LINE - if len(self.line_connected) == 1: - self.vertex_class = VertexClass.FOUR_WAY_ONE_PRIMARY_LINE - if len(self.line_connected) == 2: - self.vertex_class = VertexClass.FOUR_WAY_TWO_PRIMARY_LINE - elif len(self.line_list) == 3: - if len(self.line_connected) == 0: - self.vertex_class = VertexClass.THREE_WAY_ZERO_PRIMARY_LINE - if len(self.line_connected) == 1: - self.vertex_class = VertexClass.THREE_WAY_ONE_PRIMARY_LINE - elif len(self.line_list) == 2: - if len(self.line_connected) == 0: - self.vertex_class = VertexClass.TWO_WAY_ZERO_PRIMARY_LINE - elif len(self.line_list) == 1: - self.vertex_class = VertexClass.SINGLE_WAY - - def all_has_valid_group_attr(self): - """If all values in group list are valid value, return True.""" - # TODO: if some line has no group, give advice - for i in self.line_list: - if i.group is None: - return False - - return True - - def need_regrouping(self): - pass - - def check_connectivity(self, use_angle_grouping=True): - # Fill missing group with -1 - for line in self.line_list: - if line.group is None: - line.group = -1 - - if self.need_regrouping(): - self.group_regroup() - - if use_angle_grouping: - self.group_line_by_angle() - else: - self.update_connectivity_by_group() - - # record line not connected - all_line_ids = self.get_all_line_ids() - self.line_not_connected = list(all_line_ids - set(chain(*self.line_connected))) - - self.assign_vertex_class() - - def group_regroup(self): - pass - - def update_connectivity_by_group(self): - group_line = defaultdict(list) - for i in self.line_list: - group_line[i.group].append(i.line_id) - - for value in group_line.values(): - if len(value) > 1: - self.line_connected.append(value) - - def group_line_by_angle(self): - """Generate connectivity of all lines.""" - if len(self.line_list) == 1: - return - - # if there are 2 and more lines - new_angles = [i.get_angle_for_line() for i in self.line_list] - angle_visited = [False] * len(new_angles) - - if len(self.line_list) == 2: - angle_diff = abs(new_angles[0] - new_angles[1]) - angle_diff = angle_diff if angle_diff <= np.pi else angle_diff - np.pi - - # TODO: check if need to connect when turn angle < TURN_ANGLE_TOLERANCE - # if angle_diff >= TURN_ANGLE_TOLERANCE: - self.line_connected.append( - ( - self.line_list[0].line_id, - self.line_list[1].line_id, - ) - ) - return - - # three and more lines - for i, angle_1 in enumerate(new_angles): - for j, angle_2 in enumerate(new_angles[i + 1 :]): - if not angle_visited[i + j + 1]: - angle_diff = abs(angle_1 - angle_2) - angle_diff = angle_diff if angle_diff <= np.pi else angle_diff - np.pi - if ( - angle_diff < ANGLE_TOLERANCE - or np.pi - ANGLE_TOLERANCE < abs(angle_1 - angle_2) < np.pi + ANGLE_TOLERANCE - ): - angle_visited[j + i + 1] = True # tenth of PI - self.line_connected.append( - ( - self.line_list[i].line_id, - self.line_list[i + j + 1].line_id, - ) - ) - - -class LineGrouping: - """Class to group lines and merge them.""" - - def __init__(self, in_line_gdf, merge_group=True, use_angle_grouping=True) -> None: - if in_line_gdf is None: - raise ValueError("Line GeoDataFrame cannot be None") - self.use_angle_grouping = use_angle_grouping - - if in_line_gdf.empty: - raise ValueError("Line GeoDataFrame cannot be empty") - - self.lines = algo_common.clean_line_geometries(in_line_gdf) - self.lines.reset_index(inplace=True, drop=True) - self.merge_group = merge_group - - self.sim_geom = self.lines.simplify(1) - - self.G = nk.Graph(len(self.lines)) - self.merged_vertex_list = [] - self.has_group_attr = False - self.need_regrouping = False - self.groups = [None] * len(self.lines) - self.merged_lines_trimmed = None # merged trimmed lines - - self.vertex_list = [] - self.vertex_of_concern = [] - self.v_index = None # sindex of all vertices for vertex_list - - self.polys = None - - # invalid geoms in final geom list - self.valid_lines = None - self.valid_polys = None - self.invalid_lines = None - self.invalid_polys = None - - def create_vertex_list(self): - # check if data has group column - if bt_const.BT_GROUP in self.lines.keys(): - self.groups = self.lines[bt_const.BT_GROUP] - self.has_group_attr = True - if self.groups.hasnans: # Todo: check for other invalid values - self.need_regrouping = True - - for idx, s_geom, geom, group in zip(*zip(*self.sim_geom.items()), self.lines.geometry, self.groups): - self.vertex_list.append(VertexNode(idx, geom, s_geom, 0, group)) - self.vertex_list.append(VertexNode(idx, geom, s_geom, -1, group)) - - v_points = [] - for i in self.vertex_list: - if i.vertex is None: - print( - f"Vertex is None, skipping. " - f"line_id={i.line_list[0].line_id if i.line_list else 'NA'}" - ) - continue - - v_points.append(i.vertex.buffer(SMALL_BUFFER)) # small polygon - - # Spatial index of all vertices - self.v_index = shapely.STRtree(v_points) - - vertex_visited = [False] * len(self.vertex_list) - for i, pt in enumerate(v_points): - if vertex_visited[i]: - continue - - s_list = self.v_index.query(pt) - vertex = self.vertex_list[i] - if len(s_list) > 1: - for j in s_list: - if j != i: - # some short line will be very close to each other - if vertex.vertex.distance(self.vertex_list[j].vertex) > bt_const.SMALL_BUFFER: - continue - - vertex.merge(self.vertex_list[j]) - vertex_visited[j] = True - - self.merged_vertex_list.append(vertex) - vertex_visited[i] = True - - for i in self.merged_vertex_list: - i.check_connectivity(self.use_angle_grouping) - - for i in self.merged_vertex_list: - if i.line_connected: - for edge in i.line_connected: - self.G.addEdge(edge[0], edge[1]) - - def group_lines(self): - cc = nk.components.ConnectedComponents(self.G) - cc.run() - # print("number of components ", cc.numberOfComponents()) - - group = 0 - for i in range(cc.numberOfComponents()): - component = cc.getComponents()[i] - for id in component: - self.groups[id] = group - - group += 1 - - def update_line_in_vertex_node(self, line_id, line): - """Update line in VertexNode after trimming.""" - idx = self.v_index.query(line) - for i in idx: - v = self.vertex_list[i] - v.update_line(line_id, line) - - def run_line_merge(self): - return algo_merge_lines.run_line_merge(self.lines, self.merge_group) - - def find_vertex_for_poly_trimming(self): - self.vertex_of_concern = [i for i in self.merged_vertex_list if i.vertex_class in CONCERN_CLASSES] - - def line_and_poly_cleanup(self): - sindex_poly = self.polys.sindex - - for vertex in self.vertex_of_concern: - s_idx = sindex_poly.query(vertex.vertex, predicate="within") - if len(s_idx) == 0: - continue - - # Trim intersections of primary lines - polys = self.polys.loc[s_idx].geometry - if not self.merge_group: - if ( - vertex.vertex_class == VertexClass.FIVE_WAY_TWO_PRIMARY_LINE - or vertex.vertex_class == VertexClass.FIVE_WAY_ONE_PRIMARY_LINE - or vertex.vertex_class == VertexClass.FOUR_WAY_ONE_PRIMARY_LINE - or vertex.vertex_class == VertexClass.FOUR_WAY_TWO_PRIMARY_LINE - or vertex.vertex_class == VertexClass.THREE_WAY_ONE_PRIMARY_LINE - ): - out_polys = vertex.trim_primary_end(polys) - if len(out_polys) == 0: - continue - - # update polygon DataFrame - for idx, out_poly in out_polys: - if out_poly: - self.polys.at[idx, "geometry"] = out_poly - - # retrieve polygons again. Some polygons may be updated - polys = self.polys.loc[s_idx] - if ( - vertex.vertex_class == VertexClass.SINGLE_WAY - or vertex.vertex_class == VertexClass.TWO_WAY_ZERO_PRIMARY_LINE - or vertex.vertex_class == VertexClass.THREE_WAY_ZERO_PRIMARY_LINE - or vertex.vertex_class == VertexClass.FOUR_WAY_ZERO_PRIMARY_LINE - or vertex.vertex_class == VertexClass.FIVE_WAY_ZERO_PRIMARY_LINE - ): - if vertex.vertex_class == VertexClass.THREE_WAY_ZERO_PRIMARY_LINE: - pass - - out_polys = vertex.trim_end_all(polys) - if len(out_polys) == 0: - continue - - # update polygon DataFrame - for idx, out_poly in out_polys: - self.polys.at[idx, "geometry"] = out_poly - - polys = self.polys.loc[s_idx] - if vertex.vertex_class != VertexClass.SINGLE_WAY: - poly_trim_list = vertex.trim_intersection(polys, self.merge_group) - for p_trim in poly_trim_list: - # update main line and polygon DataFrame - self.polys.at[p_trim.poly_index, "geometry"] = p_trim.poly_cleanup - self.lines.at[p_trim.line_index, "geometry"] = p_trim.line_cleanup - - # update VertexNode's line - self.update_line_in_vertex_node(p_trim.line_index, p_trim.line_cleanup) - - def get_merged_lines_original(self): - return self.lines.dissolve(by=bt_const.BT_GROUP) - - def run_grouping(self): - self.create_vertex_list() - if not self.has_group_attr: - self.group_lines() - - self.find_vertex_for_poly_trimming() - self.lines[bt_const.BT_GROUP] = self.groups # assign group attribute - - def run_regrouping(self): - """ - Run this when new lines are added to grouped file. - - Some new lines has empty group attributes - """ - pass - - def run_cleanup(self, in_polys): - self.polys = in_polys.copy() - self.line_and_poly_cleanup() - self.run_line_merge_trimmed() - self.check_geom_validity() - - def run_line_merge_trimmed(self): - self.merged_lines_trimmed = self.run_line_merge() - - def check_geom_validity(self): - """ - Check MultiLineString and MultiPolygon in line and polygon dataframe. - - Save to separate layers for user to double check - """ - # remove null geometry - # TODO make sure lines and polygons match in pairs - # they should have same amount and spatial coverage - self.valid_polys = self.polys[~self.polys.geometry.isna() & ~self.polys.geometry.is_empty] - - # save sh_geom.MultiLineString and sh_geom.MultiPolygon - self.invalid_polys = self.polys[(self.polys.geometry.geom_type == "MultiPolygon")] - - # check lines - self.valid_lines = self.merged_lines_trimmed[ - ~self.merged_lines_trimmed.geometry.isna() & ~self.merged_lines_trimmed.geometry.is_empty - ] - self.valid_lines.reset_index(inplace=True, drop=True) - - self.invalid_lines = self.merged_lines_trimmed[ - (self.merged_lines_trimmed.geometry.geom_type == "MultiLineString") - ] - self.invalid_lines.reset_index(inplace=True, drop=True) - - def save_file(self, out_file, out_layer="ground_footprint"): - if not self.valid_lines.empty: - self.valid_lines = algo_common.clean_geometries( - self.valid_lines, - stage="output", - out_file=out_file, - layer="rejected_output_ground_trimmed_lines", - ) - self.valid_lines["length"] = self.valid_lines.length - self.valid_lines.to_file(out_file, layer="merged_lines") - - if not self.valid_polys.empty: - self.valid_polys = algo_common.clean_geometries( - self.valid_polys, - stage="output", - out_file=out_file, - layer="rejected_output_ground_trimmed_footprint", - ) - if "length" in self.valid_polys.columns: - self.valid_polys.drop(columns=["length"], inplace=True) - - self.valid_polys["area"] = self.valid_polys.area - layer_name = out_layer - self.valid_polys.to_file(out_file, layer=layer_name) - - if not self.invalid_lines.empty: - self.invalid_lines.to_file(out_file, layer="invalid_lines") - - if not self.invalid_polys.empty: - self.invalid_polys.to_file(out_file, layer="invalid_polygons") - - -@dataclass -class PolygonTrimming: - """Store polygon and line to trim. Primary polygon is used to trim both.""" - - poly_primary: Optional[sh_geom.MultiPolygon] = None - poly_index: int = field(default=-1) - poly_cleanup: Optional[sh_geom.Polygon] = None - line_index: int = field(default=-1) - line_cleanup: Optional[sh_geom.LineString] = None - - def process(self, primary_poly_list=None, vertex=None): - # prepare primary polygon - poly_primary = shapely.union_all(primary_poly_list) - trim_distance = TRIMMING_DISTANCE - - if self.line_cleanup.length < 100.0: - trim_distance = 50.0 - - poly_primary = poly_primary.intersection(vertex.buffer(trim_distance)) - - self.poly_primary = poly_primary - - # TODO: check why there is such cases - if self.poly_cleanup is None: - print("No polygon to trim.") - return - - midpoint = self.line_cleanup.interpolate(0.5, normalized=True) - if self.poly_primary is None or self.poly_primary.is_empty: - # print("Warning: No valid primary polygon for trimming; skipping difference operation.") - # TODO: handle this case - return - diff = self.poly_cleanup.difference(self.poly_primary) - if diff.geom_type == "Polygon": - self.poly_cleanup = diff - elif diff.geom_type == "MultiPolygon": - # area = self.poly_cleanup.area - reserved = [] - for i in diff.geoms: - # if i.area > TRIM_THRESHOLD * area: # small part - # reserved.append(i) - if i.contains(midpoint): - reserved.append(i) - - if len(reserved) == 0: - pass - elif len(reserved) == 1: - self.poly_cleanup = sh_geom.Polygon(*reserved) - else: - # TODO output all MultiPolygons which should be dealt with - # self.poly_cleanup = sh_geom.MultiPolygon(reserved) - print("trim: MultiPolygon detected, please check") - - diff = self.line_cleanup.intersection(self.poly_cleanup) - if diff.geom_type == "GeometryCollection": - geoms = [] - for item in diff.geoms: - if item.geom_type == "LineString": - geoms.append(item) - elif item.geom_type == "MultiLineString": - print("trim: sh_geom.MultiLineString detected, please check") - if len(geoms) == 0: - return - elif len(geoms) == 1: - diff = geoms[0] - else: - diff = sh_geom.MultiLineString(geoms) - - if diff.geom_type == "LineString": - self.line_cleanup = diff - elif diff.geom_type == "MultiLineString": - length = self.line_cleanup.length - reserved = [] - for i in diff.geoms: - if i.length > TRIM_THRESHOLD * length: # small part - reserved.append(i) - - if len(reserved) == 0: - pass - elif len(reserved) == 1: - self.line_cleanup = sh_geom.LineString(*reserved) - else: - # TODO output all MultiPolygons which should be dealt with - self.poly_cleanup = sh_geom.MultiLineString(reserved) +sys.modules[__name__] = _moved diff --git a/beratools/core/algo_merge_lines.py b/beratools/core/algo_merge_lines.py index 3a9158a..3260407 100644 --- a/beratools/core/algo_merge_lines.py +++ b/beratools/core/algo_merge_lines.py @@ -1,276 +1,20 @@ """ -Copyright (C) 2025 Applied Geospatial Research Group. +Deprecated: moved to beratools.modules.mapping. -This script is licensed under the GNU General Public License v3.0. -See for full license details. - -Author: Richard Zeng - -Description: - This script is part of the BERA Tools. - Webpage: https://github.com/BERATool/beratools - - This file is intended to be hosting algorithms and utility functions/classes - for merging lines. +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -from itertools import pairwise -from operator import itemgetter - -import networkit as nk -import shapely.geometry as sh_geom -from shapely.geometry import GeometryCollection, LineString, MultiLineString -from shapely.ops import linemerge - -import beratools.core.algo_common as algo_common -import beratools.core.constants as bt_const - - -def safe_linemerge(geom): - if isinstance(geom, (MultiLineString, GeometryCollection)): - return linemerge(geom) - elif isinstance(geom, LineString): - return geom - else: - return geom - - -def custom_line_merge(geom): - if geom.geom_type == "MultiLineString": - # First try shapely's linemerge (fast) - merged = linemerge(geom) - # If still MultiLineString, use MergeLines for complex cases - if isinstance(merged, sh_geom.MultiLineString): - worker = MergeLines(merged) - merged = worker.merge_all_lines() - return merged if merged else geom - else: - return merged - elif geom.geom_type == "LineString": - return geom - else: - return geom - - -def run_line_merge(in_line_gdf, merge_group, group_field=bt_const.BT_GROUP): - """Merge lines sharing a group_field value into one line (BT_GROUP by default).""" - out_line_gdf = in_line_gdf - if merge_group: - if group_field not in in_line_gdf.columns: - in_line_gdf = in_line_gdf.copy() - in_line_gdf[group_field] = range(1, len(in_line_gdf) + 1) - out_line_gdf = in_line_gdf.dissolve(by=group_field, as_index=False) - - out_line_gdf.geometry = out_line_gdf.geometry.apply(safe_linemerge) - for i, row in enumerate(out_line_gdf.itertuples()): - if isinstance(row.geometry, sh_geom.MultiLineString): - worker = MergeLines(row.geometry) - merged_line = worker.merge_all_lines() - if merged_line: - out_line_gdf.at[row.Index, "geometry"] = merged_line - - out_line_gdf = algo_common.clean_line_geometries(out_line_gdf) - out_line_gdf.reset_index(inplace=True, drop=True) - out_line_gdf["length"] = out_line_gdf.geometry.length - return out_line_gdf - - -class MergeLines: - """Merge line segments in MultiLineString.""" - - def __init__(self, multi_line): - self.G = None - self.line_segs = None - self.multi_line = multi_line - self.node_poly = None - self.end = None - - self.create_graph() - - def create_graph(self): - self.line_segs = list(self.multi_line.geoms) - - # TODO: check empty line and null geoms - self.line_segs = [line for line in self.line_segs if line.length > 1e-3] - self.multi_line = sh_geom.MultiLineString(self.line_segs) - m = sh_geom.mapping(self.multi_line) - self.end = [(i[0], i[-1]) for i in m["coordinates"]] - - self.G = nk.Graph(edgesIndexed=True) - self.G.addNodes(2) - self.G.addEdge(0, 1) - - self.node_poly = [ - sh_geom.Point(self.end[0][0]).buffer(1), - sh_geom.Point(self.end[0][1]).buffer(1), - ] - - for i, line in enumerate(self.end[1:]): - node_exists = False - pt = sh_geom.Point(line[0]) - pt_buffer = pt.buffer(1) - - for node in self.G.iterNodes(): - if self.node_poly[node].contains(pt): - node_exists = True - node_start = node - if not node_exists: - node_start = self.G.addNode() - self.node_poly.append(pt_buffer) - - node_exists = False - pt = sh_geom.Point(line[1]) - pt_buffer = pt.buffer(1) - for node in self.G.iterNodes(): - if self.node_poly[node].contains(pt): - node_exists = True - node_end = node - if not node_exists: - node_end = self.G.addNode() - self.node_poly.append(pt_buffer) - - self.G.addEdge(node_start, node_end) - - def get_components(self): - cc = nk.components.ConnectedComponents(self.G) - cc.run() - components = cc.getComponents() - return components - - def is_single_path(self, component): - single_path = True - for node in component: - neighbors = list(self.G.iterNeighbors(node)) - if len(neighbors) > 2: - single_path = False - - return single_path - - def get_merged_line_for_component(self, component): - sub = nk.graphtools.subgraphFromNodes(self.G, component) - lines = None - if nk.graphtools.maxDegree(sub) >= 3: # not simple path - edges = [self.G.edgeId(i[0], i[1]) for i in list(sub.iterEdges())] - lines = itemgetter(*edges)(self.line_segs) - elif nk.graphtools.maxDegree(sub) == 2: - lines = self.merge_single_line(component) - - return lines - - def find_path_for_component(self, component): - if not component: - return [] - - neighbors = list(self.G.iterNeighbors(component[0])) - if not neighbors: - return [component[0]] - - path = [component[0]] - right = neighbors[0] - path.append(right) - - left = None - if len(neighbors) == 2: - left = neighbors[1] - path.insert(0, left) - - neighbors = list(self.G.iterNeighbors(right)) - right_safety = 0 - while len(neighbors) > 1: - right_safety += 1 - if right_safety > len(component) + 2: - break - - next_candidates = [n for n in neighbors if n not in path] - if not next_candidates: - break - - right = next_candidates[0] - path.append(right) - - neighbors = list(self.G.iterNeighbors(right)) - - # last node - if neighbors[0] not in path: - path.append(neighbors[0]) - - # process left side - if left: - neighbors = list(self.G.iterNeighbors(left)) - left_safety = 0 - while len(neighbors) > 1: - left_safety += 1 - if left_safety > len(component) + 2: - break - - next_candidates = [n for n in neighbors if n not in path] - if not next_candidates: - break - - left = next_candidates[0] - path.insert(0, left) - - neighbors = list(self.G.iterNeighbors(left)) - - # last node - if neighbors[0] not in path: - path.insert(0, neighbors[0]) - - return path - - def merge_single_line(self, component): - path = self.find_path_for_component(component) - if len(path) < 2: - return None - - pairs = list(pairwise(path)) - if not pairs: - return None - - line_list = [self.G.edgeId(i[0], i[1]) for i in pairs] - if not line_list: - return None - - vertices = [] - - for i, id in enumerate(line_list): - pair = pairs[i] - poly_t = self.node_poly[pair[0]] - point_t = sh_geom.Point(self.end[id][0]) - if poly_t.contains(point_t): - line = self.line_segs[id] - else: - # line = reverse(self.line_segs[id]) - line = self.line_segs[id].reverse() - - vertices.extend(list(line.coords)) - last_vertex = vertices.pop() - - vertices.append(last_vertex) - merged_line = sh_geom.LineString(vertices) - - return [merged_line] - - def merge_all_lines(self): - components = self.get_components() - lines = [] - for c in components: - line = self.get_merged_line_for_component(c) - if line: - if isinstance(line, tuple): - lines.extend(list(line)) - elif isinstance(line, list): - lines.extend(line) - else: - lines.append(line) - else: # TODO: check line - print(f"merge_all_lines: failed to merge: {self.multi_line.bounds}") +import sys +import warnings - # print('Merge lines done.') +from beratools.modules.mapping import algo_merge_lines as _moved - if len(lines) > 1: - return sh_geom.MultiLineString(lines) - elif len(lines) == 1: - return lines[0] - else: - return None +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" for full license details. - -Author: Richard Zeng - -Description: - This script is part of the BERA Tools. - Webpage: https://github.com/BERATool/beratools - - The purpose of this script is to move line vertices to the right - seismic line courses for improved alignment and analysis in - geospatial data processing. +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -import geopandas as gpd -import math -import numpy as np -import pandas as pd -import shapely.geometry as sh_geom -from shapely import STRtree - -import beratools.core.algo_common as algo_common -import beratools.core.algo_cost as algo_cost -import beratools.core.constants as bt_const -import beratools.core.tool_base as bt_base -from beratools.core.algo_check_seed_line import VertexPrecleaner -import beratools.utility.spatial_common as sp_common -from beratools.core import algo_dijkstra - -try: - import rasterio -except Exception: - rasterio = None - - -def update_line_end_pt(line, index, new_vertex): - if not line: - return None - - if index >= len(line.coords) or index < -1: - return line - - coords = list(line.coords) - if len(coords[index]) == 2: - coords[index] = (new_vertex.x, new_vertex.y) - elif len(coords[index]) == 3: - coords[index] = (new_vertex.x, new_vertex.y, 0.0) - - return sh_geom.LineString(coords) - - -class _SingleLine: - """Single line object with anchor point.""" - - def __init__(self, line_gdf, line_no, end_no, search_distance): - self.line_gdf = line_gdf - self.line = self.line_gdf.geometry[0] - self.line_no = line_no - self.end_no = end_no - self.search_distance = search_distance - self.anchor = None - - self.add_anchors_to_line() - - def is_valid(self): - return self.line.is_valid - - def line_coord_list(self): - return algo_common.line_coord_list(self.line) - - def get_end_vertex(self): - return self.line_coord_list()[self.end_no] - - def touches_point(self, vertex): - return algo_common.points_are_close(vertex, self.get_end_vertex()) - - def get_angle(self): - return algo_common.get_angle(self.line, self.end_no) - - def add_anchors_to_line(self): - """ - Append new vertex to vertex group, by calculating distance to existing vertices. - - An anchor point will be added together with line - """ - # Calculate anchor point for each vertex - point = self.get_end_vertex() - line_string = self.line - index = self.end_no - pts = algo_common.line_coord_list(line_string) - - pt_1 = None - pt_2 = None - if index == 0: - pt_1 = point - pt_2 = pts[1] - elif index == -1: - pt_1 = point - pt_2 = pts[-2] - - # Calculate anchor point - dist_pt = 0.0 - if pt_1 and pt_2: - dist_pt = pt_1.distance(pt_2) - - # TODO: check why two points are the same - if np.isclose(dist_pt, 0.0): - print("Points are close, return") - return None - - X = pt_1.x + (pt_2.x - pt_1.x) * self.search_distance / dist_pt - Y = pt_1.y + (pt_2.y - pt_1.y) * self.search_distance / dist_pt - self.anchor = sh_geom.Point(X, Y) # add anchor point - - -class _Vertex: - """Vertex object with multiple lines.""" - - def __init__(self, line_obj, in_raster=None, line_radius=None, cost_footprint=None): - self.vertex = line_obj.get_end_vertex() - self.search_distance = line_obj.search_distance - - self.cost_footprint = cost_footprint - self.vertex_opt = None # optimized vertex - self.centerlines = None - self.anchors = None - self.in_raster = in_raster - self.line_radius = line_radius - self.lines = [] # SingleLine objects - - self.add_line(line_obj) - - def add_line(self, line_obj): - self.lines.append(line_obj) - - def generate_anchor_pairs(self): - """ - Extend line following outward direction to length of search_distance. - - Use the end point as anchor point. - - vertex: input intersection with all related lines - return: - one or two pairs of anchors according to numbers of lines - intersected. - two pairs anchors return when 3 or 4 lines intersected - one pair anchors return when 1 or 2 lines intersected. - """ - lines = self.get_lines() - vertex = self.get_vertex() - slopes = [] - for line in self.lines: - slopes.append(line.get_angle()) - - index = 0 # the index of line which paired with first line. - pt_start_1 = None - pt_end_1 = None - pt_start_2 = None - pt_end_2 = None - - if len(slopes) == 4: - # get sort order of angles - index = np.argsort(slopes) - - # first anchor pair (first and third in the sorted array) - pt_start_1 = self.lines[index[0]].anchor - pt_end_1 = self.lines[index[2]].anchor - - pt_start_2 = self.lines[index[1]].anchor - pt_end_2 = self.lines[index[3]].anchor - elif len(slopes) == 3: - # find the largest difference between angles - angle_diff = [ - abs(slopes[0] - slopes[1]), - abs(slopes[0] - slopes[2]), - abs(slopes[1] - slopes[2]), - ] - angle_diff_norm = [2 * np.pi - i if i > np.pi else i for i in angle_diff] - index = np.argmax(angle_diff_norm) - pairs = [(0, 1), (0, 2), (1, 2)] - pair = pairs[index] - - # first anchor pair - pt_start_1 = self.lines[pair[0]].anchor - pt_end_1 = self.lines[pair[1]].anchor - - # the rest one index - remain = list({0, 1, 2} - set(pair))[0] # the remaining index - - try: - pt_start_2 = self.lines[remain].anchor - # symmetry point of pt_start_2 regarding vertex["point"] - X = vertex.x - (pt_start_2.x - vertex.x) - Y = vertex.y - (pt_start_2.y - vertex.y) - pt_end_2 = sh_geom.Point(X, Y) - except Exception as e: - print(e) - - # this scenario only use two anchors - # and find the closest point on least cost path - elif len(slopes) == 2: - pt_start_1 = self.lines[0].anchor - pt_end_1 = self.lines[1].anchor - elif len(slopes) == 1: - pt_start_1 = self.lines[0].anchor - # symmetry point of pt_start_1 regarding vertex["point"] - X = vertex.x - (pt_start_1.x - vertex.x) - Y = vertex.y - (pt_start_1.y - vertex.y) - pt_end_1 = sh_geom.Point(X, Y) - - if not pt_start_1 or not pt_end_1: - print("Anchors not found") - - # if points are outside of cost footprint, set to None - points = [pt_start_1, pt_end_1, pt_start_2, pt_end_2] - for index, pt in enumerate(points): - if pt: - if not self.cost_footprint.contains(sh_geom.Point(pt)): - points[index] = None - - if len(slopes) == 4 or len(slopes) == 3: - if None in points: - return None - else: - return points - elif len(slopes) == 2 or len(slopes) == 1: - if None in (pt_start_1, pt_end_1): - return None - else: - return pt_start_1, pt_end_1 - - def compute(self): - if self.cost_footprint is not None: - try: - if not self.cost_footprint.covers(self.get_vertex()): - return None - except Exception: - if not self.cost_footprint.contains(self.get_vertex()): - return None - - try: - self.anchors = self.generate_anchor_pairs() - except Exception as e: - print(e) - - if not self.anchors: - if bt_const.BT_DEBUGGING: - print("No anchors retrieved") - return None - - centerline_1 = None - centerline_2 = None - intersection = None - - if bt_const.CenterlineFlags.USE_SKIMAGE_GRAPH: - find_lc_path = algo_dijkstra.find_least_cost_path_skimage - else: - find_lc_path = algo_dijkstra.find_least_cost_path - - try: - if len(self.anchors) == 4: - seed_line = sh_geom.LineString(self.anchors[0:2]) - if not self._should_process_seed_line(seed_line): - return None - - raster_clip, out_meta = sp_common.clip_raster(self.in_raster, seed_line, self.line_radius) - raster_clip, _ = algo_cost.cost_raster(raster_clip, out_meta) - centerline_1 = find_lc_path(raster_clip, out_meta, seed_line) - seed_line = sh_geom.LineString(self.anchors[2:4]) - if not self._should_process_seed_line(seed_line): - return None - - raster_clip, out_meta = sp_common.clip_raster(self.in_raster, seed_line, self.line_radius) - raster_clip, _ = algo_cost.cost_raster(raster_clip, out_meta) - centerline_2 = find_lc_path(raster_clip, out_meta, seed_line) - - if centerline_1 and centerline_2: - intersection = algo_common.intersection_of_lines(centerline_1, centerline_2) - elif len(self.anchors) == 2: - seed_line = sh_geom.LineString(self.anchors) - if not self._should_process_seed_line(seed_line): - return None - - raster_clip, out_meta = sp_common.clip_raster(self.in_raster, seed_line, self.line_radius) - raster_clip, _ = algo_cost.cost_raster(raster_clip, out_meta) - centerline_1 = find_lc_path(raster_clip, out_meta, seed_line) - - if centerline_1: - intersection = algo_common.closest_point_to_line(self.get_vertex(), centerline_1) - except Exception as e: - print(e) - - # Update vertices according to intersection, new center lines are returned - if type(intersection) is sh_geom.MultiPoint: - intersection = intersection.centroid - - self.centerlines = [centerline_1, centerline_2] - self.vertex_opt = intersection - - def _should_process_seed_line(self, seed_line): - if seed_line is None or seed_line.length <= bt_const.SMALL_BUFFER: - return False - - if self.cost_footprint is not None: - try: - if not self.cost_footprint.intersects(seed_line.buffer(self.line_radius)): - return False - except Exception: - return False - - max_seed_length = max(float(self.search_distance) * 6.0, float(self.line_radius) * 10.0) - if seed_line.length > max_seed_length: - return False - - return True - - def get_lines(self): - lines = [item.line for item in self.lines] - return lines - - def get_vertex(self): - return self.vertex - - -class SeedLineCorrection: - """A class used to group vertices and perform seed line correction.""" - - def __init__( - self, - in_line, - in_raster, - search_distance, - line_radius, - processes, - call_mode, - layer=None, - optimize_internal_vertices=False, - close_distance=None, - min_segment_length=None, - angle_tol=10.0, - ): - self.in_line = in_line - self.in_layer = layer - self.in_raster = in_raster - self.line_radius = float(line_radius) - self.search_distance = float(search_distance) - self.processes = processes - self.call_mode = call_mode - self.optimize_internal_vertices = bool(optimize_internal_vertices) - - self.crs = None - self.vertex_grp = [] - self.sindex = None - - self.line_list = [] - self.line_visited = None - self.source_lines_gdf = None - - self.close_distance = close_distance - self.min_segment_length = min_segment_length - self.angle_tol = float(angle_tol) - - if self.close_distance is None: - self.close_distance = self._default_close_distance() - else: - self.close_distance = float(self.close_distance) - - if self.min_segment_length is None: - self.min_segment_length = self.close_distance - else: - self.min_segment_length = float(self.min_segment_length) - - # calculate cost raster footprint - self.cost_footprint = algo_common.generate_raster_footprint(self.in_raster, latlon=False) - - def _default_close_distance(self): - fallback = 2.0 - if rasterio is None: - return fallback - - try: - with rasterio.open(self.in_raster) as src: - transform = src.transform - cell_size = min(abs(transform.a), abs(transform.e)) - if np.isclose(cell_size, 0.0): - return fallback - return float(max(2.0, 1.5 * cell_size)) - except Exception: - return fallback - - def create_vertex_group(self, line_obj): - """ - Create a new vertex group. - - Args: - line_obj : _SingleLine - - """ - # all end points not added will stay with this vertex - vertex = line_obj.get_end_vertex() - vertex_obj = _Vertex( - line_obj, - in_raster=self.in_raster, - line_radius=self.line_radius, - cost_footprint=self.cost_footprint, - ) - search = self.sindex.query(vertex.buffer(bt_const.SMALL_BUFFER)) - - # add more vertices to the new group - for i in search: - line = self.line_list[i] - if i == line_obj.line_no: - continue - - if not self.line_visited[i][0]: - new_line = _SingleLine(line, i, 0, self.search_distance) - if new_line.touches_point(vertex): - vertex_obj.add_line(new_line) - self.line_visited[i][0] = True - - if not self.line_visited[i][-1]: - new_line = _SingleLine(line, i, -1, self.search_distance) - if new_line.touches_point(vertex): - vertex_obj.add_line(new_line) - self.line_visited[i][-1] = True - - self.vertex_grp.append(vertex_obj) - - def prepare_lines(self, lines_gdf=None): - print("Preparing lines...", flush=True) - print(f"in_file: {self.in_line}") - print(f"in_layer: {self.in_layer}") - - if lines_gdf is None: - lines_gdf = algo_common.read_geospatial_file(self.in_line, layer=self.in_layer) - - if lines_gdf is None: - self.source_lines_gdf = None - self.line_list = [] - self.sindex = None - self.line_visited = None - return - - # Keep in-memory and file-based paths consistent with shared input hygiene. - if "fid" in lines_gdf.columns: - lines_gdf = lines_gdf.rename(columns={"fid": "orig_fid"}) - - lines_gdf = algo_common.clean_geometries(lines_gdf, stage="input") - lines_gdf = lines_gdf.reset_index(drop=True) - if bt_const.BT_UID not in lines_gdf.columns: - lines_gdf[bt_const.BT_UID] = range(len(lines_gdf)) - - self.source_lines_gdf = lines_gdf.copy() - lines_gdf = VertexPrecleaner( - self.close_distance, - self.angle_tol, - ).remove_close_vertices(lines_gdf) - - if self.optimize_internal_vertices: - self.line_list = algo_common.split_lines_to_segments(algo_common.keep_source_seg(lines_gdf)) - else: - self.line_list = algo_common.lines_gdf_to_list(lines_gdf) - - if not self.line_list: - print("No lines available for seed line correction.") - self.sindex = None - self.line_visited = None - return - - self.sindex = STRtree([item.geometry[0] for item in self.line_list]) - self.line_visited = [{0: False, -1: False} for _ in range(len(self.line_list))] - - def group_vertices(self): - if not self.line_list or self.line_visited is None: - return - - for line_no in range(len(self.line_list)): - for end_no in [0, -1]: - if self.line_visited[line_no][end_no]: - continue - - line = _SingleLine(self.line_list[line_no], line_no, end_no, self.search_distance) - if not line.is_valid(): - print(f"Line {line.line_no} is invalid") - continue - - self.create_vertex_group(line) - self.line_visited[line_no][end_no] = True - - def create_all_vertex_groups(self): - self.prepare_lines() - self.group_vertices() - - def update_all_lines(self): - for vertex_obj in self.vertex_grp: - for line in vertex_obj.lines: - if not vertex_obj.vertex_opt: - continue - - old_line = self.line_list[line.line_no].geometry[0] - self.line_list[line.line_no].geometry = [ - update_line_end_pt(old_line, line.end_no, vertex_obj.vertex_opt) - ] - - def _post_update_vertex_cleanup(self, mode="endpoint_only"): - if not self.line_list or mode == "off": - return - - if mode not in VertexPrecleaner.VALID_MODES: - raise ValueError(f"Unsupported post-update vertex cleanup mode: {mode}") - - cleaned_lines = [] - precleaner = VertexPrecleaner(self.close_distance, self.angle_tol) - - for item in self.line_list: - line = item.geometry.iloc[0] - cleaned_line = precleaner.cleanup_line(line, mode=mode) - - if cleaned_line is None or cleaned_line.is_empty: - continue - - cleaned_item = item.copy() - cleaned_item.geometry = [cleaned_line] - cleaned_lines.append(cleaned_item) - - self.line_list = cleaned_lines - - def get_optimized_lines(self): - if not self.line_list: - if self.source_lines_gdf is None: - return None - - lines = self.source_lines_gdf.iloc[0:0] - return algo_common.clean_geometries( - lines, - stage="output", - layer="rejected_output_vertex_optimization_lines", - ) - - lines = pd.concat(self.line_list, ignore_index=True) - - if self.optimize_internal_vertices and bt_const.BT_UID in lines.columns: - import beratools.core.algo_merge_lines as algo_merge_lines - - # join the segments back into their input rows, keeping each row's BT_GROUP - lines = algo_merge_lines.run_line_merge(lines, merge_group=True, group_field=bt_const.BT_UID) - lines = algo_common.restore_source_seg(lines) - - if "length" not in lines.columns: - lines["length"] = lines.geometry.length - - return algo_common.clean_geometries( - lines, - stage="output", - layer="rejected_output_vertex_optimization_lines", - ) - - def get_debug_layers(self): - lines = self.get_optimized_lines() - out_crs = None if lines is None else lines.crs - - lc_path_rows = [] - anchor_rows = [] - vertex_rows = [] - for group_id, item in enumerate(self.vertex_grp): - if item.centerlines: - for geom in item.centerlines: - if geom is not None: - lc_path_rows.append({"SLC_GROUP": int(group_id), "geometry": geom}) - if item.anchors: - for geom in item.anchors: - if geom is not None: - anchor_rows.append({"SLC_GROUP": int(group_id), "geometry": geom}) - if item.vertex_opt: - vertex_rows.append({"SLC_GROUP": int(group_id), "geometry": item.vertex_opt}) - - lc_paths = gpd.GeoDataFrame(lc_path_rows, columns=["SLC_GROUP", "geometry"], crs=out_crs) - anchors = gpd.GeoDataFrame(anchor_rows, columns=["SLC_GROUP", "geometry"], crs=out_crs) - vertices = gpd.GeoDataFrame(vertex_rows, columns=["SLC_GROUP", "geometry"], crs=out_crs) - - return { - "lc_paths": lc_paths, - "anchors": anchors, - "vertices": vertices, - } - - def optimize(self): - self.compute() - self.update_all_lines() - self._post_update_vertex_cleanup(mode="endpoint_only") - return self.get_optimized_lines() - - def compute(self): - compute_processes = self.processes if self.processes is not None else 0 +import sys +import warnings - vertex_grp = bt_base.execute_multiprocessing( - algo_common.process_single_item, - self.vertex_grp, - "Vertex Optimization", - compute_processes, - self.call_mode, - ) +from beratools.modules.mapping import algo_seed_line_correction as _moved - self.vertex_grp = vertex_grp +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" dist2: - end_idx = nearest_pt_idx + 1 - - # Create a new segment - new_coords = line_coords[start_idx:end_idx] - if start_pt: # Append start point - new_coords = [start_pt] + new_coords - - if end_pt: # Append end point - new_coords = new_coords + [end_pt] - - nearest_segment = LineString(new_coords) - start_idx = end_idx - start_pt = end_pt - - segments.append(nearest_segment) - - # Add remaining part of the line after the last point - if start_idx < len(line_coords): - # If last point is not close to end point of line - if start_pt.distance(line_coords[-1]) > EPSILON: - remaining_part = LineString([start_pt] + line_coords[end_idx:]) - segments.append(remaining_part) - - return segments - - def find_intersections(self): - """ - Find intersections between lines in the GeoDataFrame. - - Return: - List of Point geometries where the lines intersect. - - """ - visited_pairs = set() - intersection_points = [] - - # Iterate through each line geometry to find intersections - for idx, line1 in enumerate(self.line_gdf.geometry): - # Use spatial index to find candidates for intersection - indices = list(self.sindex.intersection(line1.bounds)) - indices.remove(idx) # Remove the current index from the list - - for match_idx in indices: - line2 = self.line_gdf.iloc[match_idx].geometry - - # Create an index pair where the smaller index comes first - pair = tuple(sorted([idx, match_idx])) - - # Skip if this pair has already been visited - if pair in visited_pairs: - continue - - # Mark the pair as visited - visited_pairs.add(pair) - - # Only check lines that are different and intersect - line1 = snap(line1, line2, tolerance=EPSILON) - if line1.intersects(line2): - # Find intersection points (can be multiple) - intersections = line1.intersection(line2) - - if intersections.is_empty: - continue - - # Intersection can be Point, MultiPoint, LineString - # or GeometryCollection - if isinstance(intersections, Point): - intersection_points.append(intersections) - else: - # record for further inspection - # GeometryCollection, MultiLineString - if isinstance(intersections, MultiPoint): - intersection_points.extend(intersections.geoms) - elif isinstance(intersections, LineString): - intersection_points.append(intersections.interpolate(0.5, normalized=True)) - - # if minimum distance between points is greater than threshold - # mark line as valid - if isinstance(intersections, MultiPoint): - if min_distance_in_multipoint(intersections) > algo_common.DISTANCE_THRESHOLD: - continue - # if intersection is a line, mark line as valid - if isinstance(intersections, LineString): - continue - - for item in pair: - self.inter_status[item] = 0 - - self.intersection_gdf = gpd.GeoDataFrame(geometry=intersection_points, crs=self.line_gdf.crs) - - def split_lines_at_intersections(self): - """ - Split lines at the given intersection points. - - Args: - intersection_points: List of Point geometries where the lines should be split. - - Returns: - A GeoDataFrame with the split lines. - - """ - # Create a spatial index for faster point-line intersection checks - sindex = self.intersection_gdf.sindex - - # List to hold the new split line segments - new_rows = [] - - # Iterate through each intersection point to split lines at that point - for row in self.line_gdf.itertuples(): - if not isinstance(row.geometry, LineString): - continue - - # Use spatial index to find possible line candidates for intersection - possible_matches = sindex.query(row.geometry.buffer(EPSILON)) - end_pts = MultiPoint([row.geometry.coords[0], row.geometry.coords[-1]]) - - pt_list = [] - new_segments = [row.geometry] - - for idx in possible_matches: - point = self.intersection_gdf.loc[idx].geometry - # Check if the point is on the line - if row.geometry.distance(point) < EPSILON: - if end_pts.distance(point) < EPSILON: - continue - else: - pt_list.append(point) - - if len(pt_list) > 0: - # Split the line at the intersection - new_segments = self.cut_line_by_points(row.geometry, pt_list) - - # If the line was split into multiple segments, create new rows - for segment in new_segments: - new_row = row._asdict() # Convert the original row into a dictionary - new_row["geometry"] = segment # Update the geometry with the split one - new_rows.append(new_row) - - self.split_lines_gdf = gpd.GeoDataFrame( - new_rows, columns=self.line_gdf.columns, crs=self.line_gdf.crs - ) - - self.split_lines_gdf = algo_common.clean_line_geometries(self.split_lines_gdf) - - # Debugging: print how many segments were created - print(f"Total new line segments created: {len(new_rows)}") - - def save_to_geopackage( - self, - input_gpkg, - line_layer="split_lines", - intersection_layer=None, - invalid_layer=None, - ): - """ - Save the split lines and intersection points to the GeoPackage. - - Args: - line_layer: split lines layer name in the GeoPackage. - intersection_layer: layer name for intersection points in the GeoPackage. - - """ - # Save intersection points and split lines to the GeoPackage - if self.split_lines_gdf is not None and intersection_layer: - if len(self.intersection_gdf) > 0: - self.intersection_gdf.to_file(input_gpkg, layer=intersection_layer, driver="GPKG") - - if self.split_lines_gdf is not None and line_layer: - if len(self.split_lines_gdf) > 0: - self.split_lines_gdf["length"] = self.split_lines_gdf.geometry.length - self.split_lines_gdf.to_file(input_gpkg, layer=line_layer, driver="GPKG") - - # save invalid splits - invalid_splits = self.line_gdf.loc[self.line_gdf[INTER_STATUS_COL] == 0] - if not invalid_splits.empty and invalid_layer: - if len(invalid_splits) > 0: - invalid_splits.to_file(input_gpkg, layer=invalid_layer, driver="GPKG") - - def process(self, intersection_gdf=None): - """ - Find intersection points, split lines at intersections. - - Args: - intersection_gdf: external GeoDataFrame with intersection points. - - """ - if intersection_gdf is not None: - self.intersection_gdf = intersection_gdf - else: - self.find_intersections() - - if self.inter_status: - for idx in self.inter_status.keys(): - self.line_gdf.loc[idx, INTER_STATUS_COL] = self.inter_status[idx] - - if not self.intersection_gdf.empty: - # Split the lines at intersection points - self.split_lines_at_intersections() - else: - print("No intersection points found, no lines to split.") - -if __name__ == "__main__": - input_gpkg = r"I:\Temp\footprint_final.gpkg" - layer_name = "merged_lines_original" - - gdf = gpd.read_file(input_gpkg, layer=layer_name) - if "fid" in gdf.columns: - gdf = gdf.rename(columns={"fid": "orig_fid"}) - splitter = LineSplitter(gdf) - splitter.process() - splitter.save_to_geopackage(input_gpkg) +""" +Deprecated: moved to beratools.modules.mapping. + +Kept so old imports keep working, with a DeprecationWarning, until it is removed. +""" + +import sys +import warnings + +from beratools.modules.mapping import algo_split_with_lines as _moved + +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" for full license details. - -Author: Richard Zeng - -Description: - This script is part of the BERA Tools. - Webpage: https://github.com/BERATool/beratools - - The purpose of this script is to move line vertices to the right - seismic line courses for improved alignment and analysis in - geospatial data processing. +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -from pathlib import Path - -import geopandas as gpd -import numpy as np -import pandas as pd -import shapely.geometry as sh_geom -from shapely import STRtree - -import beratools.core.algo_common as algo_common -import beratools.core.algo_cost as algo_cost -import beratools.core.algo_merge_lines as algo_merge_lines -import beratools.core.algo_vertex_preclean as algo_vertex_preclean -import beratools.core.constants as bt_const -import beratools.core.tool_base as bt_base -import beratools.utility.spatial_common as sp_common -from beratools.core import algo_dijkstra - -try: - import rasterio -except Exception: - rasterio = None - - -def update_line_end_pt(line, index, new_vertex): - if not line: - return None - - if index >= len(line.coords) or index < -1: - return line - - coords = list(line.coords) - if len(coords[index]) == 2: - coords[index] = (new_vertex.x, new_vertex.y) - elif len(coords[index]) == 3: - coords[index] = (new_vertex.x, new_vertex.y, 0.0) - - return sh_geom.LineString(coords) - - -class _SingleLine: - """Single line object with anchor point.""" - - def __init__(self, line_gdf, line_no, end_no, search_distance): - self.line_gdf = line_gdf - self.line = self.line_gdf.geometry[0] - self.line_no = line_no - self.end_no = end_no - self.search_distance = search_distance - self.anchor = None - - self.add_anchors_to_line() - - def is_valid(self): - return self.line.is_valid - - def line_coord_list(self): - return algo_common.line_coord_list(self.line) - - def get_end_vertex(self): - return self.line_coord_list()[self.end_no] - - def touches_point(self, vertex): - return algo_common.points_are_close(vertex, self.get_end_vertex()) - - def get_angle(self): - return algo_common.get_angle(self.line, self.end_no) - - def add_anchors_to_line(self): - """ - Append new vertex to vertex group, by calculating distance to existing vertices. - - An anchor point will be added together with line - """ - # Calculate anchor point for each vertex - point = self.get_end_vertex() - line_string = self.line - index = self.end_no - pts = algo_common.line_coord_list(line_string) - - pt_1 = None - pt_2 = None - if index == 0: - pt_1 = point - pt_2 = pts[1] - elif index == -1: - pt_1 = point - pt_2 = pts[-2] - - # Calculate anchor point - dist_pt = 0.0 - if pt_1 and pt_2: - dist_pt = pt_1.distance(pt_2) - - # TODO: check why two points are the same - if np.isclose(dist_pt, 0.0): - print("Points are close, return") - return None - - X = pt_1.x + (pt_2.x - pt_1.x) * self.search_distance / dist_pt - Y = pt_1.y + (pt_2.y - pt_1.y) * self.search_distance / dist_pt - self.anchor = sh_geom.Point(X, Y) # add anchor point - - -class _Vertex: - """Vertex object with multiple lines.""" - - def __init__(self, line_obj): - self.vertex = line_obj.get_end_vertex() - self.search_distance = line_obj.search_distance - - self.cost_footprint = None - self.vertex_opt = None # optimized vertex - self.centerlines = None - self.anchors = None - self.in_raster = None - self.line_radius = None - self.lines = [] # SingleLine objects - - self.add_line(line_obj) - - def add_line(self, line_obj): - self.lines.append(line_obj) - - def generate_anchor_pairs(self): - """ - Extend line following outward direction to length of search_distance. - - Use the end point as anchor point. - - vertex: input intersection with all related lines - return: - one or two pairs of anchors according to numbers of lines - intersected. - two pairs anchors return when 3 or 4 lines intersected - one pair anchors return when 1 or 2 lines intersected. - """ - lines = self.get_lines() - vertex = self.get_vertex() - slopes = [] - for line in self.lines: - slopes.append(line.get_angle()) - - index = 0 # the index of line which paired with first line. - pt_start_1 = None - pt_end_1 = None - pt_start_2 = None - pt_end_2 = None - - if len(slopes) == 4: - # get sort order of angles - index = np.argsort(slopes) - - # first anchor pair (first and third in the sorted array) - pt_start_1 = self.lines[index[0]].anchor - pt_end_1 = self.lines[index[2]].anchor - - pt_start_2 = self.lines[index[1]].anchor - pt_end_2 = self.lines[index[3]].anchor - elif len(slopes) == 3: - # find the largest difference between angles - angle_diff = [ - abs(slopes[0] - slopes[1]), - abs(slopes[0] - slopes[2]), - abs(slopes[1] - slopes[2]), - ] - angle_diff_norm = [2 * np.pi - i if i > np.pi else i for i in angle_diff] - index = np.argmax(angle_diff_norm) - pairs = [(0, 1), (0, 2), (1, 2)] - pair = pairs[index] - - # first anchor pair - pt_start_1 = self.lines[pair[0]].anchor - pt_end_1 = self.lines[pair[1]].anchor - - # the rest one index - remain = list({0, 1, 2} - set(pair))[0] # the remaining index - - try: - pt_start_2 = self.lines[remain].anchor - # symmetry point of pt_start_2 regarding vertex["point"] - X = vertex.x - (pt_start_2.x - vertex.x) - Y = vertex.y - (pt_start_2.y - vertex.y) - pt_end_2 = sh_geom.Point(X, Y) - except Exception as e: - print(e) - - # this scenario only use two anchors - # and find the closest point on least cost path - elif len(slopes) == 2: - pt_start_1 = self.lines[0].anchor - pt_end_1 = self.lines[1].anchor - elif len(slopes) == 1: - pt_start_1 = self.lines[0].anchor - # symmetry point of pt_start_1 regarding vertex["point"] - X = vertex.x - (pt_start_1.x - vertex.x) - Y = vertex.y - (pt_start_1.y - vertex.y) - pt_end_1 = sh_geom.Point(X, Y) - - if not pt_start_1 or not pt_end_1: - print("Anchors not found") - - # if points are outside of cost footprint, set to None - points = [pt_start_1, pt_end_1, pt_start_2, pt_end_2] - for index, pt in enumerate(points): - if pt: - if not self.cost_footprint.contains(sh_geom.Point(pt)): - points[index] = None - - if len(slopes) == 4 or len(slopes) == 3: - if None in points: - return None - else: - return points - elif len(slopes) == 2 or len(slopes) == 1: - if None in (pt_start_1, pt_end_1): - return None - else: - return pt_start_1, pt_end_1 - - def compute(self): - if self.cost_footprint is not None: - try: - if not self.cost_footprint.covers(self.get_vertex()): - return None - except Exception: - if not self.cost_footprint.contains(self.get_vertex()): - return None - - try: - self.anchors = self.generate_anchor_pairs() - except Exception as e: - print(e) - - if not self.anchors: - if bt_const.BT_DEBUGGING: - print("No anchors retrieved") - return None - - centerline_1 = None - centerline_2 = None - intersection = None - - if bt_const.CenterlineFlags.USE_SKIMAGE_GRAPH: - find_lc_path = algo_dijkstra.find_least_cost_path_skimage - else: - find_lc_path = algo_dijkstra.find_least_cost_path - - try: - if len(self.anchors) == 4: - seed_line = sh_geom.LineString(self.anchors[0:2]) - if not self._should_process_seed_line(seed_line): - return None - - raster_clip, out_meta = sp_common.clip_raster(self.in_raster, seed_line, self.line_radius) - raster_clip, _ = algo_cost.cost_raster(raster_clip, out_meta) - centerline_1 = find_lc_path(raster_clip, out_meta, seed_line) - seed_line = sh_geom.LineString(self.anchors[2:4]) - if not self._should_process_seed_line(seed_line): - return None - - raster_clip, out_meta = sp_common.clip_raster(self.in_raster, seed_line, self.line_radius) - raster_clip, _ = algo_cost.cost_raster(raster_clip, out_meta) - centerline_2 = find_lc_path(raster_clip, out_meta, seed_line) - - if centerline_1 and centerline_2: - intersection = algo_common.intersection_of_lines(centerline_1, centerline_2) - elif len(self.anchors) == 2: - seed_line = sh_geom.LineString(self.anchors) - if not self._should_process_seed_line(seed_line): - return None - - raster_clip, out_meta = sp_common.clip_raster(self.in_raster, seed_line, self.line_radius) - raster_clip, _ = algo_cost.cost_raster(raster_clip, out_meta) - centerline_1 = find_lc_path(raster_clip, out_meta, seed_line) - - if centerline_1: - intersection = algo_common.closest_point_to_line(self.get_vertex(), centerline_1) - except Exception as e: - print(e) - - # Update vertices according to intersection, new center lines are returned - if type(intersection) is sh_geom.MultiPoint: - intersection = intersection.centroid - - self.centerlines = [centerline_1, centerline_2] - self.vertex_opt = intersection - - def _should_process_seed_line(self, seed_line): - if seed_line is None or seed_line.length <= bt_const.SMALL_BUFFER: - return False - - if self.cost_footprint is not None: - try: - if not self.cost_footprint.intersects(seed_line.buffer(self.line_radius)): - return False - except Exception: - return False - - max_seed_length = max(float(self.search_distance) * 6.0, float(self.line_radius) * 10.0) - if seed_line.length > max_seed_length: - return False - - return True - - def get_lines(self): - lines = [item.line for item in self.lines] - return lines - - def get_vertex(self): - return self.vertex - - -class VertexGrouping: - """A class used to group vertices and perform vertex optimization.""" - - def __init__( - self, - in_line, - in_raster, - search_distance, - line_radius, - processes, - call_mode, - layer=None, - optimize_internal_vertices=False, - close_distance=None, - min_segment_length=None, - angle_tol=10.0, - ): - self.in_line = in_line - self.in_layer = layer - self.in_raster = in_raster - self.line_radius = float(line_radius) - self.search_distance = float(search_distance) - self.processes = processes - self.call_mode = call_mode - self.optimize_internal_vertices = bool(optimize_internal_vertices) - - self.crs = None - self.vertex_grp = [] - self.sindex = None - - self.line_list = [] - self.line_visited = None - - self.close_distance = close_distance - self.min_segment_length = min_segment_length - self.angle_tol = float(angle_tol) - - if self.close_distance is None: - self.close_distance = self._default_close_distance() - else: - self.close_distance = float(self.close_distance) - - if self.min_segment_length is None: - self.min_segment_length = self.close_distance - else: - self.min_segment_length = float(self.min_segment_length) - - # calculate cost raster footprint - self.cost_footprint = algo_common.generate_raster_footprint(self.in_raster, latlon=False) - - def _default_close_distance(self): - fallback = 2.0 - if rasterio is None: - return fallback - - try: - with rasterio.open(self.in_raster) as src: - transform = src.transform - cell_size = min(abs(transform.a), abs(transform.e)) - if np.isclose(cell_size, 0.0): - return fallback - return float(max(2.0, 1.5 * cell_size)) - except Exception: - return fallback - - def create_vertex_group(self, line_obj): - """ - Create a new vertex group. - - Args: - line_obj : _SingleLine - - """ - # all end points not added will stay with this vertex - vertex = line_obj.get_end_vertex() - vertex_obj = _Vertex(line_obj) - search = self.sindex.query(vertex.buffer(bt_const.SMALL_BUFFER)) - - # add more vertices to the new group - for i in search: - line = self.line_list[i] - if i == line_obj.line_no: - continue - - if not self.line_visited[i][0]: - new_line = _SingleLine(line, i, 0, self.search_distance) - if new_line.touches_point(vertex): - vertex_obj.add_line(new_line) - self.line_visited[i][0] = True - - if not self.line_visited[i][-1]: - new_line = _SingleLine(line, i, -1, self.search_distance) - if new_line.touches_point(vertex): - vertex_obj.add_line(new_line) - self.line_visited[i][-1] = True - - vertex_obj.in_raster = self.in_raster - - vertex_obj.line_radius = self.line_radius - vertex_obj.cost_footprint = self.cost_footprint - self.vertex_grp.append(vertex_obj) - - def create_all_vertex_groups(self): - print(f"Preparing lines...{self.in_line}", flush=True) - print("create_all_vertex_groups") - print(f"in_file: {self.in_line}, in_layer: {self.in_layer}") - - if self.optimize_internal_vertices: - lines_gdf = algo_common.read_geospatial_file(self.in_line, layer=self.in_layer) - lines_gdf = algo_vertex_preclean.preclean_vertices( - lines_gdf, - self.close_distance, - self.min_segment_length, - self.angle_tol, - ) - self.line_list = algo_common.split_lines_to_segments(algo_common.keep_source_seg(lines_gdf)) - else: - lines_gdf = algo_common.read_geospatial_file(self.in_line, layer=self.in_layer) - lines_gdf = algo_vertex_preclean.preclean_vertices( - lines_gdf, - self.close_distance, - self.min_segment_length, - self.angle_tol, - ) - self.line_list = algo_common.lines_gdf_to_list(lines_gdf) - - if not self.line_list: - print("No lines available for vertex optimization.") - return - - self.sindex = STRtree([item.geometry[0] for item in self.line_list]) - self.line_visited = [{0: False, -1: False} for _ in range(len(self.line_list))] - - i = 0 - for line_no in range(len(self.line_list)): - if not self.line_visited[line_no][0]: - line = _SingleLine(self.line_list[line_no], line_no, 0, self.search_distance) - - if not line.is_valid(): - print(f"Line {line.line_no} is invalid") - continue - - self.create_vertex_group(line) - self.line_visited[line_no][0] = True - i += 1 - - if not self.line_visited[line_no][-1]: - line = _SingleLine(self.line_list[line_no], line_no, -1, self.search_distance) - - if not line.is_valid(): - print(f"Line {line.line_no} is invalid") - continue - - self.create_vertex_group(line) - self.line_visited[line_no][-1] = True - i += 1 - - def update_all_lines(self): - for vertex_obj in self.vertex_grp: - for line in vertex_obj.lines: - if not vertex_obj.vertex_opt: - continue - - old_line = self.line_list[line.line_no].geometry[0] - self.line_list[line.line_no].geometry = [ - update_line_end_pt(old_line, line.end_no, vertex_obj.vertex_opt) - ] - - def save_all_layers(self, line_file): - out_file, out_layer = sp_common.decode_file_layer(line_file) - line_file = Path(line_file) - - if not self.line_list: - lines = algo_common.read_geospatial_file(self.in_line, layer=self.in_layer) - if lines is None: - print(f"No output written to: {line_file} (failed to read input lines)", flush=True) - return - - lines = lines.iloc[0:0] - lines = algo_common.clean_geometries( - lines, - stage="output", - out_file=out_file, - layer="rejected_output_vertex_optimization_lines", - ) - lines.to_file(out_file, layer=out_layer) - print(f"Saved output to: {line_file}", flush=True) - return - - lines = pd.concat(self.line_list, ignore_index=True) - - if self.optimize_internal_vertices and bt_const.BT_UID in lines.columns: - # join the segments back into their input rows, keeping each row's BT_GROUP - lines = algo_merge_lines.run_line_merge(lines, merge_group=True, group_field=bt_const.BT_UID) - lines = algo_common.restore_source_seg(lines) - - lines = algo_common.clean_geometries( - lines, - stage="output", - out_file=out_file, - layer="rejected_output_vertex_optimization_lines", - ) - lines.to_file(out_file, layer=out_layer) - print(f"Saved output to: {line_file}", flush=True) - - aux_file = algo_common.get_aux_path(out_file) - - lc_paths = [] - anchors = [] - vertices = [] - for item in self.vertex_grp: - if item.centerlines: - lc_paths.extend(item.centerlines) - if item.anchors: - anchors.extend(item.anchors) - if item.vertex_opt: - vertices.append(item.vertex_opt) - - lc_paths = [item for item in lc_paths if item is not None] - anchors = [item for item in anchors if item is not None] - vertices = [item for item in vertices if item is not None] - - lc_paths = gpd.GeoDataFrame(geometry=lc_paths, crs=lines.crs) - anchors = gpd.GeoDataFrame(geometry=anchors, crs=lines.crs) - vertices = gpd.GeoDataFrame(geometry=vertices, crs=lines.crs) - - if bt_const.BT_DEBUGGING: - lc_paths.to_file(aux_file, layer="lc_paths") - anchors.to_file(aux_file, layer="anchors") - vertices.to_file(aux_file, layer="vertices") - - def compute(self): - compute_processes = self.processes - if self.optimize_internal_vertices and (compute_processes is None or int(compute_processes) <= 0): - compute_processes = 1 +import sys +import warnings - vertex_grp = bt_base.execute_multiprocessing( - algo_common.process_single_item, - self.vertex_grp, - "Vertex Optimization", - compute_processes, - self.call_mode, - ) +from beratools.modules.mapping import algo_vertex_optimization as _moved - self.vertex_grp = vertex_grp +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" bt_const.SMALL_BUFFER: - out.append(coord) - - return out - - -def _preclean_line(line, close_distance, min_segment_length, angle_tol): - coords = list(line.coords) - if len(coords) <= 2: - return line - - cleaned = [coords[0]] - - for i in range(1, len(coords) - 1): - prev_coord = cleaned[-1] - curr_coord = coords[i] - next_coord = coords[i + 1] - - prev_dist = _point_distance(prev_coord, curr_coord) - next_dist = _point_distance(curr_coord, next_coord) - - if prev_dist < close_distance or next_dist < close_distance: - continue - - if (prev_dist < min_segment_length or next_dist < min_segment_length) and _is_near_collinear( - prev_coord, curr_coord, next_coord, angle_tol - ): - continue - - cleaned.append(curr_coord) - - cleaned.append(coords[-1]) - cleaned = _dedupe_consecutive_coords(cleaned) - - while len(cleaned) > 2 and _point_distance(cleaned[0], cleaned[1]) < min_segment_length: - cleaned.pop(1) - - while len(cleaned) > 2 and _point_distance(cleaned[-2], cleaned[-1]) < min_segment_length: - cleaned.pop(-2) - - if len(cleaned) < 2: - return None - - if _point_distance(cleaned[0], cleaned[-1]) <= bt_const.SMALL_BUFFER: - return None - - return sh_geom.LineString(cleaned) - - -def _simplify_line_fr_dist_offset(line, close_distance, min_segment_length, angle_tol=None): - """ - 1) Remove repeated points from the input line, - 2) Remove vertices based on back and forward internal distances (e.g. < min_segment_length) and offset constraints - (e.g. perpendicular offset or collinearity < offset threshold). - - Return - Simplified line - """ - line = sh.remove_repeated_points(line, tolerance=0.0) - vertices = np.array(line.coords) - if len(vertices) < 3: - return line - # Initialize with first point - simplified = [sh_geom.Point(vertices[0])] - skipped = False - for i in range(1, len(vertices) - 1): - prev = vertices[i - 1] - curr = vertices[i] - nxt = vertices[i + 1] - - # Calculate distances to previous and next vertex - dist_prev = np.linalg.norm(curr - prev) - dist_next = np.linalg.norm(nxt - curr) - # Calculate offset distances from curr point to previous and next vertex - current_p = sh_geom.Point(curr) - whole_l = sh_geom.LineString([prev, nxt]) - if skipped is False: - # Condition: either distances must be > 2 meters apart (example constraint) - if dist_prev > min_segment_length and dist_next > min_segment_length: - # perpendicular offset or collinearity > offset threshold, keep current point - if current_p.distance(whole_l) > close_distance: - simplified.append(current_p) - skipped = False - else: - # skip current when smaller - skipped = True - continue - - else: # Condition: distances < 2 meters apart, skip current - skipped = True - continue - else: - # if skipped in previous point, keep current point - simplified.append(current_p) - skipped = False - - # Always keep the last point - simplified.append(sh_geom.Point(vertices[-1])) - - return sh_geom.LineString(simplified) - - -def preclean_vertices(gdf, close_distance, min_segment_length, angle_tol): - """Remove redundant close internal vertices on each line independently.""" - if gdf is None or gdf.empty: - return gdf - - if isinstance(gdf, gpd.GeoSeries): - gdf = gpd.GeoDataFrame(geometry=gdf) - - out_gdf = gdf.copy() - - if any(geom.geom_type == "MultiLineString" for geom in out_gdf.geometry): - out_gdf = out_gdf.explode(index_parts=False) - - cleaned_geoms = [] - for geom in out_gdf.geometry: - if geom is None or geom.is_empty: - cleaned_geoms.append(None) - continue - - if geom.geom_type != "LineString": - cleaned_geoms.append(geom) - continue - - cleaned_geoms.append(_simplify_line_fr_dist_offset(geom, close_distance, min_segment_length, angle_tol)) - - out_gdf.geometry = cleaned_geoms - out_gdf = out_gdf[~out_gdf.geometry.isna() & ~out_gdf.geometry.is_empty] - out_gdf = out_gdf[out_gdf.geometry.length > bt_const.SMALL_BUFFER] - out_gdf.reset_index(drop=True, inplace=True) - - return out_gdf +""" +Deprecated: moved to beratools.modules.mapping. + +Kept so old imports keep working, with a DeprecationWarning, until it is removed. +""" + +import sys +import warnings + +from beratools.modules.mapping import algo_vertex_preclean as _moved + +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" for full license details. - -Author: Richard Zeng, Maverick Fong - -Description: - This file hosts alternate CHM clipping/filtering logic for centerline runs. +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -import math - -import numpy as np -import rasterio -from rasterio import mask, features -import scipy.ndimage as ndimage -import skimage as ski -import shapely as shp -import beratools.core.constants as bt_const - - -def alt_clip_and_filter_regional_maxima_wgap( - seedline_class, - in_raster_file, - clip_geom, - buffer=1.0, - default_nodata=bt_const.BT_NODATA, - ): - - def erose_all_labels(labels_array): - erose_array = np.zeros_like(labels_array) - unique_labels = np.unique(labels_array) - for label in unique_labels: - if label == 0: - continue # Skip background - - # Create a binary mask for the current label - mask = (labels_array == label) - - # Dilate the mask for this specific label - erose_mask = ski.morphology.erosion(mask) - - # Assign the dilated mask back into the new array with the correct label value - erose_array[erose_mask] = label - - return erose_array - - with rasterio.open(in_raster_file) as src: - - clip_geo_buffer = [shp.simplify(clip_geom,0.25).buffer(buffer)] - out_image, out_transform = rasterio.mask.mask(src, clip_geo_buffer, crop=True) - shapes = [(shp.simplify(clip_geom,0.25).buffer(buffer), 1)] # Burn value '1' into the raster - raster_array = features.rasterize(shapes, - out_shape=out_image.shape[1:], - transform=out_transform, - fill=0, - dtype=np.uint8, - all_touched=True, - - ) - valid_area=raster_array==1 - valid_area=valid_area[np.newaxis,...] - if src.nodata is not None: - out_image[out_image == src.nodata] = 0. - out_image[raster_array[np.newaxis,:] == 0] = default_nodata - ras_nodata = src.meta["nodata"] - cell_size = max(out_transform[0], -out_transform[4]) - if ras_nodata is None: - ras_nodata = default_nodata - - #generate mask for valid raster data - # data_mask = ~(np.ma.masked_equal(out_image, ras_nodata).mask) - data_mask = valid_area - #fill unmasked data with 0, otherwise keep the original value - data_filled = np.where(data_mask, out_image, 0) - data_filled = np.where(data_filled==ras_nodata,0, data_filled) - - - #calulate the gaussian_filter's sigma to remove sharp noise without removing small crowns. - sigma = math.ceil(seedline_class.tree_radius) * 0.5 - smoothed_data = ndimage.gaussian_filter(data_filled, sigma=sigma) - #generate search tree crown footprint - footprint = ski.morphology.disk(math.ceil(seedline_class.tree_radius)) - footprint = footprint.reshape(-1, footprint.shape[0], footprint.shape[1]) - - smooth_mask = ndimage.gaussian_filter(data_mask.astype(float), sigma=sigma) - mask_normalization = smoothed_data / smooth_mask - mask_normalization[~data_mask] = np.nan - mask_normalization = np.ma.masked_invalid(mask_normalization) - tree_tops_indices = ski.feature.peak_local_max( - mask_normalization, - min_distance=1, #find maximum number of tree tops - exclude_border=False, - num_peaks_per_label=1, - footprint=footprint, - ) - if len(tree_tops_indices) > 0: - mask_ = np.ma.zeros_like(mask_normalization) - for i, (_, row, col) in enumerate(tree_tops_indices): - mask_[_, row, col] = 1 - markers = ski.measure.label(mask_) - - markers_tree = ski.segmentation.expand_labels(markers, distance=max(math.ceil(seedline_class.tree_radius), 1)) - markers_tree_=erose_all_labels(ski.segmentation.expand_labels(markers_tree,10)) - tree_area = markers_tree_.astype(bool) - new_chm = np.ma.zeros_like(mask_normalization) - new_chm[tree_area] = mask_normalization[tree_area] - new_chm[~valid_area] = np.nan - - new_chm_gaps = np.ma.zeros_like(mask_normalization) - new_chm_gaps=np.ma.where(markers_tree_==0,mask_normalization.data,0) - new_chm_gaps = np.ma.where(mask_normalization.mask , 0, new_chm_gaps) - - filtered_image = new_chm - - else: - filtered_image = mask_normalization # - markers = np.ma.zeros_like(mask_normalization) - tree_area = np.ma.zeros_like(mask_normalization, dtype=bool) - filtered_image[filtered_image < 0.0] = 0.0 - if np.ma.is_masked(filtered_image): - filtered_image.fill_value = default_nodata - else: - filtered_image = np.ma.masked_invalid(filtered_image) - filtered_image.fill_value = default_nodata - - ras_nodata = default_nodata - - # Update Metadata - out_meta = src.meta.copy() - out_meta.update({ - "driver": "GTiff", - "height": filtered_image.shape[1], - "width": filtered_image.shape[2], - "nodata": ras_nodata, - "transform": out_transform - }) +import sys +import warnings - tree_crown = ski.segmentation.watershed(-mask_normalization, markers, mask=~mask_normalization.mask, - watershed_line=True) - tree_crown_ = ski.morphology.erosion(tree_crown, footprint=ski.morphology.square(3)[np.newaxis,:] ) - tree_crown_area = tree_crown_.astype(bool) - new_crown = np.ma.zeros_like(mask_normalization) - new_crown[tree_crown_area] = mask_normalization[tree_crown_area] - new_crown[~tree_crown_area] = 0. +from beratools.modules.mapping import alt_spatial_common as _moved - return filtered_image, out_meta,new_chm_gaps.squeeze()#,markers.squeeze(),tree_area.squeeze(), new_crown.squeeze(), +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" list: - """ - Buffers an input geometry nring (number of rings) times, with a distance between - rings of ringdist and returns a list of non overlapping buffers - """ - import numpy as np - rings = [] # A list to hold the individual buffers - for ring in np.arange(0, ringdist, nrings): # For each ring (1, 2, 3, ..., nrings) - big_ring = geom.buffer( - nrings + ring, single_sided=True, cap_style="flat" - ) # Create one big buffer - small_ring = geom.buffer( - ring, single_sided=True, cap_style="flat" - ) # Create one smaller one - the_ring = big_ring.difference(small_ring) # Difference the big with the small to create a ring - if ( - ~shapely.is_empty(the_ring) - or ~shapely.is_missing(the_ring) - or not None - or ~the_ring.area == 0 - ): - if isinstance(the_ring, shapely.MultiPolygon) or isinstance(the_ring, shapely.Polygon): - rings.append(the_ring) # Append the ring to the rings list - else: - if isinstance(the_ring, shapely.GeometryCollection): - for i in range(0, len(the_ring.geoms)): - if not isinstance(the_ring.geoms[i], shapely.LineString): - rings.append(the_ring.geoms[i]) - print(" {}% ".format((ring / ringdist) * 100)) - - return rings # return the list - - -def main_canopy_threshold_relative( - in_line: str, - in_chm: str, - canopy_percentile: int, - canopy_thresh_percentage: int, - full_step: bool, - processes:int, - out_dyn_centerline: str=None, #for Test tool only -)-> str | None: - """ - This is a function finding approximate surrounding forest canopy height - and surrounding forest edge distance from input CHM - Args: - in_line: Path like string - in_chm: Path like string - canopy_percentile: Percentile as integer range 1-100 - canopy_thresh_percentage: Percentage as integer range 1-100 - - Returns: - Path like string of the saved centerlines with extra attributes - """ - file_path, in_file_name = os.path.split(Path(in_line)) - in_file, layer = decode_file_layer(in_line) - if out_dyn_centerline==None: - out_dyn_centerline = os.path.join(Path(file_path), "DynCanTh_" + in_file_name) - out_cl_file, out_layer = decode_file_layer(out_dyn_centerline) - line_seg = gpd.GeoDataFrame.from_file(in_file, layer=layer) - _,processes=parallel_mode(processes) - # check coordinate systems between line and raster features - # with rasterio.open(in_chm) as in_raster: - if compare_crs(vector_crs(in_file,layer), raster_crs(in_chm)): - pass - else: - print("Line and raster spatial references are not same, please check.") - exit() - - # Check the canopy threshold percent in 0-100 range. If it is not, 50% will be applied - if not 100 >= int(canopy_percentile) > 0: - canopy_percentile = 50 - - # Check the Dynamic Canopy threshold column in data. If it is not, new column will be created - if "DynCanTh" not in line_seg.columns.array: - print("New column created: {}".format("DynCanTh")) - line_seg["DynCanTh"] = np.nan - - # Check the OLnFID column in data. If it is not, column will be created - if "OLnFID" not in line_seg.columns.array: - print("New column created: {}".format("OLnFID")) - line_seg["OLnFID"] = line_seg.index - - # Check the OLnSEG column in data. If it is not, column will be created - if "OLnSEG" not in line_seg.columns.array: - print("New column created: {}".format("OLnSEG")) - line_seg["OLnSEG"] = 0 - - # Check input line for multipart - line_seg = chk_df_multipart(line_seg, "LineString")[0] - - #Not splitting lines - proc_segments = False - if proc_segments: - line_seg = split_into_segments(line_seg) - else: - pass - - # copy original line input to another GeoDataframe and simplify the line geometry for buffering - workln_df_c = gpd.GeoDataFrame.copy(line_seg, deep=True) - workln_df_c.geometry = workln_df_c.geometry.simplify(tolerance=0.5, preserve_topology=True) - - print("{}%".format(5)) - # copy simplified line input for ring buffer for two sides buffering - worklnbuffer_df_l_ring = gpd.GeoDataFrame.copy((workln_df_c),deep=True) - worklnbuffer_df_r_ring = gpd.GeoDataFrame.copy((workln_df_c),deep=True) - - print("Create ring buffer for input line to find the forest edge....") - - # Create a column with the rings as a list - print("Create rings buffer to forest edge on both side of centerlines....") - with Pool(processes) as pool: - worklnbuffer_df_l_ring["mgeometry"] = pool.map( - partial(multiringbuffer, nrings=1, ringdist=15), - worklnbuffer_df_l_ring.geometry, - chunksize=max(1, len(worklnbuffer_df_l_ring) // (processes * 4)), - ) - worklnbuffer_df_r_ring["mgeometry"] = pool.map( - partial(multiringbuffer, nrings=-1, ringdist=-15), - worklnbuffer_df_r_ring.geometry, - chunksize=max(1, len(worklnbuffer_df_r_ring) // (processes * 4)), - ) - - # Explode to create a row for each ring - worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.explode("mgeometry") - worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.set_geometry("mgeometry") - worklnbuffer_df_l_ring = ( - worklnbuffer_df_l_ring.drop(columns=["geometry"]).rename_geometry("geometry").set_crs(workln_df_c.crs) - ) - worklnbuffer_df_l_ring["iRing"] = worklnbuffer_df_l_ring.groupby(["OLnFID", "OLnSEG"]).cumcount() - worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.sort_values(by=["OLnFID", "OLnSEG", "iRing"]) - worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.reset_index(drop=True) - - worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.explode("mgeometry") # Explode to create a row for each ring - worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.set_geometry("mgeometry") - worklnbuffer_df_r_ring = ( - worklnbuffer_df_r_ring.drop(columns=["geometry"]).rename_geometry("geometry").set_crs(workln_df_c.crs) - ) - worklnbuffer_df_r_ring["iRing"] = worklnbuffer_df_r_ring.groupby(["OLnFID", "OLnSEG"]).cumcount() - worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.sort_values(by=["OLnFID", "OLnSEG", "iRing"]) - worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.reset_index(drop=True) - - print("Create rings buffer.... done.") - print("{}%".format(20)) - - worklnbuffer_df_r_ring["Percentile_RRing"] = np.nan - worklnbuffer_df_l_ring["Percentile_LRing"] = np.nan - line_seg["CL_CutHt"] = np.nan - line_seg["CR_CutHt"] = np.nan - line_seg["RDist_Cut"] = np.nan - line_seg["LDist_Cut"] = np.nan - print("{}%".format(30)) - - # calculate the Height percentile for each parallel area using CHM - worklnbuffer_df_l_ring = multiprocessing_percentile( - worklnbuffer_df_l_ring, - int(canopy_percentile), - int(canopy_thresh_percentage), - in_chm, - processes, - side="LRing", - ) - - worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.sort_values(by=["OLnFID", "OLnSEG", "iRing"]) - worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.reset_index(drop=True) - print("{}%".format(60)) - worklnbuffer_df_r_ring = multiprocessing_percentile( - worklnbuffer_df_r_ring, - int(canopy_percentile), - int(canopy_thresh_percentage), - in_chm, - processes, - side="RRing", - ) - - worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.sort_values(by=["OLnFID", "OLnSEG", "iRing"]) - worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.reset_index(drop=True) - - result = multiprocessing_RofC(line_seg, worklnbuffer_df_l_ring, worklnbuffer_df_r_ring, processes) - print("{}%".format(80)) - print("Calculating forest population done.") - - print("Saving percentile information to input line ...") - gpd.GeoDataFrame.to_file(result, out_cl_file, layer=out_layer) - print("Saving percentile information to input line ...done.") - - if full_step: - return out_dyn_centerline # TODO: make sure this is correct - - print("{}%".format(100)) - - -def rate_of_change(in_arg): # ,max_chmht): - x = in_arg[0] - Olnfid = in_arg[1] - Olnseg = in_arg[2] - side = in_arg[3] - df = in_arg[4] - index = in_arg[5] - - # Since the x interval is 1 unit, the array 'diff' is the rate of change (slope) - diff = np.ediff1d(x) - cut_dist = len(x) / 5 - - median_percentile = np.nanmedian(x) - if not np.isnan(median_percentile): - cut_percentile = math.floor(median_percentile) - else: - cut_percentile = 0.5 - found = False - changes = 1.50 - Change = np.insert(diff, 0, 0) - scale_down = 1 - - # test the rate of change is > than 150% (1.5), if it is - # no result found then lower to 140% (1.4) until 110% (1.1) - try: - while not found and changes >= 1.1: - for ii in range(0, len(Change) - 1): - if x[ii] >= 0.5: - if (Change[ii]) >= changes: - cut_dist = (ii + 1) * scale_down - cut_percentile = math.floor(x[ii]) - # median_diff=(cut_percentile-median_percentile) - if 0.5 >= cut_percentile: - if cut_dist > 5: - cut_percentile = 2 - cut_dist = cut_dist * scale_down**3 - print( - "{}: OLnFID:{}, OLnSEG: {} @<0.5 found and modified".format( - side, Olnfid, Olnseg - ), - flush=True, - ) - elif 0.5 < cut_percentile <= 5.0: - if cut_dist > 6: - cut_dist = cut_dist * scale_down**3 # 4.0 - print( - "{}: OLnFID:{}, OLnSEG: {} @0.5-5.0 found and modified".format( - side, Olnfid, Olnseg - ), - flush=True, - ) - elif 5.0 < cut_percentile <= 10.0: - if cut_dist > 8: # 5 - cut_dist = cut_dist * scale_down**3 - print( - "{}: OLnFID:{}, OLnSEG: {} @5-10 found and modified".format( - side, Olnfid, Olnseg - ), - flush=True, - ) - elif 10.0 < cut_percentile <= 15: - if cut_dist > 5: - cut_dist = cut_dist * scale_down**3 # 5.5 - print( - "{}: OLnFID:{}, OLnSEG: {} @10-15 found and modified".format( - side, Olnfid, Olnseg - ), - flush=True, - ) - elif 15 < cut_percentile: - if cut_dist > 4: - cut_dist = cut_dist * scale_down**2 - cut_percentile = 15.5 - print( - "{}: OLnFID:{}, OLnSEG: {} @>15 found and modified".format( - side, Olnfid, Olnseg - ), - flush=True, - ) - found = True - print( - "{}: OLnFID:{}, OLnSEG: {} rate of change found".format(side, Olnfid, Olnseg), - flush=True, - ) - break - changes = changes - 0.1 - - except IndexError: - pass - - # if still is no result found, lower to 10% (1.1), if no result found then default is used - if not found: - if 0.5 >= median_percentile: - cut_dist = 4 * scale_down # 3 - cut_percentile = 0.5 - elif 0.5 < median_percentile <= 5.0: - cut_dist = 4.5 * scale_down # 4.0 - cut_percentile = math.floor(median_percentile) - elif 5.0 < median_percentile <= 10.0: - cut_dist = 5.5 * scale_down # 5 - cut_percentile = math.floor(median_percentile) - elif 10.0 < median_percentile <= 15: - cut_dist = 6 * scale_down # 5.5 - cut_percentile = math.floor(median_percentile) - elif 15 < median_percentile: - cut_dist = 5 * scale_down # 5 - cut_percentile = 15.5 - print( - "{}: OLnFID:{}, OLnSEG: {} Estimated".format(side, Olnfid, Olnseg), - flush=True, - ) - if side == "Right": - df["RDist_Cut"] = cut_dist - df["CR_CutHt"] = cut_percentile - elif side == "Left": - df["LDist_Cut"] = cut_dist - df["CL_CutHt"] = cut_percentile - - return df - - -def multiprocessing_RofC(line_seg, worklnbuffer_dfLRing, worklnbuffer_dfRRing, processes): - in_argsL = [] - in_argsR = [] - - for index in line_seg.index: - resultsL = [] - resultsR = [] - Olnfid = int(line_seg.OLnFID.iloc[index]) - Olnseg = int(line_seg.OLnSEG.iloc[index]) - sql_dfL = worklnbuffer_dfLRing.loc[ - (worklnbuffer_dfLRing["OLnFID"] == Olnfid) & (worklnbuffer_dfLRing["OLnSEG"] == Olnseg) - ].sort_values(by=["iRing"]) - PLRing = list(sql_dfL["Percentile_LRing"]) - sql_dfR = worklnbuffer_dfRRing.loc[ - (worklnbuffer_dfRRing["OLnFID"] == Olnfid) & (worklnbuffer_dfRRing["OLnSEG"] == Olnseg) - ].sort_values(by=["iRing"]) - PRRing = list(sql_dfR["Percentile_RRing"]) - in_argsL.append([PLRing, Olnfid, Olnseg, "Left", line_seg.loc[index], index]) - in_argsR.append([PRRing, Olnfid, Olnseg, "Right", line_seg.loc[index], index]) - print(' "PROGRESS_LABEL Preparing grouped buffer areas...." ', flush=True) - print(" {}% ".format(((index + 1) / len(line_seg)) * 100)) - - total_steps = len(in_argsL) + len(in_argsR) - featuresL = [] - featuresR = [] - - if PARALLEL_MODE == ParallelMode.MULTIPROCESSING: - with Pool(processes=int(processes)) as pool: - step = 0 - # execute tasks in order, process results out of order - try: - for resultL in pool.imap_unordered(rate_of_change, in_argsL): - if BT_DEBUGGING: - print("Got result: {}".format(resultL), flush=True) - featuresL.append(resultL) - step += 1 - print( - ' "PROGRESS_LABEL Calculate Rate of Change In Buffer Area {} of {}" '.format( - step, total_steps - ), - flush=True, - ) - print("{}%".format(step / total_steps * 100), flush=True) - except Exception: - print(Exception) - raise - - gpdL = gpd.GeoDataFrame(pd.concat(featuresL, axis=1).T) - with Pool(processes=int(processes)) as pool: - step=0 - try: - for resultR in pool.imap_unordered(rate_of_change, in_argsR): - if BT_DEBUGGING: - print("Got result: {}".format(resultR), flush=True) - featuresR.append(resultR) - step += 1 - print( - ' "PROGRESS_LABEL Calculate Rate of Change Area {} of {}" '.format( - step + len(in_argsL), total_steps - ), - flush=True, - ) - print( - "{}%".format((step + len(in_argsL)) / total_steps * 100), - flush=True, - ) - except Exception: - print(Exception) - raise - gpdR = gpd.GeoDataFrame(pd.concat(featuresR, axis=1).T) - else: - for rowL in in_argsL: - featuresL.append(rate_of_change(rowL)) - - for rowR in in_argsR: - featuresR.append(rate_of_change(rowR)) - - gpdL = gpd.GeoDataFrame(pd.concat(featuresL, axis=1).T) - gpdR = gpd.GeoDataFrame(pd.concat(featuresR, axis=1).T) - - line_seg = line_seg.set_index(['OLnFID', 'OLnSEG'], drop=True) - gpdL['geometry'] = gpdL['geometry'].normalize() - gpdL['wkt'] = gpdL['geometry'].apply(lambda x: x.wkt) - deduplicated_gpdL = gpdL.drop_duplicates(subset=['wkt'], keep='first') - deduplicated_gpdL = deduplicated_gpdL.drop(columns=['wkt']).reset_index(drop=True) - gpdR['geometry'] = gpdR['geometry'].normalize() - gpdR['wkt'] = gpdR['geometry'].apply(lambda x: x.wkt) - deduplicated_gpdR = gpdR.drop_duplicates(subset=['wkt'], keep='first') - deduplicated_gpdR = deduplicated_gpdR.drop(columns=['wkt']).reset_index(drop=True) - - mapping_left_ldist_cut = deduplicated_gpdL.set_index(['OLnFID', 'OLnSEG'])['LDist_Cut'] - mapping_left_rdist_cut = deduplicated_gpdR.set_index(['OLnFID', 'OLnSEG'])['RDist_Cut'] - mapping_left_lcl_cut = deduplicated_gpdL.set_index(['OLnFID', 'OLnSEG'])['CL_CutHt'] - mapping_left_rcl_cut = deduplicated_gpdR.set_index(['OLnFID', 'OLnSEG'])['CR_CutHt'] - - condition_ldist_cut = line_seg.index.isin(mapping_left_ldist_cut.index) - condition_rdist_cut = line_seg.index.isin(mapping_left_rdist_cut.index) - condition_lcl_cut = line_seg.index.isin(mapping_left_lcl_cut.index) - condition_rcl_cut = line_seg.index.isin(mapping_left_rcl_cut.index) - - line_seg.loc[condition_ldist_cut, "LDist_Cut"] = line_seg.index.map(mapping_left_ldist_cut) - line_seg.loc[condition_rdist_cut, "RDist_Cut"] = line_seg.index.map(mapping_left_rdist_cut) - line_seg.loc[condition_lcl_cut, "CL_CutHt"] = line_seg.index.map(mapping_left_lcl_cut) - line_seg.loc[condition_rcl_cut, "CR_CutHt"] = line_seg.index.map(mapping_left_rcl_cut) - line_seg["DynCanTh"] = (line_seg["CL_CutHt"] + line_seg["CR_CutHt"]) / 2 - line_seg=line_seg.reset_index(drop=False) - - - return line_seg - - -def split_line_fc(line): - if line: - return list(map(shapely.LineString, zip(line.coords[:-1], line.coords[1:]))) - else: - return None - - -def split_into_segments(df): - odf = df - crs = odf.crs - if "OLnSEG" not in odf.columns.array: - df["OLnSEG"] = np.nan - else: - pass - df = odf.assign(geometry=odf.apply(lambda x: split_line_fc(x.geometry), axis=1)) - df = df.explode() - - df["OLnSEG"] = df.groupby("OLnFID").cumcount() - gdf = gpd.GeoDataFrame(df, geometry=df.geometry, crs=crs) - gdf = gdf.sort_values(by=["OLnFID", "OLnSEG"]) - gdf = gdf.reset_index(drop=True) - return gdf - -def multiprocessing_percentile(df:gpd.GeoDataFrame, - can_percentile:int, - can_thr_percentage:int, - in_chm: str, - processes:int, - side:str)->gpd.GeoDataFrame | None: - try: - line_arg = [] - total_steps = len(df) - cal_percentile = cal_percentile_ring - which_side = side - per_col="Percentile_LRing" - if side == "LRing": - per_col = "Percentile_LRing" - which_side = "left" - elif side == "RRing": - per_col = "Percentile_RRing" - which_side = "right" - - print("Calculating surrounding ({}) forest population for buffer area ...".format(which_side)) - - for item in df.index: - item_list = [ - df.iloc[[item]], - can_percentile, - can_thr_percentage, - in_chm, - item, - per_col, - ] - line_arg.append(item_list) - print( - ' "PROGRESS_LABEL Preparing lines... {} of {}" '.format(item + 1, len(df)), - flush=True, - ) - print(" {}% ".format(item / len(df) * 100), flush=True) - - features = [] - - if PARALLEL_MODE == ParallelMode.MULTIPROCESSING: - with Pool(processes=int(processes)) as pool: - step = 0 - # execute tasks in order, process results out of order - try: - for result in pool.imap_unordered(cal_percentile, line_arg): - if BT_DEBUGGING: - print("Got result: {}".format(result), flush=True) - features.append(result) - step += 1 - print( - ' "PROGRESS_LABEL Calculate Percentile In Buffer Area {} of {}" '.format( - step, total_steps - ), - flush=True, - ) - print("{}%".format(step / total_steps * 100), flush=True) - except Exception: - print(Exception) - raise - del line_arg - - return gpd.GeoDataFrame(pd.concat(features)) - else: - verbose = False - total_steps = len(line_arg) - step = 0 - for row in line_arg: - features.append(cal_percentile(row)) - step += 1 - if verbose: - print( - ' "PROGRESS_LABEL Calculate Percentile on line {} of {}" '.format(step, total_steps), - flush=True, - ) - print(" {}% ".format(step / total_steps * 100), flush=True) - return gpd.GeoDataFrame(pd.concat(features)) - - except OperationCancelledException: - print("Operation cancelled") - return None - - -def cal_percentile_ring(line_arg): - from shapely import ops - import traceback - - try: - df = line_arg[0] - can_percentile = line_arg[1] - can_thr_percentage = line_arg[2] - in_chm = line_arg[3] - row_index = line_arg[4] - per_col = line_arg[5] - - percentile = 1 - dyn_canopy_threshold = 1 - - line_buffer = df.loc[row_index, "geometry"] - if line_buffer.is_empty or shapely.is_missing(line_buffer): - return None - if line_buffer.has_z: - line_buffer = ops.transform(lambda x, y, z=None: (x, y), line_buffer) - - except Exception as e: - print(e) - print("Assigning variable on index:{} Error: ".format(line_arg) + traceback.format_exc()) - exit() - - if isinstance(can_percentile,int): - if 100>can_percentile>0: - pass - else: - can_percentile = 50 - else: - can_percentile =50 - - try: - - clipped_raster, out_meta = clip_raster(in_chm, line_buffer, 0) - clipped_raster = np.squeeze(clipped_raster, axis=0) - - # mask all -9999 (nodata) value cells - masked_raster = np.ma.masked_where(clipped_raster == BT_NODATA, clipped_raster) - filled_raster = np.ma.filled(masked_raster, np.nan) - - percentile = np.nanpercentile(filled_raster, can_percentile) - - if percentile > 1: - dyn_canopy_threshold = percentile * (can_thr_percentage/100) - else: - dyn_canopy_threshold = 1 - - del clipped_raster, out_meta - - # return the generated value - except Exception as e: - print(e) - print("Default values are used.") - - finally: - df.loc[row_index, per_col] = percentile - df.loc[row_index, "DynCanTh"] = dyn_canopy_threshold - return df - - -def copyparallel_lineLRC(line_arg): - dfL = line_arg[0] - dfR = line_arg[1] - - # Simplify input center lines - geom = dfL.loc[line_arg[6], "geometry"] - if not geom: - return None - - lineL = dfL.loc[line_arg[6], "geometry"].simplify(tolerance=0.05, preserve_topology=True) - lineR = dfR.loc[line_arg[6], "geometry"].simplify(tolerance=0.05, preserve_topology=True) - # lineC = dfC.loc[line_arg[6], 'geometry'].simplify(tolerance=0.05, preserve_topology=True) - offset_distL = float(line_arg[3]) - offset_distR = float(line_arg[4]) - - # Older alternative method to the offset_curve() method, - # but uses resolution instead of quad_segs and a side keyword (‘left’ or ‘right’) instead - # of sign of the distance. This method is kept for backwards compatibility for now, - # but it is recommended to use offset_curve() instead. - # (ref: https://shapely.readthedocs.io/en/stable/manual.html#object.offset_curve) - parallel_lineL = lineL.parallel_offset( - distance=offset_distL, side="left", join_style=shapely.BufferJoinStyle.mitre - ) - - parallel_lineR = lineR.parallel_offset( - distance=-offset_distR, side="right", join_style=shapely.BufferJoinStyle.mitre - ) - - if not parallel_lineL.is_empty: - dfL.loc[line_arg[6], "geometry"] = parallel_lineL - if not parallel_lineR.is_empty: - dfR.loc[line_arg[6], "geometry"] = parallel_lineR - - return dfL.iloc[[line_arg[6]]], dfR.iloc[[line_arg[6]]] +""" +Deprecated: moved to beratools.modules.mapping. + +Kept so old imports keep working, with a DeprecationWarning, until it is removed. +""" + +import sys +import warnings + +from beratools.modules.mapping import canopy_threshold_relative as _moved + +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(". -# -# --------------------------------------------------------------------------- -# -# Refactor to use for produce dynamic footprint from dynamic canopy and cost raster with open source libraries -# Prerequisite: Line feature class must have the attribute Fields:"CorridorTh" "DynCanTh" "OLnFID" -# line_footprint_function.py -# Maverick Fong -# Date: 2023-Dec -# This script is part of the BERA toolset -# Webpage: https://github.com/ -# -# Purpose: Creates dynamic footprint polygons for each input line based on a least -# cost corridor method and individual line thresholds. -# -# --------------------------------------------------------------------------- - -from geopandas import GeoDataFrame -from rasterio import features -from rasterio.mask import mask -from shapely import LineString, MultiPolygon, Point, buffer -from shapely.geometry import shape -from skimage.graph import MCP_Flexible -from pathlib import Path -from xrspatial import convolution - -import beratools.core.algo_common as algo_common -from beratools.core.algo_centerline import * -from beratools.core.canopy_threshold_relative import OperationCancelledException -from beratools.core.constants import * -from beratools.core.tool_base import * -from beratools.tools.common import * -from beratools.utility.spatial_common import * - - -def dyn_canopy_cost_raster(args): - in_chm_raster = args[0] - DynCanTh = args[1] - tree_radius = args[2] - max_line_dist = args[3] - canopy_avoid = args[4] - exponent = args[5] - res = args[6] - nodata = args[7] - line_df = args[8] - out_meta = args[9] - line_id = args[10] - Cut_Dist = args[11] - Side = args[12] - canopy_thresh_percentage = float(args[13]) / 100 - line_buffer = args[14] - exp_shk_cell=args[15] - - if Side == "Left": - canopy_ht_threshold = line_df.CL_CutHt.iloc[0] * canopy_thresh_percentage - elif Side == "Right": - canopy_ht_threshold = line_df.CR_CutHt.iloc[0] * canopy_thresh_percentage - elif Side == "Center": - canopy_ht_threshold = DynCanTh * canopy_thresh_percentage - else: - canopy_ht_threshold = 0.5 - - canopy_ht_threshold = float(canopy_ht_threshold) - if canopy_ht_threshold <= 0: - canopy_ht_threshold = 0.5 - tree_radius = float(tree_radius) # get the round up integer number for tree search radius - max_line_dist = float(max_line_dist) - canopy_avoid = float(canopy_avoid) - cost_raster_exponent = float(exponent) - - try: - clipped_rasterC, out_meta = clip_raster(in_chm_raster, line_buffer, 0) - - in_chm = np.squeeze(clipped_rasterC, axis=0) - if BT_DEBUGGING: - print('[Debug]: Loading CHM ...') - cell_x, cell_y = out_meta["transform"][0], -out_meta["transform"][4] - - if BT_DEBUGGING: - print('[Debug]: Preparing Kernel window ...') - kernel = convolution.circle_kernel(cell_x, cell_y, int(tree_radius)) - - # Generate Canopy Raster and return the Canopy array - if BT_DEBUGGING: - print('[Debug]: Generate Canopy Raster ...') - dyn_canopy_ndarray = dyn_np_cc_map(in_chm, canopy_ht_threshold, BT_NODATA) - - # Calculating focal statistic from canopy raster - if BT_DEBUGGING: - print('[Debug]: Calculating focal statistic from Canopy Raster ...') - cc_std, cc_mean = dyn_fs_raster_stdmean(dyn_canopy_ndarray, kernel, BT_NODATA) - - # Smoothing raster - if BT_DEBUGGING: - print('[Debug]: Generating smoothed cost raster ...') - cc_smooth = dyn_smooth_cost(dyn_canopy_ndarray, max_line_dist, [cell_x, cell_y]) - avoidance = max(min(float(canopy_avoid), 1), 0) - cost_clip = dyn_np_cost_raster( - dyn_canopy_ndarray, - cc_mean, - cc_std, - cc_smooth, - avoidance, - cost_raster_exponent, - ) - negative_cost_clip = np.where( - np.isnan(cost_clip), -9999, cost_clip - ) # TODO was nodata, changed to BT_NODATA_COST - return ( - line_df, - dyn_canopy_ndarray, - negative_cost_clip, - out_meta, - max_line_dist, - nodata, - line_id, - Cut_Dist, - line_buffer, - exp_shk_cell - ) - - except Exception as e: - print("[Error]: Error in creating (dynamic) cost raster @ {}: {}".format(line_id, e)) - return None - - -def split_line_fc(line): - return list(map(LineString, zip(line.coords[:-1], line.coords[1:]))) - - -def split_line_npart(line): - # Work out n parts for each line (divided by LP_SEGMENT_LENGTH) - n = int(np.ceil(line.length / LP_SEGMENT_LENGTH)) - if n > 1: - # divided line into n-1 equal parts; - distances = np.linspace(0, line.length, n) - points = [line.interpolate(distance) for distance in distances] - line = LineString(points) - mline = split_line_fc(line) - else: - mline = line - return mline - - -def split_into_segments(df): - odf = df - crs = odf.crs - if "OLnSEG" not in odf.columns.array: - df["OLnSEG"] = np.nan - - df = odf.assign(geometry=odf.apply(lambda x: split_line_fc(x.geometry), axis=1)) - df = df.explode() - - df["OLnSEG"] = df.groupby("OLnFID").cumcount() - gdf = GeoDataFrame(df, geometry=df.geometry, crs=crs) - gdf = gdf.sort_values(by=["OLnFID", "OLnSEG"]) - gdf = gdf.reset_index(drop=True) - return gdf - - -def split_into_equal_nth_segments(df): - odf = df - crs = odf.crs - if "OLnSEG" not in odf.columns.array: - df["OLnSEG"] = np.nan - df = odf.assign(geometry=odf.apply(lambda x: split_line_npart(x.geometry), axis=1)) - df = df.explode(index_parts=True) - - df["OLnSEG"] = df.groupby("OLnFID").cumcount() - gdf = GeoDataFrame(df, geometry=df.geometry, crs=crs) - gdf = gdf.sort_values(by=["OLnFID", "OLnSEG"]) - gdf = gdf.reset_index(drop=True) - return gdf - - -def generate_line_args( - line_seg, - work_in_bufferL, - work_in_bufferC, - raster, - tree_radius, - max_line_dist, - canopy_avoidance, - exponent, - work_in_bufferR, - canopy_thresh_percentage, -): - line_argsL = [] - line_argsR = [] - line_argsC = [] - line_id = 0 - for record in range(0, len(work_in_bufferL)): - line_bufferL = work_in_bufferL.loc[record, "geometry"] - line_bufferC = work_in_bufferC.loc[record, "geometry"] - LCut = work_in_bufferL.loc[record, "LDist_Cut"] - - clipped_rasterL, out_transformL = mask( - raster, [line_bufferL], crop=True, nodata=BT_NODATA, filled=True - ) - clipped_rasterL = np.squeeze(clipped_rasterL, axis=0) - - clipped_rasterC, out_transformC = mask( - raster, [line_bufferC], crop=True, nodata=BT_NODATA, filled=True - ) - - clipped_rasterC = np.squeeze(clipped_rasterC, axis=0) - - # make rasterio meta for saving raster later - out_metaL = raster.meta.copy() - out_metaL.update( - { - "driver": "GTiff", - "height": clipped_rasterL.shape[0], - "width": clipped_rasterL.shape[1], - "nodata": BT_NODATA, - "transform": out_transformL, - } - ) - - out_metaC = raster.meta.copy() - out_metaC.update( - { - "driver": "GTiff", - "height": clipped_rasterC.shape[0], - "width": clipped_rasterC.shape[1], - "nodata": BT_NODATA, - "transform": out_transformC, - } - ) - - nodata = BT_NODATA - line_argsL.append( - [ - clipped_rasterL, - float(work_in_bufferL.loc[record, "DynCanTh"]), - float(tree_radius), - float(max_line_dist), - float(canopy_avoidance), - float(exponent), - raster.res, - nodata, - line_seg.iloc[[record]], - out_metaL, - line_id, - LCut, - "Left", - canopy_thresh_percentage, - line_bufferC, - ] - ) - - line_argsC.append( - [ - clipped_rasterC, - float(work_in_bufferC.loc[record, "DynCanTh"]), - float(tree_radius), - float(max_line_dist), - float(canopy_avoidance), - float(exponent), - raster.res, - nodata, - line_seg.iloc[[record]], - out_metaC, - line_id, - 10, - "Center", - canopy_thresh_percentage, - line_bufferC, - ] - ) - - print(' "PROGRESS_LABEL Preparing line arguments... {} of {}" '.format( - line_id ,len(work_in_bufferL) + len(work_in_bufferR)), - flush=True ) - print(" {}% ".format( - (line_id / (len(work_in_bufferL) + len(work_in_bufferR))) * 100) - ,flush=True ) - - line_id += 1 - - line_id = 0 - for record in range(0, len(work_in_bufferR)): - line_bufferR = work_in_bufferR.loc[record, "geometry"] - RCut = work_in_bufferR.loc[record, "RDist_Cut"] - clipped_rasterR, out_transformR = mask( - raster, [line_bufferR], crop=True, nodata=BT_NODATA, filled=True - ) - clipped_rasterR = np.squeeze(clipped_rasterR, axis=0) - - # make rasterio meta for saving raster later - out_metaR = raster.meta.copy() - out_metaR.update( - { - "driver": "GTiff", - "height": clipped_rasterR.shape[0], - "width": clipped_rasterR.shape[1], - "nodata": BT_NODATA, - "transform": out_transformR, - } - ) - line_bufferC = work_in_bufferC.loc[record, "geometry"] - clipped_rasterC, out_transformC = mask( - raster, [line_bufferC], crop=True, nodata=BT_NODATA, filled=True - ) - - clipped_rasterC = np.squeeze(clipped_rasterC, axis=0) - out_metaC = raster.meta.copy() - out_metaC.update( - { - "driver": "GTiff", - "height": clipped_rasterC.shape[0], - "width": clipped_rasterC.shape[1], - "nodata": BT_NODATA, - "transform": out_transformC, - } - ) - - nodata = BT_NODATA - # TODO deal with inherited nodata and BT_NODATA_COST - # TODO convert nodata to BT_NODATA_COST - line_argsR.append( - [ - clipped_rasterR, - float(work_in_bufferR.loc[record, "DynCanTh"]), - float(tree_radius), - float(max_line_dist), - float(canopy_avoidance), - float(exponent), - raster.res, - nodata, - line_seg.iloc[[record]], - out_metaR, - line_id, - RCut, - "Right", - canopy_thresh_percentage, - line_bufferC, - ] - ) - - print( - ' "PROGRESS_LABEL Preparing line arguments... {} of {}" '.format( - line_id + 1 + len(work_in_bufferL), - len(work_in_bufferL) + len(work_in_bufferR), - ), - flush=True, - ) - print( - " {}% ".format( - (line_id + 1 + len(work_in_bufferL)) / (len(work_in_bufferL) + len(work_in_bufferR)) * 100 - ), - flush=True, - ) - - line_id += 1 - - return line_argsL, line_argsR, line_argsC - - -# -# def find_corridor_threshold_boundary(canopy_clip, least_cost_path, corridor_raster): -# threshold = -1 -# thresholds = [-1] * 10 -# -# # morphological filters to get polygons from canopy raster -# canopy_bin = np.where(np.isclose(canopy_clip, 1.0), True, False) -# clean_holes = remove_small_holes(canopy_bin) -# clean_obj = remove_small_objects(clean_holes) -# -# polys = features.shapes(skimage.img_as_ubyte(clean_obj), mask=clean_obj) -# polys = [shape(poly).segmentize(FP_SEGMENTIZE_LENGTH) for poly, _ in polys] -# -# # perpendicular segments intersections with polygons -# size = corridor_raster.shape -# pts = [] -# for poly in polys: -# pts.extend(list(poly.exterior.coords)) -# -# index_0 = [] -# index_1 = [] -# for pt in pts: -# if int(pt[0]) < size[1] and int(pt[1]) < size[0]: -# index_0.append(int(pt[0])) -# index_1.append(int(pt[1])) -# -# try: -# thresholds = corridor_raster[index_1, index_0] -# except Exception as e: -# print(e) -# -# # trimmed mean of values at intersections -# threshold = stats.trim_mean(thresholds, 0.3) -# -# return threshold - - -def find_corridor_threshold(raster): - """ - Find the optimal corridor threshold by raster histogram - Parameters - ---------- - raster : corridor raster - - Returns - ------- - corridor_threshold : float - - """ - corridor_threshold = -1.0 - hist, bins = np.histogram(raster.flatten(), bins=100, range=(0, 100)) - CostStd = np.nanstd(raster.flatten()) - half_count = np.sum(hist) / 2 - sub_count = 0 - - for count, bin_no in zip(hist, bins): - sub_count += count - if sub_count > half_count: - break - - corridor_threshold = bin_no - - return corridor_threshold - - -def process_single_line_relative(segment): - # this function takes single line to generate the line footprint - # Input segment arguments: - # [in_chm, float(work_in_bufferR.loc[record, 'DynCanTh']), float(tree_radius), - # float(max_line_dist), float(canopy_avoidance), float(exponent), raster.res, nodata, - # line_seg.iloc[[record]], out_meta, line_id,RCut,Side,canopy_thresh_percentage,line_buffer] - - # this will change segment content, and parameters will be changed - segment = dyn_canopy_cost_raster(segment) - if segment is None: - return None - # segment: - """ - 0:line_df, - 1:dyn_canopy_ndarray, - 2:negative_cost_clip, - 3:out_meta, - 4:max_line_dist, - 5:nodata, - 6:line_id, - 7:Cut_Dist, - 8: line_buffer, - 9: exp_shk_cell - """ - - # (regardless it process the whole line or individual segment) - df = segment[0] - in_canopy_r = segment[1] - in_cost_r = segment[2] - in_meta = segment[3] - no_data = segment[5] - Cut_Dist = segment[7] - exp_shk_cell=segment[9] - shapefile_proj = df.crs - in_transform = in_meta["transform"] - - if np.isnan(in_canopy_r).all(): - print("Canopy raster empty") - - if np.isnan(in_cost_r).all(): - print("Cost raster empty") - - FID = df["OLnSEG"] # segment line feature ID - OID = df["OLnFID"] # original line ID for segment line - - segment_list = [] - - feat = df.geometry.iloc[0] - for coord in feat.coords: - segment_list.append(coord) - - cell_size_x = in_transform[0] - cell_size_y = -in_transform[4] - - # Work out the corridor from both end of the centerline - try: - # TODO: further investigate and submit issue to skimage - # There is a severe bug in skimage find_costs - # when nan is present in clip_cost_r, find_costs cause access violation - # no message/exception will be caught - # change all nan to BT_NODATA_COST for workaround - if len(in_cost_r.shape) > 2: - in_cost_r = np.squeeze(in_cost_r, axis=0) - remove_nan_from_array(in_cost_r) - in_cost_r[in_cost_r == no_data] = np.inf - - # generate 1m interval points along line - distance_delta = 1 - distances = np.arange(0, feat.length, distance_delta) - multipoint_along_line = [feat.interpolate(distance) for distance in distances] - multipoint_along_line.append(Point(segment_list[-1])) - # Rasterize points along line - rasterized_points_Alongln = features.rasterize( - multipoint_along_line, - out_shape=in_cost_r.shape, - transform=in_transform, - fill=0, - all_touched=True, - default_value=1, - ) - points_Alongln = np.transpose(np.nonzero(rasterized_points_Alongln)) - - # Find minimum cost paths through an N-d costs array. - mcp_flexible1 = MCP_Flexible(in_cost_r, sampling=(cell_size_x, cell_size_y), fully_connected=True) - flex_cost_alongLn, flex_back_alongLn = mcp_flexible1.find_costs(starts=points_Alongln) - - # Generate corridor - corridor = flex_cost_alongLn # +flex_cost_dest #cum_cost_tosource+cum_cost_todestination - corridor = np.ma.masked_invalid(corridor) - - # Calculate minimum value of corridor raster - if not np.ma.min(corridor) is None: - corr_min = float(np.ma.min(corridor)) - else: - corr_min = 0.5 - - # normalize corridor raster by deducting corr_min - corridor_norm = corridor - corr_min - - # Set minimum as zero and save minimum file - # corridor_th_value = find_corridor_threshold(corridor_norm) - corridor_th_value = Cut_Dist / cell_size_x - if corridor_th_value < 0: # if no threshold found, use default value - corridor_th_value = FP_CORRIDOR_THRESHOLD / cell_size_x - - # corridor_th_value = FP_CORRIDOR_THRESHOLD - corridor_thresh = np.ma.where(corridor_norm >= corridor_th_value, 1.0, 0.0) - corridor_thresh_cl = np.ma.where(corridor_norm >= (corridor_th_value + (5 / cell_size_x)), 1.0, 0.0) - - # find contiguous corridor polygon for centerline - corridor_poly_gpd = find_corridor_polygon(corridor_thresh_cl, in_transform, df) - - # Process: Stamp CC and Max Line Width - # Original code here - # RasterClass = SetNull(IsNull(CorridorMin),((CorridorMin) + ((Canopy_Raster) >= 1)) > 0) - temp1 = corridor_thresh + in_canopy_r - raster_class = np.ma.where(temp1 == 0, 1, 0).data - - # BERA proposed Binary morphology - # RasterClass_binary=np.where(RasterClass==0,False,True) - if exp_shk_cell > 0 and cell_size_x < 1: - # Process: Expand - # FLM original Expand equivalent - cell_size = int(exp_shk_cell * 2 + 1) - - expanded = ndimage.grey_dilation(raster_class, size=(cell_size, cell_size)) - - # BERA proposed Binary morphology Expand - # Expanded = ndimage.binary_dilation(RasterClass_binary, iterations=exp_shk_cell,border_value=1) - - # Process: Shrink - # FLM original Shrink equivalent - file_shrink = ndimage.grey_erosion(expanded, size=(cell_size, cell_size)) - - # BERA proposed Binary morphology Shrink - # fileShrink = ndimage.binary_erosion((Expanded),iterations=Exp_Shk_cell,border_value=1) - else: - - file_shrink = raster_class - - # Process: Boundary Clean - clean_raster = ndimage.gaussian_filter(file_shrink, sigma=0, mode="nearest") - - # creat mask for non-polygon area - polygon_mask = np.where(clean_raster == 1, True, False) - if clean_raster.dtype == np.int64: - clean_raster = clean_raster.astype(np.int32) - - # Process: ndarray to shapely Polygon - out_polygon = features.shapes(clean_raster, mask=polygon_mask, transform=in_transform) - - # create a shapely multipolygon - multi_polygon = [] - for poly, value in out_polygon: - multi_polygon.append(shape(poly)) - poly = MultiPolygon(multi_polygon) - - # create a pandas dataframe for the FP - out_data = pd.DataFrame( - { - "OLnFID": OID, - "OLnSEG": FID, - "CorriThresh": corridor_th_value, - "geometry": poly, - } - ) - out_gdata = GeoDataFrame(out_data, geometry="geometry", crs=shapefile_proj) - - return out_gdata, corridor_poly_gpd - - except Exception as e: - print("Exception: {}".format(e)) - - -def multiprocessing_footprint_relative(line_args, processes): - try: - total_steps = len(line_args) - - feats = [] - with Pool(processes=processes) as pool: - step = 0 - # execute tasks in order, process results out of order - for result in pool.imap_unordered(process_single_line_relative, line_args): - if BT_DEBUGGING: - print("Got result: {}".format(result), flush=True) - if result != None: - feats.append(result) - step += 1 - print( - ' "PROGRESS_LABEL Dynamic Segment Line Footprint {} of {}" '.format(step, total_steps), - flush=True, - ) - print(" {}% ".format(step / total_steps * 100), flush=True) - return feats - except OperationCancelledException: - print("Operation cancelled") - return None - - -def main_line_footprint_relative( - in_line:str, - in_chm: str, - max_ln_width: float, - out_footprint:str, - out_centerline:str, - exp_shk_cell:int, - tree_radius:float, - max_line_dist:float, - canopy_avoidance:float, - exponent:float, - full_step:bool, - canopy_thresh_percentage:int, - processes:int, - debug_mode:bool=BT_DEBUGGING, - merge_by_original_line:bool=False, -)-> None: - """ - This function take the centerlines with forest canopy height and distance to edge to generate - dynamic footprint from input CHM. An option smooth centerlines will be generated. - Args: - in_line: Path like string for input centerlines - in_chm: Path like string input CHM - max_ln_width: Maximum processing width for input lines - out_footprint: Path like string output footprint - out_centerline: (Option) Path like string output centerline - exp_shk_cell: Range as integer used for cell erosion - tree_radius: Radius of trees influence in the cost raster - max_line_dist: Maximum Euclidean distance from canopy - canopy_avoidance: 0 < Ratio < 1 of importance between canopy search radius and Euclidean distance - exponent: Affects the cost of vegetated areas in an exponential fashion - canopy_thresh_percentage: Percentage as integer range 1-100 - merge_by_original_line: Merge outputs sharing an OLnFID into one feature, otherwise - keep one footprint and centerline per input line (OLnFID, OLnSEG) - - Returns: - New saved footprints and/or with smoothed centerlines dataset(s). - """ - in_file, layer = decode_file_layer(in_line) - line_seg = GeoDataFrame.from_file(in_file, layer=layer) - _, processes = parallel_mode(processes) - - # If Dynamic canopy threshold column not found, create one - if "DynCanTh" not in line_seg.columns.array: - print("[Warning]: Field {} is not found and will be populated default values.".format("DynCanTh")) - line_seg['DynCanTh']=3.0 - - if not float(canopy_thresh_percentage): - canopy_thresh_percentage = 50 - else: - canopy_thresh_percentage = float(canopy_thresh_percentage) - - if float(canopy_avoidance) <= 0.0: - canopy_avoidance = 0.0 - if float(exponent) <= 0.0: - exponent = 1.0 - # If OLnFID column is not found, column will be created - if "OLnFID" not in line_seg.columns.array: - print("[info]: Created {} column in input line data.".format("OLnFID")) - line_seg["OLnFID"] = line_seg.index - - if "OLnSEG" not in line_seg.columns.array: - line_seg["OLnSEG"] = 0 - - print("{}%".format(10)) - - # check coordinate systems between line and raster features - with rasterio.open(in_chm) as raster: - line_args = [] - - if compare_crs(vector_crs(in_file,layer), raster_crs(in_chm)): - proc_segments = False - if proc_segments: - print("[Info]: Splitting lines into segments...") - line_seg_split = split_into_segments(line_seg) - print("[info]: Splitting lines into segments...Done") - else: - if full_step: - print("[info]: Tool runs on input lines......") - line_seg_split = line_seg - else: - print("[info]: Tool runs on input segment lines......") - line_seg_split = split_into_equal_Nth_segments(line_seg, 250) - - print("{}%".format(20)) - - work_in_bufferL1 = GeoDataFrame.copy(line_seg_split) - work_in_bufferL2 = GeoDataFrame.copy(line_seg_split) - work_in_bufferR1 = GeoDataFrame.copy(line_seg_split) - work_in_bufferR2 = GeoDataFrame.copy(line_seg_split) - work_in_bufferC = GeoDataFrame.copy(line_seg_split) - work_in_bufferL1["geometry"] = buffer( - work_in_bufferL1["geometry"], - distance=float(max_ln_width) + 1, - cap_style=3, - single_sided=True, - ) - - work_in_bufferL2["geometry"] = buffer( - work_in_bufferL2["geometry"], - distance=-1, - cap_style=3, - single_sided=True, - ) - - work_in_bufferL = GeoDataFrame(pd.concat([work_in_bufferL1, work_in_bufferL2])) - work_in_bufferL = work_in_bufferL.dissolve(by=["OLnFID", "OLnSEG"], as_index=False) - - work_in_bufferR1["geometry"] = buffer( - work_in_bufferR1["geometry"], - distance=-float(max_ln_width) - 1, - cap_style=3, - single_sided=True, - ) - work_in_bufferR2["geometry"] = buffer( - work_in_bufferR2["geometry"], distance=1, cap_style=3, single_sided=True - ) - - work_in_bufferR = GeoDataFrame(pd.concat([work_in_bufferR1, work_in_bufferR2])) - work_in_bufferR = work_in_bufferR.dissolve(by=["OLnFID", "OLnSEG"], as_index=False) - - work_in_bufferC["geometry"] = buffer( - work_in_bufferC["geometry"], - distance=float(max_ln_width), - cap_style=3, - single_sided=False, - ) - print("[info]: Prepare arguments for Dynamic FP ...") - # Just prepare arguments for multiprocessing - line_argsL, line_argsR, line_argsC = generate_line_args_DFP_NoClip( - line_seg_split, - work_in_bufferL, - work_in_bufferC, - raster, - in_chm, - tree_radius, - max_line_dist, - canopy_avoidance, - exponent, - work_in_bufferR, - canopy_thresh_percentage, - exp_shk_cell, - ) - - else: - print("[info]: Line and canopy raster spatial references are not same, please check.") - exit() - # pass center lines for footprint - print("[info]: Generating Dynamic footprint ...") - - feat_listL = [] - feat_listR = [] - poly_listL = [] - poly_listR = [] - footprint_listL = [] - footprint_listR = [] - if PARALLEL_MODE == ParallelMode.MULTIPROCESSING: - feat_listL = multiprocessing_footprint_relative(line_argsL, processes) - feat_listR = multiprocessing_footprint_relative(line_argsR, processes) - - elif PARALLEL_MODE == ParallelMode.SEQUENTIAL: - step = 1 - total_steps = len(line_argsL) - print("[info]: There are {} result to process.".format(total_steps)) - for row in line_argsL: - feat_listL.append(process_single_line_relative(row)) - print("[info]: Footprint (left side) for line {} is done".format(step)) - print( - ' "PROGRESS_LABEL Dynamic Line Footprint {} of {}" '.format(step, total_steps), - flush=True, - ) - print(" {}% ".format((step / total_steps) * 100)) - step += 1 - step = 1 - total_steps = len(line_argsR) - for row in line_argsR: - feat_listR.append(process_single_line_relative(row)) - print("[info]: Footprint for (right side) line {} is done".format(step)) - print( - ' "PROGRESS_LABEL Dynamic Line Footprint {} of {}" '.format(step, total_steps), - flush=True, - ) - print(" {}% ".format((step / total_steps) * 100)) - step += 1 - - print("{}%".format(80)) - - - for feat in feat_listL: - if feat: - footprint_listL.append(feat[0]) - poly_listL.append(feat[1]) - - for feat in feat_listR: - if feat: - footprint_listR.append(feat[0]) - poly_listR.append(feat[1]) - - resultsL = GeoDataFrame(pd.concat(footprint_listL,ignore_index=True)) - resultsL["geometry"] = resultsL["geometry"].buffer(0.005) - resultsR = GeoDataFrame(pd.concat(footprint_listR,ignore_index=True)) - resultsR["geometry"] = resultsR["geometry"].buffer(0.005) - resultsL = resultsL.sort_values(by=["OLnFID", "OLnSEG"]) - resultsR = resultsR.sort_values(by=["OLnFID", "OLnSEG"]) - resultsL = resultsL.reset_index(drop=True) - resultsR = resultsR.reset_index(drop=True) - # - - # one output per input line, or per original line when merging, as in the centerline tool - dissolve_keys = ["OLnFID"] if merge_by_original_line else ["OLnFID", "OLnSEG"] - resultsAll = GeoDataFrame(pd.concat([resultsL, resultsR],ignore_index=True)) - dissolved_results = resultsAll.dissolve(by=dissolve_keys, as_index=False) - dissolved_results["geometry"] = dissolved_results["geometry"].buffer(-0.005) - if merge_by_original_line: - dissolved_results["OLnSEG"] = -1 - print("[info]: Saving output ...") - out_ft_file, layer = decode_file_layer(out_footprint) - dissolved_results.to_file(out_ft_file, layer=layer) - print("[info]: Footprint file saved") - - # dissolved polygon group by column 'OLnFID' - print("[info]: Generating centerlines from corridor polygons ...") - resultsCL = GeoDataFrame(pd.concat(poly_listL)) - resultsCL["geometry"] = resultsCL["geometry"].buffer(0.005) - resultsCR = GeoDataFrame(pd.concat(poly_listR)) - resultsCR["geometry"] = resultsCR["geometry"].buffer(0.005) - - resultsCLR = GeoDataFrame(pd.concat([resultsCL, resultsCR])) - resultsCLR = resultsCLR.dissolve(by=dissolve_keys, as_index=False) - resultsCLR = resultsCLR.sort_values(by=["OLnFID", "OLnSEG"]) - resultsCLR = resultsCLR.reset_index(drop=True) - resultsCLR["geometry"] = resultsCLR["geometry"].buffer(-0.005) - - # save lines to file - if out_centerline: - out_cl_file, layer = decode_file_layer(out_centerline) - guide_lines = line_seg - if merge_by_original_line: - # corridor polygons are dissolved per OLnFID, so guide each by all pieces of its original line - guide_lines = algo_common.merge_lines_by_original_id( - line_seg, group_field="OLnFID", order_field="OLnSEG" - ).drop(columns="OLnSEG") - poly_centerline_gpd = find_centerlines(resultsCLR, guide_lines, processes) - poly_gpd = poly_centerline_gpd.copy() - centerline_gpd = poly_centerline_gpd.copy() - - centerline_gpd = centerline_gpd.set_geometry("centerline") - centerline_gpd = centerline_gpd.drop(columns=["geometry"]) - centerline_gpd.crs = poly_centerline_gpd.crs - if merge_by_original_line: - centerline_gpd["OLnSEG"] = -1 - - # save polygons from smooth centerline for debug - if debug_mode: - path = Path(out_cl_file) - path = path.with_stem(path.stem + "_poly") - poly_gpd = poly_gpd.drop(columns=["centerline"]) - poly_gpd.to_file(path,layer='smoothedCL_poly') - print("[info]: Polygon from smoothed centerline file saved") - - centerline_gpd.to_file(out_cl_file, layer=layer) - print("[info]: Smoothed centerline file saved") - - print("{}%".format(100)) +""" +Deprecated: moved to beratools.modules.mapping. + +Kept so old imports keep working, with a DeprecationWarning, until it is removed. +""" + +import sys +import warnings + +from beratools.modules.mapping import line_footprint_functions as _moved + +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=("" can be linked; - an output parameter with "produces": {"": [patterns]} provides that kind. An empty - list means the output itself (e.g. a vector file|layer); otherwise the first + list means the output folder itself (e.g. a folder of point clouds); otherwise the first pattern that matches files in the output folder is used, newest file first. Usage: @@ -33,21 +33,15 @@ import uuid from pathlib import Path +from beratools.core.registry import get_registry, tool_script + PIPELINE_FORMAT = 2 -TOOLS_DIR = Path(__file__).resolve().parents[1] / "tools" -TOOLS_JSON = Path(__file__).resolve().parents[1] / "gui" / "assets" / "beratools.json" PACKAGE_ROOT = Path(__file__).resolve().parents[2] @functools.lru_cache(maxsize=None) def _tool_params(): - with open(TOOLS_JSON, "r") as tool_json_file: - bera_tools = json.load(tool_json_file) - return { - tool["tool_api"]: tool.get("parameters", []) - for toolbox in bera_tools["toolbox"] - for tool in toolbox["tools"] - } + return {tool_api: tool.get("parameters", []) for tool_api, tool in get_registry().by_api().items()} def linkable_inputs(tool_api): @@ -96,7 +90,8 @@ def default_links(steps, tool_api): def relink(steps): - """Reset every step's links to the defaults for its place in the list. + """ + Reset every step's links to the defaults for its place in the list. Called after adding, moving or removing a step. """ @@ -118,9 +113,13 @@ def validate_pipeline(steps): elif i is None: errors.append(f"Step {n}: the step '{variable}' reads from no longer exists.") elif i >= n - 1: - errors.append(f"Step {n}: '{variable}' reads the output of step {i + 1}, which runs after it.") + errors.append( + f"Step {n}: '{variable}' reads the output of step {i + 1}, which runs after it." + ) elif accepts[variable] not in produced_kinds(steps[i]["tool_api"]): - errors.append(f"Step {n}: step {i + 1} doesn't produce the {accepts[variable]} that '{variable}' needs.") + errors.append( + f"Step {n}: step {i + 1} doesn't produce the {accepts[variable]} that '{variable}' needs." + ) else: out_variable, _ = produced_kinds(steps[i]["tool_api"])[accepts[variable]] if not steps[i]["args"].get(out_variable): @@ -129,7 +128,8 @@ def validate_pipeline(steps): def missing_inputs(steps): - """Return a problem for each input file or folder a step reads that doesn't exist. + """ + Return a problem for each input file or folder a step reads that doesn't exist. Linked inputs are skipped, since an earlier step writes them while the pipeline runs. """ @@ -198,16 +198,22 @@ def load_pipeline(path): with open(path, "r") as pipeline_file: data = json.load(pipeline_file) file_format = data.get("format") - if file_format != PIPELINE_FORMAT: + if file_format not in (1, PIPELINE_FORMAT): raise ValueError(f"Unsupported pipeline format: {file_format}") - return [new_step(s["tool_api"], s.get("args"), s.get("links"), s.get("id")) for s in data.get("steps", [])] + steps = [] + for s in data.get("steps", []): + links = s.get("links", {}) + if file_format == 1 and s.get("input_from"): # format 1 linked only the LiDAR folder + links = {"in_las_folder": s["input_from"]} + steps.append(new_step(s["tool_api"], s.get("args"), links, s.get("id"))) + return steps def tool_command(tool_api, args, processes, call_mode="CLI"): """Arguments to run one tool script in its own process, as the GUI does.""" return [ - (TOOLS_DIR / f"{tool_api}.py").as_posix(), + tool_script(tool_api).as_posix(), "-i", json.dumps(stringify_args(args)), "-p", str(processes), "-c", call_mode, diff --git a/beratools/core/registry.py b/beratools/core/registry.py new file mode 100644 index 0000000..51ea0ac --- /dev/null +++ b/beratools/core/registry.py @@ -0,0 +1,279 @@ +""" +Tool registry: the merged toolbox of every module. + +Each module describes its tools in its own tools.json. The registry finds those files, checks each one +against gui/assets/module.schema.json and against the others, and merges them into one toolbox that +the GUI, CLI and pipeline read. A module whose file breaks a rule is skipped with a warning that names +the problem; the other modules still load. + +A module or tool with "status": "wip" is work in progress: it is left out of the registry, so the +GUI, CLI and pipelines don't offer it, unless the environment variable BERATOOLS_WIP is set to 1. +Its code is also left out of the packages (see the excludes in pyproject.toml), so with BERATOOLS_WIP +set an installed copy still leaves out a WIP tool whose code isn't there. + +A module's requires_frame names the frame versions it works with, e.g. ">=0.7"; a module that +doesn't include this frame's version (beratools.__version__) is skipped like a broken one. +""" + +from __future__ import annotations + +import copy +import functools +import importlib +import importlib.util +import json +import logging +import os +from collections.abc import Iterable, Iterator +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any +from urllib.parse import urljoin + +from packaging.specifiers import InvalidSpecifier, SpecifierSet + +log = logging.getLogger(__name__) + +PACKAGE_DIR = Path(__file__).resolve().parents[1] +ASSETS_DIR = PACKAGE_DIR / "gui" / "assets" +SCHEMA_PATH = ASSETS_DIR / "module.schema.json" +MODULES_DIRS = (PACKAGE_DIR / "modules",) + +UNIQUE_TOOL_KEYS = ("name", "tool_api", "cli_name") + +WIP_ENV = "BERATOOLS_WIP" + + +def wip_enabled() -> bool: + """Whether work-in-progress modules and tools are loaded (BERATOOLS_WIP=1).""" + return os.environ.get(WIP_ENV, "").strip() == "1" + + +def _code_exists(tool: dict[str, Any]) -> bool: + module_name = tool["entry"].partition(":")[0] + try: + return importlib.util.find_spec(module_name) is not None + except ImportError: # a parent package is missing too + return False + + +@dataclass +class Registry: + """Toolboxes in load order, one per module, and why any module was skipped.""" + + toolbox: list[dict[str, Any]] = field(default_factory=list) + errors: list[str] = field(default_factory=list) + + def tools(self) -> Iterator[dict[str, Any]]: + for box in self.toolbox: + yield from box["tools"] + + def by_api(self) -> dict[str, dict[str, Any]]: + return {tool["tool_api"]: tool for tool in self.tools()} + + def tool(self, tool_api: str) -> dict[str, Any]: + for tool in self.tools(): + if tool["tool_api"] == tool_api: + return tool + raise ValueError(f"Unsupported tool_api: {tool_api}") + + def cli_names(self) -> dict[str, str]: + """{cli_name: tool_api} in toolbox order.""" + return {tool["cli_name"]: tool["tool_api"] for tool in self.tools()} + + def as_dict(self) -> dict[str, Any]: + """Return a copy in the shape of the old beratools.json: {"toolbox": [{category, tools, ...}]}.""" + return {"toolbox": copy.deepcopy(self.toolbox)} + + +def module_files(modules_dirs: tuple[Path, ...] = MODULES_DIRS) -> list[Path]: + files = [p for d in modules_dirs for p in d.glob("*/tools.json")] + return sorted(files, key=lambda p: p.parent.name) + + +@functools.lru_cache(maxsize=1) +def _schema_validator(): + try: + import jsonschema + except ImportError: + log.warning("jsonschema is not installed; module files are checked without the schema") + return None + schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8")) + return jsonschema.Draft202012Validator(schema) + + +def _schema_errors(data: Any) -> list[str]: + validator = _schema_validator() + if validator is None: + return _basic_errors(data) + errors = sorted(validator.iter_errors(data), key=lambda e: list(e.absolute_path)) + return [f"{_json_path(e.absolute_path)}: {e.message}" for e in errors] + + +def _basic_errors(data: Any) -> list[str]: + """Check what the rest of the frame depends on, for when jsonschema is missing.""" + if not isinstance(data, dict): + return ["the file is not a JSON object"] + errors = [f"'{k}' is a required property" for k in ("module", "category", "tools") if k not in data] + tools = data.get("tools") + if not isinstance(tools, list): + return errors + ["tools: not a list"] + for i, tool in enumerate(tools): + if not isinstance(tool, dict): + errors.append(f"tools[{i}]: not an object") + continue + for key in ("name", "tool_api", "cli_name", "entry", "parameters"): + if key not in tool: + errors.append(f"tools[{i}]: '{key}' is a required property") + return errors + + +def _json_path(parts: Iterable[Any]) -> str: + text = "" + for part in parts: + text += f"[{part}]" if isinstance(part, int) else (f".{part}" if text else str(part)) + return text or "(top level)" + + +def _tool_errors(data: dict[str, Any]) -> list[str]: + """Rules the schema can't express: variables unique in a tool, and links to real variables.""" + errors = [] + for i, tool in enumerate(data["tools"]): + params = tool["parameters"] + variables = [p["variable"] for p in params] + for var in sorted({v for v in variables if variables.count(v) > 1}): + errors.append(f"tools[{i}] ({tool['name']}): variable '{var}' is used more than once") + known = set(variables) + for j, param in enumerate(params): + where = f"tools[{i}].parameters[{j}] ({param['variable']})" + if param.get("field_of") and param["field_of"] not in known: + errors.append(f"{where}: field_of '{param['field_of']}' is not a variable of this tool") + depends = param.get("depends_on") or {} + conditions = depends.get("conditions", [depends] if "variable" in depends else []) + for cond in conditions: + if cond["variable"] not in known: + errors.append(f"{where}: depends_on '{cond['variable']}' is not a variable of this tool") + return errors + + +def _clash_errors(data: dict[str, Any], seen: dict[str, dict[str, str]]) -> list[str]: + """Names, tool_api and cli_name already taken by a module loaded earlier, or twice in this one.""" + errors = [] + own: dict[str, set[str]] = {key: set() for key in UNIQUE_TOOL_KEYS} + for i, tool in enumerate(data["tools"]): + for key in UNIQUE_TOOL_KEYS: + value = tool[key] + if value in seen[key]: + errors.append(f"tools[{i}]: {key} '{value}' is already used by module '{seen[key][value]}'") + elif value in own[key]: + errors.append(f"tools[{i}]: {key} '{value}' is used more than once in this module") + own[key].add(value) + return errors + + +def _frame_errors(data: dict[str, Any], frame_version: str) -> list[str]: + spec = data["requires_frame"] + try: + # a development frame (0.8.0.dev1, say) still counts as the version it leads to + fits = SpecifierSet(spec).contains(frame_version, prereleases=True) + except InvalidSpecifier: + return [f"requires_frame '{spec}' is not a version range such as '>=0.7'"] + return [] if fits else [f"needs frame {spec}, this frame is {frame_version}"] + + +def load_registry( + paths: Iterable[Path] | None = None, wip: bool | None = None, frame_version: str | None = None +) -> Registry: + """ + Load and merge module files, in the given order (default: every modules/*/tools.json). + + wip: load work-in-progress modules and tools too; None (the default) reads BERATOOLS_WIP. WIP + entries are still checked, and still count for name clashes, when they are left out. + + frame_version: the version to check each module's requires_frame against; None (the default) is + beratools.__version__. + """ + if wip is None: + wip = wip_enabled() + if frame_version is None: + import beratools + + frame_version = beratools.__version__ + registry = Registry() + seen: dict[str, dict[str, str]] = {key: {} for key in UNIQUE_TOOL_KEYS} + + for path in module_files() if paths is None else paths: + path = Path(path) + label = path.parent.name if path.name == "tools.json" else path.name + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as err: + problems = [f"cannot read {path}: {err}"] + else: + problems = _schema_errors(data) + if not problems: + label = data["module"] + problems = ( + _frame_errors(data, frame_version) or _tool_errors(data) or _clash_errors(data, seen) + ) + + if problems: + registry.errors.extend(f"{label}: {p}" for p in problems) + log.warning("Module '%s' skipped:\n %s", label, "\n ".join(problems)) + continue + + docs_url = data.get("docs_url") + module_status = data.get("status", "released") + tools = [] + for tool in data["tools"]: + for key in UNIQUE_TOOL_KEYS: + seen[key][tool[key]] = data["module"] + # a tool in a WIP module is WIP whatever it says itself + tool["status"] = "wip" if module_status == "wip" else tool.get("status", "released") + if tool["status"] == "wip" and not (wip and _code_exists(tool)): + continue + tool.setdefault("tool_type", "python") + # a relative tech_link is a page on the module's docs site; a full URL stays as it is + if docs_url and tool.get("tech_link"): + tool["tech_link"] = urljoin(docs_url, tool["tech_link"]) + tools.append(tool) + + if not tools: + log.info("Module '%s' left out: work in progress (set %s=1 to load it)", label, WIP_ENV) + continue + registry.toolbox.append( + { + "module": data["module"], + "category": data["category"], + "description": data.get("description", ""), + "status": module_status, + "tools": tools, + } + ) + return registry + + +@functools.lru_cache(maxsize=1) +def get_registry() -> Registry: + """Return the registry of the installed modules, loaded once per process.""" + return load_registry() + + +def _split_entry(tool_api: str) -> tuple[str, str]: + module_name, _, func_name = get_registry().tool(tool_api)["entry"].partition(":") + return module_name, func_name + + +def tool_function(tool_api: str): + """Import and return the function a tool's entry names.""" + module_name, func_name = _split_entry(tool_api) + return getattr(importlib.import_module(module_name), func_name) + + +def tool_script(tool_api: str) -> Path: + """Return the file of the module a tool's entry names, to run as a script in its own process.""" + module_name, _ = _split_entry(tool_api) + spec = importlib.util.find_spec(module_name) + if spec is None or spec.origin is None: + raise ValueError(f"Cannot find module {module_name} for tool {tool_api}") + return Path(spec.origin) diff --git a/beratools/core/tool_base.py b/beratools/core/tool_base.py index 5c4e3ea..138e414 100644 --- a/beratools/core/tool_base.py +++ b/beratools/core/tool_base.py @@ -14,21 +14,21 @@ """ import concurrent.futures as con_futures -import warnings -import multiprocessing -from beratools.core.logger import Logger import logging import logging.handlers +import multiprocessing +import warnings from multiprocessing.pool import Pool -import psutil import geopandas as gpd import pandas as pd +import psutil from tqdm.auto import tqdm import beratools.core.constants as bt_const -from beratools.utility.tool_args import CallMode, determine_cpu_core_limit +from beratools.core.logger import Logger from beratools.gui.bt_data import BTData +from beratools.utility.tool_args import CallMode, determine_cpu_core_limit bt = BTData() warnings.simplefilter(action="ignore", category=FutureWarning) @@ -108,10 +108,27 @@ def listener_process(queue, logfile,logger_name=None): handler.flush() handler.close() -def configure_worker_logging(queue): +def _stop_log_listener(log_queue, listener, timeout=10): """ - Configure worker process logger. + Stop the log listener process without leaving anything that blocks interpreter exit. + + multiprocessing joins non-daemon children at exit, and the queue joins its feeder + thread, so a listener that never receives the sentinel would hang the process forever. """ + try: + log_queue.put(None, timeout=timeout) + except Exception: + pass + listener.join(timeout=timeout) + if listener.is_alive(): + listener.terminate() + listener.join() + log_queue.cancel_join_thread() + log_queue.close() + + +def configure_worker_logging(queue): + """Configure worker process logger.""" Logger.set_queue(queue) root = logging.getLogger() root.handlers.clear() @@ -150,11 +167,18 @@ def execute_multiprocessing( print("Using {} CPU cores".format(processes), flush=True) log_file = bt.get_logger_file_name(logger_name) log_queue = multiprocessing.Queue(maxsize=50000) - listener = multiprocessing.Process(target=listener_process, args=(log_queue, log_file,logger_name),daemon=False, ) + listener = multiprocessing.Process( + target=listener_process, + args=(log_queue, log_file, logger_name), + daemon=False, + ) listener.start() try: - with Pool(processes,maxtasksperchild=100,initializer=configure_worker_logging, - initargs=(log_queue,)) as pool: + # Not "with Pool(...)": its __exit__ calls terminate(), which can kill a worker + # while it holds log_queue's write lock and leave the listener blocked forever. + pool = Pool(processes, maxtasksperchild=100, initializer=configure_worker_logging, + initargs=(log_queue,)) + try: with tqdm(total=total_steps, disable=verbose) as pbar: for result in pool.imap_unordered(in_func, in_data): if result_is_valid(result): @@ -165,9 +189,13 @@ def execute_multiprocessing( print_msg(app_name, step, total_steps) else: pbar.update() + pool.close() + pool.join() # let workers exit cleanly and flush their log records + except BaseException: + pool.terminate() + raise finally: - log_queue.put(None) - listener.join(timeout=10) + _stop_log_listener(log_queue, listener) elif mode == bt_const.ParallelMode.SEQUENTIAL: print("Sequential processing started...", flush=True) with tqdm(total=total_steps, disable=verbose) as pbar: @@ -186,7 +214,14 @@ def execute_multiprocessing( print("Using {} CPU cores".format(processes), flush=True) log_file = bt.get_logger_file_name(logger_name) log_queue = multiprocessing.Queue(maxsize=50000) - listener = multiprocessing.Process(target=listener_process, args=(log_queue, log_file,),daemon=False, ) + listener = multiprocessing.Process( + target=listener_process, + args=( + log_queue, + log_file, + ), + daemon=False, + ) listener.start() try: with con_futures.ProcessPoolExecutor( @@ -208,8 +243,7 @@ def execute_multiprocessing( else: pbar.update() finally: - log_queue.put(None) - listener.join(timeout=10) + _stop_log_listener(log_queue, listener) except Exception as e: print(e) return None diff --git a/beratools/core/tool_geo_simplify.py b/beratools/core/tool_geo_simplify.py index cce446d..50aef92 100644 --- a/beratools/core/tool_geo_simplify.py +++ b/beratools/core/tool_geo_simplify.py @@ -1,125 +1,20 @@ -"""Tooling helpers for invoking geo-simplify binaries.""" - -from __future__ import annotations - -import os -import platform -import stat -import subprocess -import tempfile -from pathlib import Path - -import geopandas as gpd -from shapely.geometry import LineString - - -def validate_diameter(value): - try: - diameter = float(value) - except (TypeError, ValueError): - raise ValueError("simplify_diameter must be a number >= 0.") - - if diameter < 0: - raise ValueError("simplify_diameter must be >= 0.") - - return diameter - - -def build_temp_output_same_folder(out_file, suffix=".gpkg", prefix="centerline_tmp_"): - out_path = Path(out_file) - out_dir = out_path.parent if out_path.parent else Path(".") - out_dir.mkdir(parents=True, exist_ok=True) - fd, temp_path = tempfile.mkstemp(prefix=prefix, suffix=suffix, dir=out_dir) - os.close(fd) - return Path(temp_path) - - -def simplify_line_reduce_bend(line: LineString, *, crs, diameter: float, smooth_line=True) -> LineString: - if diameter <= 0: - return line - - with tempfile.TemporaryDirectory(prefix="beratools_line_simplify_") as temp_dir: - temp_path = Path(temp_dir) - input_file = temp_path / "input.gpkg" - output_file = temp_path / "output.gpkg" - in_layer = "line_temp" - out_layer = "line_simplified" - gdf = gpd.GeoDataFrame([{}], geometry=[line], crs=crs) - gdf.to_file(input_file, layer=in_layer) - run_reduce_bend( - input_file=input_file, - in_layer=in_layer, - output_file=output_file.as_posix(), - out_layer=out_layer, - diameter=diameter, - smooth_line=smooth_line, - ) - simplified = gpd.read_file(output_file, layer=out_layer) - if simplified.empty: - raise RuntimeError("geo-simplify returned no features") - geom = simplified.geometry.iloc[0] - if geom is None or geom.is_empty: - raise RuntimeError("geo-simplify returned empty geometry") - if geom.geom_type == "MultiLineString" and len(geom.geoms) == 1: - geom = geom.geoms[0] - if not isinstance(geom, LineString): - raise RuntimeError(f"geo-simplify returned unsupported geometry: {geom.geom_type}") - return geom - - -def run_reduce_bend(input_file, in_layer, output_file, out_layer, diameter, smooth_line=True): - binary_path = _geo_simplify_resolve_binary_path() - command = [ - str(binary_path), - "reduce-bend", - "--input", - str(input_file), - "--in-layer", - in_layer, - "--output", - output_file, - "--diameter", - str(diameter), - ] - - if smooth_line: - command.append("--smooth-line") - - if out_layer: - command.extend(["--out-layer", out_layer]) - - result = subprocess.run(command, capture_output=True, text=True) - if result.returncode != 0: - raise RuntimeError( - "geo-simplify reduce-bend failed " - f"(exit code {result.returncode})\n" - f"Command: {' '.join(command)}\n" - f"stdout:\n{result.stdout}\n" - f"stderr:\n{result.stderr}" - ) - - -def _geo_simplify_resolve_binary_path(): - external_dir = Path(__file__).resolve().parents[1] / "external" / "geo_simplify" - system_name = platform.system() - - if system_name == "Windows": - binary_path = external_dir / "geo-simplify-win-x64.exe" - elif system_name == "Linux": - binary_path = external_dir / "geo-simplify-linux-x64" - else: - raise RuntimeError(f"Centerline simplify is not supported on OS: {system_name}") - - if not binary_path.exists(): - raise FileNotFoundError(f"Missing geo-simplify binary: {binary_path}") - - if system_name == "Linux": - _geo_simplify_ensure_executable(binary_path) - - return binary_path - - -def _geo_simplify_ensure_executable(binary_path): - mode = binary_path.stat().st_mode - if not (mode & stat.S_IXUSR): - binary_path.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) +""" +Deprecated: moved to beratools.modules.mapping. + +Kept so old imports keep working, with a DeprecationWarning, until it is removed. +""" + +import sys +import warnings + +from beratools.modules.mapping import tool_geo_simplify as _moved + +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=("=5m) may cause excessive smoothing of the cost raster which can lead to least cost paths ignoring forest-line nuances in sparsely vegetated forests. A small radius (<=1m) may cause the least cost path to cut corners through small gaps in sparse vegetation as well as avoid small obstacles that should not affect overall line shape.", - "type": "number", - "subtype": "float", - "default": 1.5, - "output": false, - "optional": true - }, - { - "variable": "max_line_dist", - "label": "Maximum Line Distance", - "description": "Maximum euclidean distance from canopy. This is a second smoothing factor which helps to position the forest line shape in the center of the line footprint. An excessively small (<=1m) or large (>20m) value may cause the center line to be positioned close to one of the edges of the footprint.", - "type": "number", - "subtype": "float", - "default": 1.5, - "output": false, - "optional": true - }, - { - "variable": "canopy_avoidance", - "label": "Canopy Avoidance", - "description": "Ratio of importance between canopy search radius and euclidean distance. A value close to zero (0) prioritizes search radius whereas a value close to one (1) prioritizes euclidean distance. A small value (<=0.1) may cause the forest lines to miss nuances in sparsely vegetated terrain whereas a big value (>=0.5) may overemphasize turns in complex trails. This factor influences final footprint size in a minor way.", - "type": "number", - "subtype": "float", - "default": 0.0, - "output": false, - "optional": true - }, - { - "variable": "exponent", - "label": "Cost Raster Exponent", - "description": "Affects the cost of vegetated areas in an exponential fashion. A low (<=1) exponent may lead to lines cutting through corners, whereas a large (>=3) exponent may lead to least cost paths completely avoiding narrow lines.", - "type": "number", - "subtype": "int", - "default": 1, - "output": false, - "optional": true - } - ] - }, - { - "name": "Ground Footprint", - "info": "Generating fixed width ground footprint", - "tool_type": "python", - "tool_api": "ground_footprint", - "icon": "ground_footprint.gif", - "tech_link": "https://beratool.github.io/beratools/user/ground_footprint", - "parameters": [ - { - "variable": "in_line", - "accepts": "line", - "label": "Centerline", - "description": "Input centerline file.", - "type": "file", - "subtype": "vector|line", - "default": "", - "output": false, - "optional": false - }, - { - "variable": "in_footprint", - "accepts": "footprint", - "label": "Input Footprint", - "description": "Input footprint.", - "type": "file", - "subtype": "vector|polygon", - "default": "", - "output": false, - "optional": false - }, - { - "variable": "n_samples", - "label": "Sampling number", - "description": "Sampling number for each line.", - "type": "number", - "subtype": "int", - "default": 15, - "output": false, - "optional": true - }, - { - "variable": "offset", - "label": "Perpendicular line length (m)", - "description": "The length of the perpendicular line in meters. Internally converted to layer CRS units.", - "type": "number", - "subtype": "float", - "default": 30.0, - "output": false, - "optional": true - }, - { - "variable": "max_width", - "label": "Use maximum width", - "description": "Use maximum sampled width for footprint.", - "type": "list", - "subtype": "bool", - "data": [true, false], - "default": true, - "output": false, - "optional": true - }, - { - "variable": "merge_by_original_line", - "label": "Merge by Original Line", - "description": "Merge lines and footprints that share an original line ID (OLnFID) into one feature, e.g. lines split at intersections by Check Seed Lines", - "type": "list", - "subtype": "bool", - "data": [true, false], - "default": false, - "output": false, - "optional": true - }, - { - "variable": "out_footprint", - "produces": { - "footprint": [] - }, - "label": "Output Ground Footprint", - "description": "Output fixed width ground footprint file.", - "type": "file", - "subtype": "vector", - "default": "", - "output": true, - "optional": false - } - ] - } - ] - }, - { - "category": "Templates", - "description": "Tools template.", - "tools": [ - { - "name": "Feature Buffer", - "info": "Buffer input feature class.", - "tool_type": "python", - "tool_api": "tool_template", - "icon": "tool_template.gif", - "tech_link": "https://beratool.github.io/beratools/developer/tool_template/", - "parameters": [ - { - "variable": "in_feature", - "label": "Input Feature Class", - "description": "Input Feature Class.", - "type": "file", - "subtype": "vector", - "default": "", - "output": false, - "optional": false - }, - { - "variable": "buffer_dist", - "label": "Buffer Distance (m)", - "description": "Set distance to generate buffer for input features.", - "type": "number", - "subtype": "float", - "default": 10, - "output": false, - "optional": false - }, - { - "variable": "out_feature", - "label": "Output Buffered Features", - "description": "Output buffered features.", - "type": "file", - "subtype": "vector", - "default": "", - "output": true, - "optional": false - } - ] - } - ] - } - ] -} diff --git a/beratools/gui/assets/module.schema.json b/beratools/gui/assets/module.schema.json new file mode 100644 index 0000000..2746c24 --- /dev/null +++ b/beratools/gui/assets/module.schema.json @@ -0,0 +1,269 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://beratool.github.io/schemas/module.schema.json", + "title": "BERA Tools module", + "description": "One module's tools.json: a single category block plus the fields the frame needs to load it without code changes. Checks the loader still runs across files: name, tool_api and cli_name unique across all modules; variable unique within a tool; depends_on, field_of variables exist in the same tool.", + "$comment": "This file is the rulebook for a module's tools.json. At startup the frame checks each tools.json against it and skips a module that breaks a rule, with a message that names the field; the other modules still load. Developers can run the same check before adding a module. additionalProperties: false everywhere means an unknown or misspelled key (e.g. unti for unit) is an error, not ignored. It checks one file's shape only: the loader checks that names are unique across modules and that depends_on and field_of point at real variables.", + "type": "object", + "required": ["module", "version", "requires_frame", "category", "description", "tools"], + "additionalProperties": false, + "properties": { + "$schema": { + "type": "string", + "description": "Optional pointer to this schema, for editor support." + }, + "module": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$", + "description": "Module id; also its Python package name and its entry-point name in the beratools.modules group, e.g. pc2products." + }, + "version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+([.-]?[0-9A-Za-z.+-]+)?$", + "description": "The module's own version, e.g. 0.1.0." + }, + "requires_frame": { + "type": "string", + "pattern": "^\\s*(==|!=|<=|>=|<|>|~=)\\s*\\d+(\\.\\d+)*(\\s*,\\s*(==|!=|<=|>=|<|>|~=)\\s*\\d+(\\.\\d+)*)*\\s*$", + "description": "PEP 440 version specifier for the frame API this module works with, e.g. \">=0.7\"." + }, + "category": { + "type": "string", + "minLength": 1, + "description": "Toolbox category shown in the GUI, e.g. PC2Products." + }, + "description": { + "type": "string", + "description": "One line about the category, shown in the GUI." + }, + "docs_url": { + "type": "string", + "pattern": "^https?://\\S+/$", + "description": "Base URL of the module's public docs site, ending in /, e.g. https://beratool.github.io/beratools/pc2products/. A relative tech_link is resolved against it." + }, + "status": { + "$ref": "#/$defs/status", + "description": "wip keeps the whole module, and every tool in it, out of the GUI, CLI and pipelines unless BERATOOLS_WIP=1 is set. Missing means released." + }, + "tools": { + "type": "array", + "minItems": 1, + "description": "The module's tools, in toolbox order.", + "items": { "$ref": "#/$defs/tool" } + } + }, + "$defs": { + "identifier": { + "description": "A Python name: letters, digits and _, not starting with a digit.", + "type": "string", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" + }, + "status": { + "enum": ["released", "wip"], + "description": "released: shown to everyone. wip: work in progress, shown only when BERATOOLS_WIP=1 is set; its code is also left out of the packages (see pyproject.toml)." + }, + "kind": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$", + "description": "A data kind that links pipeline steps, e.g. las, dtm, chm, line, footprint." + }, + "tool": { + "description": "One tool: its toolbox entry, its bt command and its form.", + "type": "object", + "required": ["name", "info", "tool_api", "cli_name", "entry", "tech_link", "parameters"], + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + "minLength": 1, + "description": "Display name; unique across all modules." + }, + "info": { + "type": "string", + "description": "Short description shown in the GUI and CLI help." + }, + "tool_api": { + "$ref": "#/$defs/identifier", + "description": "Stable tool id used for saved parameters, history and pipelines; unique across all modules." + }, + "cli_name": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$", + "description": "bt subcommand, e.g. dtm; unique across all modules." + }, + "entry": { + "type": "string", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)*:[A-Za-z_][A-Za-z0-9_]*$", + "description": "package.module:function the frame imports on demand, e.g. pc2products.rpy_dtm_by:rpy_dtm." + }, + "tool_type": { + "enum": ["python", "executable"], + "default": "python", + "description": "How the frame runs the tool." + }, + "tech_link": { + "type": "string", + "description": "The tool's doc page: a path on the module's docs site, e.g. user/dtm/, resolved against docs_url; or a full URL." + }, + "icon": { + "type": "string", + "description": "Icon file name, resolved from the module's own folder. Empty or missing means the default icon." + }, + "status": { + "$ref": "#/$defs/status", + "description": "wip keeps this tool out of the GUI, CLI and pipelines unless BERATOOLS_WIP=1 is set. Missing means released, or the module's status." + }, + "batch_processing": { + "type": ["boolean", "null"], + "description": "Whether the tool can run over many inputs in one go." + }, + "parameters": { + "type": "array", + "description": "The form's fields in display order; each one is a keyword argument of the entry function.", + "items": { "$ref": "#/$defs/parameter" } + } + } + }, + "parameter": { + "description": "One field on the tool's form and one argument of its function.", + "type": "object", + "required": ["variable", "label", "description", "type", "subtype", "default", "output", "optional"], + "additionalProperties": false, + "properties": { + "variable": { + "$ref": "#/$defs/identifier", + "description": "Argument name passed to the tool function; unique within the tool." + }, + "label": { + "type": "string", + "minLength": 1, + "description": "Text shown next to the field in the GUI, without a trailing period." + }, + "description": { + "type": "string", + "description": "Tooltip text for the field." + }, + "type": { + "enum": ["number", "file", "files", "list", "text", "directory"], + "description": "The widget: number box, file picker, multi-file picker, drop-down, text box or folder picker." + }, + "subtype": { + "description": "Pipe-separated tokens or a list of them, e.g. \"vector|line\", \"raster\", \"float\", \"bool\".", + "oneOf": [ + { "type": "string" }, + { "type": "array", "items": { "type": "string" } } + ] + }, + "default": { + "type": ["string", "number", "boolean", "array", "null"], + "items": { "type": "string" }, + "description": "The field's starting value; a list of paths for type files." + }, + "output": { + "type": "boolean", + "description": "true if the tool writes to this path." + }, + "optional": { + "type": "boolean", + "description": "true if the field may be left empty." + }, + "data": { + "type": "array", + "minItems": 1, + "items": { "type": ["string", "number", "boolean"] }, + "description": "Choices for a list parameter." + }, + "unit": { + "type": "string", + "description": "Unit shown with a number, e.g. m or deg." + }, + "allow_directory": { + "type": "boolean", + "description": "A file input also accepts a folder of such files." + }, + "field_of": { + "$ref": "#/$defs/identifier", + "description": "Variable of the vector input whose fields this text parameter picks from." + }, + "field_check": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$", + "description": "Name of a field check that a module registers with the frame, e.g. year." + }, + "accepts": { + "$ref": "#/$defs/kind", + "description": "Input only: pipeline kind this input can be linked to." + }, + "produces": { + "type": "object", + "description": "Output only: kinds this output provides, each with file globs inside the output folder (empty = the output itself).", + "propertyNames": { "$ref": "#/$defs/kind" }, + "additionalProperties": { + "type": "array", + "items": { "type": "string", "minLength": 1 } + } + }, + "depends_on": { "$ref": "#/$defs/depends_on" } + }, + "allOf": [ + { + "$comment": "A drop-down must list its choices.", + "if": { "properties": { "type": { "const": "list" } } }, + "then": { "required": ["data"] } + }, + { + "$comment": "An output can't have accepts; an input can't have produces.", + "if": { "properties": { "output": { "const": true } } }, + "then": { "not": { "required": ["accepts"] } }, + "else": { "not": { "required": ["produces"] } } + }, + { + "$comment": "A field picker is a text parameter.", + "if": { "required": ["field_of"] }, + "then": { "properties": { "type": { "const": "text" } } } + } + ] + }, + "depends_on": { + "description": "Show or hide this parameter by the value of others in the same tool.", + "oneOf": [ + { + "type": "object", + "required": ["variable", "condition"], + "additionalProperties": false, + "properties": { + "variable": { "$ref": "#/$defs/identifier" }, + "condition": { "$ref": "#/$defs/condition_value" }, + "mode": { "enum": ["hide", "inline"], "default": "hide" } + } + }, + { + "type": "object", + "required": ["conditions"], + "additionalProperties": false, + "properties": { + "conditions": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": ["variable", "condition"], + "additionalProperties": false, + "properties": { + "variable": { "$ref": "#/$defs/identifier" }, + "condition": { "$ref": "#/$defs/condition_value" } + } + } + }, + "logic": { "enum": ["and", "or"], "default": "or" }, + "mode": { "const": "hide", "default": "hide" } + } + } + ] + }, + "condition_value": { + "description": "Value of the controlling parameter that shows this one (plain equality); \"__hidden__\" keeps it hidden.", + "type": ["string", "number", "boolean"] + } + } +} diff --git a/beratools/gui/bt_data.py b/beratools/gui/bt_data.py index 633911b..efe8d4a 100644 --- a/beratools/gui/bt_data.py +++ b/beratools/gui/bt_data.py @@ -19,13 +19,12 @@ import re import subprocess from collections import OrderedDict -from importlib import metadata as importlib_metadata from pathlib import Path import pyogrio -from packaging.version import InvalidVersion, Version import beratools.core.constants as bt_const +from beratools.core.registry import get_registry, tool_script from beratools.gui.geometry_types import ( format_expected_families, get_allowed_geometry_families, @@ -96,168 +95,35 @@ def _resolve_git_revision(repo_root): return _run_git_command(["git", "rev-parse", "--short", "HEAD"], cwd=repo_root) -def _iter_beratools_distributions(): - for dist in importlib_metadata.distributions(): - try: - dist_name = (dist.metadata.get("Name") or "").strip().lower() - except Exception: - dist_name = "" - if dist_name == "beratools": - yield dist - - -def _resolve_metadata_version(): - candidates = [] - for dist in _iter_beratools_distributions(): - raw_version = str(getattr(dist, "version", "")).strip() - if not raw_version: - continue - - try: - normalized = Version(raw_version) - except InvalidVersion: - _LOG.warning("Skipping BERATools metadata entry with invalid version: %s", raw_version) - continue - - dist_path = str(getattr(dist, "_path", "")) - sort_key = (dist_path, raw_version) - candidates.append( - { - "raw_version": raw_version, - "normalized": normalized, - "source": dist_path, - "sort_key": sort_key, - } - ) - - if candidates: - highest = max(item["normalized"] for item in candidates) - highest_candidates = [item for item in candidates if item["normalized"] == highest] - winner = sorted(highest_candidates, key=lambda item: item["sort_key"])[0] - - if len(candidates) > 1: - discovered = [ - item["raw_version"] for item in sorted(candidates, key=lambda item: item["sort_key"]) - ] - _LOG.warning( - "Detected multiple BERATools metadata versions: %s; selected=%s (source=%s)", - discovered, - winner["raw_version"], - winner["source"] or "unknown", - ) - - return winner["raw_version"] - - try: - return importlib_metadata.version("BERATools") - except Exception: - return None - - -def _parse_git_version(git_describe, git_revision): - if git_describe: - describe = git_describe.strip() - is_dirty = describe.endswith("-dirty") - if is_dirty: - describe = describe[: -len("-dirty")] - - ahead_match = re.match(r"^v?(\d+\.\d+\.\d+)-(\d+)-g([0-9a-fA-F]+)$", describe) - if ahead_match: - tag_version = ahead_match.group(1) - ahead_count = ahead_match.group(2) - revision = ahead_match.group(3).lower() - if ahead_count == "0" and not is_dirty: - return { - "version": tag_version, - "short_version": tag_version, - "git_revision": revision, - "is_release": True, - } - - version_value = f"{tag_version}+{ahead_count}.g{revision}" - if is_dirty: - version_value = f"{version_value}.dirty" - return { - "version": version_value, - "short_version": tag_version, - "git_revision": revision, - "is_release": False, - } - - tag_match = re.match(r"^v?(\d+\.\d+\.\d+)$", describe) - if tag_match and not is_dirty: - tag_version = tag_match.group(1) - return { - "version": tag_version, - "short_version": tag_version, - "git_revision": (git_revision or "").lower() or None, - "is_release": True, - } - - if git_revision: - revision = git_revision.strip().lower() - return { - "version": f"0+g{revision}", - "short_version": "0", - "git_revision": revision, - "is_release": False, - } - - return None +def _is_git_checkout(repo_root): + # .git is a folder in a clone and a file in a worktree; an installed package has neither beside it + return (Path(repo_root) / ".git").exists() def get_app_version_info(): - repo_root = Path(__file__).resolve().parents[2] + """ + The version for the About dialog: beratools.__version__, the one place the version is set. + Run from a source checkout, the code may be ahead of that version, so the git revision is added + to it and it doesn't count as a release. BERATOOLS_APP_VERSION overrides it. + """ override_version = os.getenv("BERATOOLS_APP_VERSION", "").strip() if override_version: version_info = _normalize_version_string(override_version) version_info["git_revision"] = _extract_git_revision_from_version(override_version) - _LOG.debug("Resolved app version via BERATOOLS_APP_VERSION") return version_info - try: - installed_version = _resolve_metadata_version() - if not installed_version: - raise importlib_metadata.PackageNotFoundError - version_info = _normalize_version_string(installed_version) - if not version_info["git_revision"]: - version_info["git_revision"] = _extract_git_revision_from_version(installed_version) - if not version_info["git_revision"]: - version_info["git_revision"] = _resolve_git_revision(repo_root) - _LOG.debug("Resolved app version via metadata") - return version_info - except Exception: - pass - - git_describe = _run_git_command( - ["git", "describe", "--tags", "--long", "--always", "--dirty"], - cwd=repo_root, - ) - git_revision = _resolve_git_revision(repo_root) - git_version_info = _parse_git_version(git_describe, git_revision) - if git_version_info: - _LOG.debug("Resolved app version via git") - return git_version_info - - try: - import beratools - - static_version = getattr(beratools, "__version__", None) - if static_version: - version_info = _normalize_version_string(static_version) - _LOG.debug("Resolved app version via static __version__") - return version_info - except Exception: - pass + import beratools - _LOG.debug("Resolved app version as unknown") - return { - "version": "unknown", - "short_version": "unknown", - "git_revision": None, - "is_release": False, - } + version_info = _normalize_version_string(beratools.__version__) + repo_root = Path(__file__).resolve().parents[2] + if _is_git_checkout(repo_root): + version_info["is_release"] = False + revision = _resolve_git_revision(repo_root) + if revision: + version_info["git_revision"] = revision.lower() + version_info["version"] = f"{version_info['version']}+g{version_info['git_revision']}" + return version_info def get_global_docs_url(): @@ -584,7 +450,7 @@ def prepare_tool_run(self, tool_api, args, callback=None): if tool_type == "python": tool_args = [ - self.work_dir.joinpath(f"tools/{tool_api}.py").as_posix(), + tool_script(tool_api).as_posix(), "-i", args_string, "-p", str(self.get_selected_cpu_cores()), "-c", CallMode.GUI, @@ -675,12 +541,8 @@ def get_saved_tool_params(self, tool_api, variable=None): return self.settings_manager.get_saved_tool_params(tool_api, variable) def get_bera_tools(self): - tool_json_path = Path(self.current_file_path).joinpath(bt_const.ASSETS_PATH, r"beratools.json") - if tool_json_path.exists(): - with open(tool_json_path, "r") as tool_json_file: - self.bera_tools = json.load(tool_json_file) - else: - print("Tool configuration file not exists") + """Merged toolbox of every module's tools.json (see core/registry.py).""" + self.bera_tools = get_registry().as_dict() def get_bera_tool_list(self): self.tools_list = [] @@ -718,7 +580,7 @@ def get_bera_toolboxes(self): self.toolbox_list = [] def _set_param_flag_and_saved_value(self, single_param, param, tool): - """Set parameter variable and load saved value if it exists in beratools.json.""" + """Set parameter variable and load its saved value, if any.""" saved_value = None if "variable" in param.keys(): single_param["variable"] = param["variable"] @@ -741,6 +603,8 @@ def _set_param_type_for_input(self, single_param, param): single_param["parameter_type"] = subtypes elif param["type"] == "file": single_param["parameter_type"] = {"ExistingFile": subtypes} + elif param["type"] == "files": + single_param["parameter_type"] = {"FileList": subtypes} elif param["type"] == "directory": single_param["parameter_type"] = {"Directory": subtypes} else: @@ -761,7 +625,7 @@ def _find_tool_params(self, tool_name): Eliminates duplication across multiple methods. Returns: - List of parameter definitions from beratools.json, or empty list if not found. + List of parameter definitions from the tool's tools.json, or empty list if not found. """ if self.bera_tools and "toolbox" in self.bera_tools: for toolbox in self.bera_tools["toolbox"]: @@ -772,13 +636,13 @@ def _find_tool_params(self, tool_name): def validate_tool_parameter(self, value, param_def): """ - Validate and convert parameter to correct type based on beratools.json definition. + Validate and convert parameter to correct type based on its tools.json definition. Orchestrates validation by dispatching to type-specific validators. Args: value: The value from GUI input - param_def: The original parameter definition from beratools.json + param_def: The original parameter definition from tools.json Returns: Converted and validated value @@ -787,7 +651,7 @@ def validate_tool_parameter(self, value, param_def): ValueError: If validation fails """ # GUARD CLAUSE 1: Handle None/empty for optional parameters - if value is None or value == "": + if value is None or value == "" or value == []: if param_def.get("optional", False): return param_def.get("default", None) @@ -801,6 +665,8 @@ def validate_tool_parameter(self, value, param_def): return self._validate_number(value, param_def) elif param_type == "file": return self._validate_file(value, param_def) + elif param_type == "files": + return self._validate_files(value, param_def) elif param_type == "directory": return self._validate_directory(value, param_def) elif param_type == "text": @@ -847,6 +713,9 @@ def _validate_file(self, value, param_def): if not file_path.exists(): raise ValueError(f"File not found: {actual_file_path}") + # a file parameter with "allow_directory" also takes a folder (of such files) + if file_path.is_dir() and param_def.get("allow_directory"): + return value if not file_path.is_file(): raise ValueError(f"Path is not a file: {actual_file_path}") @@ -889,6 +758,17 @@ def _validate_file(self, value, param_def): return value + def _validate_files(self, value, param_def): + """Validate a list of input files; a single path string is taken as a one-file list.""" + variable = param_def.get("variable", "unknown") + if isinstance(value, str): + value = [value] + if not isinstance(value, (list, tuple)): + raise ValueError(f"Parameter '{variable}' must be a list of file paths") + if not value and not param_def.get("optional", False): + raise ValueError(f"Parameter '{variable}' needs at least one file") + return [self._validate_file(path, param_def) for path in value] + def _validate_directory(self, value, param_def): """Validate directory exists and is accessible.""" variable = param_def.get("variable", "unknown") @@ -978,10 +858,10 @@ def _convert_float(self, value, variable): def validate_tool_params(self, tool_name, kwargs): """ - Validate and convert all tool parameters against beratools.json definitions. + Validate and convert all tool parameters against their tools.json definitions. Args: - tool_name: Tool name to lookup in beratools.json + tool_name: Tool name to look up in the registry kwargs: Dict of parameter values from GUI input Returns: @@ -992,7 +872,7 @@ def validate_tool_params(self, tool_name, kwargs): """ raw_params = self._find_tool_params(tool_name) - # Build a mapping of variable -> beratools.json param definition + # Build a mapping of variable -> tools.json param definition params_by_variable = {} for param in raw_params: if "variable" in param: @@ -1005,7 +885,7 @@ def validate_tool_params(self, tool_name, kwargs): validated_kwargs[key] = value continue - # Validate tool parameters against beratools.json definitions + # Validate tool parameters against tools.json definitions if key in params_by_variable: param_def = params_by_variable[key] try: @@ -1023,7 +903,7 @@ def get_bera_tool_params(self, tool_name): new_param_whole = {"parameters": []} tool = {} - # Find tool in beratools.json + # Find tool in the registry if self.bera_tools and "toolbox" in self.bera_tools: for toolbox in self.bera_tools["toolbox"]: for single_tool in toolbox["tools"]: @@ -1058,9 +938,14 @@ def get_bera_tool_params(self, tool_name): single_param["depends_on"] = param["depends_on"] if "unit" in param: single_param["unit"] = param["unit"] + for key in ("field_of", "field_check"): + if key in param: + single_param[key] = param[key] single_param["default_value"] = param["default"] single_param["optional"] = param.get("optional", False) + if param.get("allow_directory"): + single_param["allow_directory"] = True new_param_whole["parameters"].append(single_param) diff --git a/beratools/gui/bt_gui_main.py b/beratools/gui/bt_gui_main.py index 5f0b9a3..9026485 100644 --- a/beratools/gui/bt_gui_main.py +++ b/beratools/gui/bt_gui_main.py @@ -17,20 +17,45 @@ import json import os import platform +import re import shlex import signal import sys import webbrowser from pathlib import Path +from PyQt5 import QtCore, QtGui, QtWidgets + import beratools.core.constants as bt_const from beratools.core import pipeline from beratools.gui import bt_data from beratools.gui.pipeline_panel import PipelinePanel -from beratools.utility import env_checks from beratools.gui.tool_widgets import ToolWidgets +from beratools.utility import env_checks -from PyQt5 import QtCore, QtGui, QtWidgets +# A redraw of a text progress bar, such as lidR's catalog bar: " |===== | 43%" +TEXT_PROGRESS_BAR = re.compile(r"^\s*\|[=\-\s]*(\|[\s\d%]*)?$") +# A finished redraw with other output right after it, as when R prints next without a newline: +# ' |===== | 55%[1] "Classify ground start...."' +TEXT_PROGRESS_BAR_THEN_TEXT = re.compile(r"^\s*\|[=\-\s]*\|\s*(\d{1,3})%") +# lidR's report of one tile when R runs non-interactively: "Chunk 3 of 7 (42.9%): state ✓". +# R on Windows may write the symbol as its code point, e.g. "" for ✓. +LIDR_CHUNK_LINE = re.compile(r"Chunk (\d+) of (\d+) \(([\d.]+)%\): state (\S+)") +# A step's own bar within one tile, such as CSF's: "[=========> ] 74% ETA: 0s" +TILE_STEP_BAR = re.compile(r"^\s*\[[=>\s\-]*\]\s*(\d{1,3})%(\s*ETA:\s*\S*)?\s*$") +# States of a tile that was done (✓) or empty (∅), as symbols or code points +LIDR_CHUNK_DONE = ("✓", "∅", "", "") +# How the log describes a tile that ended with a warning (⚠) or an error (✗); the R tools print the +# warnings once each when the run ends +LIDR_CHUNK_STATES = { + "⚠": "done with a warning (the warnings are listed when the run ends)", + "": "done with a warning (the warnings are listed when the run ends)", + "✗": "failed", + "": "failed", +} +# An R tool that processes its tiles in several lidR runs (one per tile size) prints +# "R_TILES::" before each run +R_TILES = re.compile(r"R_TILES:(\d+):(\d+)") bt = bt_data.BTData() @@ -143,14 +168,24 @@ def search_text_changed(self, text=None): self.tree_view.collapseAll() def add_tool_list_to_tree(self, toolbox_list, sorted_tools): + # WIP modules and tools are only loaded with BERATOOLS_WIP=1 (see core/registry.py); mark them + # in italics with a tooltip. The item text stays the tool name, which the rest of the GUI looks up. + boxes = bt.bera_tools.get("toolbox", []) if bt.bera_tools else [] + wip_boxes = {box["category"] for box in boxes if box.get("status") == "wip"} + wip_tools = {tool["name"] for box in boxes for tool in box["tools"] if tool.get("status") == "wip"} + first_child = None for i, toolbox in enumerate(toolbox_list): parent = QtGui.QStandardItem( QtGui.QIcon(os.path.join(bt_const.ASSETS_PATH, "close.gif")), toolbox ) parent.setDragEnabled(False) + if toolbox in wip_boxes: + self._mark_wip(parent, "module") for j, tool in enumerate(sorted_tools[i]): child = QtGui.QStandardItem(QtGui.QIcon(os.path.join(bt_const.ASSETS_PATH, "tool.gif")), tool) + if tool in wip_tools: + self._mark_wip(child, "tool") if i == 0 and j == 0: first_child = child @@ -159,6 +194,13 @@ def add_tool_list_to_tree(self, toolbox_list, sorted_tools): return first_child + @staticmethod + def _mark_wip(item, what): + font = item.font() + font.setItalic(True) + item.setFont(font) + item.setToolTip(f"Work in progress: this {what} is hidden in releases (shown as BERATOOLS_WIP=1)") + def tree_view_selection_changed(self, new, old): if len(new.indexes()) == 0: return @@ -285,7 +327,10 @@ def __init__(self, current, maximum, parent=None): def slider_moved(self, value): actual_value = int(self.slider.value()) bt.set_selected_cpu_cores(actual_value) - QtWidgets.QToolTip.showText(QtGui.QCursor.pos(), f"{actual_value}") + # Only while the handle is dragged: shown on every change, it flashed at the mouse wherever + # it was whenever code set the slider. The label beside it shows the value either way. + if self.slider.isSliderDown(): + QtWidgets.QToolTip.showText(QtGui.QCursor.pos(), f"{actual_value}") self.label.setText(self.generate_label_text(actual_value)) def generate_label_text(self, value=None): @@ -400,6 +445,13 @@ def __init__(self): self.process = None self.cancel_op = False self._stdout_buffer = "" + # start of the current R stage on the progress bar, from the last "R_PROGRESS:"; + # None until the tool prints one + self._progress_stage_start = None + # (done, total) from lidR's last "Chunk j of n" line, for the label of a tile in progress + self._tiles_done = None + # (tiles done before the current lidR run, tiles in all runs) from the last "R_TILES" line + self._tile_runs = None # pipeline: the step shown in the tool form, and the steps of a running pipeline self.pipeline_step = None @@ -623,7 +675,7 @@ def set_tool(self, tool=None): self.tool_widget.update_widgets(self.tool_drafts[self.tool_name]) def _save_tool_draft(self): - """Remember the values in a tool's form (not a step's), to restore them when the tool is shown again.""" + """Remember the values in a tool's form (not a step's), to restore them when it is shown again.""" if self.pipeline_step is None: self.tool_drafts[self.tool_name] = self.tool_widget.get_widgets_values() @@ -671,7 +723,8 @@ def show_pipeline_step(self, step): self._show_tool_form(self.tool_name, f"Step {index + 1}: {self.tool_name}") self.tool_widget.update_widgets(step["args"]) - # linked inputs show what they will read (it may not exist until the pipeline runs) and can't be edited + # linked inputs show what they will read (it may not exist until the pipeline runs) and can't be + # edited for variable, source_id in step["links"].items(): input_widget = self.tool_widget.widgets_by_variable.get(variable) source = pipeline.step_index(steps, source_id) @@ -693,6 +746,8 @@ def _store_pipeline_step_args(self, *_): def save_tool_parameter(self): # Retrieve tool parameters from GUI args = self.tool_widget.get_widgets_arguments() + if not args: + self._report_argument_errors() bt.add_tool_history(self.tool_api, args) bt.save_tool_info() @@ -802,6 +857,31 @@ def show_advanced(self): self.top_right_layout.activate() self.top_right_layout.update() + def _set_stage_progress(self, percent): + """ + Show a stage's own progress (such as lidR's tiles) on the progress bar, between the start + of the stage (the last "R_PROGRESS:") and 99, never moving the bar back. Before the + tool's first R_PROGRESS, such as lidR's bar for reading the file headers, the bar is left + alone, as mapping it to 0-99 would hold the bar at 99 for the rest of the run. + """ + start = self._progress_stage_start + if start is None: + return + value = start + percent * (99 - start) // 100 + self.progress_bar.setValue(max(self.progress_bar.value(), value)) + + def _show_tile_step(self, percent): + """ + Show a step's progress within one tile (such as CSF's bar) on the label, not the progress + bar, which follows the tiles overall: a bar per tile made it restart for every tile. + """ + if self._tiles_done and self._tiles_done[0] < self._tiles_done[1]: + self.progress_label.setText( + f"Tile {self._tiles_done[0] + 1} of {self._tiles_done[1]}: {percent}%" + ) + else: + self.progress_label.setText(f"Current tile: {percent}%") + def custom_callback(self, value): """Define custom callback that deals with tool output.""" value = str(value) @@ -812,18 +892,80 @@ def custom_callback(self, value): if rm_str in value: value = value.replace(rm_str, "") - if "%" in value: + # Text progress bars redraw themselves with carriage returns, which the output box would + # show as one line per redraw. Take their percentage for the progress bar and drop the + # redraws and the blank ones that clear them, keeping any other text on the line. + if ("\r" in value or TEXT_PROGRESS_BAR.match(value) or TEXT_PROGRESS_BAR_THEN_TEXT.match(value) + or TILE_STEP_BAR.match(value)): + kept = [] + for segment in value.split("\r"): + bar_then_text = TEXT_PROGRESS_BAR_THEN_TEXT.match(segment) + if TEXT_PROGRESS_BAR.match(segment): + percent = re.search(r"(\d{1,3})%", segment) + if percent: + self._set_stage_progress(min(100, int(percent.group(1)))) + elif bar_then_text: + self._set_stage_progress(min(100, int(bar_then_text.group(1)))) + if segment[bar_then_text.end():].strip(): + kept.append(segment[bar_then_text.end():]) + elif TILE_STEP_BAR.match(segment): + self._show_tile_step(min(100, int(TILE_STEP_BAR.match(segment).group(1)))) + elif segment.strip(): + kept.append(segment) + value = "".join(kept) + if not value.strip(): + return + + # lidR reports each tile as "Chunk 3 of 7 (42.9%): state ✓" when R runs non-interactively, + # as the R tools run it. Show it on the progress bar and label; log only tiles that ended + # with a warning or an error, not the ones that were done (✓) or empty (∅). + tile_runs = R_TILES.search(value) + if tile_runs: + self._tile_runs = (int(tile_runs.group(1)), int(tile_runs.group(2))) + return + chunk = LIDR_CHUNK_LINE.search(value) + if chunk: + done, total = int(chunk.group(1)), int(chunk.group(2)) + percent = float(chunk.group(3)) + if self._tile_runs: + # count the tiles of all runs, not only of this one + done, total = self._tile_runs[0] + done, max(self._tile_runs[1], total) + percent = 100 * done / total + self._set_stage_progress(min(100, int(percent))) + self._tiles_done = (done, total) + self.progress_label.setText(f"Tile {done} of {total}") + if chunk.group(4) in LIDR_CHUNK_DONE: + return + state = LIDR_CHUNK_STATES.get(chunk.group(4)) + if state: + value = f"Tile {done} of {total}: {state}" + + # A percentage in other output moves the bar for the Python tools; once an R tool has started + # its stages, only those and its tiles do + if "%" in value and self._progress_stage_start is None: try: str_progress = extract_string_from_printout(value, "%") - # remove progress string + # remove progress string; the number may come before or after the "%" ("45.0%" or + # "%45.0"), and other text may be stuck to it value = value.replace(str_progress, "").strip() - progress = float(str_progress.replace("%", "").strip()) - self.progress_bar.setValue(int(progress)) + number = re.search(r"\d+(?:\.\d+)?", str_progress) + if number: + self.progress_bar.setValue(int(float(number.group()))) except ValueError as e: print("custom_callback: Problem parsing data into number: ", e) except Exception as e: print(e) + # R tools print "R_PROGRESS:". lidR's progress bar clears itself with spaces and + # carriage returns but no newline, so the marker can come after that on the same line. + r_progress = re.search(r"R_PROGRESS:(\d+)", value) + if r_progress: + # a stage starts here; the bar never moves back within a run + self._progress_stage_start = max(self._progress_stage_start or 0, int(r_progress.group(1))) + self.progress_bar.setValue(max(self.progress_bar.value(), self._progress_stage_start)) + value = value[: r_progress.start()] + value[r_progress.end() :] + if not value.strip(): + return if "PROGRESS_LABEL" in value: str_label = extract_string_from_printout(value, "PROGRESS_LABEL") value = value.replace(str_label, "").strip() # remove progress string @@ -840,10 +982,16 @@ def message(self, s): def load_default_args(self): self.tool_widget.load_default_args() + def _report_argument_errors(self): + """Show why the form's arguments were rejected in the output panel.""" + for message in getattr(self.tool_widget, "argument_errors", []): + self.print_line_to_output(message) + self.print_line_to_output("Please check the parameters.") + def start_process(self): args = self.tool_widget.get_widgets_arguments() if not args: - print("Please check the parameters.") + self._report_argument_errors() return bt.recent_tool = self.tool_name @@ -874,6 +1022,9 @@ def _launch_tool(self, tool_name, tool_api, args): self.print_line_to_output(f"Tool {tool_name} started") self.print_line_to_output("-----------------------") self._stdout_buffer = "" + self._progress_stage_start = None + self._tiles_done = None + self._tile_runs = None self.process = QtCore.QProcess() # Keep a reference to the QProcess self.process.readyReadStandardOutput.connect(self.handle_stdout) self.process.readyReadStandardError.connect(self.handle_stderr) @@ -912,7 +1063,9 @@ def _start_pipeline_step(self): except FileNotFoundError as err: self._finish_pipeline(f"Pipeline stopped before step {self.pipeline_index + 1}: {err}") return - self._launch_tool(f"{tool_name} (step {self.pipeline_index + 1}/{len(steps)})", step["tool_api"], args) + self._launch_tool( + f"{tool_name} (step {self.pipeline_index + 1}/{len(steps)})", step["tool_api"], args + ) def _continue_pipeline(self, step_ok): if self.cancel_op: @@ -964,11 +1117,14 @@ def _drain_stdout(self, flush_partial=False): self._stdout_buffer += chunk while True: - newline_idx = self._stdout_buffer.find("\n") - if newline_idx < 0: + # A line ends at a newline, or at a carriage return that is not the start of "\r\n": + # text progress bars redraw with carriage returns only, and each redraw should show + # at once. A carriage return at the end of the buffer waits for the next character. + end = re.search(r"\r\n|\n|\r(?=.)", self._stdout_buffer, re.DOTALL) + if not end: break - line = self._stdout_buffer[: newline_idx + 1] - self._stdout_buffer = self._stdout_buffer[newline_idx + 1 :] + line = self._stdout_buffer[: end.end()] + self._stdout_buffer = self._stdout_buffer[end.end() :] self.custom_callback(line) if flush_partial and self._stdout_buffer: @@ -998,11 +1154,16 @@ def process_finished(self): if stderr_data: self.message(bytes(stderr_data).decode("utf8")) if self.pipeline_run is not None: - step_ok = self.process.exitStatus() == QtCore.QProcess.NormalExit and self.process.exitCode() == 0 + step_ok = ( + self.process.exitStatus() == QtCore.QProcess.NormalExit and self.process.exitCode() == 0 + ) self.message("Process finished.") self.process = None self._stdout_buffer = "" + self._progress_stage_start = None + self._tiles_done = None + self._tile_runs = None self.progress_bar.setValue(0) self.progress_label.setText("") diff --git a/beratools/gui/main.py b/beratools/gui/main.py index 066e507..498762a 100644 --- a/beratools/gui/main.py +++ b/beratools/gui/main.py @@ -15,8 +15,8 @@ ## Set GDAL_DATA path to avoid GDAL # warning: Warning 3: Cannot find gdalvrt.xsd (GDAL_DATA is not defined)# import os -import sys import pathlib +import sys # Configure GDAL immediately env_root = pathlib.Path(sys.executable).parent @@ -29,8 +29,15 @@ if proj_data.exists(): os.environ["PROJ_LIB"] = str(proj_data) +# The environment's DLL folders go first on PATH, for a start without activating it (e.g. from an +# IDE); the tools the GUI starts inherit this PATH +from beratools.utility.env_checks import put_conda_dlls_on_path # noqa: E402 + +put_conda_dlls_on_path() + # Import after environment variables are set -from beratools.gui.bt_gui_main import runner +from beratools.gui.bt_gui_main import runner # noqa: E402 + def gui_main(): runner() diff --git a/beratools/gui/pipeline_panel.py b/beratools/gui/pipeline_panel.py index c9a48af..603d360 100644 --- a/beratools/gui/pipeline_panel.py +++ b/beratools/gui/pipeline_panel.py @@ -127,7 +127,6 @@ def __init__(self, bt_data_obj, parent=None): layout.addWidget(self.list_widget) layout.addWidget(self.links_box) layout.addWidget(self.btn_run) - # scroll the content when it doesn't fit, rather than resizing the panel content = QtWidgets.QWidget() content.setLayout(layout) @@ -144,8 +143,12 @@ def __init__(self, bt_data_obj, parent=None): self.list_widget.step_moved.connect(self.move_step) self.list_widget.currentRowChanged.connect(self.row_changed) self.btn_add.clicked.connect(self.add_requested) - self.btn_up.clicked.connect(lambda: self.move_step(self.list_widget.currentRow(), self.list_widget.currentRow() - 1)) - self.btn_down.clicked.connect(lambda: self.move_step(self.list_widget.currentRow(), self.list_widget.currentRow() + 2)) + self.btn_up.clicked.connect( + lambda: self.move_step(self.list_widget.currentRow(), self.list_widget.currentRow() - 1) + ) + self.btn_down.clicked.connect( + lambda: self.move_step(self.list_widget.currentRow(), self.list_widget.currentRow() + 2) + ) self.btn_remove.clicked.connect(self.remove_step) self.btn_clear.clicked.connect(self.clear_steps) self.btn_load.clicked.connect(self.load) @@ -306,7 +309,9 @@ def load(self): unknown = [s["tool_api"] for s in steps if self.bt.get_bera_tool_name(s["tool_api"]) is None] if unknown: - QtWidgets.QMessageBox.warning(self, "Load pipeline", f"Unknown tools in {path}: {', '.join(unknown)}") + QtWidgets.QMessageBox.warning( + self, "Load pipeline", f"Unknown tools in {path}: {', '.join(unknown)}" + ) return self.set_steps(steps) diff --git a/beratools/gui/tool_widgets.py b/beratools/gui/tool_widgets.py index d82882c..55b8176 100644 --- a/beratools/gui/tool_widgets.py +++ b/beratools/gui/tool_widgets.py @@ -16,6 +16,7 @@ import json import sys from collections import OrderedDict +from datetime import datetime from pathlib import Path import pyogrio @@ -49,6 +50,7 @@ def __init__(self, tool_name, tool_args, show_advanced, bt_data_obj=None, parent self.widget_list = [] self.ui_widget_list = [] self.widgets_by_variable = {} + self.argument_errors = [] self._depends_on_specs = {} self._inline_controllers = {} self.setWindowTitle("Tool widgets") @@ -72,22 +74,26 @@ def __init__(self, tool_name, tool_args, show_advanced, bt_data_obj=None, parent self.setLayout(layout) def get_widgets_arguments(self): + """ + Return the tool arguments, or None if any are missing. + + The reasons for a None result are left in ``self.argument_errors`` so that the main window + can show them in its output panel. + """ args = {} - param_missing = False + self.argument_errors = [] for widget in self.widget_list: if getattr(widget, "missing_input_error", ""): - print(f"[Missing input]: {widget.name}: {widget.missing_input_error}") - param_missing = True + self.argument_errors.append(f"[Missing input]: {widget.name}: {widget.missing_input_error}") continue v = widget.get_value() # get_value() returns {variable: ""} for an empty field, which is truthy if v and (widget.optional or not self._is_empty_value(widget, v.get(widget.variable))): args.update(v) else: - print(f"[Missing argument]: {widget.name} not specified.", "missing") - param_missing = True + self.argument_errors.append(f"[Missing argument]: {widget.name} not specified.") - if param_missing: + if self.argument_errors: args = None return args @@ -110,12 +116,18 @@ def connect_value_changed(self, callback): widget.combobox.currentIndexChanged.connect(callback) elif isinstance(widget, NumericInput) and widget.data_input is not None: widget.data_input.valueChanged.connect(callback) + elif isinstance(widget, TextInput): + widget.line_edit.textChanged.connect(callback) + elif isinstance(widget, FieldSelector): + widget.combobox.currentTextChanged.connect(callback) elif isinstance(widget, FileSelector): widget.in_file.textChanged.connect(callback) widget.layer_combo.currentTextChanged.connect(callback) + elif isinstance(widget, MultiFileSelector): + widget.files_changed.connect(callback) def create_widgets(self, tool_args): - valid_types = {"number", "file", "list", "text", "directory"} + valid_types = {"number", "file", "files", "list", "text", "directory"} for p in tool_args: # Validate parameter type is not a subtype value sub_type = p.get("type", None) @@ -127,10 +139,12 @@ def create_widgets(self, tool_args): pt = p["parameter_type"] widget = None - if "ExistingFile" in pt or "NewFile" in pt or "Directory" in pt: + if pt == "Text": + widget = FieldSelector(json_str) if p.get("field_of") else TextInput(json_str) + elif "ExistingFile" in pt or "NewFile" in pt or "Directory" in pt: widget = FileSelector(json_str, None, bt_data_obj=self.bt_data) elif "FileList" in pt: - widget = MultiFileSelector(json_str, None) + widget = MultiFileSelector(json_str, None, bt_data_obj=self.bt_data) elif "Boolean" in pt: widget = BooleanInput(json_str) elif "OptionList" in pt: @@ -189,14 +203,25 @@ def create_widgets(self, tool_args): self.widget_list.append(widget) + self._bind_field_selectors() self._configure_widget_dependencies() + def _bind_field_selectors(self): + for widget in self.widget_list: + if not isinstance(widget, FieldSelector): + continue + source = self.widgets_by_variable.get(widget.field_of) + if isinstance(source, FileSelector): + widget.bind_source(source) + else: + print(f"[Warning] Field list for '{widget.variable}' needs file input '{widget.field_of}'.") + @classmethod def _is_empty_value(cls, widget, value): # an output with a layer but no path encodes as "|layer", so check the path itself if isinstance(widget, FileSelector): return not cls._extract_file_selector_path(value) - return value is None or value == "" + return value is None or value == "" or value == [] @staticmethod def _extract_file_selector_path(value): @@ -271,18 +296,21 @@ def _configure_widget_dependencies(self): if missing_vars: print( - f"[Warning] Missing depends_on controller(s) {missing_vars} for '{widget.variable}'. Widget will remain visible." + f"[Warning] Missing depends_on controller(s) {missing_vars} for '{widget.variable}'. " + "Widget will remain visible." ) continue if mode == "inline": if "conditions" in depends_on or len(controller_vars) != 1: print( - f"[Warning] Inline depends_on for '{widget.variable}' requires exactly one controller variable. Widget remains separate." + f"[Warning] Inline depends_on for '{widget.variable}' requires exactly one " + "controller variable. Widget remains separate." ) elif controller_vars[0] in self._inline_controllers: print( - f"[Warning] Multiple inline dependents for '{controller_vars[0]}' are not supported. '{widget.variable}' remains separate." + f"[Warning] Multiple inline dependents for '{controller_vars[0]}' are not supported. " + f"'{widget.variable}' remains separate." ) elif self._attach_inline_widget(controller_widgets[0], widget): self._inline_controllers[controller_vars[0]] = widget.variable @@ -296,10 +324,12 @@ def _configure_widget_dependencies(self): self._update_dependency_states() def _align_all_labels(self): - """Set every widget's label (QLabel or QCheckBox) to the same fixed width + """ + Set every widget's label (QLabel or QCheckBox) to the same fixed width so that all input controls start at the same horizontal position. Inline widgets are skipped — their label is hidden and alignment is - governed by the controller checkbox they are embedded in.""" + governed by the controller checkbox they are embedded in. + """ inlined_vars = set(self._inline_controllers.values()) anchor_width = BT_LABEL_MIN_WIDTH checkbox_indicator_overhead = 0 @@ -382,9 +412,24 @@ def _connect_widget_change_signal(widget, callback): widget._depends_on_signal_connected = True return + if isinstance(widget, TextInput): + widget.line_edit.textChanged.connect(callback) + widget._depends_on_signal_connected = True + return + + if isinstance(widget, FieldSelector): + widget.combobox.currentTextChanged.connect(callback) + widget._depends_on_signal_connected = True + return + if isinstance(widget, FileSelector): widget.in_file.textChanged.connect(callback) widget._depends_on_signal_connected = True + return + + if isinstance(widget, MultiFileSelector): + widget.files_changed.connect(callback) + widget._depends_on_signal_connected = True def _get_widget_value(self, variable): widget = self.widgets_by_variable.get(variable) @@ -469,6 +514,29 @@ def get_layers(gpkg_file): _layers_cache = {} +def file_type_filter(file_type): + """Return the file dialog name filter for a parameter subtype such as "raster" or "lidar".""" + if file_type == "raster": + return """Tiff raster files (*.tif *.tiff);; + Other raster files (*.dep *.bil *.flt *.sdat *.asc *grd *.img *.vrt *.adf)""" + if file_type == "lidar": + return "LiDAR files (*.las *.zlidar *.laz *.zip)" + if file_type == "vector": + return """GeoPackage (*.gpkg);; + Shapefiles (*.shp)""" + if file_type == "text": + return "Text files (*.txt);; all files (*.*)" + if file_type == "csv": + return "CSV files (*.csv);; all files (*.*)" + if file_type == "dat": + return "Binary data files (*.dat);; all files (*.*)" + if file_type == "html": + return "HTML files (*.html)" + if file_type == "json": + return "JSON files (*.json)" + return "All files (*.*)" + + def _read_layers(gpkg_file): try: # Get the list of layers and their geometry types from the GeoPackage file @@ -514,7 +582,6 @@ def __init__(self, json_str, parent=None, bt_data_obj=None): self._loading = True self.parse_params(json_str) self.initialize_values() - self.handle_vector_io() self.setup_ui() self._loading = False @@ -530,6 +597,10 @@ def parse_params(self, json_str): self.is_directory = False if isinstance(self.parameter_type, dict): self.is_directory = "Directory" in self.parameter_type + # an input file parameter that also takes a folder (of such files) + self.allow_directory = ( + bool(params.get("allow_directory")) and not self.is_directory and not self.output + ) self.file_type = "" if "ExistingFile" in self.parameter_type: @@ -567,24 +638,6 @@ def initialize_values(self): else: self.value = self.saved_value if self.saved_value is not None else self.default_value - def handle_vector_io(self): - if not self.is_vector: - return - path = self.value["path"] - layer = self.value["layer"] - ext = Path(path).suffix.lower().replace(".", "") - if ext not in self.VECTOR_FORMATS: - return - if self.output: - # Output: preserve path/layer even if file doesn't exist - pass - else: - # Input: keep a saved file that no longer exists; it is flagged in the form - if not Path(path).exists(): - return - elif ext == "gpkg" and layer and self._missing_gpkg_layer(path, layer): - print(f"[Error] Invalid Layer: Layer '{layer}' not found in file: {path}") - def setup_ui(self): self.layout = QtWidgets.QHBoxLayout() self.label = QtWidgets.QLabel(self.name) @@ -595,6 +648,11 @@ def setup_ui(self): self.in_file = QtWidgets.QLineEdit(self.value) self.btn_select = QtWidgets.QPushButton("...") self.btn_select.clicked.connect(self.select_file) + self.btn_select_folder = None + if self.allow_directory: + self.btn_select_folder = QtWidgets.QPushButton("Folder...") + self.btn_select_folder.setToolTip("Select a folder instead of a file") + self.btn_select_folder.clicked.connect(self.select_input_folder) self.layer_combo = QtWidgets.QComboBox() self.layer_combo.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) self.layer_combo.setSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Fixed) @@ -608,6 +666,8 @@ def setup_ui(self): self.layout.addWidget(self.in_file, 1) self.layout.addWidget(self.layer_combo, 0) self.layout.addWidget(self.btn_select) + if self.btn_select_folder is not None: + self.layout.addWidget(self.btn_select_folder) self.setLayout(self.layout) # Populate combo box if vector and file exists if self.is_vector and self.value["path"] and Path(self.value["path"]).exists(): @@ -852,26 +912,7 @@ def get_first_type(type_val): return type_val[0] return type_val - file_types = "All files (*.*)" - ft = get_first_type(self.file_type) - if ft == "raster": - file_types = """Tiff raster files (*.tif *.tiff);; - Other raster files (*.dep *.bil *.flt *.sdat *.asc *grd)""" - elif ft == "lidar": - file_types = "LiDAR files (*.las *.zlidar *.laz *.zip)" - elif ft == "vector": - file_types = """GeoPackage (*.gpkg);; - Shapefiles (*.shp)""" - elif ft == "text": - file_types = "Text files (*.txt);; all files (*.*)" - elif ft == "csv": - file_types = "CSV files (*.csv);; all files (*.*)" - elif ft == "dat": - file_types = "Binary data files (*.dat);; all files (*.*)" - elif ft == "html": - file_types = "HTML files (*.html)" - elif ft == "json": - file_types = "JSON files (*.json)" + file_types = file_type_filter(get_first_type(self.file_type)) # Check for GeoPackage/Shapefile first in filter order by current value if isinstance(self.value, str) and self.value.lower().endswith(".gpkg"): @@ -993,6 +1034,14 @@ def get_first_type(type_val): except Exception as e: print(e) print("[Error] Could not find the selected file.") + def select_input_folder(self): + """Pick a folder for a file parameter that also takes one (allow_directory).""" + start_dir, _ = self._resolve_dialog_start_directory(self.in_file.text()) + folder = QtWidgets.QFileDialog.getExistingDirectory(self, "Select Folder", str(start_dir)) + if folder: + self.set_value(folder) + self._save_last_browse_dir(folder) + def select_directory(self): if self.is_directory: start_dir, _ = self._resolve_dialog_start_directory(self.in_file.text()) @@ -1111,7 +1160,8 @@ def set_value(self, value): self._loading = loading def _set_value(self, value): - if self.is_directory: + if self.is_directory or (self.allow_directory and isinstance(value, str) and value + and Path(value).is_dir()): self.value = value self.in_file.setText(value) self.in_file.setToolTip(value) @@ -1148,7 +1198,7 @@ def _set_value(self, value): self.value = value self.in_file.setText(self.value) self.in_file.setToolTip(self.value) - except Exception as e: + except Exception: # do nothing if first time initialize the tool with no previous values self.value = "" self.in_file.setText(self.value) @@ -1208,6 +1258,147 @@ def set_default_value(self): self.set_value(default_value) +class MultiFileSelector(QtWidgets.QWidget): + """Widget for an input that takes several existing files; its value is a list of paths.""" + + files_changed = QtCore.pyqtSignal() + VISIBLE_ROWS = 4 + + def __init__(self, json_str, parent=None, bt_data_obj=None): + super(MultiFileSelector, self).__init__(parent) + params = json.loads(json_str) + self.bt_data = bt_data_obj + self.name = params["name"] + self.description = params["description"] + self.variable = params["variable"] + self.parameter_type = params["parameter_type"] + self.optional = params["optional"] + self.default_value = self._as_list(params["default_value"]) + file_type = parse_subtype_tokens(self.parameter_type.get("FileList", [])) + self.file_type = file_type[0] if file_type else "" + self.missing_input_error = "" + + self.label = QtWidgets.QLabel(self.name) + self.label.setMinimumWidth(200) + self.label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop) + self.file_list = QtWidgets.QListWidget() + self.file_list.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) + row_height = self.file_list.fontMetrics().height() + 4 + self.file_list.setMaximumHeight(row_height * self.VISIBLE_ROWS + 2 * self.file_list.frameWidth()) + self.btn_add = QtWidgets.QPushButton("Add...") + self.btn_add.clicked.connect(self.select_files) + self.btn_remove = QtWidgets.QPushButton("Remove") + self.btn_remove.clicked.connect(self.remove_selected) + self.btn_clear = QtWidgets.QPushButton("Clear") + self.btn_clear.clicked.connect(self.clear) + for w in (self.label, self.file_list, self.btn_add): + w.setToolTip(self.description) + self.btn_remove.setToolTip("Remove the selected files from the list") + self.btn_clear.setToolTip("Remove all files from the list") + + buttons = QtWidgets.QVBoxLayout() + buttons.setAlignment(QtCore.Qt.AlignTop) + for btn in (self.btn_add, self.btn_remove, self.btn_clear): + buttons.addWidget(btn) + self.layout = QtWidgets.QHBoxLayout() + self.layout.addWidget(self.label) + self.layout.addWidget(self.file_list, 1) + self.layout.addLayout(buttons) + self.setLayout(self.layout) + + saved = params.get("saved_value") + self.set_value(saved if saved not in (None, "", []) else self.default_value) + + @staticmethod + def _as_list(value): + """Return value as a list of paths; a single path string becomes a one-item list.""" + if value is None or value == "": + return [] + if isinstance(value, str): + return [value] + return [str(v) for v in value if v] + + @property + def value(self): + return [self.file_list.item(i).text() for i in range(self.file_list.count())] + + def set_inline_mode(self, unit=""): + self.label.setVisible(False) + self.layout.setContentsMargins(0, 0, 0, 0) + + def add_files(self, paths): + existing = set(self.value) + added = False + for path in self._as_list(paths): + if path not in existing: + self.file_list.addItem(path) + existing.add(path) + added = True + if added: + self._value_changed() + + def remove_selected(self): + rows = sorted((self.file_list.row(item) for item in self.file_list.selectedItems()), reverse=True) + for row in rows: + self.file_list.takeItem(row) + if rows: + self._value_changed() + + def clear(self): + if self.file_list.count(): + self.file_list.clear() + self._value_changed() + + def _value_changed(self): + self._update_missing_input_warning() + self.files_changed.emit() + + def _update_missing_input_warning(self): + missing = [p for p in self.value if not Path(p).is_file()] + self.missing_input_error = f"file not found: {', '.join(missing)}" if missing else "" + for i in range(self.file_list.count()): + item = self.file_list.item(i) + if item.text() in missing: + item.setForeground(QtCore.Qt.red) + item.setToolTip("File not found") + else: + item.setData(QtCore.Qt.ForegroundRole, None) # back to the palette's text colour + item.setToolTip(item.text()) + + def _start_directory(self): + if self.bt_data: + last_browse_dir = self.bt_data.get_last_browse_dir() + if last_browse_dir and Path(last_browse_dir).expanduser().is_dir(): + return Path(last_browse_dir).expanduser() + for path in reversed(self.value): + parent = Path(path).expanduser().parent + if parent.is_dir(): + return parent + return Path.home() + + def select_files(self): + file_names, _ = QtWidgets.QFileDialog.getOpenFileNames( + self, "Select Files", str(self._start_directory()), file_type_filter(self.file_type) + ) + if not file_names: + return + self.add_files(file_names) + if self.bt_data: + self.bt_data.set_last_browse_dir(str(Path(file_names[-1]).parent)) + + def set_value(self, value): + self.file_list.clear() + self.add_files(value) + self._update_missing_input_warning() + + def set_default_value(self): + self.set_value(self.default_value) + self.files_changed.emit() + + def get_value(self): + return {self.variable: self.value} + + class OptionsInput(QtWidgets.QWidget): """OptionsInput class for creating option selection widgets.""" @@ -1241,6 +1432,9 @@ def __init__(self, json_str, parent=None): if self.option_list: # convert to strings self.option_list = [str(item) for item in self.option_list] + # a saved value from an older tool version may no longer be an option + if str(self.value) not in self.option_list: + self.value = self.default_value values = () for v in self.option_list: @@ -1269,6 +1463,8 @@ def selection_change(self, i): self.value = self.option_list[i] def set_value(self, value): + if str(value) not in self.option_list: + return self.value = value for v in self.option_list: if value == v: @@ -1284,6 +1480,200 @@ def get_value(self): return {self.variable: self.value} +class TextInput(QtWidgets.QWidget): + """TextInput class for creating free text widgets, such as field names.""" + + def __init__(self, json_str, parent=None): + super(TextInput, self).__init__(parent) + params = json.loads(json_str) + self.name = params["name"] + self.description = params["description"] + self.variable = params["variable"] + self.parameter_type = params["parameter_type"] + self.optional = params["optional"] + self.default_value = "" if params["default_value"] is None else str(params["default_value"]) + self.value = self.default_value + if params.get("saved_value") is not None: + self.value = str(params["saved_value"]) + + self.label = QtWidgets.QLabel(self.name) + self.label.setMinimumWidth(BT_LABEL_MIN_WIDTH) + self.line_edit = QtWidgets.QLineEdit(self.value) + self.line_edit.textChanged.connect(self.update_value) + self.label.setToolTip(self.description) + self.line_edit.setToolTip(self.description) + + self.layout = QtWidgets.QHBoxLayout() + self.layout.addWidget(self.label) + self.layout.addWidget(self.line_edit, 1) + self.setLayout(self.layout) + + def set_inline_mode(self, unit=""): + self.label.setVisible(False) + self.label.setMinimumWidth(0) + self.label.setMaximumWidth(0) + self.layout.setContentsMargins(0, 0, 0, 0) + + def update_value(self, text): + self.value = text + + def set_value(self, value): + self.line_edit.setText("" if value is None else str(value)) + + def set_default_value(self): + self.line_edit.setText(self.default_value) + + def get_value(self): + return {self.variable: self.value.strip()} + + +class FieldSelector(QtWidgets.QWidget): + """FieldSelector class for choosing a field of the vector layer picked in another parameter.""" + + WARNING_STYLE = "QComboBox { background-color: #fff3cd; }" + ERROR_STYLE = "QComboBox { background-color: #f8d7da; }" + + def __init__(self, json_str, parent=None): + super(FieldSelector, self).__init__(parent) + params = json.loads(json_str) + self.name = params["name"] + self.description = params["description"] + self.variable = params["variable"] + self.parameter_type = params["parameter_type"] + self.optional = params["optional"] + self.field_of = params["field_of"] + self.field_check = params.get("field_check", "") + self.default_value = "" if params["default_value"] is None else str(params["default_value"]) + self.value = self.default_value + if params.get("saved_value") is not None: + self.value = str(params["saved_value"]) + self.source = None + self.fields = [] + self.missing_input_error = "" + self._year_checks = {} + + self.label = QtWidgets.QLabel(self.name) + self.label.setMinimumWidth(BT_LABEL_MIN_WIDTH) + self.combobox = QtWidgets.QComboBox() + self.combobox.setEditable(True) + self.combobox.setInsertPolicy(QtWidgets.QComboBox.NoInsert) + self.combobox.setMinimumWidth(BT_NUMERIC_BOX_WIDTH) + self.combobox.setEditText(self.value) + self.combobox.currentTextChanged.connect(self.update_value) + self.status = QtWidgets.QLabel() + self.status.setWordWrap(True) + self.status.setVisible(False) + self.label.setToolTip(self.description) + self.combobox.setToolTip(self.description) + + self.layout = QtWidgets.QHBoxLayout() + self.layout.addWidget(self.label) + self.layout.addWidget(self.combobox) + self.layout.addWidget(self.status, 1) + self.setLayout(self.layout) + + def set_inline_mode(self, unit=""): + self.label.setVisible(False) + self.label.setMinimumWidth(0) + self.label.setMaximumWidth(0) + self.layout.setContentsMargins(0, 0, 0, 0) + + def bind_source(self, source): + """List the fields of the layer chosen in `source`, a FileSelector, and follow its changes.""" + self.source = source + source.in_file.textChanged.connect(self.refresh_fields) + source.layer_combo.currentTextChanged.connect(self.refresh_fields) + self.refresh_fields() + + def _source_path_layer(self): + if self.source is None: + return "", None + encoded = self.source.get_value().get(self.source.variable, "") + if not isinstance(encoded, str) or not encoded: + return "", None + path, _, layer = encoded.partition("|") + return path, layer or None + + def refresh_fields(self, *_): + path, layer = self._source_path_layer() + fields = [] + if path and Path(path).is_file(): + try: + fields = [str(field) for field in pyogrio.read_info(path, layer=layer)["fields"]] + except Exception as e: + print(f"[Error] Could not read fields from {path}: {e}") + self.fields = fields + + current = self.value + self.combobox.blockSignals(True) + self.combobox.clear() + self.combobox.addItems(fields) + index = self.combobox.findText(current) + if index >= 0: + self.combobox.setCurrentIndex(index) + else: + self.combobox.setEditText(current) + self.combobox.blockSignals(False) + self.check_field() + + def check_field(self): + """Flag a field missing from the layer, or (for year fields) one without usable years.""" + error, warning = "", "" + field = self.value.strip() + if self.fields: + if not field: + if not self.optional: + error = "Select a field." + elif field not in self.fields: + error = f"Field '{field}' is not in the layer." + elif self.field_check == "year": + error, warning = self._check_year_field(field) + self._show_status(error, warning) + + def _check_year_field(self, field): + from beratools.utility.field_checks import check_year_values + + path, layer = self._source_path_layer() + key = (path, layer, field) + if key not in self._year_checks: + try: + table = pyogrio.read_dataframe(path, layer=layer, columns=[field], read_geometry=False) + error, warning = check_year_values(table[field], datetime.now().year) + error = f"Field '{field}' {error}." if error else "" + warning = f"Field '{field}': {warning}." if warning else "" + except Exception as e: + error, warning = f"Could not read field '{field}': {e}", "" + self._year_checks[key] = (error, warning) + return self._year_checks[key] + + def _show_status(self, error, warning): + self.missing_input_error = error + message = error or warning + self.combobox.setStyleSheet(self.ERROR_STYLE if error else self.WARNING_STYLE if warning else "") + self.combobox.setToolTip(message or self.description) + self.status.setText(message) + self.status.setVisible(bool(message)) + + def update_value(self, text): + self.value = text + self.check_field() + + def set_value(self, value): + text = "" if value is None else str(value) + index = self.combobox.findText(text) + if index >= 0: + self.combobox.setCurrentIndex(index) + else: + self.combobox.setEditText(text) + self.update_value(text) + + def set_default_value(self): + self.set_value(self.default_value) + + def get_value(self): + return {self.variable: self.value.strip()} + + class NumericInput(QtWidgets.QWidget): """NumericInput class for creating numeric input widgets (int and float).""" @@ -1534,3 +1924,4 @@ def sliderChange(self, change): ) dlg.show() sys.exit(app.exec_()) + diff --git a/beratools/modules/__init__.py b/beratools/modules/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/beratools/modules/mapping/__init__.py b/beratools/modules/mapping/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/beratools/modules/mapping/algo_astar.py b/beratools/modules/mapping/algo_astar.py new file mode 100644 index 0000000..2f322a9 --- /dev/null +++ b/beratools/modules/mapping/algo_astar.py @@ -0,0 +1,547 @@ +"""Reusable A* path and corridor algorithms for centerline workflows.""" + +from __future__ import annotations + +import heapq +import logging +import math +from dataclasses import dataclass +from itertools import count +from typing import Iterable + +import numpy as np +import rasterio +import shapely.geometry as sh_geom +import shapely.ops as sh_ops +from rasterio.features import geometry_mask +from scipy import ndimage +from shapely.geometry import LineString + +import beratools.modules.mapping.algo_common as algo_common + +LOGGER_NAME = "centerline" +logger = logging.getLogger(LOGGER_NAME) + + + +SQRT2 = math.sqrt(2.0) +ASTAR_LINE_BIAS = 0.001 +DEFAULT_CORRIDOR_LINE_BIAS_WEIGHT = 0.1 +DEFAULT_CORRIDOR_DISTANCE_PENALTY_WEIGHT = 0.2 + +NEIGHBORS: tuple[tuple[int, int], ...] = ( + (1, 0), + (0, -1), + (-1, 0), + (0, 1), + (1, -1), + (1, 1), + (-1, -1), + (-1, 1), +) + + +@dataclass(frozen=True) +class AStarAccumulation: + path: list[tuple[int, int]] + best_cost: float + g_scores: np.ndarray + closed: np.ndarray + +def nearest_valid_cell(cost, start_rc, max_radius=20): + """Find the nearest valid cell if lcp start/end point land on nodata cell.""" + r0, c0 = start_rc + if np.isfinite(cost[r0, c0]): + return start_rc + rows, cols = cost.shape + for radius in range(1, max_radius + 1): + rmin = max(0, r0 - radius) + rmax = min(rows, r0 + radius + 1) + cmin = max(0, c0 - radius) + cmax = min(cols, c0 + radius + 1) + best_cell = None + best_dist = float("inf") + for r in range(rmin, rmax): + for c in range(cmin, cmax): + if not np.isfinite(cost[r, c]): + continue + dist = (r - r0) ** 2 + (c - c0) ** 2 + if dist < best_dist: + best_dist = dist + best_cell = (r, c) + if best_cell is not None: + return best_cell + return None + +def nearest_valid_location_on_line( + cost_arr, + transform, + line, + from_start=True, + step=1.0, + max_search=20.0, +): + length = line.length + + if from_start: + distances = np.arange(0, min(max_search, length), step) + else: + distances = np.arange( + length, + max(length - max_search, 0), + -step, + ) + + for d in distances: + pt = line.interpolate(d) + + r, c = rasterio.transform.rowcol( + transform, + pt.x, + pt.y, + ) + + if np.isfinite(cost_arr[r, c]): + return pt, (r, c) + + return None, None + +def find_least_cost_path_astar_closest_line( + cost_arr, meta: dict, input_line: LineString, cid=None +) -> LineString | None: + """Find an 8-neighbor A* LCP, tie-broken toward the seed-line direction.""" + if input_line is None or input_line.is_empty or len(input_line.coords) < 2: + logger.info(cid+f"Input line is empty or too short: {input_line}") + return None + + x1, y1 = input_line.coords[0] + x2, y2 = input_line.coords[-1] + costs, walkable = _prepare_lcp_costs(cost_arr, meta.get("nodata")) + rows, cols = costs.shape + transformer = rasterio.transform.AffineTransformer(meta["transform"]) + start_rc = rasterio.transform.rowcol(meta["transform"], x1, y1) + end_rc = rasterio.transform.rowcol(meta["transform"], x2, y2) + if not walkable[start_rc]: + start_xy_pt,start_rc_fixed=nearest_valid_location_on_line(cost_arr, meta["transform"], input_line, + from_start=True,step=meta["transform"].a, + max_search=10.0) + if start_rc_fixed is None: + start_rc_fixed = nearest_valid_cell(cost_arr, start_rc) + if start_rc_fixed is None: + logger.info(cid+f"Start point is not traversable: {start_rc}") + return None + else: + sx,sy=rasterio.transform.xy(meta["transform"], start_rc_fixed[0], start_rc_fixed[-1]) + start_xy_pt =sh_geom.Point(sx,sy) + + ds=input_line.project(start_xy_pt) + start_connector=sh_ops.substring(input_line,0,ds) + logger.warning( + cid + + f" start_connector_type={type(start_connector).__name__ if start_connector is not None else None}" + ) + start_xy=start_xy_pt.coords[0] + logger.warning( + cid + + f" moved start {start_rc}->{start_rc_fixed}" + ) + else: + start_rc_fixed = start_rc + start_connector=None + start_xy = (x1, y1) + if not walkable[end_rc]: + end_xy_pt,end_rc_fixed=nearest_valid_location_on_line(cost_arr, meta["transform"], input_line, + from_start=False,step=meta["transform"].a, + max_search=10.0) + if end_rc_fixed is None: + end_rc_fixed= nearest_valid_cell(cost_arr, end_rc) + if end_rc_fixed is None: + logger.info(cid+f"End point is not traversable: {end_rc}") + return None + else: + ex,ey=rasterio.transform.xy(meta["transform"], end_rc_fixed[0], end_rc_fixed[-1]) + end_xy_pt =sh_geom.Point(ex,ey) + de = input_line.project(end_xy_pt) + end_connector = sh_ops.substring(input_line, de, input_line.length) + logger.warning( + cid + + f" end_connector_type={type(end_connector).__name__ if end_connector is not None else None}" + ) + end_xy = end_xy_pt.coords[0] + logger.warning( + cid + + f" moved end {end_rc}->{end_rc_fixed}" + ) + else: + end_rc_fixed = end_rc + end_xy = (x2, y2) + end_connector = None + + start = _clamp_row_col(start_rc_fixed, rows, cols) + end = _clamp_row_col(end_rc_fixed, rows, cols) + if not walkable[start] or not walkable[end]: + logger.info(cid+ + f"Start or end point is not traversable: {start_rc_fixed} or {end_rc_fixed}") + return None + + min_cost = float(costs[walkable].min()) if np.any(walkable) else 0.0 + tie_scores = np.full((rows, cols), math.inf, dtype="float64") + g_scores = np.full((rows, cols), math.inf, dtype="float64") + came_from: dict[tuple[int, int], tuple[int, int] | None] = {start: None} + closed: set[tuple[int, int]] = set() + sequence = count() + heap: list[tuple] = [] + + g_scores[start] = 0.0 + tie_scores[start] = 0.0 + heapq.heappush(heap, _lcp_queue_entry(start, end, start, 0.0, 0.0, min_cost, next(sequence))) + + while heap: + *_, current = heapq.heappop(heap) + if current in closed: + continue + if current == end: + lcp = _path_to_linestring(_reconstruct_path(came_from, end), transformer, start_xy, end_xy) + segments = [] + if start_connector is not None: + segments.append(start_connector) + + segments.append(lcp) + + if end_connector is not None: + segments.append(end_connector) + if len(segments) == 1: + return segments[0] + return algo_common._safe_linemerge(sh_geom.MultiLineString(segments)) + + closed.add(current) + + for neighbor in _neighbors(current, rows, cols, walkable): + if neighbor in closed: + continue + new_g = g_scores[current] + _lcp_edge_cost(costs, current, neighbor) + new_tie = _line_bias_score(neighbor, start, end) + current_g = g_scores[neighbor] + current_tie = tie_scores[neighbor] + improved = new_g < current_g - 1e-6 + tied_better = abs(new_g - current_g) <= 1e-6 and new_tie < current_tie + if not improved and not tied_better: + continue + g_scores[neighbor] = new_g + tie_scores[neighbor] = new_tie + came_from[neighbor] = current + heapq.heappush( + heap, + _lcp_queue_entry(neighbor, end, start, new_g, new_tie, min_cost, next(sequence)), + ) + logger.info(cid+f'No path found between {start_rc_fixed} and {end_rc_fixed} using A* LCP.') + return None + + +def astar_accumulation_corridor_raster( + cost_arr, + meta: dict, + lc_path: LineString, + *, + corridor_threshold: float, + line_bias_weight: float = DEFAULT_CORRIDOR_LINE_BIAS_WEIGHT, + distance_penalty_weight: float = DEFAULT_CORRIDOR_DISTANCE_PENALTY_WEIGHT, +) -> tuple[np.ma.MaskedArray, dict[str, object]]: + """Build an A* accumulation corridor raster using BERA's 0-inside/1-outside convention.""" + if lc_path is None or lc_path.is_empty or len(lc_path.coords) < 2: + raise RuntimeError("A* corridor requires a valid least-cost path") + + cost = _prepare_corridor_cost_surface(cost_arr, meta) + rows, cols = cost.shape + transform = meta["transform"] + transformer = rasterio.transform.AffineTransformer(transform) + start_xy = lc_path.coords[0] + end_xy = lc_path.coords[-1] + source = _clamp_row_col(transformer.rowcol(*start_xy), rows, cols) + destination = _clamp_row_col(transformer.rowcol(*end_xy), rows, cols) + if not np.isfinite(cost[source]): + _, source = nearest_valid_location_on_line( + cost_arr, meta["transform"], lc_path, from_start=True, step=meta["transform"].a + ) + + if not np.isfinite(cost[destination]): + _, destination = nearest_valid_location_on_line( + cost_arr, meta["transform"], lc_path, from_start=False, step=meta["transform"].a + ) + sampling = _raster_sampling(transform) + + forward = _astar_mcp_geometric_accumulation( + cost, + source, + destination, + sampling=sampling, + line_bias_weight=line_bias_weight, + ) + reverse = _astar_mcp_geometric_accumulation( + cost, + destination, + source, + sampling=sampling, + line_bias_weight=line_bias_weight, + ) + + valid = forward.closed & reverse.closed + score_data = forward.g_scores + reverse.g_scores - forward.best_cost + if distance_penalty_weight > 0.0: + astar_path = _path_to_linestring(forward.path, transformer, start_xy, end_xy) + distance_to_path = _distance_raster_to_line(astar_path, meta, cost.shape) + score_data = score_data + distance_to_path * distance_penalty_weight + + score = np.ma.masked_invalid(score_data) + score = np.ma.array(score, mask=np.ma.getmaskarray(score) | ~valid) + inside = (~np.ma.getmaskarray(score)) & np.asarray(score.filled(np.inf) < corridor_threshold, dtype=bool) + corridor = np.ma.where(inside, 0.0, 1.0) + corridor = np.ma.array(corridor, mask=np.ma.getmaskarray(score)) + + details = { + "corridor_threshold": float(corridor_threshold), + "astar_line_bias_weight": float(line_bias_weight), + "astar_distance_penalty_weight": float(distance_penalty_weight), + "astar_best_cost": float(forward.best_cost), + "inside_cells": int(np.count_nonzero(inside)), + "inside_area": float(np.count_nonzero(inside) * _cell_area(transform)), + "forward_closed_cells": int(np.count_nonzero(forward.closed)), + "reverse_closed_cells": int(np.count_nonzero(reverse.closed)), + "both_closed_cells": int(np.count_nonzero(valid)), + "astar_path_vertices": int(len(forward.path)), + } + return corridor, details + + +def _prepare_lcp_costs(cost_arr, nodata) -> tuple[np.ndarray, np.ndarray]: + array = np.ma.asarray(cost_arr) + if array.ndim > 2: + array = np.ma.squeeze(array, axis=0) + costs = np.asarray(array.filled(np.nan), dtype="float64") + walkable = np.isfinite(costs) & (costs > 0.0) + if nodata is not None: + walkable &= costs != float(nodata) + return costs, walkable + + +def _prepare_corridor_cost_surface(cost_arr, meta: dict) -> np.ndarray: + arr = np.ma.asarray(cost_arr) + if arr.ndim > 2: + arr = np.ma.squeeze(arr, axis=0) + cost = np.asarray(arr.filled(np.inf), dtype="float64") + nodata = meta.get("nodata") + if nodata is not None: + cost[cost == float(nodata)] = np.inf + cost[~np.isfinite(cost)] = np.inf + cost[cost <= 0.0] = np.inf + return cost + + +def _astar_mcp_geometric_accumulation( + cost: np.ndarray, + source: tuple[int, int], + destination: tuple[int, int], + *, + sampling: tuple[float, float], + line_bias_weight: float, +) -> AStarAccumulation: + if not np.isfinite(cost[source]) or not np.isfinite(cost[destination]): + raise RuntimeError("A* source or destination is not traversable") + + rows, cols = cost.shape + walkable = np.isfinite(cost) & (cost > 0.0) + min_cost = float(cost[walkable].min()) if np.any(walkable) else 0.0 + g_scores = np.full(cost.shape, math.inf, dtype="float64") + tie_scores = np.full(cost.shape, math.inf, dtype="float64") + came_from: dict[tuple[int, int], tuple[int, int] | None] = {source: None} + closed_nodes: set[tuple[int, int]] = set() + closed = np.zeros(cost.shape, dtype=bool) + sequence = count() + heap: list[tuple[float, float, float, int, tuple[int, int]]] = [] + + g_scores[source] = 0.0 + tie_scores[source] = 0.0 + destination_path = None + destination_cost = None + heapq.heappush( + heap, + _corridor_queue_entry( + source, + destination, + source, + 0.0, + 0.0, + min_cost, + sampling, + line_bias_weight, + next(sequence), + ), + ) + + while heap: + *_, current = heapq.heappop(heap) + if current in closed_nodes: + continue + if current == destination and destination_path is None: + destination_path = _reconstruct_path(came_from, destination) + destination_cost = float(g_scores[destination]) + closed_nodes.add(current) + closed[current] = True + + for neighbor in _neighbors(current, rows, cols, walkable): + if neighbor in closed_nodes: + continue + new_g = g_scores[current] + _geometric_edge_cost(cost, current, neighbor, sampling) + new_tie = _line_bias_score(neighbor, source, destination) + improved = new_g < g_scores[neighbor] - 1e-9 + tied_better = abs(new_g - g_scores[neighbor]) <= 1e-9 and new_tie < tie_scores[neighbor] + if not improved and not tied_better: + continue + g_scores[neighbor] = new_g + tie_scores[neighbor] = new_tie + came_from[neighbor] = current + heapq.heappush( + heap, + _corridor_queue_entry( + neighbor, + destination, + source, + new_g, + new_tie, + min_cost, + sampling, + line_bias_weight, + next(sequence), + ), + ) + + if destination_path is None or destination_cost is None: + raise RuntimeError("A* path did not reach destination") + + return AStarAccumulation( + path=destination_path, + best_cost=destination_cost, + g_scores=g_scores, + closed=closed, + ) + + +def _neighbors( + node: tuple[int, int], rows: int, cols: int, walkable: np.ndarray +) -> Iterable[tuple[int, int]]: + row, col = node + for d_row, d_col in NEIGHBORS: + neighbor = row + d_row, col + d_col + if 0 <= neighbor[0] < rows and 0 <= neighbor[1] < cols and walkable[neighbor]: + yield neighbor + + +def _lcp_edge_cost(costs: np.ndarray, current: tuple[int, int], neighbor: tuple[int, int]) -> float: + base = (float(costs[current]) + float(costs[neighbor])) / 2.0 + return base * (SQRT2 if current[0] != neighbor[0] and current[1] != neighbor[1] else 1.0) + + +def _geometric_edge_cost( + cost: np.ndarray, + current: tuple[int, int], + neighbor: tuple[int, int], + sampling: tuple[float, float], +) -> float: + d_row = neighbor[0] - current[0] + d_col = neighbor[1] - current[1] + offset_length = math.hypot(d_row * sampling[0], d_col * sampling[1]) + return offset_length * 0.5 * (float(cost[current]) + float(cost[neighbor])) + + +def _lcp_queue_entry( + node: tuple[int, int], + end: tuple[int, int], + start: tuple[int, int], + g_score: float, + tie_score: float, + min_cost: float, + sequence: int, +) -> tuple: + heuristic = _octile(node, end) * min_cost + priority = g_score + heuristic + tie_score * ASTAR_LINE_BIAS + return priority, g_score + heuristic, tie_score, heuristic, sequence, node + + +def _corridor_queue_entry( + node: tuple[int, int], + destination: tuple[int, int], + source: tuple[int, int], + g_score: float, + tie_score: float, + min_cost: float, + sampling: tuple[float, float], + line_bias_weight: float, + sequence: int, +) -> tuple[float, float, float, int, tuple[int, int]]: + heuristic = _euclidean_grid_distance(node, destination, sampling) * min_cost + priority = g_score + heuristic + tie_score * line_bias_weight + return priority, heuristic, _line_bias_score(node, source, destination), sequence, node + + +def _octile(a: tuple[int, int], b: tuple[int, int]) -> float: + d_row = abs(a[0] - b[0]) + d_col = abs(a[1] - b[1]) + return d_row + d_col + (SQRT2 - 2.0) * min(d_row, d_col) + + +def _euclidean_grid_distance(a: tuple[int, int], b: tuple[int, int], sampling: tuple[float, float]) -> float: + return math.hypot((a[0] - b[0]) * sampling[0], (a[1] - b[1]) * sampling[1]) + + +def _line_bias_score(node: tuple[int, int], start: tuple[int, int], end: tuple[int, int]) -> float: + dx1 = node[1] - end[1] + dy1 = node[0] - end[0] + dx2 = start[1] - end[1] + dy2 = start[0] - end[0] + return abs(dx1 * dy2 - dx2 * dy1) / max(1.0, math.hypot(dx2, dy2)) + + +def _reconstruct_path( + came_from: dict[tuple[int, int], tuple[int, int] | None], end: tuple[int, int] +) -> list[tuple[int, int]]: + path = [end] + current = end + while came_from[current] is not None: + current = came_from[current] + path.append(current) + path.reverse() + return path + + +def _path_to_linestring(path: list[tuple[int, int]], transformer, start_xy, end_xy) -> LineString | None: + if len(path) < 2: + return None + points = [transformer.xy(row, col) for row, col in path] + points[0] = (start_xy[0], start_xy[1]) + points[-1] = (end_xy[0], end_xy[1]) + return LineString(points) + + +def _distance_raster_to_line(line: LineString, meta: dict, shape: tuple[int, int]) -> np.ndarray: + transform = meta["transform"] + cell_size = max(abs(float(transform.a)), abs(float(transform.e))) + path_mask = geometry_mask( + [line.buffer(cell_size * 0.5)], + out_shape=shape, + transform=transform, + invert=True, + all_touched=True, + ) + return ndimage.distance_transform_edt(~path_mask, sampling=_raster_sampling(transform)) + + +def _raster_sampling(transform) -> tuple[float, float]: + return (abs(float(transform.e)), abs(float(transform.a))) + + +def _cell_area(transform) -> float: + return abs(float(transform.a) * float(transform.e)) + + +def _clamp_row_col(row_col: tuple[int, int], rows: int, cols: int) -> tuple[int, int]: + return max(0, min(int(row_col[0]), rows - 1)), max(0, min(int(row_col[1]), cols - 1)) diff --git a/beratools/modules/mapping/algo_canopy_footprint_absolute.py b/beratools/modules/mapping/algo_canopy_footprint_absolute.py new file mode 100644 index 0000000..4edc2c4 --- /dev/null +++ b/beratools/modules/mapping/algo_canopy_footprint_absolute.py @@ -0,0 +1,990 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng, Maverick Fong + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + The purpose of this script is to provide main interface for adaptive relative canopy footprint tool. + The tool is used to generate the canopy footprint of a line based on adaptive relative threshold. +""" + +import math +from dataclasses import dataclass, field +from enum import Enum + +import geopandas as gpd +import numpy as np +import pandas as pd +import rasterio.features as ras_feat +import shapely +import shapely.geometry as sh_geom +import shapely.ops as sh_ops +from rasterio.transform import rowcol +from skimage.graph import MCP_Flexible + +import beratools.core.constants as bt_const +import beratools.core.tool_base as bt_base +import beratools.modules.mapping.algo_common as algo_common +import beratools.modules.mapping.algo_cost as algo_cost +import beratools.modules.mapping.algo_geometry as algo_geometry +import beratools.utility.spatial_common as sp_common +from beratools.utility.tool_args import CallMode, to_bool + + +@dataclass +class CanopyFootprintRequest: + """Common request contract for canopy footprint runs.""" + + in_line: str + in_chm: str + out_footprint: str + max_ln_width: float = 32.0 + processes: int = 0 + call_mode: CallMode | str = CallMode.CLI + log_level: str = "INFO" + corridor_thresh: float | None = None + exp_shk_cell: int | None = None + tree_radius: float | None = None + max_line_dist: float | None = None + canopy_avoidance: float | None = None + exponent: float | None = None + canopy_thresh_percentage: float | None = None + simplify_footprint_polygon: bool = True + footprint_simplify_length: float = 0.5 + smooth_footprint_polygon: bool = False + footprint_polygon_smooth_iterations: int = 1 + merge_by_original_line: bool = False + + +@dataclass +class CanopyFootprintResult: + """Common result contract for canopy footprint runs.""" + + footprints_gdf: gpd.GeoDataFrame | None = None + aux_layers: dict[str, gpd.GeoDataFrame] = field(default_factory=dict) + stats: dict[str, int] = field(default_factory=dict) + messages: list[str] = field(default_factory=list) + + +def cast_request_types(request: CanopyFootprintRequest) -> CanopyFootprintRequest: + """Cast optional numeric values to expected types.""" + request.max_ln_width = float(request.max_ln_width) + request.processes = int(request.processes) + + if request.corridor_thresh is not None: + request.corridor_thresh = float(request.corridor_thresh) + if request.exp_shk_cell is not None: + request.exp_shk_cell = int(request.exp_shk_cell) + if request.tree_radius is not None: + request.tree_radius = float(request.tree_radius) + if request.max_line_dist is not None: + request.max_line_dist = float(request.max_line_dist) + if request.canopy_avoidance is not None: + request.canopy_avoidance = float(request.canopy_avoidance) + if request.exponent is not None: + request.exponent = float(request.exponent) + if request.canopy_thresh_percentage is not None: + request.canopy_thresh_percentage = float(request.canopy_thresh_percentage) + request.simplify_footprint_polygon = to_bool(request.simplify_footprint_polygon) + request.footprint_simplify_length = float(request.footprint_simplify_length) + request.smooth_footprint_polygon = to_bool(request.smooth_footprint_polygon) + request.footprint_polygon_smooth_iterations = int(request.footprint_polygon_smooth_iterations) + request.merge_by_original_line = to_bool(request.merge_by_original_line) + + return request + + +def copy_line_ids(footprint, line): + """Carry the source line's OLnFID/OLnSEG onto its footprint, so footprints can be merged per line.""" + if footprint is None or line is None: + return footprint + for col in ("OLnFID", "OLnSEG"): + if col in line.columns: + footprint[col] = line[col].iloc[0] + return footprint + + +def merge_footprints_by_original_line(footprints_gdf, printer=print): + """Dissolve footprints sharing an OLnFID into one, as the centerline tool merges lines.""" + if footprints_gdf is None or footprints_gdf.empty: + return footprints_gdf + if "OLnFID" not in footprints_gdf.columns: + printer("[Warning]: OLnFID not found in input lines; footprints are not merged.") + return footprints_gdf + merged = footprints_gdf.dissolve(by="OLnFID", as_index=False) + merged["OLnSEG"] = -1 + return merged + + +def process_footprint_polygon_gdf( + footprint_gdf, + *, + simplify_footprint_polygon=True, + footprint_simplify_length=0.5, + smooth_footprint_polygon=False, + footprint_polygon_smooth_iterations=1, +): + if footprint_gdf is None or footprint_gdf.empty: + return footprint_gdf + + processed = footprint_gdf.copy() + processed.geometry = processed.geometry.apply( + lambda geom: algo_geometry.process_corridor_polygon( + geom, + simplify=simplify_footprint_polygon, + simplify_length=footprint_simplify_length, + smooth=smooth_footprint_polygon, + smooth_iterations=footprint_polygon_smooth_iterations, + ) + ) + return processed + + +def save_main_footprint( + result: CanopyFootprintResult, + out_footprint: str, + rejected_layer_name: str, + default_layer_name: str = "canopy_footprint", + printer=print, +) -> bool: + """Save main footprint output and return whether save succeeded.""" + if result.footprints_gdf is None or result.footprints_gdf.empty: + printer("Warning: No footprints generated. Output file not written.") + return False + + out_file, out_layer = sp_common.decode_file_layer(out_footprint) + layer_name = out_layer if out_layer else default_layer_name + + results = gpd.GeoDataFrame(result.footprints_gdf).reset_index(drop=True) + results = algo_common.clean_geometries( + results, + stage="output", + out_file=out_file, + layer=rejected_layer_name, + ) + + if results is None or results.empty: + printer("Warning: No valid footprints generated after cleaning. Output file not written.") + return False + + results.to_file(out_file, layer=layer_name) + printer(f"Saved footprint to {out_file}, layer: {layer_name}") + return True + + +def save_aux_layers(result: CanopyFootprintResult, out_footprint: str, printer=print) -> list[str]: + """Save optional auxiliary layers and return saved layer names.""" + saved_layers = [] + if not result.aux_layers: + return saved_layers + + out_file, _ = sp_common.decode_file_layer(out_footprint) + out_file_aux = algo_common.get_aux_path(out_file) + + for layer_name, gdf in result.aux_layers.items(): + if gdf is None or not hasattr(gdf, "empty") or gdf.empty: + continue + gdf.to_file(out_file_aux, layer=layer_name) + saved_layers.append(layer_name) + printer(f"Saved auxiliary layer '{layer_name}' to {out_file_aux}") + + return saved_layers + + +class Side(Enum): + """Constants for left and right side.""" + + left = "left" + right = "right" + + +@dataclass(frozen=True) +class CutParams: + """Cut distance and cut height for one side.""" + + cut_dist: float + cut_height: float + + +@dataclass(frozen=True) +class SideRasterInputs: + """Inputs required to compute side-specific canopy cost raster.""" + + line_buffer: object + cut_dist: float + canopy_height_thresh: float + + +@dataclass(frozen=True) +class SideFootprintResult: + """Result wrapper for side footprint generation.""" + + footprint_gdf: gpd.GeoDataFrame | None + reason: str | None = None + + +class FootprintCanopyAdaptive: + """Adaptive relative canopy footprint class.""" + + def __init__( + self, + in_geom, + in_chm, + max_line_width=32.0, + tree_radius=1.5, + max_line_dist=1.5, + canopy_avoidance=0.0, + exponent=1.0, + canopy_thresh_percentage=50.0, + exp_shk_cell=0, + simplify_footprint_polygon=True, + footprint_simplify_length=0.5, + smooth_footprint_polygon=False, + footprint_polygon_smooth_iterations=1, + ): + in_file, in_layer = sp_common.decode_file_layer(in_geom) + data = algo_common.read_geospatial_file(in_file, layer=in_layer) + if data is None: + data = gpd.GeoDataFrame() + self.lines = [] + self.cut_params = [] + + for idx in data.index: + line = LineInfo( + data.loc[[idx]].copy(), + in_chm, + max_line_width=max_line_width, + tree_radius=tree_radius, + max_line_dist=max_line_dist, + canopy_avoidance=canopy_avoidance, + exponent=exponent, + canopy_thresh_percentage=canopy_thresh_percentage, + exp_shk_cell=exp_shk_cell, + simplify_footprint_polygon=simplify_footprint_polygon, + footprint_simplify_length=footprint_simplify_length, + smooth_footprint_polygon=smooth_footprint_polygon, + footprint_polygon_smooth_iterations=footprint_polygon_smooth_iterations, + ) + self.lines.append(line) + + def compute(self, processes, call_mode=CallMode.CLI): + result = bt_base.execute_multiprocessing( + algo_common.process_single_item, + self.lines, + "Canopy Footprint", + processes, + call_mode, + ) + + footprint_list = [] + percentile = [] + cut_params = [] + try: + for item in result: + if item.footprint is not None: + footprint_list.append(item.footprint) + else: + print("Footprint is None for one of the lines.") + + if item.lines_percentile is not None: + percentile.append(item.lines_percentile) + else: + print("lines_percentile is None for one of the lines.") + + cut_params.append( + { + "left_cut_dist": float(item.left_cut_dist), + "left_cut_height": float(item.left_cut_height), + "right_cut_dist": float(item.right_cut_dist), + "right_cut_height": float(item.right_cut_height), + } + ) + + self.footprints = pd.concat(footprint_list, ignore_index=True) if footprint_list else None + self.lines_percentile = pd.concat(percentile, ignore_index=True) if percentile else None + self.cut_params = cut_params + + if self.footprints is None: + print("No valid footprints to save.") + if self.lines_percentile is None: + print("No valid lines_percentile to save.") + except Exception as e: + print(f"Error during processing: {e}") + + def save_footprint(self, out_footprint, layer=None): + if self.footprints is not None and isinstance(self.footprints, gpd.GeoDataFrame): + self.footprints = algo_common.clean_geometries( + self.footprints, + stage="output", + out_file=out_footprint, + layer="rejected_output_canopy_footprint_adaptive", + ) + self.footprints.to_file(out_footprint, layer=layer) + else: + print("No footprints to save (None or not a GeoDataFrame).") + + def save_line_percentile(self, out_percentile): + if self.lines_percentile is not None and isinstance(self.lines_percentile, gpd.GeoDataFrame): + self.lines_percentile.to_file(out_percentile) + else: + print("No lines_percentile to save (None or not a GeoDataFrame).") + + +class BufferRing: + """Buffer ring class.""" + + def __init__(self, ring_poly, side): + self.geometry = ring_poly + self.side = side + self.percentile = 0.5 + + +class LineInfo: + """Class to store line information.""" + + def __init__( + self, + line_gdf, + in_chm, + max_line_width=32.0, + tree_radius=1.5, + max_line_dist=1.5, + canopy_avoidance=0.0, + exponent=1.0, + canopy_thresh_percentage=50.0, + exp_shk_cell=0, + simplify_footprint_polygon=True, + footprint_simplify_length=0.5, + smooth_footprint_polygon=False, + footprint_polygon_smooth_iterations=1, + ): + self.line = line_gdf + self.in_chm = in_chm + self.line_simplified = self.line.geometry.simplify(tolerance=0.5, preserve_topology=True) + + self.buffer_rings = [] + + self.left_cut_height = np.nan + self.right_cut_height = np.nan + self.right_cut_dist = np.nan + self.left_cut_dist = np.nan + + self.canopy_thresh_percentage = canopy_thresh_percentage + self.canopy_avoidance = canopy_avoidance + self.exponent = exponent + self.exp_shk_cell = exp_shk_cell + self.simplify_footprint_polygon = to_bool(simplify_footprint_polygon) + self.footprint_simplify_length = float(footprint_simplify_length) + self.smooth_footprint_polygon = to_bool(smooth_footprint_polygon) + self.footprint_polygon_smooth_iterations = int(footprint_polygon_smooth_iterations) + self.max_line_width = max_line_width + self.max_line_dist = max_line_dist + self.tree_radius = tree_radius + + self.buffer_left = None + self.buffer_right = None + self.footprint = None + + self.lines_percentile = None + + def compute(self): + self.buffer_rings = self._build_rings_with_percentiles() + self.lines_percentile = self._build_lines_percentile() + + self.rate_of_change(self.get_percentile_array(Side.left), Side.left) + self.rate_of_change(self.get_percentile_array(Side.right), Side.right) + + self.prepare_line_buffer() + + fp_left = self.process_single_footprint(Side.left) + fp_right = self.process_single_footprint(Side.right) + + merged = self.merge_side_footprints(fp_left, fp_right) + if merged is None: + self.footprint = None + return + self.footprint = merged + self.footprint = process_footprint_polygon_gdf( + self.footprint, + simplify_footprint_polygon=self.simplify_footprint_polygon, + footprint_simplify_length=self.footprint_simplify_length, + smooth_footprint_polygon=self.smooth_footprint_polygon, + footprint_polygon_smooth_iterations=self.footprint_polygon_smooth_iterations, + ) + + # Transfer group value to footprint if present + if bt_const.BT_GROUP in self.line.columns: + self.footprint[bt_const.BT_GROUP] = self.line[bt_const.BT_GROUP].iloc[0] + copy_line_ids(self.footprint, self.line) + + def _build_rings_with_percentiles(self): + self.prepare_ring_buffer() + ring_list = [] + for item in self.buffer_rings: + ring = self.calc_ring_percentile(item) + if ring is not None: + ring_list.append(ring) + return ring_list + + def _build_lines_percentile(self): + percentile_records = [ + {"geometry": ring.geometry, "percentile": ring.percentile, "side": ring.side.value} + for ring in self.buffer_rings + ] + if not percentile_records: + return None + + lines_percentile = gpd.GeoDataFrame(percentile_records, geometry="geometry") + if self.line.crs: + lines_percentile = lines_percentile.set_crs(self.line.crs, allow_override=True) + return lines_percentile + + def merge_side_footprints(self, fp_left, fp_right): + if fp_left is None or fp_right is None: + print("One or both footprints are None in LineInfo.") + return None + + try: + fp_left.geometry = fp_left.geometry.buffer(0) + fp_right.geometry = fp_right.geometry.buffer(0) + + fp_combined = pd.concat([fp_left, fp_right], ignore_index=True) + if fp_combined.empty or not isinstance(fp_combined, gpd.GeoDataFrame): + print("Combined footprint is invalid or empty.") + return None + + fp_combined = fp_combined.dissolve() + fp_combined.geometry = fp_combined.geometry.buffer(-0.005) + return fp_combined + except Exception as e: + print(f"Error combining footprints: {e}") + return None + + def prepare_ring_buffer(self): + for ring_step, ring_max_dist, side in [(1, 15, Side.left), (-1, -15, Side.right)]: + ring_list = self.multi_ring_buffer(self.line_simplified, ring_step, ring_max_dist) + for ring_poly in ring_list: + self.buffer_rings.append(BufferRing(ring_poly, side)) + + def calc_ring_percentile(self, ring): + try: + line_buffer = ring.geometry + if line_buffer.is_empty or shapely.is_missing(line_buffer): + return None + if line_buffer.has_z: + line_buffer = sh_ops.transform(lambda x, y, z=None: (x, y), line_buffer) + + except Exception as e: + print(f"calc_ring_percentile: {e}") + return None + + try: + clipped_raster, _ = sp_common.clip_raster(self.in_chm, line_buffer, 0) + clipped_raster = np.squeeze(clipped_raster, axis=0) + + # mask all -9999 (nodata) value cells + masked_raster = np.ma.masked_where(clipped_raster == bt_const.BT_NODATA, clipped_raster) + filled_raster = np.ma.filled(masked_raster, np.nan) + + # Calculate the percentile + ring.percentile = np.nanpercentile(filled_raster, 50) + except Exception as e: + print(e) + print("Default values are used.") + + return ring + + def get_percentile_array(self, side): + return [ring.percentile for ring in self.buffer_rings if ring.side == side] + + def derive_cut_params(self, percentile_array): + # Since the x interval is 1 unit, the array 'diff' is the rate of change (slope) + diff = np.ediff1d(percentile_array) + cut_dist = len(percentile_array) / 5 + + median_percentile = np.nanmedian(percentile_array) + if not np.isnan(median_percentile): + cut_percentile = float(math.floor(median_percentile)) + else: + cut_percentile = 0.5 + + found = False + changes = 1.50 + rate_change = np.insert(diff, 0, 0) + # test the rate of change is > than 150% (1.5), if it is + # no result found then lower to 140% (1.4) until 110% (1.1) + while not found and changes >= 1.1: + for idx in range(0, len(rate_change) - 1): + if percentile_array[idx] >= 0.5: + if rate_change[idx] >= changes: + cut_dist = idx + 1 + cut_percentile = math.floor(percentile_array[idx]) + + if 0.5 >= cut_percentile: + if cut_dist > 5: + cut_percentile = 2 + # @<0.5 found and modified + elif 15 < cut_percentile: + if cut_dist > 4: + cut_percentile = 15.5 + found = True + # rate of change found + break + changes = changes - 0.1 + + # if still no result found, lower to 10% (1.1), + # if no result found then default is used + if not found: + if 0.5 >= median_percentile: + cut_dist = 4 + cut_percentile = 0.5 + elif 0.5 < median_percentile <= 5.0: + cut_dist = 4.5 + cut_percentile = math.floor(median_percentile) + elif 5.0 < median_percentile <= 10.0: + cut_dist = 5.5 + cut_percentile = math.floor(median_percentile) + elif 10.0 < median_percentile <= 15: + cut_dist = 6 + cut_percentile = math.floor(median_percentile) + elif 15 < median_percentile: + cut_dist = 5 + cut_percentile = 15.5 + + return CutParams(cut_dist=cut_dist, cut_height=float(cut_percentile)) + + def rate_of_change(self, percentile_array, side): + cut_params = self.derive_cut_params(percentile_array) + + if side == Side.right: + self.right_cut_dist = cut_params.cut_dist + self.right_cut_height = cut_params.cut_height + elif side == Side.left: + self.left_cut_dist = cut_params.cut_dist + self.left_cut_height = cut_params.cut_height + + def multi_ring_buffer(self, df, ring_step, ring_max_dist): + """ + Buffers an input DataFrames geometry with concentric rings. + + Compute with a distance between rings of ring_step and returns + a list of non overlapping buffers + """ + rings = [] + line = df.geometry.iloc[0] + for ring in np.arange(0, ring_max_dist, ring_step): + big_ring = line.buffer(ring_step + ring, single_sided=True, cap_style="flat") + small_ring = line.buffer(ring, single_sided=True, cap_style="flat") + the_ring = big_ring.difference(small_ring) + if not shapely.is_empty(the_ring) and not shapely.is_missing(the_ring) and the_ring.area > 0: + if isinstance(the_ring, (sh_geom.MultiPolygon, shapely.Polygon)): + rings.append(the_ring) + elif isinstance(the_ring, shapely.GeometryCollection): + for geom in the_ring.geoms: + if not isinstance(geom, shapely.LineString): + rings.append(geom) + + return rings + + def prepare_line_buffer(self): + self.buffer_left, self.buffer_right = self.build_line_side_buffers( + self.line.geometry.iloc[0], self.max_line_width + ) + + def build_line_side_buffers(self, line, max_line_width): + buffer_left_1 = line.buffer( + distance=max_line_width + 1, + cap_style=3, + single_sided=True, + ) + + buffer_left_2 = line.buffer( + distance=-1, + cap_style=3, + single_sided=True, + ) + + buffer_left = sh_ops.unary_union([buffer_left_1, buffer_left_2]) + + buffer_right_1 = line.buffer( + distance=-max_line_width - 1, + cap_style=3, + single_sided=True, + ) + buffer_right_2 = line.buffer(distance=1, cap_style=3, single_sided=True) + + buffer_right = sh_ops.unary_union([buffer_right_1, buffer_right_2]) + return buffer_left, buffer_right + + def _get_side_raster_inputs(self, side): + canopy_thresh_ratio = self.canopy_thresh_percentage / 100 + + if side == Side.left: + return SideRasterInputs( + line_buffer=self.buffer_left, + cut_dist=self.left_cut_dist, + canopy_height_thresh=float(self.left_cut_height * canopy_thresh_ratio), + ) + if side == Side.right: + return SideRasterInputs( + line_buffer=self.buffer_right, + cut_dist=self.right_cut_dist, + canopy_height_thresh=float(self.right_cut_height * canopy_thresh_ratio), + ) + raise ValueError(f"Unsupported side: {side}") + + def dyn_canopy_cost_raster(self, side): + side_inputs = self._get_side_raster_inputs(side) + canopy_height_thresh = side_inputs.canopy_height_thresh + if canopy_height_thresh <= 0: + canopy_height_thresh = 0.5 + + try: + clipped_raster, out_meta = sp_common.clip_raster(self.in_chm, side_inputs.line_buffer, 0) + negative_cost_clip, dyn_canopy_ndarray = algo_cost.cost_raster( + clipped_raster, + out_meta, + self.tree_radius, + canopy_height_thresh, + self.max_line_dist, + self.canopy_avoidance, + self.exponent, + ) + + return dyn_canopy_ndarray, negative_cost_clip, out_meta, side_inputs.cut_dist + + except Exception as e: + print(f"dyn_canopy_cost_raster: {e}") + return None + + def _extract_coords(self, feat): + """Extract coordinate list from a geometry (single or multi).""" + coords = [] + if hasattr(feat, "geoms"): + for geom in feat.geoms: + coords.extend(geom.coords) + else: + coords.extend(feat.coords) + return coords + + def process_single_footprint(self, side): + result = self.dyn_canopy_cost_raster(side) + if result is None: + return None + canopy_raster, cost_raster, in_meta, cut_dist = result + + if canopy_raster is None or cost_raster is None or in_meta is None or cut_dist is None: + return None + + if np.isnan(canopy_raster).all(): + print("Canopy raster empty") + return None + + if np.isnan(cost_raster).all(): + print("Cost raster empty") + return None + + in_transform = in_meta["transform"] + feat = self.line.geometry.iloc[0] + segment_list = self._extract_coords(feat) + + result = self.build_corridor_polygon( + canopy_raster, cost_raster, in_transform, cut_dist, feat, segment_list + ) + if result.reason is not None: + print(result.reason) + return result.footprint_gdf + + def build_corridor_polygon(self, canopy_raster, cost_raster, in_transform, cut_dist, feat, segment_list): + cell_size_x = in_transform[0] + cell_size_y = -in_transform[4] + + # Work out the corridor from both end of the centerline + try: + if len(cost_raster.shape) > 2: + cost_raster = np.squeeze(cost_raster, axis=0) + + algo_cost.remove_nan_from_array_refactor(cost_raster) + cost_raster[cost_raster == bt_const.BT_NODATA] = np.inf + + # generate 1m interval points along line + distances = np.arange(0, feat.length, 1) + multipoint_along_line = [feat.interpolate(d) for d in distances] + multipoint_along_line.append(sh_geom.Point(segment_list[-1])) + + # Rasterize points along line + rasterized_points = ras_feat.rasterize( + multipoint_along_line, + out_shape=cost_raster.shape, + transform=in_transform, + fill=0, + all_touched=True, + default_value=1, + ) + points_along_line = np.transpose(np.nonzero(rasterized_points)) + + # Find minimum cost paths through an N-d costs array. + mcp = MCP_Flexible(cost_raster, sampling=(cell_size_x, cell_size_y), fully_connected=True) + mcp_cost_surface, _ = mcp.find_costs(starts=points_along_line) + + # Generate corridor + corridor = np.ma.masked_invalid(mcp_cost_surface) + + # Calculate minimum value of corridor raster + corridor_min = float(np.ma.min(corridor)) if np.ma.min(corridor) is not None else 0.5 + + # normalize corridor raster by deducting corridor_min + corridor_norm = corridor - corridor_min + + # Set minimum as zero and save minimum file + corridor_threshold = cut_dist / cell_size_x + if corridor_threshold < 0: # if no threshold found, use default value + corridor_threshold = bt_const.FP_CORRIDOR_THRESHOLD / cell_size_x + + corridor_thresh = np.ma.where(corridor_norm >= corridor_threshold, 1.0, 0.0) + clean_raster = algo_common.morph_raster( + corridor_thresh, canopy_raster, self.exp_shk_cell, cell_size_x + ) + + # create mask for non-polygon area + mask = np.where(clean_raster == 1, True, False) + if clean_raster.dtype == np.int64: + clean_raster = clean_raster.astype(np.int32) + + # Process: ndarray to shapely Polygon + out_polygon = ras_feat.shapes(clean_raster, mask=mask, transform=in_transform) + + # create a shapely MultiPolygon + multi_polygon = [] + if out_polygon is not None: + try: + for poly, value in out_polygon: + multi_polygon.append(sh_geom.shape(poly)) + except TypeError as e: + return SideFootprintResult(None, f"Invalid polygon output: {e}") + + if not multi_polygon: + return SideFootprintResult(None, "No polygons generated from raster. Returning None.") + + poly = sh_geom.MultiPolygon(multi_polygon) + + # create GeoDataFrame directly from dictionary + footprint_gdf = gpd.GeoDataFrame( + {"corridor_thresh": [corridor_threshold], "geometry": [poly]}, + geometry="geometry", + ) + if self.line.crs: + footprint_gdf = footprint_gdf.set_crs(self.line.crs, allow_override=True) + + if footprint_gdf.empty or footprint_gdf.geometry.isnull().all(): + return SideFootprintResult(None, "Empty GeoDataFrame from process_single_footprint.") + + return SideFootprintResult(footprint_gdf) + + except Exception as e: + return SideFootprintResult(None, "Exception: {}".format(e)) + + +class FootprintCanopyAbsolute: + """Class to compute the footprint of a line based on absolute threshold.""" + + def __init__( + self, + line_seg, + in_chm, + corridor_thresh, + max_ln_width, + exp_shk_cell, + simplify_footprint_polygon=True, + footprint_simplify_length=0.5, + smooth_footprint_polygon=False, + footprint_polygon_smooth_iterations=1, + ): + self.line_seg = line_seg + self.in_chm = in_chm + self.corridor_thresh = corridor_thresh + self.max_ln_width = max_ln_width + self.exp_shk_cell = exp_shk_cell + self.simplify_footprint_polygon = to_bool(simplify_footprint_polygon) + self.footprint_simplify_length = float(footprint_simplify_length) + self.smooth_footprint_polygon = to_bool(smooth_footprint_polygon) + self.footprint_polygon_smooth_iterations = int(footprint_polygon_smooth_iterations) + + self.footprint = None + self.corridor_poly_gpd = None + self.centerline = None + + def compute(self): + """Generate line footprint.""" + prep = self.prepare_inputs() + raster = self.compute_cost_surface(prep["feat"]) + + corridor_thresh = algo_common.corridor_raster( + raster["clip_cost"], + raster["out_meta"], + raster["source"], + raster["destination"], + (raster["cell_size_x"], raster["cell_size_y"]), + prep["corridor_thresh"], + ) + + clean_raster = algo_common.morph_raster( + corridor_thresh, + raster["clip_canopy"], + self.exp_shk_cell, + raster["cell_size_x"], + ) + self.footprint = self.build_candidate_polygon(clean_raster, raster["out_transform"]) + self.footprint = process_footprint_polygon_gdf( + self.footprint, + simplify_footprint_polygon=self.simplify_footprint_polygon, + footprint_simplify_length=self.footprint_simplify_length, + smooth_footprint_polygon=self.smooth_footprint_polygon, + footprint_polygon_smooth_iterations=self.footprint_polygon_smooth_iterations, + ) + copy_line_ids(self.footprint, self.line_seg) + self.postprocess_output( + corridor_thresh, + raster["out_transform"], + prep["line_gpd"], + prep["feat"], + self.exp_shk_cell, + ) + + def prepare_inputs(self): + corridor_thresh = self.corridor_thresh + try: + corridor_thresh = float(corridor_thresh) + if corridor_thresh < 0.0: + corridor_thresh = 3.0 + except ValueError: + corridor_thresh = 3.0 + except Exception: + corridor_thresh = 3.0 + + feat = self.line_seg.geometry[0] + return { + "line_gpd": self.line_seg, + "corridor_thresh": corridor_thresh, + "feat": feat, + } + + def compute_cost_surface(self, feat): + clip_cost, out_meta = sp_common.clip_raster(self.in_chm, feat, self.max_ln_width) + out_transform = out_meta["transform"] + cell_size_x = out_transform[0] + cell_size_y = -out_transform[4] + + clip_cost, clip_canopy = algo_cost.cost_raster(clip_cost, out_meta) + if len(clip_canopy.shape) > 2: + clip_canopy = np.squeeze(clip_canopy, axis=0) + + source = [rowcol(out_transform, feat.coords[0][0], feat.coords[0][1])] + destination = [rowcol(out_transform, feat.coords[-1][0], feat.coords[-1][1])] + + return { + "clip_cost": clip_cost, + "clip_canopy": clip_canopy, + "out_meta": out_meta, + "out_transform": out_transform, + "cell_size_x": cell_size_x, + "cell_size_y": cell_size_y, + "source": source, + "destination": destination, + } + + def build_candidate_polygon(self, clean_raster, out_transform): + mask = np.where(clean_raster == 1, True, False) + if clean_raster.dtype == np.int64: + clean_raster = clean_raster.astype(np.int32) + + out_polygon = ras_feat.shapes(clean_raster, mask=mask, transform=out_transform) + + multi_polygon = [] + for shp, _value in out_polygon: + multi_polygon.append(sh_geom.shape(shp)) + poly = sh_geom.MultiPolygon(multi_polygon) + + crs_str = None + if hasattr(self.line_seg, "crs") and self.line_seg.crs: + if hasattr(self.line_seg.crs, "to_string"): + crs_str = self.line_seg.crs.to_string() + else: + crs_str = str(self.line_seg.crs) + else: + crs_str = "EPSG:4326" + + if not isinstance(poly, (sh_geom.Polygon, sh_geom.MultiPolygon)): + poly = sh_geom.MultiPolygon([poly]) if poly else None + + if not crs_str or not isinstance(crs_str, str) or not crs_str.startswith("EPSG"): + crs_str = "EPSG:4326" + + if poly is not None and isinstance(poly, (sh_geom.Polygon, sh_geom.MultiPolygon)): + geometry_list = [poly] + else: + geometry_list = [] + + footprint = gpd.GeoDataFrame({"geometry": geometry_list}) + footprint.set_crs(crs_str, inplace=True) + return footprint + + def postprocess_output(self, corridor_thresh, out_transform, line_gpd, feat, exp_shk_cell=0): + import beratools.modules.mapping.algo_centerline as algo_cl + + corridor_poly_gpd = algo_cl.find_corridor_polygon( + corridor_thresh, out_transform, line_gpd, exp_shk_cell=exp_shk_cell + ) + centerline, _status = algo_cl.find_centerline(corridor_poly_gpd.geometry.iloc[0], feat) + + self.corridor_poly_gpd = corridor_poly_gpd + self.centerline = centerline + + +def process_single_absolute_line(line_footprint): + """Compute one absolute line footprint.""" + try: + line_footprint.compute() + except Exception as err: + print(f"process_single_absolute_line: exception {err}") + return line_footprint + + +def generate_absolute_line_class_list( + in_line, + in_chm, + corridor_thresh, + max_ln_width, + exp_shk_cell, + simplify_footprint_polygon=True, + footprint_simplify_length=0.5, + smooth_footprint_polygon=False, + footprint_polygon_smooth_iterations=1, + in_layer=None, +): + """Build absolute footprint work list.""" + line_classes = [] + line_list = algo_common.prepare_lines_gdf(in_line, in_layer, proc_segments=False) + + for line in line_list: + line_classes.append( + FootprintCanopyAbsolute( + line, + in_chm, + corridor_thresh, + max_ln_width, + exp_shk_cell, + simplify_footprint_polygon=simplify_footprint_polygon, + footprint_simplify_length=footprint_simplify_length, + smooth_footprint_polygon=smooth_footprint_polygon, + footprint_polygon_smooth_iterations=footprint_polygon_smooth_iterations, + ) + ) + + return line_classes diff --git a/beratools/modules/mapping/algo_centerline.py b/beratools/modules/mapping/algo_centerline.py new file mode 100644 index 0000000..b56b623 --- /dev/null +++ b/beratools/modules/mapping/algo_centerline.py @@ -0,0 +1,1192 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + This file is intended to be hosting algorithms and utility functions/classes + for centerline tool. +""" + +import enum +import logging +from dataclasses import dataclass +from itertools import compress + +import geopandas as gpd +import numpy as np +import pandas as pd +import rasterio +import shapely +import shapely.geometry as sh_geom +import shapely.ops as sh_ops +from scipy import ndimage + +import beratools.core.constants as bt_const +import beratools.core.tool_base as bt_base +import beratools.modules.mapping.algo_astar as algo_astar + +# Lazy-imported in find_centerline() to avoid ~5s startup cost +# from beratools.external.polygon_centerline import get_centerline +import beratools.modules.mapping.algo_common as algo_common +import beratools.modules.mapping.algo_cost as algo_cost +import beratools.modules.mapping.algo_dijkstra as bt_dijkstra +import beratools.modules.mapping.algo_geometry as algo_geometry +import beratools.modules.mapping.alt_spatial_common as alt_sp_common +import beratools.modules.mapping.tool_geo_simplify as tool_geo_simplify +import beratools.utility.spatial_common as sp_common +from beratools.utility.tool_args import to_bool + +LOGGER_NAME = "centerline" +logger = logging.getLogger(LOGGER_NAME) + + + +class CenterlineParams(float, enum.Enum): + """ + Parameters for centerline generation. + + These parameters are used to control the behavior of centerline generation + and should be adjusted based on the specific requirements of the application. + """ + + BUFFER_CLIP = 5.0 + SEGMENTIZE_LENGTH = 1.0 + SIMPLIFY_LENGTH = 0.5 + SMOOTH_SIGMA = 0.8 + CLEANUP_POLYGON_BY_AREA = 1.0 + ENDPOINT_ANCHOR_TOL = 1e-9 + GUIDED_FALLBACK_MAX_SNAP = 2.0 + GUIDE_SAMPLE_INTERVAL = 10.0 + MIN_GUIDE_LENGTH_RATIO = 0.94 + MAX_SHORTCUT_MEDIAN_DISTANCE = 2.0 + + +@enum.unique +class CenterlineStatus(enum.IntEnum): + """ + Status of centerline generation. + + This enum is used to indicate the status of centerline generation. + It can be used to track the success or failure of the centerline generation process. + + """ + + SUCCESS = 1 + FAILED = 2 + REGENERATE_SUCCESS = 3 + REGENERATE_FAILED = 4 + CENTERLINE_FAILED_LCP_FALLBACK = 5 + LCP_FAILED_SEED_FALLBACK = 6 + THIN_POLYGON_STABILIZED_SUCCESS = 7 + ABSOLUTE_FOOTPRINT_SUCCESS = 8 + +@dataclass(frozen=True) +class EndPointAnchorResult: + anchored: bool + reversed_match: bool + start_dist: float + end_dist: float + + +def centerline_is_valid(centerline, input_line,cid=None): + """ + Check if centerline is valid. + + Args: + centerline (_type_): _description_ + input_line (sh_geom.LineString): Seed line or least cost path. + Only two end points are used. + + Returns: + bool: True if line is valid + + """ + if not centerline: + if cid: + logger.info(f"{cid} validation failed: centerline is None") + return False + + length_check = centerline.length < input_line.length / 2 + anchor_result = _is_endpoint_anchored( + centerline, + input_line, + tol=bt_const.BT_EPSILON,) + + endpoint_check = not anchor_result.anchored + + if length_check or endpoint_check: + # logger.info( + # f"{cid} validation failed:" + # f" anchored={anchor_result.anchored}, " + # f" reversed={anchor_result.reversed_match}, " + # f" start_dist={anchor_result.start_dist:.6f}, " + # f" end_dist={anchor_result.end_dist:.6f}") + return False + + if _looks_like_shortcut(centerline, input_line, cid=cid): + return False + + return True + + +def _looks_like_shortcut(centerline, input_line, cid=None): + if not centerline or not input_line or input_line.length <= 0: + return False + + length_ratio = centerline.length / input_line.length + + if length_ratio >= CenterlineParams.MIN_GUIDE_LENGTH_RATIO: + return False + + distances = _sampled_line_distances( + input_line, + centerline, + CenterlineParams.GUIDE_SAMPLE_INTERVAL, + ) + + if not distances: + return False + + median_distance = float(np.median(distances)) + + shortcut = ( + median_distance > + CenterlineParams.MAX_SHORTCUT_MEDIAN_DISTANCE + ) + + # if cid: + # logger.file_only( + # f"{cid} shortcut check:" + # f" ratio={length_ratio:.3f}, " + # f" median_dist={median_distance:.3f}, " + # f" threshold_ratio={CenterlineParams.MIN_GUIDE_LENGTH_RATIO.value}, " + # f" threshold_dist={CenterlineParams.MAX_SHORTCUT_MEDIAN_DISTANCE.value}, " + # f" shortcut={shortcut}" + # ) + + return shortcut + +def _sampled_line_distances(source_line, target_line, interval): + if interval <= 0: + interval = 10.0 + sample_count = max(int(np.ceil(source_line.length / interval)), 1) + distances = [] + for i in range(sample_count + 1): + distance_along = min(i * interval, source_line.length) + distances.append(source_line.interpolate(distance_along).distance(target_line)) + return distances + + +def snap_end_to_end(in_line, line_reference, max_snap_dist=None,cid=None): + """ + Snap centerline ends to opposite seedline endpoints. + + Prevents: + start -> seed_start + end -> seed_start + + which creates a ring. + """ + if in_line is None or in_line.is_empty: + return line_reference + + coords = list(in_line.coords) + + if len(coords) < 2: + return line_reference + + cl_start = sh_geom.Point(coords[0]) + cl_end = sh_geom.Point(coords[-1]) + + seed_coords = list(line_reference.coords) + + seed_start = sh_geom.Point(seed_coords[0]) + seed_end = sh_geom.Point(seed_coords[-1]) + + # + # Evaluate both possible assignments + # + cost_forward = (cl_start.distance(seed_start) + + cl_end.distance(seed_end)) + + cost_reverse = (cl_start.distance(seed_end) + + cl_end.distance(seed_start)) + + if abs(cost_forward - cost_reverse) < 1.0: + + seed_dir = np.array([seed_end.x - seed_start.x, + seed_end.y - seed_start.y,]) + + center_dir = np.array([cl_end.x - cl_start.x, + cl_end.y - cl_start.y,]) + + forward = np.dot(seed_dir, center_dir) >= 0 + + elif cost_forward < cost_reverse: + + forward = True + + else: + + forward = False + + if forward: + snap_start, snap_end = seed_start, seed_end + else: + snap_start, snap_end = seed_end, seed_start + + # Only snap ends within max_snap_dist of their target + if max_snap_dist is None or cl_start.distance(snap_start) <= max_snap_dist: + coords[0] = snap_start.coords[0] + if max_snap_dist is None or cl_end.distance(snap_end) <= max_snap_dist: + coords[-1] = snap_end.coords[0] + # + # Safety check + # + if coords[0] == coords[-1]: + # keep original geometry rather than + # creating a ring + return in_line + + return sh_geom.LineString(coords) + +def _is_endpoint_anchored( + centerline, + seed_line, + tol=CenterlineParams.ENDPOINT_ANCHOR_TOL, +) -> EndPointAnchorResult: + """ + Check whether centerline endpoints match seed endpoints. + + Returns + ------- + EndPointAnchorResult + anchored : endpoints match + reversed_match : centerline orientation is reversed + start_dist : endpoint distance used for evaluation + end_dist : endpoint distance used for evaluation + """ + default_return = EndPointAnchorResult( + False, + False, + float("inf"), + float("inf"), + ) + if centerline is None or seed_line is None: + return default_return + + if not isinstance(centerline, sh_geom.LineString): + return default_return + + if not isinstance(seed_line, sh_geom.LineString): + return default_return + + cl_coords = list(centerline.coords) + seed_coords = list(seed_line.coords) + + if len(cl_coords) <=1 or len(seed_coords) <=1: + return default_return + + cl_start = sh_geom.Point(cl_coords[0]) + cl_end = sh_geom.Point(cl_coords[-1]) + + seed_start = sh_geom.Point(seed_coords[0]) + seed_end = sh_geom.Point(seed_coords[-1]) + + direct_start = cl_start.distance(seed_start) + direct_end = cl_end.distance(seed_end) + + reverse_start = cl_start.distance(seed_end) + reverse_end = cl_end.distance(seed_start) + + direct = (direct_start <= tol and direct_end <= tol) + + reversed_match = (reverse_start <= tol and reverse_end <= tol) + + if direct: + return EndPointAnchorResult( + anchored=True, + reversed_match=False, + start_dist=direct_start, + end_dist=direct_end,) + + if reversed_match: + return EndPointAnchorResult( + anchored=True, + reversed_match=True, + start_dist=reverse_start, + end_dist=reverse_end,) + + if (direct_start + direct_end) <= ( + reverse_start + reverse_end): + return EndPointAnchorResult( + anchored=False, + reversed_match=False, + start_dist=direct_start, + end_dist=direct_end, + ) + + return EndPointAnchorResult( + anchored=False, + reversed_match=True, + start_dist=reverse_start, + end_dist=reverse_end, + ) + + +def _trim_and_snap_centerline(centerline, input_line, max_snap_dist=None): + cl_coords = list(centerline.coords) + + head_buffer = sh_geom.Point(cl_coords[0]).buffer(CenterlineParams.BUFFER_CLIP) + centerline = centerline.difference(head_buffer) + + end_buffer = sh_geom.Point(cl_coords[-1]).buffer(CenterlineParams.BUFFER_CLIP) + centerline = centerline.difference(end_buffer) + + if not centerline: + return None + + try: + if centerline.is_empty: + return None + except Exception as e: + logger.info(f"find_centerline: {e}") + + return snap_end_to_end(centerline, input_line, max_snap_dist=max_snap_dist) + + +def _extract_centerline_from_polygon( + poly, + src_geom, + dst_geom, + guided_strategy, + endpoint_mode='strict', + endpoint_candidate_k=5, + cell_size=1.0, + corridor_id="UNKNOWN", + guide_line=None, +): + from beratools.external.polygon_centerline import get_centerline + from beratools.external.polygon_centerline._src import get_last_centerline_info + + _extract_centerline_from_polygon.last_info = {} + centerline = get_centerline( + poly, + segmentize_maxlen=1, + max_points=3000, + simplification=0.05, + smooth_sigma=CenterlineParams.SMOOTH_SIGMA, + max_paths=1, + src_geom=src_geom, + dst_geom=dst_geom, + guided_strategy=guided_strategy, + endpoint_mode=endpoint_mode, + endpoint_candidate_k=endpoint_candidate_k, + cell_size=cell_size, + corridor_id=corridor_id, + input_line=guide_line, + ) + _extract_centerline_from_polygon.last_info = get_last_centerline_info() + return centerline + + +_extract_centerline_from_polygon.last_info = {} + + +def _last_extraction_used_stabilized_voronoi(): + info = getattr(_extract_centerline_from_polygon, "last_info", {}) or {} + return info.get("qhull_retry") not in {None, "none"} or bool(info.get("polygon_stabilized")) + + +def find_centerline(poly, input_line, + guided_strategy="main_route", + endpoint_mode=None, + endpoint_candidate_k=8, + allow_regeneration=True, + cell_size=1.0, + corridor_id="UNKNOWN", + ): + """ + Find centerline from polygon and input line. + + Args: + poly : sh_geom.Polygon + input_line ( sh_geom.LineString): Least cost path or seed line + + Returns: + centerline (sh_geom.LineString): Centerline + status (CenterlineStatus): Status of centerline generation + + """ + cid = f"[CID={corridor_id}] " if corridor_id else "[CID=UNKNOWN] " + default_return = input_line, CenterlineStatus.FAILED + valid_guided_strategies = {"main_route", "pairwise", "virtual_nodes", "direct_insert"} + ordered_valid_guided_strategies = ["pairwise", "virtual_nodes", "direct_insert", "main_route"] + if guided_strategy not in valid_guided_strategies: + raise ValueError("guided_strategy must be one of {}".format(sorted(valid_guided_strategies))) + effective_strategy = guided_strategy + + if not poly: + logger.info(cid+ + "find_centerline: No polygon found") + return default_return + + poly = shapely.segmentize(poly, max_segment_length=CenterlineParams.SEGMENTIZE_LENGTH) + + # buffer to reduce MultiPolygons + poly = poly.buffer(bt_const.SMALL_BUFFER) + if type(poly) is sh_geom.MultiPolygon: + logger.info("sh_geom.MultiPolygon encountered, skip.") + return default_return + + exterior_pts = list(poly.exterior.coords) + + if bt_const.CenterlineFlags.DELETE_HOLES: + poly = sh_geom.Polygon(exterior_pts) + if bt_const.CenterlineFlags.SIMPLIFY_POLYGON: + poly = poly.simplify(CenterlineParams.SIMPLIFY_LENGTH) + + line_coords = list(input_line.coords) + + src_geom = None + dst_geom = None + if guided_strategy in {"pairwise", "virtual_nodes", "direct_insert"}: + src_geom = sh_geom.Point(line_coords[0]) + dst_geom = sh_geom.Point(line_coords[-1]) + start_covered = poly.buffer(0.5).covers(src_geom) + end_covered = poly.buffer(0.5).covers(dst_geom) + buffer_dist=-0.5 + inner_poly=poly + # to prevent buffering from shrinking the polygon but use min buffer + for buffer_dist in np.arange(-0.5,0.00,0.05): + try_buffer = poly.buffer(buffer_dist) + if try_buffer.is_empty: + break + if try_buffer.area 1: + logger.info(" Multiple centerline segments detected, no further processing.") + return centerline, status # TODO: inspect + elif len(centerline.geoms) == 1: + centerline = centerline.geoms[0] + else: + return default_return + + needs_trim_snap = effective_strategy == "main_route" + if effective_strategy in {"pairwise", "virtual_nodes"}: + result = _is_endpoint_anchored( + centerline, + input_line, + tol=CenterlineParams.ENDPOINT_ANCHOR_TOL, + ) + needs_trim_snap = not result.anchored + if needs_trim_snap: + max_snap_dist = None + if effective_strategy in {"pairwise", "virtual_nodes"}: + max_snap_dist = CenterlineParams.GUIDED_FALLBACK_MAX_SNAP + centerline = _trim_and_snap_centerline( + centerline, + input_line, + max_snap_dist=max_snap_dist, + ) + if not centerline: + return default_return + + # Check centerline. If valid, regenerate by splitting polygon into two halves. + if allow_regeneration and not centerline_is_valid(centerline, input_line,cid=cid): + try: + logger.info(f"{cid} " + f"Regenerating line ...") + centerline = regenerate_centerline(poly, input_line,corridor_id) + logger.info( + f"{cid}" + f" COMPUTE_RESULT regenerate_centerline " + f"status={status.name} " + f"has_centerline={centerline is not None}" + ) + if not centerline: + return input_line, CenterlineStatus.REGENERATE_FAILED + try: + if centerline.is_empty: + return input_line, CenterlineStatus.REGENERATE_FAILED + except Exception as e: + logger.info(f"find_centerline: {e}") + return input_line, CenterlineStatus.REGENERATE_FAILED + return centerline, CenterlineStatus.REGENERATE_SUCCESS + except Exception as e: + logger.info(f"find_centerline: {e}") + return input_line, CenterlineStatus.REGENERATE_FAILED + logger.info( + f"{cid}" + f" FIND_CENTERLINE_RETURN " + f"status={status.name} " + f"length={centerline.length:.2f}" + ) + + return centerline, status + + +def find_corridor_polygon(corridor_thresh, in_transform, + line_gpd, exp_shk_cell=0.,cid=None): + # Threshold corridor raster used for generating centerline + corridor_thresh_cl = algo_common.corridor_threshold_to_mask(corridor_thresh) + labels_before, n_before = ndimage.label(corridor_thresh_cl) + corridor_thresh_cl = algo_common.generalize_binary_mask(corridor_thresh_cl, exp_shk_cell) + labels_after, n_after = ndimage.label(corridor_thresh_cl) + + sizes = np.bincount(labels_after.ravel())[1:] + + logger.info( + f"{cid} " + f"mask_components before-after: " + f"{n_before}->{n_after}" + f" raster_cc={n_after} " + f"largest={sizes.max() if len(sizes) else 0}" + ) + if corridor_thresh_cl.dtype == np.int64: + corridor_thresh_cl = corridor_thresh_cl.astype(np.int32) + + corridor_mask = np.where(1 == corridor_thresh_cl, True, False) + poly_generator = rasterio.features.shapes(corridor_thresh_cl, mask=corridor_mask, transform=in_transform) + corridor_polygon = [] + + try: + for poly, value in poly_generator: + if sh_geom.shape(poly).area > 1: + corridor_polygon.append(sh_geom.shape(poly)) + except Exception as e: + logger.info(f"find_corridor_polygon: {e}") + + if corridor_polygon: + corridor_polygon = sh_ops.unary_union(corridor_polygon) + if type(corridor_polygon) is sh_geom.MultiPolygon: + largest_area=max([geom.area for geom in corridor_polygon.geoms]) + parts = [ + p for p in corridor_polygon.geoms + if p.area >=largest_area*0.01 + ] + if len(parts)>=1: + # poly_list = shapely.get_parts(corridor_polygon) + merge_poly = parts[0] + for i in range(1, len(parts)): + p1, p2 = sh_ops.nearest_points( + merge_poly, + parts[i]) + bridge = sh_geom.LineString([p1, p2]).buffer(3 if exp_shk_cell==0 else exp_shk_cell*3) + merged = shapely.union(merge_poly, bridge) + merge_poly = shapely.union(merged, parts[i]) + corridor_polygon = merge_poly + elif len(parts) == 1: + corridor_polygon = sh_ops.unary_union(parts) + else: + corridor_polygon = None + + else: + corridor_polygon = None + + # create GeoDataFrame for centerline + corridor_poly_gpd = gpd.GeoDataFrame.copy(line_gpd) + corridor_poly_gpd.geometry = [corridor_polygon] + + return corridor_poly_gpd + + +def process_single_centerline(row_and_path): + """ + Find centerline. + + Args: + row_and_path (list of row (gdf and lc_path)): and least cost path + first is GeoPandas row, second is input line, (least cost path) + + Returns: + row: GeoPandas row with centerline + + """ + row = row_and_path[0] + lc_path = row_and_path[1] + corridor_id = f"{row['OLnFID'].iloc[0]}_{row['OLnSEG'].iloc[0]}" + + poly = row.geometry.iloc[0] + centerline, status = find_centerline(poly, lc_path, + guided_strategy="pairwise", + corridor_id=corridor_id,) + row["centerline"] = centerline + + return row + + +def find_centerlines(poly_gpd, line_seg, processes): + centerline_gpd = [] + rows_and_paths = [] + + try: + for i in poly_gpd.index: + row = poly_gpd.loc[[i]] + if "OLnSEG" in line_seg.columns: + line_id, Seg_id = row["OLnFID"].iloc[0], row["OLnSEG"].iloc[0] + lc_path = line_seg.loc[(line_seg.OLnFID == line_id) & (line_seg.OLnSEG == Seg_id)][ + "geometry" + ].iloc[0] + else: + line_id = row["OLnFID"].iloc[0] + lc_path = line_seg.loc[(line_seg.OLnFID == line_id)]["geometry"].iloc[0] + + rows_and_paths.append((row, lc_path)) + except Exception as e: + logger.info(f"find_centerlines: {e}") + + centerline_gpd = bt_base.execute_multiprocessing( + process_single_centerline, rows_and_paths, "find_centerlines", processes, 1 + ) + return pd.concat(centerline_gpd) + + +def regenerate_centerline(poly, input_line,corridor_id="UNKNOWN", + cell_size=1.0, + guided_strategy="pairwise", + endpoint_mode="strict", + endpoint_candidate_k=8, + ): + """ + Regenerates centerline when initial poly is not valid. + Split the corridor polygon, extract each half independently, + and merge the two centerlines. + + Args: + input_line (sh_geom.LineString): Seed line or least cost path. + Only two end points will be used + + Returns: + sh_geom.MultiLineString + + """ + cid = (f"[CID={corridor_id}] "if corridor_id else "[CID=UNKNOWN] ") + half_line_length = input_line.length / 2 + split_pt=input_line.interpolate(half_line_length) + line_1 = sh_ops.substring(input_line, start_dist=0.0, end_dist=half_line_length) + line_2 = sh_ops.substring(input_line, start_dist=half_line_length, end_dist=input_line.length) + + pts = shapely.force_2d( + [ + sh_geom.Point(list(input_line.coords)[0]), + split_pt, + sh_geom.Point(list(input_line.coords)[-1]), + ] + ) + perp = algo_common.generate_perpendicular_line_precise(pts) + + # sh_geom.MultiPolygon is rare, but need to be dealt with + # remove polygon of area less than CenterlineParams.CLEANUP_POLYGON_BY_AREA + poly = poly.buffer(bt_const.SMALL_BUFFER) + if type(poly) is sh_geom.MultiPolygon: + poly_geoms = list(poly.geoms) + poly_valid = [True] * len(poly_geoms) + for i, item in enumerate(poly_geoms): + if item.area < CenterlineParams.CLEANUP_POLYGON_BY_AREA: + poly_valid[i] = False + + poly_geoms = list(compress(poly_geoms, poly_valid)) + if len(poly_geoms) != 1: # still multi polygon + logger.info("regenerate_centerline: Multi or none polygon found, pass.") + + poly = sh_geom.Polygon(poly_geoms[0]) + + poly_exterior = sh_geom.Polygon(poly.buffer(bt_const.SMALL_BUFFER).exterior) + + poly_split = sh_ops.split(poly_exterior, perp) + + if len(poly_split.geoms) < 2: + logger.file_only(cid+ + "regenerate_centerline: polygon sh_ops.split failed, pass.") + return None + + poly_1 = poly_split.geoms[0] + poly_2 = poly_split.geoms[1] + + # find polygon and line pairs + pair_line_1 = line_1 + pair_line_2 = line_2 + if not poly_1.intersects(line_1): + pair_line_1 = line_2 + pair_line_2 = line_1 + elif poly_1.intersection(line_1).length < line_1.length / 3: + pair_line_1 = line_2 + pair_line_2 = line_1 + + + center_line_1 = find_centerline(poly_1, pair_line_1,corridor_id=corridor_id,allow_regeneration=False,) + center_line_2 = find_centerline(poly_2, pair_line_2,corridor_id=corridor_id,allow_regeneration=False,) + + center_line_1 = center_line_1[0] + center_line_2 = center_line_2[0] + + if not center_line_1 or not center_line_2: + logger.info("Regenerate line: centerline is None") + return None + + try: + if center_line_1.is_empty or center_line_2.is_empty: + logger.info("Regenerate line: centerline is empty") + return None + except Exception as e: + logger.info(f"regenerate_centerline: {e}") + + center_line_1 = orient_to_split(center_line_1, + split_pt,want_end_at_split=True) + + center_line_2 = orient_to_split(center_line_2, + split_pt,want_end_at_split=False) + + result=algo_common._safe_linemerge(sh_geom.MultiLineString([center_line_1, center_line_2])) + + if isinstance(result, sh_geom.MultiLineString): + return None + return result + +class SeedLine: + """Class to store seed line and least cost path.""" + + def __init__( + self, + line_gdf, + ras_file, + proc_segments, + line_radius, + guided_strategy="main_route", + centerline_method=bt_const.CENTERLINE_METHOD.value, + lcp_simplify_enabled=False, + lcp_simplify_diameter=10.0, + lcp_smooth_enabled=False, + lcp_smooth_iterations=1, + chm_mode=bt_const.CENTERLINE_CHM_MODE.value, + chm_buffer_width=5.0, + chm_buffer_multiplier=0.5, + astar_corridor_line_bias_weight=0.1, + astar_corridor_distance_penalty_weight=0.2, + corridor_simplify_polygon=False, + corridor_simplify_length=0.5, + corridor_smooth_polygon=False, + corridor_polygon_smooth_iterations=1, + ): + self.line = line_gdf + self.raster = ras_file + self.line_radius = line_radius + self.guided_strategy = guided_strategy + self.centerline_method = centerline_method + self.lcp_simplify_enabled = to_bool(lcp_simplify_enabled) + self.lcp_simplify_diameter = float(lcp_simplify_diameter) + self.lcp_smooth_enabled = to_bool(lcp_smooth_enabled) + self.lcp_smooth_iterations = max(int(lcp_smooth_iterations), 0) + if isinstance(chm_mode, bt_const.CenterlineChmMode): + chm_mode = chm_mode.value + if chm_mode not in {mode.value for mode in bt_const.CenterlineChmMode}: + valid_modes = [mode.value for mode in bt_const.CenterlineChmMode] + raise ValueError("chm_mode must be one of {}".format(valid_modes)) + self.chm_mode = chm_mode + self.chm_buffer_width = float(chm_buffer_width) + self.chm_buffer_multiplier = float(chm_buffer_multiplier) + if self.chm_buffer_width < 0.0: + raise ValueError("chm_buffer_width must be greater than or equal to zero") + if not 0.0 <= self.chm_buffer_multiplier <= 1.0: + raise ValueError("chm_buffer_multiplier must be between zero and one") + self.astar_corridor_line_bias_weight = max(float(astar_corridor_line_bias_weight), 0.0) + self.astar_corridor_distance_penalty_weight = max(float(astar_corridor_distance_penalty_weight), 0.0) + self.corridor_simplify_polygon = to_bool(corridor_simplify_polygon) + self.corridor_simplify_length = max(float(corridor_simplify_length), 0.0) + self.corridor_smooth_polygon = to_bool(corridor_smooth_polygon) + self.corridor_polygon_smooth_iterations = max(int(corridor_polygon_smooth_iterations), 0) + self.lc_path = None + self.centerline = None + self.corridor_poly_gpd = None + self.endpoint_mode="strict" + self.endpoint_candidate_k=5 + self.cell_size=1.0 + self.cid = "UNKNOWN" + self.tree_radius = 2.5 + + def compute(self): + line = self.line.geometry[0] + line_radius = self.line_radius + in_raster = self.raster + seed_line = line # LineString + ## corridor_id is used to identify features in the log file. + corridor_id = ( + f"{self.line['OLnFID'].iloc[0]}_" + f"{self.line['OLnSEG'].iloc[0]}" + ) + cid=f"[CID:{corridor_id}] " + self.cid=cid + try: + ras_clip, out_meta,*tree_gaps = self._clip_chm(in_raster, seed_line, line_radius) + if self.chm_mode == bt_const.CenterlineChmMode.BUFFER.value: + ras_clip = algo_cost.reduce_chm_in_line_buffer( + ras_clip, + out_meta, + seed_line, + self.chm_buffer_width, + self.chm_buffer_multiplier, + ) + if self.chm_mode==bt_const.CenterlineChmMode.ALT.value: + cost_clip, _ = algo_cost.alt_cost_raster(ras_clip, out_meta,tree_gaps[0]) + else: + cost_clip, _ = algo_cost.cost_raster(ras_clip, out_meta) + # rest CHM mode to current mode for the rest of the code. + self.chm_mode = bt_const.CenterlineChmMode.CURRENT.value + except Exception as e: + logger.info(f"{self.cid}:{e}") + self._set_fallback_outputs( + seed_line, + seed_line, + CenterlineStatus.LCP_FAILED_SEED_FALLBACK, + corridor_geometry=seed_line.buffer(line_radius), + ) + return + + lc_path = line + + try: + if self.centerline_method == bt_const.CenterlineMethod.ASTAR.value: + lc_path = algo_astar.find_least_cost_path_astar_closest_line( + cost_clip, out_meta, seed_line, cid=self.cid + ) + if lc_path is None: + logger.warning( + f"{self.cid} A* returned None" + ) + else: + logger.warning( + f"{self.cid} " + f"A* vertices={len(list(lc_path.coords))} " + f"length={lc_path.length:.2f}" + ) + elif bt_const.CenterlineFlags.USE_SKIMAGE_GRAPH: + lc_path = bt_dijkstra.find_least_cost_path_skimage(cost_clip, out_meta, seed_line) + else: + lc_path = bt_dijkstra.find_least_cost_path(cost_clip, out_meta, seed_line) + except Exception as e: + logger.info(f"{self.cid}:{e}") + self._set_fallback_outputs( + seed_line, + seed_line, + CenterlineStatus.LCP_FAILED_SEED_FALLBACK, + corridor_geometry=seed_line.buffer(line_radius), + ) + return + + if lc_path: + lc_path_coords = lc_path.coords + else: + lc_path_coords = [] + + # search for centerline + if len(lc_path_coords) < 2: + logger.info(self.cid+"No least cost path detected, use input line.") + self._set_fallback_outputs( + seed_line, + seed_line, + CenterlineStatus.LCP_FAILED_SEED_FALLBACK, + corridor_geometry=seed_line.buffer(line_radius), + ) + return + + # get corridor raster + lc_path = sh_geom.LineString(lc_path_coords) + lc_path = self._postprocess_lcp(lc_path, out_meta.get("crs")) + lc_path_coords = list(lc_path.coords) + try: + ras_clip, out_meta = self._clip_chm(in_raster, lc_path, line_radius * 0.9) + cost_clip, _ = algo_cost.cost_raster(ras_clip, out_meta) + + out_transform = out_meta["transform"] + transformer = rasterio.transform.AffineTransformer(out_transform) + cell_size = (out_transform[0], -out_transform[4]) + + x1, y1 = lc_path_coords[0] + x2, y2 = lc_path_coords[-1] + source = [transformer.rowcol(x1, y1)] + destination = [transformer.rowcol(x2, y2)] + if self.centerline_method == bt_const.CenterlineMethod.ASTAR.value: + corridor_thresh_cl, _details = algo_astar.astar_accumulation_corridor_raster( + cost_clip, + out_meta, + lc_path, + corridor_threshold=bt_const.FP_CORRIDOR_THRESHOLD, + line_bias_weight=self.astar_corridor_line_bias_weight, + distance_penalty_weight=self.astar_corridor_distance_penalty_weight, + ) + else: + corridor_thresh_cl = algo_common.corridor_raster( + cost_clip, + out_meta, + source, + destination, + cell_size, + bt_const.FP_CORRIDOR_THRESHOLD, + ) + except Exception as e: + logger.info(f"Corridor error {cid}:{e}, fall back lcp buffer line_radius") + self._set_fallback_outputs( + lc_path, + lc_path, + CenterlineStatus.CENTERLINE_FAILED_LCP_FALLBACK, + corridor_geometry=lc_path.buffer(line_radius), + ) + return + + # find contiguous corridor polygon and extract centerline + try: + df = gpd.GeoDataFrame(geometry=[seed_line], crs=out_meta["crs"]) + corridor_poly_gpd = find_corridor_polygon( + corridor_thresh_cl, out_transform, df, exp_shk_cell=self.cell_size, cid=cid + ) + corridor_poly_gpd = self._postprocess_corridor_polygon(corridor_poly_gpd) + center_line, status = find_centerline( + corridor_poly_gpd.geometry.iloc[0], + lc_path, + guided_strategy=self.guided_strategy, + corridor_id=corridor_id + ) + logger.warning( + f"{cid}" + f" COMPUTE_RESULT " + f"status={status.name} " + f"has_centerline={center_line is not None}" + ) + except Exception as e: + logger.info(f"{cid}:{e}") + corridor_poly_gpd = self.line.copy() + corridor_poly_gpd.geometry = [lc_path.buffer(line_radius)] + center_line = lc_path + status = CenterlineStatus.CENTERLINE_FAILED_LCP_FALLBACK + + status = CenterlineStatus(status) + if status in {CenterlineStatus.FAILED, CenterlineStatus.REGENERATE_FAILED}: + corridor_geom = corridor_poly_gpd.geometry.iloc[0] + if pd.notna(corridor_geom) and not corridor_geom.is_empty: + estimated_width = corridor_poly_gpd.geometry.iloc[0].area / max(lc_path.length, 1e-6) + else: + estimated_width = line_radius/2 + buffer_width = min(line_radius,estimated_width / 2.0) + absolute_footprint = lc_path.buffer(buffer_width) + try: + absolute_centerline, absolute_status = find_centerline( + absolute_footprint, + lc_path, + guided_strategy=self.guided_strategy, + corridor_id=corridor_id, + allow_regeneration=False,) + logger.info( + f"{cid}" + f" COMPUTE_RESULT absolute_footprint " + f"status={status.name} " + f"has_centerline={center_line is not None}" + ) + absolute_status = CenterlineStatus(absolute_status) + if absolute_status not in {CenterlineStatus.FAILED, CenterlineStatus.REGENERATE_FAILED}: + center_line = absolute_centerline + status = CenterlineStatus.ABSOLUTE_FOOTPRINT_SUCCESS + corridor_poly_gpd = self.line.copy() + corridor_poly_gpd.geometry = [absolute_footprint] + + else: + status = CenterlineStatus.CENTERLINE_FAILED_LCP_FALLBACK + center_line = lc_path + except Exception as e: + logger.info(f"{cid}:{e}") + status = CenterlineStatus.CENTERLINE_FAILED_LCP_FALLBACK + center_line = lc_path + + self.line["cl_status"] = status.value + self.line["cl_status_name"] = status.name + + self.lc_path = self.line.copy() + self.lc_path.geometry = [lc_path] + self.lc_path["centerline_method"] = self.centerline_method + self.lc_path["lcp_simplified"] = bool(self.lcp_simplify_enabled and self.lcp_simplify_diameter > 0) + self.lc_path["lcp_smoothed"] = bool(self.lcp_smooth_enabled and self.lcp_smooth_iterations > 0) + + self.centerline = self.line.copy() + self.centerline.geometry = [center_line] + self.centerline["centerline_method"] = self.centerline_method + self.centerline["OLnFID"] = self.lc_path["OLnFID"] + self.centerline["OLnSEG"] = self.lc_path["OLnSEG"] + + self.corridor_poly_gpd = corridor_poly_gpd + self.corridor_poly_gpd["centerline_method"] = self.centerline_method + self.corridor_poly_gpd["cl_status"] = status.value + self.corridor_poly_gpd["cl_status_name"] = status.name + self.corridor_poly_gpd["OLnFID"] = self.lc_path["OLnFID"] + self.corridor_poly_gpd["OLnSEG"] = self.lc_path["OLnSEG"] + for field in (algo_common.SOURCE_ROW_FIELD, algo_common.SOURCE_SEG_FIELD): + if field in self.lc_path.columns: + self.corridor_poly_gpd[field] = self.lc_path[field] + + def _set_fallback_outputs(self, lc_path, centerline, status, corridor_geometry=None): + status = CenterlineStatus(status) + self.line["cl_status"] = status.value + self.line["cl_status_name"] = status.name + + self.lc_path = self.line.copy() + self.lc_path.geometry = [lc_path] + self.lc_path["centerline_method"] = self.centerline_method + self.lc_path["lcp_simplified"] = False + self.lc_path["lcp_smoothed"] = False + + self.centerline = self.line.copy() + self.centerline.geometry = [centerline] + self.centerline["centerline_method"] = self.centerline_method + self.centerline["OLnFID"] = self.lc_path["OLnFID"] + self.centerline["OLnSEG"] = self.lc_path["OLnSEG"] + + self.corridor_poly_gpd = self.line.copy() + self.corridor_poly_gpd.geometry = [corridor_geometry] + self.corridor_poly_gpd["centerline_method"] = self.centerline_method + self.corridor_poly_gpd["OLnFID"] = self.lc_path["OLnFID"] + self.corridor_poly_gpd["OLnSEG"] = self.lc_path["OLnSEG"] + + def _clip_chm(self, in_raster, clip_geometry, buffer): + tree_gaps=[] + if self.chm_mode == bt_const.CenterlineChmMode.ALT.value: + ras_clip, out_meta,tree_gaps = alt_sp_common.alt_clip_and_filter_regional_maxima_wgap( + self, + in_raster, + clip_geometry, + buffer, + ) + return ras_clip, out_meta,tree_gaps + return sp_common.clip_raster(in_raster, clip_geometry, buffer) + + def _postprocess_lcp(self, lc_path, crs): + processed = lc_path + if self.lcp_simplify_enabled and self.lcp_simplify_diameter > 0: + processed = tool_geo_simplify.simplify_line_reduce_bend( + processed, + crs=crs, + diameter=self.lcp_simplify_diameter, + smooth_line=True, + ) + if self.lcp_smooth_enabled and self.lcp_smooth_iterations > 0: + processed = algo_geometry.chaikin_smooth_line( + processed, + iterations=self.lcp_smooth_iterations, + ) + return processed + + def _postprocess_corridor_polygon(self, corridor_poly_gpd): + polygon = corridor_poly_gpd.geometry.iloc[0] + processed = algo_geometry.process_corridor_polygon( + polygon,cid=self.cid, + delete_holes=bool(bt_const.CenterlineFlags.DELETE_HOLES), + simplify=self.corridor_simplify_polygon, + simplify_length=self.corridor_simplify_length, + smooth=self.corridor_smooth_polygon, + smooth_iterations=self.corridor_polygon_smooth_iterations, + ) + corridor_poly_gpd = corridor_poly_gpd.copy() + corridor_poly_gpd.geometry = [processed] + return corridor_poly_gpd + +def orient_to_split(line, split_pt, want_end_at_split=True): + + start_gap = sh_geom.Point(line.coords[0]).distance(split_pt) + + end_gap = sh_geom.Point(line.coords[-1]).distance(split_pt) + + if want_end_at_split: + if start_gap < end_gap: + return algo_common._reverse_line(line) + else: + if end_gap < start_gap: + return algo_common._reverse_line(line) + + return line diff --git a/beratools/modules/mapping/algo_check_seed_line.py b/beratools/modules/mapping/algo_check_seed_line.py new file mode 100644 index 0000000..24a0a63 --- /dev/null +++ b/beratools/modules/mapping/algo_check_seed_line.py @@ -0,0 +1,925 @@ +"""Per-line vertex preclean helpers for line optimization workflows.""" + +import logging +import math + +import geopandas as gpd +import numpy as np +import pyproj +import shapely.geometry as sh_geom +from shapely import ops as sh_ops +from shapely.geometry import LineString, Point + +import beratools.core.constants as bt_const +import beratools.modules.mapping.algo_common as algo_common +import beratools.utility.spatial_common as sp_common +import beratools.utility.unit_conversion as unit_conversion + +try: + import rasterio +except Exception: + rasterio = None + +logger = logging.getLogger(__name__) + + +class VertexPrecleaner: + VALID_MODES = {"full", "endpoint_only"} + + def __init__(self, close_distance, angle_tol): + self.close_distance = float(close_distance) + self.angle_tol = float(angle_tol) + + @staticmethod + def _point_distance(coord_a, coord_b): + return math.hypot(coord_b[0] - coord_a[0], coord_b[1] - coord_a[1]) + + def _bend_score(self, coord_a, coord_b, coord_c): + v1x = coord_b[0] - coord_a[0] + v1y = coord_b[1] - coord_a[1] + v2x = coord_c[0] - coord_b[0] + v2y = coord_c[1] - coord_b[1] + + norm1 = math.hypot(v1x, v1y) + norm2 = math.hypot(v2x, v2y) + if norm1 <= bt_const.SMALL_BUFFER or norm2 <= bt_const.SMALL_BUFFER: + return 180.0 + + dot = v1x * v2x + v1y * v2y + cos_val = max(-1.0, min(1.0, dot / (norm1 * norm2))) + return math.degrees(math.acos(cos_val)) + + def _shape_loss(self, work_coords, remove_index): + prev_coord = work_coords[remove_index - 1] if remove_index - 1 >= 0 else None + curr_coord = work_coords[remove_index] + next_coord = work_coords[remove_index + 1] if remove_index + 1 < len(work_coords) else None + + old_scores = [] + if prev_coord is not None and remove_index - 2 >= 0: + old_scores.append(self._bend_score(work_coords[remove_index - 2], prev_coord, curr_coord)) + if next_coord is not None and remove_index + 2 < len(work_coords): + old_scores.append(self._bend_score(curr_coord, next_coord, work_coords[remove_index + 2])) + if prev_coord is not None and next_coord is not None: + old_scores.append(self._bend_score(prev_coord, curr_coord, next_coord)) + + new_scores = [] + if prev_coord is not None and next_coord is not None: + if remove_index - 2 >= 0: + new_scores.append(self._bend_score(work_coords[remove_index - 2], prev_coord, next_coord)) + if remove_index + 2 < len(work_coords): + new_scores.append(self._bend_score(prev_coord, next_coord, work_coords[remove_index + 2])) + + old_peak = max(old_scores) if old_scores else 0.0 + new_peak = max(new_scores) if new_scores else 0.0 + significant_penalty = 50.0 if old_peak > self.angle_tol and new_peak <= self.angle_tol else 0.0 + return abs(old_peak - new_peak) + significant_penalty + + def _dedupe_consecutive_coords(self, coords): + if not coords: + return [] + + work_coords = [coords[0]] + for coord in coords[1:]: + if self._point_distance(work_coords[-1], coord) > bt_const.SMALL_BUFFER: + work_coords.append(coord) + + return work_coords + + def _finalize_line(self, coords, original_line): + if len(coords) < 2: + return None + + if self._point_distance(coords[0], coords[-1]) <= bt_const.SMALL_BUFFER: + return None + + if len(coords) == len(original_line.coords): + return original_line + + return sh_geom.LineString(coords) + + def _cleanup_endpoint_only(self, coords): + while len(coords) > 2 and self._point_distance(coords[0], coords[1]) < self.close_distance: + coords.pop(1) + + while len(coords) > 2 and self._point_distance(coords[-2], coords[-1]) < self.close_distance: + coords.pop(-2) + + return coords + + def cleanup_line(self, line, mode="full"): + if mode not in self.VALID_MODES: + raise ValueError(f"Unsupported vertex cleanup mode: {mode}") + + coords = [tuple(coord) for coord in line.coords] + if len(coords) <= 2: + return line + + work_coords = self._dedupe_consecutive_coords(coords) + if len(work_coords) <= 2: + return self._finalize_line(work_coords, line) + + work_coords = self._cleanup_endpoint_only(work_coords) + if mode == "endpoint_only": + return self._finalize_line(work_coords, line) + + i = 1 + while i < len(work_coords) - 2: + left_coord = work_coords[i] + right_coord = work_coords[i + 1] + if self._point_distance(left_coord, right_coord) >= self.close_distance: + i += 1 + continue + + left_score = self._bend_score(work_coords[i - 1], left_coord, right_coord) + right_score = self._bend_score(left_coord, right_coord, work_coords[i + 2]) + + if left_score > self.angle_tol and right_score <= self.angle_tol: + remove_index = i + 1 + elif right_score > self.angle_tol and left_score <= self.angle_tol: + remove_index = i + else: + remove_left_loss = self._shape_loss(work_coords, i) + remove_right_loss = self._shape_loss(work_coords, i + 1) + remove_index = i if remove_left_loss <= remove_right_loss else i + 1 + + work_coords.pop(remove_index) + if i > 1: + i -= 1 + + return self._finalize_line(work_coords, line) + + def remove_close_vertices(self, gdf, mode="full"): + if mode not in self.VALID_MODES: + raise ValueError(f"Unsupported vertex cleanup mode: {mode}") + + if gdf is None or gdf.empty: + return gdf + + if isinstance(gdf, gpd.GeoSeries): + gdf = gpd.GeoDataFrame(geometry=gdf) + + out_gdf = gdf.copy() + + if any(getattr(geom, "geom_type", None) == "MultiLineString" for geom in out_gdf.geometry): + out_gdf = out_gdf.explode(index_parts=False) + + cleaned_geoms = [] + for geom in out_gdf.geometry: + if geom is None or geom.is_empty: + cleaned_geoms.append(None) + continue + + if geom.geom_type != "LineString": + cleaned_geoms.append(geom) + continue + + cleaned_geoms.append(self.cleanup_line(geom, mode=mode)) + + geom_series = gpd.GeoSeries(cleaned_geoms, index=out_gdf.index, crs=out_gdf.crs) + valid_mask = geom_series.notna() & ~geom_series.is_empty + out_gdf = out_gdf.loc[valid_mask].copy() + out_gdf.set_geometry(geom_series.loc[valid_mask], inplace=True) + out_gdf = out_gdf[out_gdf.geometry.length > bt_const.SMALL_BUFFER] + out_gdf = gpd.GeoDataFrame(out_gdf, crs=gdf.crs) + out_gdf.reset_index(drop=True, inplace=True) + + return out_gdf + + +def _iter_line_parts(geom): + if geom is None or geom.is_empty: + return [] + + if geom.geom_type == "LineString": + return [geom] + + if geom.geom_type == "MultiLineString": + return [part for part in geom.geoms if part and not part.is_empty and part.geom_type == "LineString"] + + if geom.geom_type == "GeometryCollection": + parts = [] + for item in geom.geoms: + parts.extend(_iter_line_parts(item)) + return parts + + return [] + + +def _normalize_to_lines(gdf): + if gdf is None: + return gdf + + if gdf.empty: + return gdf + + exploded = gdf.explode(index_parts=False).reset_index(drop=True) + records = [] + + for _, row in exploded.iterrows(): + line_parts = _iter_line_parts(row.geometry) + if not line_parts: + continue + + row_dict = row.to_dict() + for line_geom in line_parts: + rec = row_dict.copy() + rec["geometry"] = line_geom + records.append(rec) + + return gpd.GeoDataFrame(records, columns=gdf.columns, crs=gdf.crs) + + +def _require_crs(gdf, parameter_label): + return unit_conversion.require_crs(gdf, parameter_label) + + +def _build_linear_unit_context(crs, reference_geom): + return unit_conversion.build_linear_unit_context(crs, reference_geom) + + +def _meters_to_native_units(distance_m, unit_ctx): + return unit_conversion.meters_to_native_units(distance_m, unit_ctx) + + +def _geometry_length_meters(geom, unit_ctx): + return unit_conversion.geometry_length_meters(geom, unit_ctx) + + +def _geographic_raster_cell_size_m(src, crs, x_res, y_res): + geod = crs.get_geod() + if geod is None: + raise ValueError("Unable to build geodesic calculator for geographic CRS.") + + bounds = src.bounds + center_x = float((bounds.left + bounds.right) / 2.0) + center_y = float((bounds.bottom + bounds.top) / 2.0) + max_lat = 89.999999 + min_lat = -89.999999 + y_for_dx = min(max(center_y, min_lat), max_lat) + y_start = min(max(center_y, min_lat), max_lat) + y_for_dy = min(max(center_y + float(y_res), min_lat), max_lat) + dist_x = abs(geod.inv(center_x, y_for_dx, center_x + float(x_res), y_for_dx)[2]) + dist_y = abs(geod.inv(center_x, y_start, center_x, y_for_dy)[2]) + return min(dist_x, dist_y) + + +def _default_close_distance_m(in_raster): + fallback = 2.0 + max_auto_default = 30.0 + + def _fallback(reason, exc=None): + if exc is None: + logger.warning( + "Using fallback preclean distance %.2f m: %s (raster=%s)", + fallback, + reason, + in_raster, + ) + else: + logger.warning( + "Using fallback preclean distance %.2f m: %s (raster=%s, error=%s)", + fallback, + reason, + in_raster, + exc, + ) + return fallback + + if not in_raster or rasterio is None: + reason = "missing input raster" + if rasterio is None: + reason = "rasterio unavailable" + return _fallback(reason) + + try: + with rasterio.open(in_raster) as src: + crs = pyproj.CRS.from_user_input(src.crs) if src.crs else None + if crs is None: + return _fallback("raster CRS missing or unreadable") + + x_res, y_res = src.res + cell_size_native = min(abs(float(x_res)), abs(float(y_res))) + if math.isclose(cell_size_native, 0.0): + return _fallback("raster resolution is zero") + + if crs.is_geographic: + try: + cell_size_m = _geographic_raster_cell_size_m(src, crs, x_res, y_res) + except ValueError as exc: + return _fallback(str(exc)) + else: + unit_factor = crs.axis_info[0].unit_conversion_factor if crs.axis_info else None + if unit_factor is None or unit_factor <= 0: + return _fallback("unable to determine projected CRS linear unit factor") + cell_size_m = cell_size_native * float(unit_factor) + + if math.isclose(cell_size_m, 0.0): + return _fallback("computed metric cell size is zero") + inferred_default = 1.5 * float(cell_size_m) + return float(min(max_auto_default, max(fallback, inferred_default))) + except Exception as exc: + return _fallback("failed to derive raster-based default", exc=exc) + + +def _preclean_lines_full(gdf, close_distance_m, angle_tol_deg): + if gdf.empty: + return gdf, gdf.iloc[0:0].copy() + + valid_mask = ~gdf.geometry.isna() & ~gdf.geometry.is_empty + out = gdf[valid_mask].copy() + rejected = gdf[~valid_mask].copy() + if out.empty: + return out.reset_index(drop=True), rejected.reset_index(drop=True) + + crs = _require_crs(out, "Preclean close distance (m)") + precleaner = VertexPrecleaner(close_distance=close_distance_m, angle_tol=angle_tol_deg) + cleaned_records = [] + removed_records = [] + + if crs.is_geographic: + reference_geom = out.unary_union.envelope + unit_ctx = _build_linear_unit_context(crs, reference_geom) + for _, row in out.iterrows(): + geom = row.geometry + if geom is None or geom.is_empty or geom.geom_type != "LineString": + rec = row.to_dict() + if geom is None or geom.is_empty: + removed_records.append(rec) + else: + cleaned_records.append(rec) + continue + + geom_metric = sh_ops.transform(unit_ctx["to_metric"].transform, geom) + cleaned_metric = precleaner.cleanup_line(geom_metric, mode="full") + if cleaned_metric is None or cleaned_metric.is_empty: + removed_records.append(row.to_dict()) + continue + + rec = row.to_dict() + rec["geometry"] = sh_ops.transform(unit_ctx["to_source"].transform, cleaned_metric) + cleaned_records.append(rec) + else: + unit_ctx = _build_linear_unit_context(crs, out.unary_union.envelope) + close_distance_native = max( + _meters_to_native_units(close_distance_m, unit_ctx), bt_const.SMALL_BUFFER + ) + precleaner_native = VertexPrecleaner(close_distance=close_distance_native, angle_tol=angle_tol_deg) + for _, row in out.iterrows(): + geom = row.geometry + if geom is None or geom.is_empty or geom.geom_type != "LineString": + rec = row.to_dict() + if geom is None or geom.is_empty: + removed_records.append(rec) + else: + cleaned_records.append(rec) + continue + + cleaned = precleaner_native.cleanup_line(geom, mode="full") + if cleaned is None or cleaned.is_empty: + removed_records.append(row.to_dict()) + continue + + rec = row.to_dict() + rec["geometry"] = cleaned + cleaned_records.append(rec) + + cleaned_gdf = gpd.GeoDataFrame(cleaned_records, columns=gdf.columns, crs=gdf.crs) + removed_gdf = gpd.GeoDataFrame( + [*rejected.to_dict("records"), *removed_records], columns=gdf.columns, crs=gdf.crs + ) + return cleaned_gdf.reset_index(drop=True), removed_gdf.reset_index(drop=True) + + +def _clean_line_geometries_min_length_m(line_gdf, min_length_m): + if line_gdf is None: + return line_gdf, None + if line_gdf.empty: + return line_gdf.copy(), line_gdf.copy() + + valid_mask = ~line_gdf.geometry.isna() & ~line_gdf.geometry.is_empty + out = line_gdf[valid_mask] + rejected = line_gdf[~valid_mask].copy() + + if out.empty: + return out.reset_index(drop=True), rejected.reset_index(drop=True) + + crs = _require_crs(out, "Minimum line length (m)") + + reference_geom = out.unary_union.envelope + unit_ctx = _build_linear_unit_context(crs, reference_geom) + min_len_m = max(float(min_length_m), bt_const.SMALL_BUFFER) + + if unit_ctx["is_geographic"]: + mask = out.geometry.apply(lambda geom: _geometry_length_meters(geom, unit_ctx) > min_len_m) + kept = out[mask] + removed_short = out[~mask] + else: + min_len_native = max(_meters_to_native_units(min_len_m, unit_ctx), bt_const.SMALL_BUFFER) + kept = out[out.geometry.length > min_len_native] + removed_short = out[~(out.geometry.length > min_len_native)] + + if rejected.empty: + rejected = removed_short.copy() + elif not removed_short.empty: + rejected = gpd.GeoDataFrame( + [*rejected.to_dict("records"), *removed_short.to_dict("records")], + columns=line_gdf.columns, + crs=line_gdf.crs, + ) + + return kept.reset_index(drop=True), rejected.reset_index(drop=True) + + +def _clip_to_chm_footprint(gdf, in_raster, shrink_m): + footprint = sp_common.generate_raster_footprint(in_raster, latlon=False) + if footprint is None or footprint.is_empty: + raise ValueError("Unable to build CHM footprint from input raster.") + + shrink_dist_m = abs(float(shrink_m)) + crs = _require_crs(gdf, "CHM footprint shrink (m)") + unit_ctx = _build_linear_unit_context(crs, footprint) + + if unit_ctx["is_geographic"]: + footprint_metric = sh_ops.transform(unit_ctx["to_metric"].transform, footprint) + shrunken_metric = footprint_metric.buffer(-shrink_dist_m) + shrunken = sh_ops.transform(unit_ctx["to_source"].transform, shrunken_metric) + else: + shrink_dist_units = _meters_to_native_units(shrink_dist_m, unit_ctx) + shrunken = footprint.buffer(-shrink_dist_units) + + if shrunken is None or shrunken.is_empty: + raise ValueError("CHM footprint became empty after inward shrink; reduce 'CHM footprint shrink (m)'.") + + clipped_records = [] + rejected_records = [] + for _, row in gdf.iterrows(): + geom = row.geometry + if geom is None or geom.is_empty: + rejected_records.append(row.to_dict()) + continue + + clipped = geom.intersection(shrunken) + if clipped is None or clipped.is_empty: + rejected_records.append(row.to_dict()) + continue + + rec = row.to_dict() + rec["geometry"] = clipped + clipped_records.append(rec) + + clipped_gdf = gpd.GeoDataFrame(clipped_records, columns=gdf.columns, crs=gdf.crs) + rejected_gdf = gpd.GeoDataFrame(rejected_records, columns=gdf.columns, crs=gdf.crs) + return clipped_gdf, rejected_gdf, shrunken + + +def _parse_line_id(raw_id): + if isinstance(raw_id, bool): + return None + try: + val = int(raw_id) + return val + except (TypeError, ValueError): + return None + + +def _choose_anchor(endpoint_a, endpoint_b): + line_id_a = _parse_line_id(endpoint_a.get("line_id")) + line_id_b = _parse_line_id(endpoint_b.get("line_id")) + + score_a = ( + -int(endpoint_a.get("degree", 0)), + -endpoint_a["line_length"], + 0 if line_id_a is not None else 1, + line_id_a if line_id_a is not None else float("inf"), + endpoint_a["discovery_order"], + ) + score_b = ( + -int(endpoint_b.get("degree", 0)), + -endpoint_b["line_length"], + 0 if line_id_b is not None else 1, + line_id_b if line_id_b is not None else float("inf"), + endpoint_b["discovery_order"], + ) + + if score_a <= score_b: + return endpoint_a, endpoint_b + return endpoint_b, endpoint_a + + +def _snap_close_endpoints(gdf, tolerance): + if gdf.empty: + return gdf + + tol_m = float(tolerance) + if tol_m <= bt_const.SMALL_BUFFER: + return gdf + + crs = _require_crs(gdf, "Snap tolerance (m)") + reference_geom = gdf.unary_union.envelope + unit_ctx = _build_linear_unit_context(crs, reference_geom) + tol_native = _meters_to_native_units(tol_m, unit_ctx) + + endpoints = [] + discovery_order = 0 + for row_index, row in gdf.iterrows(): + geom = row.geometry + if geom is None or geom.is_empty or geom.geom_type != "LineString": + continue + + coords = list(geom.coords) + if len(coords) < 2: + continue + + line_length = _geometry_length_meters(geom, unit_ctx) + line_id = row.get("line_id") + for endpoint_idx, coord in ((0, coords[0]), (-1, coords[-1])): + metric_point = None + if unit_ctx["is_geographic"]: + metric_point = sh_ops.transform(unit_ctx["to_metric"].transform, Point(coord)) + endpoints.append( + { + "gdf_index": row_index, + "endpoint_idx": endpoint_idx, + "point": Point(coord), + "metric_point": metric_point, + "line_length": line_length, + "line_id": line_id, + "discovery_order": discovery_order, + } + ) + discovery_order += 1 + + if len(endpoints) < 2: + return gdf + + neighbor_graph = {idx: set() for idx in range(len(endpoints))} + for i in range(len(endpoints)): + for j in range(i + 1, len(endpoints)): + ep_i = endpoints[i] + ep_j = endpoints[j] + + if ep_i["gdf_index"] == ep_j["gdf_index"]: + continue + + if unit_ctx["is_geographic"]: + dist = ep_i["metric_point"].distance(ep_j["metric_point"]) + close_threshold = bt_const.SMALL_BUFFER + snap_threshold = tol_m + else: + dist = ep_i["point"].distance(ep_j["point"]) + close_threshold = bt_const.SMALL_BUFFER + snap_threshold = tol_native + + if dist <= close_threshold: + continue + if dist <= snap_threshold: + neighbor_graph[i].add(j) + neighbor_graph[j].add(i) + + if not any(neighbor_graph.values()): + return gdf + + for idx, endpoint in enumerate(endpoints): + endpoint["degree"] = len(neighbor_graph[idx]) + + visited = set() + components = [] + active_nodes = [idx for idx, neighbors in neighbor_graph.items() if neighbors] + for node in active_nodes: + if node in visited: + continue + stack = [node] + component = [] + while stack: + curr = stack.pop() + if curr in visited: + continue + visited.add(curr) + component.append(curr) + for neighbor in neighbor_graph[curr]: + if neighbor not in visited: + stack.append(neighbor) + + if len(component) > 1: + components.append(component) + + if not components: + return gdf + + updates = {} + for component in components: + anchor_endpoint = endpoints[component[0]] + for idx in component[1:]: + candidate = endpoints[idx] + anchor_endpoint, _ = _choose_anchor(anchor_endpoint, candidate) + + anchor_coord = tuple(anchor_endpoint["point"].coords[0]) + anchor_key = (anchor_endpoint["gdf_index"], anchor_endpoint["endpoint_idx"]) + + for idx in component: + endpoint = endpoints[idx] + endpoint_key = (endpoint["gdf_index"], endpoint["endpoint_idx"]) + if endpoint_key == anchor_key: + continue + updates[endpoint_key] = anchor_coord + + if not updates: + return gdf + + out = gdf.copy() + for row_index, row in out.iterrows(): + geom = row.geometry + if geom is None or geom.is_empty or geom.geom_type != "LineString": + continue + + coords = list(geom.coords) + changed = False + for endpoint_idx in (0, -1): + key = (row_index, endpoint_idx) + if key in updates: + target_coord = updates[key] + if endpoint_idx == 0: + coords[0] = target_coord + else: + coords[-1] = target_coord + changed = True + + if changed: + out.at[row_index, "geometry"] = LineString(coords) + + return out + + +def _interp_coord(start, end, ratio): + n_dims = min(len(start), len(end)) + return tuple(start[i] + (end[i] - start[i]) * ratio for i in range(n_dims)) + + +def _densify_linestring(line, max_segment_length): + if line is None or line.is_empty or line.geom_type != "LineString": + return line + + max_seg = float(max_segment_length) + if max_seg <= bt_const.SMALL_BUFFER: + raise ValueError("Max segment length must be greater than zero.") + + total_len = float(line.length) + if total_len <= max_seg: + return line + + n_parts = int(math.ceil(total_len / max_seg)) + spacing = total_len / n_parts + split_distances = [spacing * i for i in range(1, n_parts)] + + coords = list(line.coords) + if len(coords) < 2: + return line + + out_coords = [coords[0]] + curr_dist = 0.0 + split_idx = 0 + + for seg_idx in range(len(coords) - 1): + start = coords[seg_idx] + end = coords[seg_idx + 1] + seg_len = Point(start).distance(Point(end)) + if seg_len <= bt_const.SMALL_BUFFER: + continue + + seg_end_dist = curr_dist + seg_len + while split_idx < len(split_distances) and split_distances[split_idx] < seg_end_dist: + ratio = (split_distances[split_idx] - curr_dist) / seg_len + interp = _interp_coord(start, end, ratio) + if Point(out_coords[-1]).distance(Point(interp)) > bt_const.SMALL_BUFFER: + out_coords.append(interp) + split_idx += 1 + + if Point(out_coords[-1]).distance(Point(end)) > bt_const.SMALL_BUFFER: + out_coords.append(end) + curr_dist = seg_end_dist + + if len(out_coords) < 2: + return line + return LineString(out_coords) + + +def _densify_long_lines(gdf, max_segment_length): + if gdf.empty: + return gdf + + max_seg_m = float(max_segment_length) + if max_seg_m <= bt_const.SMALL_BUFFER: + raise ValueError("Max segment length must be greater than zero.") + + valid = gdf[~gdf.geometry.isna() & ~gdf.geometry.is_empty] + if valid.empty: + return gdf + + crs = _require_crs(valid, "Max segment length (m)") + reference_geom = valid.unary_union.envelope + unit_ctx = _build_linear_unit_context(crs, reference_geom) + + out = gdf.copy() + + if unit_ctx["is_geographic"]: + for idx, row in out.iterrows(): + geom = row.geometry + if geom is None or geom.is_empty or geom.geom_type != "LineString": + continue + + geom_metric = sh_ops.transform(unit_ctx["to_metric"].transform, geom) + if geom_metric.length <= max_seg_m: + continue + + densified_metric = _densify_linestring(geom_metric, max_seg_m) + out.at[idx, "geometry"] = sh_ops.transform(unit_ctx["to_source"].transform, densified_metric) + + return out + + max_seg_native = max(_meters_to_native_units(max_seg_m, unit_ctx), bt_const.SMALL_BUFFER) + for idx, row in out.iterrows(): + geom = row.geometry + if geom is None or geom.is_empty or geom.geom_type != "LineString": + continue + if geom.length <= max_seg_native: + continue + out.at[idx, "geometry"] = _densify_linestring(geom, max_seg_native) + return out + + +def qc_merge_multilinestring(gdf): + """ + QC step: Merge MultiLineStrings if possible, else split into LineStrings. + + Args: + gdf (GeoDataFrame): Input GeoDataFrame. + + Returns: + GeoDataFrame: Cleaned GeoDataFrame with only LineStrings. + """ + from shapely.geometry.base import BaseGeometry + + from beratools.modules.mapping.algo_merge_lines import custom_line_merge + + records = [] + for _, row in gdf.iterrows(): + geom = row.geometry + if geom is None: + continue + row_dict = row.to_dict() + if geom.geom_type == "MultiLineString": + merged = custom_line_merge(geom) + if merged.geom_type == "MultiLineString": + for part in getattr(merged, "geoms", []): + new_row = row_dict.copy() + new_row["geometry"] = part + if part.geom_type == "LineString": + records.append(new_row) + elif merged.geom_type == "LineString": + new_row = row_dict.copy() + new_row["geometry"] = merged + records.append(new_row) + else: + new_row = row_dict.copy() + new_row["geometry"] = merged + if hasattr(merged, "geom_type") and merged.geom_type == "LineString": + records.append(new_row) + elif geom.geom_type == "LineString": + records.append(row_dict) + + valid_records = [rec for rec in records if isinstance(rec.get("geometry", None), BaseGeometry)] + out_gdf = gpd.GeoDataFrame.from_records(valid_records, columns=gdf.columns) + out_gdf.set_crs(gdf.crs, inplace=True) + out_gdf = out_gdf.reset_index(drop=True) + out_gdf, _ = algo_common.chk_df_multipart(out_gdf, 'LineString') + return out_gdf + + +def qc_split_lines_at_intersections(gdf): + """ + QC step: Split lines at intersections so each segment becomes a separate line object. + + Args: + gdf (GeoDataFrame): Input GeoDataFrame of LineStrings. + + Returns: + GeoDataFrame: New GeoDataFrame with lines split at all intersection points. + """ + from beratools.modules.mapping.algo_split_with_lines import LineSplitter + + splitter = LineSplitter(gdf) + splitter.process() + if splitter.split_lines_gdf is not None: + if isinstance(splitter.split_lines_gdf, gpd.GeoDataFrame): + return splitter.split_lines_gdf.reset_index(drop=True) + return splitter.split_lines_gdf + return gdf.reset_index(drop=True) + + + +def _bend_angle(a, b, c): + """ + Return deviation from straight line in degrees. + + 0° = perfectly straight + 90° = right angle + """ + v1 = np.array([ + a[0] - b[0], + a[1] - b[1], + ]) + + v2 = np.array([ + c[0] - b[0], + c[1] - b[1], + ]) + + n1 = np.linalg.norm(v1) + n2 = np.linalg.norm(v2) + + if n1 == 0 or n2 == 0: + return 0.0 + + cosang = np.dot(v1, v2) / (n1 * n2) + cosang = np.clip(cosang, -1.0, 1.0) + + angle = np.degrees( + np.arccos(cosang) + ) + + return min( + angle, + 180.0 - angle + ) + + +def _trim_short_terminal_segments( + line, + min_segment_length=5.0, + max_bend_angle=5.0, +): + coords = list(line.coords) + + # + # remove short tail + # + while len(coords) > 2: + + tail_len = ( + sh_geom.Point(coords[-2]) + .distance( + sh_geom.Point(coords[-1]) + ) + ) + + if tail_len >= min_segment_length: + break + + # + # check if last vertex is essentially inline + # + if len(coords) >= 3: + + angle = _bend_angle( + coords[-3], + coords[-2], + coords[-1] + ) + + if angle > max_bend_angle: + break + + coords.pop(-1) + + # + # remove short head + # + while len(coords) > 2: + + head_len = ( + sh_geom.Point(coords[0]) + .distance( + sh_geom.Point(coords[1]) + ) + ) + + if head_len >= min_segment_length: + break + + # + # check if first vertex is essentially inline + # + if len(coords) >= 3: + + angle = _bend_angle( + coords[0], + coords[1], + coords[2] + ) + + if angle > max_bend_angle: + break + + coords.pop(0) + + return sh_geom.LineString(coords) \ No newline at end of file diff --git a/beratools/modules/mapping/algo_check_seed_line_validate.py b/beratools/modules/mapping/algo_check_seed_line_validate.py new file mode 100644 index 0000000..656b536 --- /dev/null +++ b/beratools/modules/mapping/algo_check_seed_line_validate.py @@ -0,0 +1,610 @@ +"""Final validation pass on check_seed_line outputs to detect remaining issues.""" + +import math +from pathlib import Path + +import geopandas as gpd +import numpy as np +from shapely.geometry import GeometryCollection, LineString, MultiLineString, MultiPoint, Point + +import beratools.core.constants as bt_const +import beratools.utility.unit_conversion as unit_conversion + +try: + import rasterio + from osgeo import gdal # noqa: F401 # Load GDAL DLLs before rasterio on Windows/conda. + from rasterio.windows import Window +except Exception: + rasterio = None + Window = None + + +ISSUE_COLUMNS = [ + "issue_type", + "description", + "line_id", + "line_id_2", + "value", + "threshold", + "geometry", +] + + +def _iter_line_parts(geom): + if geom is None or geom.is_empty: + return [] + if geom.geom_type == "LineString": + return [geom] + if geom.geom_type == "MultiLineString": + return [part for part in geom.geoms if part is not None and not part.is_empty] + if geom.geom_type == "GeometryCollection": + parts = [] + for item in geom.geoms: + parts.extend(_iter_line_parts(item)) + return parts + return [] + + +def _build_unit_ctx(gdf): + crs = unit_conversion.require_crs(gdf, "QC report checks") + reference_geom = None if gdf.empty else gdf.unary_union.envelope + return unit_conversion.build_linear_unit_context(crs, reference_geom) + + +def _point_distance_m(point_a, point_b, unit_ctx): + if unit_ctx["is_geographic"]: + point_a_m = Point(unit_ctx["to_metric"].transform(point_a.x, point_a.y)) + point_b_m = Point(unit_ctx["to_metric"].transform(point_b.x, point_b.y)) + return float(point_a_m.distance(point_b_m)) + return float(point_a.distance(point_b)) * float(unit_ctx["unit_factor"]) + + +def _raster_cell_size_m(src, row, col, unit_ctx): + row = min(max(int(row), 0), src.height - 1) + col = min(max(int(col), 0), src.width - 1) + center = Point(src.xy(row, col)) + + samples = [] + if col + 1 < src.width: + samples.append(Point(src.xy(row, col + 1))) + if row + 1 < src.height: + samples.append(Point(src.xy(row + 1, col))) + if col > 0: + samples.append(Point(src.xy(row, col - 1))) + if row > 0: + samples.append(Point(src.xy(row - 1, col))) + + distances = [_point_distance_m(center, sample, unit_ctx) for sample in samples] + distances = [dist for dist in distances if dist > bt_const.SMALL_BUFFER] + if distances: + return min(distances) + + return max(abs(float(src.transform.a)), abs(float(src.transform.e)), bt_const.SMALL_BUFFER) + + +def _raster_valid_mask(data, nodata): + values = np.ma.getdata(data) + invalid = np.ma.getmaskarray(data).copy() + + if nodata is not None: + try: + invalid |= np.isclose(values, nodata) + except TypeError: + invalid |= values == nodata + + if np.issubdtype(values.dtype, np.floating): + invalid |= np.isnan(values) + + return ~invalid + + +def _nearest_valid_distance_m(src, valid_mask, row_offset, col_offset, point, unit_ctx, exclude_cell=None): + valid_rows, valid_cols = np.nonzero(valid_mask) + best_distance = None + + for local_row, local_col in zip(valid_rows, valid_cols): + global_row = int(row_offset + local_row) + global_col = int(col_offset + local_col) + if exclude_cell is not None and (global_row, global_col) == exclude_cell: + continue + + candidate = Point(src.xy(global_row, global_col)) + distance_m = _point_distance_m(point, candidate, unit_ctx) + if best_distance is None or distance_m < best_distance: + best_distance = float(distance_m) + + return best_distance + + +def _check_chm_point(src, point, search_radius_m, unit_ctx): + try: + row, col = src.index(point.x, point.y) + except Exception: + return {"reason": "outside_raster", "nearest_valid_m": None} + + in_bounds = 0 <= row < src.height and 0 <= col < src.width + if not in_bounds: + return {"reason": "outside_raster", "nearest_valid_m": None} + + center_row = min(max(int(row), 0), src.height - 1) + center_col = min(max(int(col), 0), src.width - 1) + cell_size_m = _raster_cell_size_m(src, center_row, center_col, unit_ctx) + radius_px = max(1, int(math.ceil(float(search_radius_m) / max(cell_size_m, bt_const.SMALL_BUFFER)))) + + row_start = max(center_row - radius_px, 0) + row_stop = min(center_row + radius_px + 1, src.height) + col_start = max(center_col - radius_px, 0) + col_stop = min(center_col + radius_px + 1, src.width) + + if row_stop <= row_start or col_stop <= col_start: + return {"reason": "outside_raster", "nearest_valid_m": None} + + window = Window(col_start, row_start, col_stop - col_start, row_stop - row_start) + data = src.read(1, window=window, masked=True) + valid_mask = _raster_valid_mask(data, src.nodata) + + center_valid = False + if in_bounds: + local_row = int(row - row_start) + local_col = int(col - col_start) + center_valid = bool(valid_mask[local_row, local_col]) + + if center_valid: + local_row = int(row - row_start) + local_col = int(col - col_start) + neighbor_row_start = max(local_row - 1, 0) + neighbor_row_stop = min(local_row + 2, valid_mask.shape[0]) + neighbor_col_start = max(local_col - 1, 0) + neighbor_col_stop = min(local_col + 2, valid_mask.shape[1]) + neighbors = valid_mask[ + neighbor_row_start:neighbor_row_stop, neighbor_col_start:neighbor_col_stop + ].copy() + neighbors[local_row - neighbor_row_start, local_col - neighbor_col_start] = False + if np.any(neighbors): + return None + + nearest_valid_m = _nearest_valid_distance_m( + src, + valid_mask, + row_start, + col_start, + point, + unit_ctx, + exclude_cell=(int(row), int(col)), + ) + return {"reason": "surrounded_by_nodata", "nearest_valid_m": nearest_valid_m} + + nearest_valid_m = _nearest_valid_distance_m(src, valid_mask, row_start, col_start, point, unit_ctx) + return {"reason": "on_nodata", "nearest_valid_m": nearest_valid_m} + + +def _segment_length_m(coord_a, coord_b, unit_ctx): + seg = LineString([coord_a, coord_b]) + return unit_conversion.geometry_length_meters(seg, unit_ctx) + + +def _intersection_points(geom): + if geom is None or geom.is_empty: + return [] + if isinstance(geom, Point): + return [geom] + if isinstance(geom, MultiPoint): + return [pt for pt in geom.geoms if pt is not None and not pt.is_empty] + if isinstance(geom, LineString): + if geom.length <= bt_const.SMALL_BUFFER: + return [] + return [geom.interpolate(0.5, normalized=True)] + if isinstance(geom, MultiLineString): + points = [] + for part in geom.geoms: + points.extend(_intersection_points(part)) + return points + if isinstance(geom, GeometryCollection): + points = [] + for part in geom.geoms: + points.extend(_intersection_points(part)) + return points + if hasattr(geom, "representative_point"): + return [geom.representative_point()] + return [] + + +def _overlap_midpoints_and_lengths(geom, unit_ctx): + if geom is None or geom.is_empty: + return [] + + items = [] + if isinstance(geom, LineString): + length_m = unit_conversion.geometry_length_meters(geom, unit_ctx) + if length_m > bt_const.SMALL_BUFFER: + items.append((geom.interpolate(0.5, normalized=True), float(length_m))) + return items + + if isinstance(geom, MultiLineString): + for part in geom.geoms: + items.extend(_overlap_midpoints_and_lengths(part, unit_ctx)) + return items + + if isinstance(geom, GeometryCollection): + for part in geom.geoms: + items.extend(_overlap_midpoints_and_lengths(part, unit_ctx)) + return items + + return items + + +def _dedupe_records(records, precision=9): + deduped = [] + seen = set() + for rec in records: + pt = rec["geometry"] + key = ( + rec["issue_type"], + int(rec["line_id"]), + -1 if rec["line_id_2"] is None else int(rec["line_id_2"]), + round(float(pt.x), precision), + round(float(pt.y), precision), + round(float(rec["value"]), 6), + round(float(rec["threshold"]), 6), + ) + if key in seen: + continue + seen.add(key) + deduped.append(rec) + return deduped + + +def check_short_lines(gdf, min_length_m, unit_ctx): + threshold = float(min_length_m) + records = [] + for line_id, geom in enumerate(gdf.geometry): + for part in _iter_line_parts(geom): + length_m = unit_conversion.geometry_length_meters(part, unit_ctx) + if length_m < threshold: + records.append( + { + "issue_type": "short_line", + "description": f"Line length {length_m:.3f}m is below minimum {threshold:.3f}m", + "line_id": int(line_id), + "line_id_2": None, + "value": float(length_m), + "threshold": threshold, + "geometry": part.interpolate(0.5, normalized=True), + } + ) + return _dedupe_records(records) + + +def check_close_vertices(gdf, close_distance_m, unit_ctx): + threshold = float(close_distance_m) + records = [] + for line_id, geom in enumerate(gdf.geometry): + for part in _iter_line_parts(geom): + coords = list(part.coords) + if len(coords) < 2: + continue + for i in range(1, len(coords)): + dist_m = _segment_length_m(coords[i - 1], coords[i], unit_ctx) + if bt_const.SMALL_BUFFER < dist_m <= threshold: + records.append( + { + "issue_type": "close_vertices", + "description": ( + f"Consecutive vertices are {dist_m:.3f}m apart; threshold {threshold:.3f}m" + ), + "line_id": int(line_id), + "line_id_2": None, + "value": float(dist_m), + "threshold": threshold, + "geometry": Point(coords[i]), + } + ) + return _dedupe_records(records) + + +def check_unsnapped_endpoints(gdf, snap_tolerance_m, unit_ctx): + threshold = float(snap_tolerance_m) + records = [] + + endpoints = [] + for line_id, geom in enumerate(gdf.geometry): + for part in _iter_line_parts(geom): + coords = list(part.coords) + if len(coords) < 2: + continue + endpoints.append({"line_id": int(line_id), "point": Point(coords[0])}) + endpoints.append({"line_id": int(line_id), "point": Point(coords[-1])}) + + if len(endpoints) < 2: + return records + + if unit_ctx["is_geographic"]: + candidates = [ + (i, j) + for i in range(len(endpoints)) + for j in range(i + 1, len(endpoints)) + if endpoints[i]["line_id"] != endpoints[j]["line_id"] + ] + else: + threshold_native = unit_conversion.meters_to_native_units(threshold, unit_ctx) + points = gpd.GeoSeries([ep["point"] for ep in endpoints], crs=gdf.crs) + sindex = points.sindex + candidates = [] + for i, ep in enumerate(endpoints): + bounds = ep["point"].buffer(threshold_native).bounds + for j in sindex.intersection(bounds): + if j <= i: + continue + if ep["line_id"] == endpoints[j]["line_id"]: + continue + candidates.append((i, int(j))) + + for i, j in candidates: + ep_a = endpoints[i] + ep_b = endpoints[j] + dist_m = _point_distance_m(ep_a["point"], ep_b["point"], unit_ctx) + if dist_m <= bt_const.SMALL_BUFFER or dist_m > threshold: + continue + + line_id_a = min(ep_a["line_id"], ep_b["line_id"]) + line_id_b = max(ep_a["line_id"], ep_b["line_id"]) + records.append( + { + "issue_type": "unsnapped_endpoint", + "description": ( + f"Endpoints are close ({dist_m:.3f}m) but not snapped (threshold {threshold:.3f}m)" + ), + "line_id": int(line_id_a), + "line_id_2": int(line_id_b), + "value": float(dist_m), + "threshold": threshold, + "geometry": ep_a["point"], + } + ) + + return _dedupe_records(records) + + +def check_self_crossing(gdf): + records = [] + threshold = 0.0 + for line_id, geom in enumerate(gdf.geometry): + for part in _iter_line_parts(geom): + if part.is_simple: + continue + + coords = list(part.coords) + if len(coords) < 4: + continue + + segments = [] + for i in range(len(coords) - 1): + seg = LineString([coords[i], coords[i + 1]]) + if seg.length > bt_const.SMALL_BUFFER: + segments.append((i, seg)) + + seg_count = len(segments) + for i in range(seg_count): + idx_a, seg_a = segments[i] + for j in range(i + 1, seg_count): + idx_b, seg_b = segments[j] + + if abs(idx_a - idx_b) <= 1: + continue + if idx_a == 0 and idx_b == len(coords) - 2 and Point(coords[0]).equals(Point(coords[-1])): + continue + + inter = seg_a.intersection(seg_b) + if inter is None or inter.is_empty: + continue + + for pt in _intersection_points(inter): + records.append( + { + "issue_type": "self_crossing", + "description": "Line has self-crossing or self-touching segments", + "line_id": int(line_id), + "line_id_2": None, + "value": 0.0, + "threshold": threshold, + "geometry": pt, + } + ) + + return _dedupe_records(records) + + +def check_overlapping_lines(gdf): + records = [] + threshold = 0.0 + + lines = [] + for line_id, geom in enumerate(gdf.geometry): + for part in _iter_line_parts(geom): + lines.append({"line_id": int(line_id), "geometry": part}) + + if len(lines) < 2: + return records + + unit_ctx = _build_unit_ctx(gdf) + + line_gdf = gpd.GeoDataFrame(lines, geometry="geometry", crs=gdf.crs) + sindex = line_gdf.sindex + + for i, row in line_gdf.iterrows(): + geom_i = row.geometry + for j in sindex.intersection(geom_i.bounds): + j = int(j) + if j <= i: + continue + other = line_gdf.iloc[j] + if int(other["line_id"]) == int(row["line_id"]): + continue + + inter = geom_i.intersection(other.geometry) + if inter is None or inter.is_empty: + continue + + for pt, overlap_len_m in _overlap_midpoints_and_lengths(inter, unit_ctx): + line_id_a = min(int(row["line_id"]), int(other["line_id"])) + line_id_b = max(int(row["line_id"]), int(other["line_id"])) + records.append( + { + "issue_type": "overlap", + "description": f"Lines share an overlapping segment ({overlap_len_m:.3f}m)", + "line_id": line_id_a, + "line_id_2": line_id_b, + "value": float(overlap_len_m), + "threshold": threshold, + "geometry": pt, + } + ) + + return _dedupe_records(records) + + +def check_chm_nodata_vertices( + gdf, + in_raster, + search_radius_m, + unit_ctx, + check_internal_vertices=False, +): + records = [] + if not in_raster or rasterio is None or Window is None: + return records + if not Path(in_raster).exists(): + return records + + threshold = float(search_radius_m) + include_internal = bool(check_internal_vertices) + + with rasterio.open(in_raster) as src: + for line_id, row in gdf.reset_index(drop=True).iterrows(): + bt_uid = row.get(bt_const.BT_UID) + for part in _iter_line_parts(row.geometry): + coords = list(part.coords) + if len(coords) < 2: + continue + + candidates = [(0, coords[0], "start_endpoint"), (len(coords) - 1, coords[-1], "end_endpoint")] + if include_internal and len(coords) > 2: + candidates.extend( + (idx, coord, "internal_vertex") for idx, coord in enumerate(coords[1:-1], start=1) + ) + + for vertex_index, coord, vertex_type in candidates: + point = Point(coord) + result = _check_chm_point(src, point, threshold, unit_ctx) + if result is None: + continue + + nearest_valid_m = result["nearest_valid_m"] + nearest_text = ( + f"nearest valid CHM cell is {nearest_valid_m:.3f}m away" + if nearest_valid_m is not None + else f"no valid CHM cell found within {threshold:.3f}m" + ) + uid_text = f"; BT_UID={bt_uid}" if bt_uid is not None else "" + reason_text = ( + "falls on CHM NoData" + if result["reason"] == "on_nodata" + else "is surrounded by CHM NoData" + if result["reason"] == "surrounded_by_nodata" + else "falls outside the CHM raster" + ) + + records.append( + { + "issue_type": "chm_nodata_vertex", + "description": ( + f"{vertex_type} {reason_text}; vertex_index={vertex_index}{uid_text}; " + f"coordinate=({point.x:.3f}, {point.y:.3f}); {nearest_text}" + ), + "line_id": int(line_id), + "line_id_2": None, + "value": -1.0 if nearest_valid_m is None else float(nearest_valid_m), + "threshold": threshold, + "geometry": point, + } + ) + + return _dedupe_records(records) + + +def generate_qc_report( + gdf, + min_length_m, + close_distance_m, + snap_tolerance_m, + in_raster=None, + warn_nodata_vertices=False, + nodata_vertex_search_radius_m=10.0, + check_internal_vertices=False, +): + if gdf is None: + gdf = gpd.GeoDataFrame(geometry=[]) + + gdf = gdf.reset_index(drop=True) + if gdf.empty: + issues_gdf = gpd.GeoDataFrame( + {col: [] for col in ISSUE_COLUMNS if col != "geometry"}, + geometry=gpd.GeoSeries([], crs=gdf.crs), + crs=gdf.crs, + ) + summary = { + "short_line": 0, + "close_vertices": 0, + "unsnapped_endpoint": 0, + "self_crossing": 0, + "overlap": 0, + "chm_nodata_vertex": 0, + "total": 0, + } + return issues_gdf, summary + + unit_ctx = _build_unit_ctx(gdf) + + short_line = check_short_lines(gdf, min_length_m=min_length_m, unit_ctx=unit_ctx) + close_vertices = check_close_vertices(gdf, close_distance_m=close_distance_m, unit_ctx=unit_ctx) + unsnapped_endpoint = check_unsnapped_endpoints( + gdf, + snap_tolerance_m=snap_tolerance_m, + unit_ctx=unit_ctx, + ) + self_crossing = check_self_crossing(gdf) + overlap = check_overlapping_lines(gdf) + chm_nodata_vertex = [] + if warn_nodata_vertices: + chm_nodata_vertex = check_chm_nodata_vertices( + gdf, + in_raster=in_raster, + search_radius_m=nodata_vertex_search_radius_m, + unit_ctx=unit_ctx, + check_internal_vertices=check_internal_vertices, + ) + + all_issues = ( + short_line + close_vertices + unsnapped_endpoint + self_crossing + overlap + chm_nodata_vertex + ) + + if all_issues: + issues_gdf = gpd.GeoDataFrame(all_issues, columns=ISSUE_COLUMNS, geometry="geometry", crs=gdf.crs) + else: + issues_gdf = gpd.GeoDataFrame( + {col: [] for col in ISSUE_COLUMNS if col != "geometry"}, + geometry=gpd.GeoSeries([], crs=gdf.crs), + crs=gdf.crs, + ) + + summary = { + "short_line": len(short_line), + "close_vertices": len(close_vertices), + "unsnapped_endpoint": len(unsnapped_endpoint), + "self_crossing": len(self_crossing), + "overlap": len(overlap), + "chm_nodata_vertex": len(chm_nodata_vertex), + } + summary["total"] = int(sum(summary.values())) + + return issues_gdf, summary diff --git a/beratools/modules/mapping/algo_common.py b/beratools/modules/mapping/algo_common.py new file mode 100644 index 0000000..6a96a69 --- /dev/null +++ b/beratools/modules/mapping/algo_common.py @@ -0,0 +1,1312 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + The purpose of this script is to provide common algorithms + and utility functions/classes. +""" + +import logging +import math +import sqlite3 +from pathlib import Path + +import geopandas as gpd +import numpy as np +import pyogrio +import rasterio +import shapely +import shapely.affinity as sh_aff +import shapely.geometry as sh_geom +import shapely.ops as sh_ops +import shapely.validation as sh_val +import skimage.graph as sk_graph +from osgeo import ogr +from scipy import ndimage + +import beratools.core.constants as bt_const +import beratools.modules.mapping.algo_cost as algo_cost + +# Moved to the frame's shared helpers; imported here so old imports keep working +from beratools.utility.spatial_common import generate_raster_footprint # noqa: F401 + +gpd.options.io_engine = "pyogrio" +DISTANCE_THRESHOLD = 2 # 1 meter for intersection neighborhood + +LOGGER_NAME = "algo_common" +logger = logging.getLogger(LOGGER_NAME) + +def log_file_only(message, level=logging.INFO, logger_name=None): + """Log a message to file handlers only, skipping console/gui handlers.""" + target_logger = logging.getLogger(logger_name) if logger_name else logging.getLogger(__name__) + record = target_logger.makeRecord( + name=target_logger.name, + level=level, + fn="", + lno=0, + msg=message, + args=(), + exc_info=None, + ) + + root_logger = logging.getLogger() + wrote_to_file = False + for handler in root_logger.handlers: + if isinstance(handler, logging.FileHandler): + handler.handle(record) + wrote_to_file = True + + if not wrote_to_file: + target_logger.log(level, message) + +def process_single_item(cls_obj): + """ + Process a class object for universal multiprocessing. + + Args: + cls_obj: Class object to be processed + + Returns: + cls_obj: Class object after processing + + """ + try: + cls_obj.compute() + return cls_obj + except Exception as e: + import traceback + + print(f"❌ Exception during compute() for object: {e}") + traceback.print_exc() + return None + + +def read_geospatial_file(file_path, layer=None): + """ + Read a geospatial file, clean the geometries and return a GeoDataFrame. + + Args: + file_path (str): The path to the geospatial file (e.g., .shp, .gpkg). + layer (str, optional): The specific layer to read if the file is + multi-layered (e.g., GeoPackage). + + Returns: + GeoDataFrame: The cleaned GeoDataFrame containing the data from the file + with valid geometries only. + None: If there is an error reading the file or layer. + + """ + try: + kwargs = {} + if layer is not None: + kwargs["layer"] = layer + + gdf = gpd.read_file(file_path, **kwargs) + + # Rename 'fid' column to avoid conflict with GeoPackage's reserved + # FID field on write. + if "fid" in gdf.columns: + gdf = gdf.rename(columns={"fid": "orig_fid"}) + + # Clean the geometries in the GeoDataFrame + gdf = clean_geometries(gdf, stage="input") + gdf = gdf.reset_index(drop=True) + gdf["BT_UID"] = range(len(gdf)) # assign temporary UID + return gdf + + except Exception as e: + print(f"Error reading file {file_path}: {e}") + return None + + +def has_multilinestring(gdf): + """Check if any geometry is a MultiLineString.""" + # Filter out None values (invalid geometries) from the GeoDataFrame + valid_geometries = gdf.geometry + return any(isinstance(geom, sh_geom.MultiLineString) for geom in valid_geometries) + + +def get_aux_path(out_file): + out_path = Path(out_file) + return out_path.with_stem(out_path.stem + "_aux").with_suffix(".gpkg").as_posix() + + +def save_aux_layer(gdf, out_file, layer): + if gdf is None or gdf.empty or out_file is None or layer is None: + return + + aux_file = get_aux_path(out_file) + try: + gdf.to_file(aux_file, layer=layer) + except Exception as exc: + logger.warning("Failed saving aux layer '%s' to %s: %s", layer, aux_file, exc) + + +def _infer_ogr_field_type(value): + if isinstance(value, bool): + return ogr.OFTInteger + if isinstance(value, int): + return ogr.OFTInteger64 + if isinstance(value, float): + return ogr.OFTReal + return ogr.OFTString + + +def save_aux_table(rows, out_file, table, overwrite=True): + if out_file is None or table is None: + return + + if rows is None: + rows = [] + + if isinstance(rows, dict): + rows = [rows] + + if not isinstance(rows, list): + logger.warning("Skipping aux table '%s': rows must be a list of dicts.", table) + return + + normalized_rows = [] + columns = [] + for row in rows: + if not isinstance(row, dict): + logger.warning("Skipping aux table row for '%s': expected dict, got %s.", table, type(row)) + continue + normalized_rows.append(row) + for key in row.keys(): + if key not in columns: + columns.append(key) + + aux_file = get_aux_path(out_file) + try: + driver = ogr.GetDriverByName("GPKG") + if driver is None: + raise RuntimeError("OGR GeoPackage driver is unavailable.") + + ds = driver.Open(aux_file, 1) + if ds is None: + ds = driver.CreateDataSource(aux_file) + if ds is None: + raise RuntimeError(f"Unable to open or create GeoPackage: {aux_file}") + + if overwrite: + layer_index = -1 + for idx in range(ds.GetLayerCount()): + layer_obj = ds.GetLayer(idx) + if layer_obj is not None and layer_obj.GetName() == table: + layer_index = idx + break + + if layer_index >= 0: + ds.DeleteLayer(layer_index) + + layer = ds.GetLayerByName(table) + if layer is None: + layer = ds.CreateLayer(table, geom_type=ogr.wkbNone) + + layer_defn = layer.GetLayerDefn() + existing_fields = [layer_defn.GetFieldDefn(i).GetName() for i in range(layer_defn.GetFieldCount())] + + for col in columns: + if col in existing_fields: + continue + + sample_value = None + for row in normalized_rows: + if row.get(col) is not None: + sample_value = row[col] + break + + field_type = _infer_ogr_field_type(sample_value) + field_defn = ogr.FieldDefn(col, field_type) + layer.CreateField(field_defn) + + layer_defn = layer.GetLayerDefn() + for row in normalized_rows: + feature = ogr.Feature(layer_defn) + for col in columns: + value = row.get(col) + if isinstance(value, bool): + value = int(value) + if value is None: + continue + feature.SetField(col, value) + layer.CreateFeature(feature) + feature = None + + ds = None + except Exception as exc: + logger.warning("Failed saving aux table '%s' to %s: %s", table, aux_file, exc) + + +def clean_geometries(gdf, stage=None, out_file=None, layer=None): + """ + Remove rows with invalid, None, or empty geometries from the GeoDataFrame. + + Args: + gdf (GeoDataFrame): The GeoDataFrame to clean. + + Returns: + GeoDataFrame: The cleaned GeoDataFrame with valid, non-null, + and non-empty geometries. + + """ + if gdf is None: + return gdf + + if gdf.empty: + return gdf + + m_null = gdf.geometry.isna() + + m_empty = m_null.copy() + m_empty[:] = False + non_null_mask = ~m_null + if non_null_mask.any(): + m_empty.loc[non_null_mask] = gdf.geometry.loc[non_null_mask].is_empty + + m_invalid = m_null.copy() + m_invalid[:] = False + valid_candidate_mask = non_null_mask & ~m_empty + if valid_candidate_mask.any(): + m_invalid.loc[valid_candidate_mask] = ~gdf.geometry.loc[valid_candidate_mask].is_valid + + rejected_mask = m_invalid | m_null | m_empty + if not rejected_mask.any(): + return gdf + + rejected_gdf = gdf[rejected_mask].copy() + rejected_gdf["BT_REJECT_REASON"] = np.where( + m_invalid[rejected_mask], + "invalid", + np.where(m_null[rejected_mask], "null", "empty"), + ) + + kept_gdf = gdf[~rejected_mask] + + n_invalid = int((rejected_gdf["BT_REJECT_REASON"] == "invalid").sum()) + n_null = int((rejected_gdf["BT_REJECT_REASON"] == "null").sum()) + n_empty = int((rejected_gdf["BT_REJECT_REASON"] == "empty").sum()) + total_removed = int(rejected_mask.sum()) + original_count = len(gdf) + + stage_prefix = f"[{stage}] " if stage else "" + logger.info( + "%sRemoved %s invalid, %s null, %s empty geometries (%s of %s rows)", + stage_prefix, + n_invalid, + n_null, + n_empty, + total_removed, + original_count, + ) + + layer_name = layer + if layer_name is None: + layer_name = f"rejected_{stage}" if stage else "rejected" + + if out_file is not None: + save_aux_layer(rejected_gdf, out_file, layer_name) + + return kept_gdf + + +def clean_line_geometries(line_gdf, min_length=bt_const.SMALL_BUFFER): + """Clean line geometries in the GeoDataFrame.""" + if line_gdf is None: + return line_gdf + + if line_gdf.empty: + return line_gdf + + line_gdf = line_gdf[~line_gdf.geometry.isna() & ~line_gdf.geometry.is_empty] + line_gdf = line_gdf[line_gdf.geometry.length > float(min_length)] + return line_gdf + + +def split_lines_to_segments(gdf): + """Split input lines to single-segment rows while preserving attributes.""" + if gdf is None: + return [] + + gdf, _ = chk_df_multipart(gdf, 'LineString') + + split_gdf_list = [] + for row in gdf.itertuples(index=False): + line = row.geometry + coords = list(line.coords) + + for i in range(len(coords) - 1): + segment = sh_geom.LineString([coords[i], coords[i + 1]]) + attributes = {col: getattr(row, col) for col in gdf.columns if col != "geometry"} + attributes["OLnSEG"] = i + single_row_gdf = gpd.GeoDataFrame([attributes], geometry=[segment], crs=gdf.crs) + split_gdf_list.append(single_row_gdf) + + return split_gdf_list + + +def lines_gdf_to_list(gdf): + """Convert lines GeoDataFrame rows to list of single-row GeoDataFrames.""" + if gdf is None: + return [] + + if has_multilinestring(gdf): + gdf = gdf.explode(index_parts=False) + + out_list = [] + for row in gdf.itertuples(index=False): + line = row.geometry + attributes = {col: getattr(row, col) for col in gdf.columns if col != "geometry"} + single_row_gdf = gpd.GeoDataFrame([attributes], geometry=[line], crs=gdf.crs) + out_list.append(single_row_gdf) + + return out_list + + +# remember which input row (and its OLnSEG) each processed piece came from +SOURCE_ROW_FIELD = "BT_SRC_ROW" +SOURCE_SEG_FIELD = "BT_SRC_SEG" + + +def keep_source_seg(gdf): + """Remember each row's OLnSEG before split_lines_to_segments renumbers it per vertex.""" + if gdf is not None and "OLnSEG" in gdf.columns: + gdf = gdf.copy() + gdf[SOURCE_SEG_FIELD] = gdf["OLnSEG"] + return gdf + + +def restore_source_seg(gdf): + """Put back the OLnSEG saved by keep_source_seg once the segments are merged into their rows.""" + if gdf is not None and SOURCE_SEG_FIELD in gdf.columns: + gdf = gdf.copy() + gdf["OLnSEG"] = gdf[SOURCE_SEG_FIELD] + gdf = gdf.drop(columns=SOURCE_SEG_FIELD) + return gdf + + +def prepare_lines_gdf(file_path, layer=None, proc_segments=True, tag_source_rows=False): + """ + Split lines at vertices or return original rows. + + It handles for MultiLineString. With tag_source_rows, OLnFID/OLnSEG are added if missing + and each row records its input row and OLnSEG, so pieces can be merged back to it. + + """ + gdf = read_geospatial_file(file_path, layer=layer) + if gdf is None: + return [] + + if tag_source_rows: + gdf, _ = chk_df_multipart(gdf, "LineString") + gdf = gdf.reset_index(drop=True) + gdf[SOURCE_ROW_FIELD] = gdf.index + gdf[SOURCE_SEG_FIELD] = gdf["OLnSEG"] + + if proc_segments: + return split_lines_to_segments(gdf) + + return lines_gdf_to_list(gdf) + + +def corridor_threshold_to_mask(corridor_thresh): + """ + Convert BERA corridor threshold raster to a binary inside-corridor mask. + + Corridor rasters use 0 for inside the selected corridor and 1 for outside. + Polygonization and morphology helpers use 1 for selected cells. + """ + return np.ma.where(corridor_thresh == 0.0, 1, 0).filled(0).astype(np.int32) + + +def apply_canopy_mask(corridor_mask, canopy_raster): + """Gate corridor cells by canopy raster where canopy value 0 means keep.""" + canopy = np.ma.asarray(canopy_raster).filled(1) + return np.where((np.asarray(corridor_mask) == 1) & (canopy == 0), 1, 0).astype(np.int32) + + +def generalize_binary_mask(binary_mask, exp_shk_cell, boundary_clean=True): + """Apply FLM-style cell-based expand/shrink and boundary clean.""" + clean_raster = np.asarray(binary_mask, dtype=np.int32) + exp_shk_cell = int(float(exp_shk_cell or 0)) + + if exp_shk_cell > 0: + # FLM original Expand/Shrink equivalent. The range is cell-based. + cell_size = int(exp_shk_cell * 2 + 1) + clean_raster = ndimage.grey_dilation(clean_raster, size=(cell_size, cell_size)) + clean_raster = ndimage.grey_erosion(clean_raster, size=(cell_size, cell_size)) + elif bt_const.BT_DEBUGGING: + print("No Expand And Shrink cell performed.") + + if boundary_clean: + # Pragmatic open-source approximation of ArcGIS BoundaryClean_sa. + clean_raster = ndimage.median_filter(clean_raster, size=3) + + return clean_raster.astype(np.int32) + + +def morph_raster(corridor_thresh, canopy_raster, exp_shk_cell, cell_size_x): + corridor_mask = corridor_threshold_to_mask(corridor_thresh) + raster_class = apply_canopy_mask(corridor_mask, canopy_raster) + return generalize_binary_mask(raster_class, exp_shk_cell) + + +def closest_point_to_line(point, line): + if not line: + return None + + pt = line.interpolate(line.project(sh_geom.Point(point))) + return pt + + +def line_coord_list(line): + point_list = [] + try: + for point in list(line.coords): # loops through every point in a line + # loops through every vertex of every segment + if point: # adds all the vertices to segment_list, which creates an array + point_list.append(sh_geom.Point(point[0], point[1])) + except Exception as e: + print(e) + + return point_list + + +def intersection_of_lines(line_1, line_2): + """ + Only LINESTRING is dealt with for now. + + Args: + line_1 : + line_2 : + + Returns: + sh_geom.Point: intersection point + + """ + # intersection collection, may contain points and lines + inter = None + if line_1 and line_2: + inter = line_1.intersection(line_2) + + # TODO: intersection may return GeometryCollection, LineString or MultiLineString + if inter: + if ( + type(inter) is sh_geom.GeometryCollection + or type(inter) is sh_geom.LineString + or type(inter) is sh_geom.MultiLineString + ): + return inter.centroid + + return inter + + +def get_angle(line, vertex_index): + """ + Calculate the angle of the first or last segment. + + # TODO: use np.arctan2 instead of np.arctan + + Args: + line: LineString + end_index: 0 or -1 of the line vertices. Consider the multipart. + + """ + pts = line_coord_list(line) + + if vertex_index == 0: + pt_1 = pts[0] + pt_2 = pts[1] + elif vertex_index == -1: + pt_1 = pts[-1] + pt_2 = pts[-2] + + delta_x = pt_2.x - pt_1.x + delta_y = pt_2.y - pt_1.y + if np.isclose(pt_1.x, pt_2.x): + angle = np.pi / 2 + if delta_y > 0: + angle = np.pi / 2 + elif delta_y < 0: + angle = -np.pi / 2 + else: + angle = np.arctan(delta_y / delta_x) + + # arctan is in range [-pi/2, pi/2], regulate all angles to [[-pi/2, 3*pi/2]] + if delta_x < 0: + angle += np.pi # the second or fourth quadrant + + return angle + + +def points_are_close(pt1, pt2): + if abs(pt1.x - pt2.x) < DISTANCE_THRESHOLD and abs(pt1.y - pt2.y) < DISTANCE_THRESHOLD: + return True + else: + return False + +def save_raster_to_file(in_raster_mem, in_meta, out_raster_file): + """ + Save raster matrix in memory to file. + + Args: + in_raster_mem: numpy raster + in_meta: input meta + out_raster_file: output raster file + + """ + with rasterio.open(out_raster_file, "w", **in_meta) as dest: + dest.write(in_raster_mem, indexes=1) + + +def generate_perpendicular_line_precise(points, offset=20): + """ + Generate a perpendicular line to the input line at the given point. + + Args: + points (list[Point]): The points where to generate the perpendicular lines. + offset (float): The length of the perpendicular line. + + Returns: + shapely.geometry.LineString: The generated perpendicular line. + + """ + # Compute the angle of the line + if len(points) not in [2, 3]: + return None + + center = points[1] + perp_line = None + + if len(points) == 2: + head = points[0] + tail = points[1] + + delta_x = head.x - tail.x + delta_y = head.y - tail.y + angle = 0.0 + + if math.isclose(delta_x, 0.0): + angle = math.pi / 2 + else: + angle = math.atan(delta_y / delta_x) + + start = [center.x + offset / 2.0, center.y] + end = [center.x - offset / 2.0, center.y] + line = sh_geom.LineString([start, end]) + perp_line = sh_aff.rotate(line, angle + math.pi / 2.0, origin=center, use_radians=True) + elif len(points) == 3: + head = points[0] + tail = points[2] + + angle_1 = _line_angle(center, head) + angle_2 = _line_angle(center, tail) + angle_diff = (angle_2 - angle_1) / 2.0 + head_new = sh_geom.Point( + center.x + offset / 2.0 * math.cos(angle_1), + center.y + offset / 2.0 * math.sin(angle_1), + ) + if head.has_z: + head_new = shapely.force_3d(head_new) + try: + perp_seg_1 = sh_geom.LineString([center, head_new]) + perp_seg_1 = sh_aff.rotate(perp_seg_1, angle_diff, origin=center, use_radians=True) + perp_seg_2 = sh_aff.rotate(perp_seg_1, math.pi, origin=center, use_radians=True) + perp_line = sh_geom.LineString([list(perp_seg_1.coords)[1], list(perp_seg_2.coords)[1]]) + except Exception as e: + print(e) + + return perp_line + + +def _line_angle(point_1, point_2): + """ + Calculate the angle of the line. + + Args: + point_1, point_2: start and end points of shapely line + + """ + delta_y = point_2.y - point_1.y + delta_x = point_2.x - point_1.x + + angle = math.atan2(delta_y, delta_x) + return angle + + +def corridor_raster(raster_clip, out_meta, source, destination, cell_size, corridor_threshold): + """ + Calculate corridor raster. + + Args: + raster_clip (raster): + out_meta : raster file meta + source (list of point tuple(s)): start point in row/col + destination (list of point tuple(s)): end point in row/col + cell_size (tuple): (cell_size_x, cell_size_y) + corridor_threshold (double) + + Returns: + corridor raster + + """ + try: + # change all nan to BT_NODATA_COST for workaround + if len(raster_clip.shape) > 2: + raster_clip = np.squeeze(raster_clip, axis=0) + + algo_cost.remove_nan_from_array_refactor(raster_clip) + + # generate the cost raster to source point + mcp_source = sk_graph.MCP_Geometric(raster_clip, sampling=cell_size) + source_cost_acc = mcp_source.find_costs(source)[0] + del mcp_source + + # # # generate the cost raster to destination point + mcp_dest = sk_graph.MCP_Geometric(raster_clip, sampling=cell_size) + dest_cost_acc = mcp_dest.find_costs(destination)[0] + + # Generate corridor + corridor = source_cost_acc + dest_cost_acc + corridor = np.ma.masked_invalid(corridor) + + # Calculate minimum value of corridor raster + if np.ma.min(corridor) is not None: + corr_min = float(np.ma.min(corridor)) + else: + corr_min = 0.5 + + # normalize corridor raster by deducting corr_min + corridor_norm = corridor - corr_min + corridor_thresh_cl = np.ma.where(corridor_norm >= corridor_threshold, 1.0, 0.0) + + except Exception as e: + print(e) + print("corridor_raster: Exception occurred.") + return None + + return corridor_thresh_cl + + +def remove_holes(geom): + if geom.geom_type == "Polygon": + if geom.interiors: + return sh_geom.Polygon(geom.exterior) + return geom + elif geom.geom_type == "MultiPolygon": + new_polygons = [] + for polygon in geom.geoms: # Iterate through MultiPolygon + if polygon.interiors: + new_polygons.append(sh_geom.Polygon(polygon.exterior)) + else: + new_polygons.append(polygon) + return sh_geom.MultiPolygon(new_polygons) + return geom # Return other geometry types as is + +def _reverse_line(line): + """Reverse a LineString coordinate sequence.""" + return sh_geom.LineString( + list(line.coords)[::-1] + ) + +def _safe_linemerge(geometry): + """ + Safely merge line geometry. + + Returns + ------- + LineString + When all input parts form one connected line. + + MultiLineString + When multiple disconnected line components remain. + + None + When the input contains no usable line geometry. + """ + def _usable_line(line): + + if line is None: + return False + + if line.is_empty: + return False + + if line.length <= 0: + return False + + if line.is_ring: + return False + + return True + + if geometry is None: + return None + + try: + if geometry.is_empty: + return geometry + except Exception: + return None + + # Already one usable line. + if isinstance(geometry, sh_geom.LineString): + if _usable_line(geometry): + return geometry + else: + valid_geom=sh_val.make_valid(geometry) + + if isinstance(valid_geom, sh_geom.LineString): + return valid_geom if _usable_line(valid_geom) else None + + elif isinstance(valid_geom, sh_geom.MultiLineString): + try: + cleaned_parts = [] + for part in valid_geom.geoms: + if not _usable_line(part): + continue + else: + cleaned_parts.append(part) + + if len(cleaned_parts) == 0: + return None + else: + return sh_ops.linemerge(cleaned_parts) + except (TypeError, ValueError): + return None + elif isinstance(valid_geom, sh_geom.GeometryCollection): + lines = [] + for part in valid_geom.geoms: + if isinstance(part, sh_geom.LineString): + if _usable_line(part): + lines.append(part) + elif isinstance(part, sh_geom.MultiLineString): + lines.extend( + line + for line in part.geoms + if _usable_line(line)) + + if not lines: + return None + + if len(lines) == 1: + return lines[0] + + return sh_ops.linemerge(lines) + + # linemerge is valid for a MultiLineString. + if isinstance(geometry, sh_geom.MultiLineString): + try: + cleaned_parts = [] + for part in geometry.geoms: + if not _usable_line(part): + continue + else: + cleaned_parts.append(part) + + if len(cleaned_parts) == 0: + return None + else: + return sh_ops.linemerge(cleaned_parts) + except (TypeError, ValueError): + return None + + # Extract line components from a mixed collection. + if isinstance(geometry, sh_geom.GeometryCollection): + lines = [] + + for part in geometry.geoms: + if part is None or part.is_empty: + continue + + if isinstance(part, sh_geom.LineString): + if _usable_line(part): + lines.append(part) + + elif isinstance(part, sh_geom.MultiLineString): + lines.extend(line + for line in part.geoms + if _usable_line(line)) + + if not lines: + return None + + if len(lines) == 1: + return lines[0] + + unioned = sh_ops.unary_union(lines) + + if isinstance(unioned, sh_geom.LineString): + return unioned + + if isinstance(unioned, sh_geom.MultiLineString): + try: + return sh_ops.linemerge(unioned) + except (TypeError, ValueError): + return unioned + + return None + + return None + +def merge_lines_by_original_id( + line_gdf, + group_field="OLnFID", + order_field="OLnSEG", + max_bridge_gap=0.5, + output_segment_value=-1, + geometry_count_field="merged_part_count", +): + """ + Reconstruct ordered LineString features by original ID. + + Works for centerlines and least-cost paths. + """ + if line_gdf is None or line_gdf.empty: + return line_gdf + + if group_field not in line_gdf.columns: + raise KeyError( + f"Missing grouping field: {group_field}" + ) + + if order_field not in line_gdf.columns: + raise KeyError( + f"Missing ordering field: {order_field}" + ) + + output_rows = [] + crs = line_gdf.crs + + for original_id, group in line_gdf.groupby( + group_field, + sort=False, + ): + group = group.sort_values( + order_field, + kind="stable", + ) + + ordered_lines = [] + + for geometry in group.geometry: + if geometry is None: + continue + + try: + if geometry.is_empty: + continue + except Exception: + continue + + if isinstance(geometry, sh_geom.LineString): + if geometry.length > 0: + ordered_lines.append(geometry) + + elif isinstance( + geometry, + sh_geom.MultiLineString, + ): + parts = [ + part + for part in geometry.geoms + if not part.is_empty + and part.length > 0 + ] + + if not parts: + continue + + locally_merged = _safe_linemerge( + sh_ops.unary_union(parts) + ) + + if isinstance( + locally_merged, + sh_geom.LineString, + ): + if locally_merged.length > 0: + ordered_lines.append(locally_merged) + + elif isinstance( + locally_merged, + sh_geom.MultiLineString, + ): + ordered_lines.extend( + part + for part in locally_merged.geoms + if not part.is_empty + and part.length > 0 + ) + + if not ordered_lines: + logger.warning( + "OLnFID=%s has no usable line parts", + original_id, + ) + continue + + oriented = [ordered_lines[0]] + + for current in ordered_lines[1:]: + + previous = oriented[-1] + + previous_end = sh_geom.Point( + previous.coords[-1] + ) + + start_gap = previous_end.distance( + sh_geom.Point(current.coords[0]) + ) + + end_gap = previous_end.distance( + sh_geom.Point(current.coords[-1]) + ) + + if end_gap < start_gap: + current = _reverse_line(current) + + oriented.append(current) + coords = list(oriented[0].coords) + + max_gap = 0.0 + + for i, line in enumerate(oriented[1:], start=1): + + line_coords = list(line.coords) + + gap = ( + sh_geom.Point(coords[-1]) + .distance( + sh_geom.Point(line_coords[0]) + ) + ) + + max_gap = max(max_gap, gap) + + if gap > max_bridge_gap: + coords.append(line_coords[0]) + coords.extend(line_coords[1:]) + + merged = sh_geom.LineString(coords) + + if merged is None or merged.is_empty: + logger.warning( + "OLnFID=%s produced no geometry during merge", + original_id, + ) + continue + + row = group.iloc[0].copy() + row.geometry = merged + row[group_field] = original_id + row[order_field] = output_segment_value + row[geometry_count_field] = len(ordered_lines) + row["merge_max_gap"] = max_gap + row["merge_status"] = ("merged" if max_gap <= max_bridge_gap else "bridged") + output_rows.append(row) + + return gpd.GeoDataFrame( + output_rows, + geometry="geometry", + crs=crs, + ).reset_index(drop=True) + +def merge_corridors_by_original_id( + corridor_gdf, + group_field="OLnFID", + order_field="OLnSEG", + repair_invalid=True, +): + """ + Union corridor polygons back to one record per + original seedline ID. + """ + if corridor_gdf is None or corridor_gdf.empty: + return corridor_gdf + + if group_field not in corridor_gdf.columns: + raise KeyError( + f"Missing grouping field: {group_field}" + ) + + output_rows = [] + crs = corridor_gdf.crs + + for original_id, group in corridor_gdf.groupby( + group_field, + sort=False, + ): + polygon_parts = [] + + for geometry in group.geometry: + if geometry is None or geometry.is_empty: + continue + + if repair_invalid and not geometry.is_valid: + geometry = geometry.buffer(0) + + if geometry is None or geometry.is_empty: + continue + + if isinstance(geometry, sh_geom.Polygon): + polygon_parts.append(geometry) + + elif isinstance( + geometry, + sh_geom.MultiPolygon, + ): + polygon_parts.extend( + list(geometry.geoms) + ) + + if not polygon_parts: + continue + + merged = sh_ops.unary_union( + polygon_parts + ) + + if repair_invalid and not merged.is_valid: + merged = merged.buffer(0) + + row = group.iloc[0].copy() + row.geometry = merged + row[group_field] = original_id + + if order_field in row.index: + row[order_field] = -1 + + row["merged_corridor_part_count"] = len( + polygon_parts + ) + + row["merge_status"] = ( + "merged" + if isinstance(merged, sh_geom.Polygon) + else "disconnected" + ) + + output_rows.append(row) + + return gpd.GeoDataFrame( + output_rows, + geometry="geometry", + crs=crs, + ).reset_index(drop=True) + +def chk_df_multipart(df:gpd.GeoDataFrame, + chk_shp_in_string:str)-> tuple[gpd.GeoDataFrame , bool]: + """ + Check whether the input geopandas.GeoDataFrame contains multipart geometry. + + If multipart geometry is found, it is exploded into single geometries. Returns the GeoDataFrame + and whether multipart geometry was found. + + Args: + df: Any geopandas.GeoDataFrame like + chk_shp_in_string: String that the input GeoDataFrame geometry type expected to contain, + i.e. 'Point', 'Polygon', 'LineString' + + Returns: Expected geometry type and boolean of multipart geometry + + """ + try: + found = False + # Check the OLnFID column in data. If it is not, column will be created + if "OLnFID" not in df.columns.array: + print("New column created: {}".format("OLnFID")) + df["OLnFID"] = df.index + + # Check the OLnSEG column in data. If it is not, column will be created + if "OLnSEG" not in df.columns.array: + print("New column created: {}".format("OLnSEG")) + df["OLnSEG"] = 0 + + if has_multilinestring(df): + found = True + df = df.explode() + if type(df) is gpd.geodataframe.GeoDataFrame: + df["OLnSEG"] = df.groupby("OLnFID").cumcount() + df = df.sort_values(by=["OLnFID", "OLnSEG"]) + df = df.reset_index(drop=True) + else: + found = False + + return df, found + except Exception as e: + print(e) + return df, True + + +def _is_degenerate_line( + line, + min_length=1.0, + endpoint_tolerance=1e-6, + min_straightness=0.10, + stage="final",): + """ + Return True when a line is unusable. + + Parameters + ---------- + line : shapely geometry + LineString or mergeable MultiLineString. + + min_length : float + Minimum length used primarily for final merged output. + + endpoint_tolerance : float + Absolute tolerance for coincident endpoints. + + min_straightness : float + Minimum endpoint-gap / line-length ratio. + + stage : {"segment", "regeneration", "final"} + Controls how strictly the line is validated. + """ + if line is None: + return True + + try: + if line.is_empty: + return True + except Exception: + return True + + if isinstance(line, sh_geom.MultiLineString): + try: + merged = _safe_linemerge(line) + except Exception: + return True + + if isinstance(merged, sh_geom.MultiLineString): + # Individual centerline should normally be connected. + # Final merge may handle components separately. + return True + + line = merged + + if not isinstance(line, sh_geom.LineString): + return True + + try: + length = float(line.length) + except (TypeError, ValueError, OverflowError): + return True + + if not np.isfinite(length): + return True + + if length <= endpoint_tolerance: + return True + + try: + coords = list(line.coords) + except Exception: + return True + + if len(coords) < 2: + return True + + xy_coords = [] + + for coord in coords: + if len(coord) < 2: + return True + + x = float(coord[0]) + y = float(coord[1]) + + if not np.isfinite(x) or not np.isfinite(y): + return True + + xy_coords.append((x, y)) + + if len(set(xy_coords)) < 2: + return True + + endpoint_gap = sh_geom.Point(xy_coords[0]).distance( + sh_geom.Point(xy_coords[-1]) + ) + + if endpoint_gap <= endpoint_tolerance: + return True + + straightness = endpoint_gap / max(length, 1e-9) + + if stage == "segment": + # Be permissive. Short segments are expected when + # proc_segments=True. + # + # Reject only an extreme loop or retracing collapse. + if length >= max(2.0 * min_length, endpoint_tolerance): + if straightness < 0.05: + return True + + return False + + if stage == "regeneration": + # Regenerated pieces need some meaningful endpoint extent, + # but can still be short. + if length < max(0.25 * min_length, endpoint_tolerance): + return True + + if straightness < 0.08: + return True + + return False + + if stage == "final": + # Strong checks apply only after restoring the original ID. + if length < min_length: + logger.info( + f"DEGENERATE length={length:.2f}" + ) + return True + + if straightness < min_straightness: + logger.info( + f"DEGENERATE straightness={straightness:.4f}" + ) + return True + + return False + + raise ValueError( + "stage must be 'segment', 'regeneration', or 'final'" + ) + + +def drop_layer_if_exists(gpkg, layer): + """Drop ``layer`` from GeoPackage ``gpkg`` (table and gpkg metadata rows) if present.""" + gpkg = Path(gpkg) + if not gpkg.exists(): + return + + layer_names = [row[0] for row in pyogrio.list_layers(gpkg)] + if layer not in layer_names: + return + + conn = sqlite3.connect(gpkg) + try: + conn.execute(f'DROP TABLE "{layer}"') + conn.execute("DELETE FROM gpkg_contents WHERE table_name=?", (layer,)) + conn.execute("DELETE FROM gpkg_geometry_columns WHERE table_name=?", (layer,)) + conn.commit() + finally: + conn.close() + + +# Backwards-compatible alias; identical behaviour. +prepare_gpkg_layer = drop_layer_if_exists diff --git a/beratools/modules/mapping/algo_cost.py b/beratools/modules/mapping/algo_cost.py new file mode 100644 index 0000000..0779ae6 --- /dev/null +++ b/beratools/modules/mapping/algo_cost.py @@ -0,0 +1,377 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + This file hosts cost raster related functions. +""" + +import numpy as np +import scipy +from rasterio.features import geometry_mask + +import beratools.core.constants as bt_const + + +def reduce_chm_in_line_buffer( + in_chm, + meta, + line, + buffer_width, + multiplier=0.5, +): + """Return a CHM copy with valid values reduced inside a line buffer.""" + buffer_width = float(buffer_width) + multiplier = float(multiplier) + if buffer_width < 0.0: + raise ValueError("buffer_width must be greater than or equal to zero") + if not 0.0 <= multiplier <= 1.0: + raise ValueError("multiplier must be between zero and one") + if line is None or line.is_empty: + raise ValueError("line must be a non-empty geometry") + + source = np.ma.asarray(in_chm) + if source.ndim == 2: + raster_shape = source.shape + elif source.ndim == 3 and source.shape[0] == 1: + raster_shape = source.shape[1:] + else: + raise ValueError("in_chm must be a 2D or single-band 3D raster") + + reduced = np.ma.array(source, dtype=float, copy=True) + if buffer_width == 0.0 or multiplier == 1.0: + return reduced + + inside_buffer = geometry_mask( + [line.buffer(buffer_width)], + out_shape=raster_shape, + transform=meta["transform"], + invert=True, + ) + if reduced.ndim == 3: + inside_buffer = inside_buffer[np.newaxis, ...] + + data = reduced.data + valid = inside_buffer & ~np.ma.getmaskarray(reduced) & np.isfinite(data) + nodata = meta.get("nodata") + if nodata is not None and np.isfinite(nodata): + valid &= data != nodata + data[valid] *= multiplier + return reduced + + +def cost_raster( + in_raster, + meta, + tree_radius=2.5, + canopy_ht_threshold=2.5, + max_line_dist=2.5, + canopy_avoid=0.4, + cost_raster_exponent=1.5, +): + """ + General version of cost_raster. + + To be merged later: variables and consistent nodata solution + + """ + if len(in_raster.shape) > 2: + in_raster = np.squeeze(in_raster, axis=0) + + # regulate canopy_avoid between 0 and 1 + avoidance = max(0, min(1, canopy_avoid)) + cell_x, cell_y = meta["transform"][0], -meta["transform"][4] + + kernel_radius = int(tree_radius / cell_x) + kernel = circle_kernel_refactor(2 * kernel_radius + 1, kernel_radius) + dyn_canopy_ndarray = dyn_np_cc_map(in_raster, canopy_ht_threshold) + + cc_std, cc_mean = cost_focal_stats(dyn_canopy_ndarray, kernel) + cc_smooth = cost_norm_dist_transform(dyn_canopy_ndarray, max_line_dist, [cell_x, cell_y]) + + cost_clip = dyn_np_cost_raster_refactor( + dyn_canopy_ndarray, cc_mean, cc_std, cc_smooth, avoidance, cost_raster_exponent + ) + + # TODO use nan or BT_DATA? + cost_clip[in_raster == bt_const.BT_NODATA] = np.nan + dyn_canopy_ndarray[in_raster == bt_const.BT_NODATA] = np.nan + + return cost_clip, dyn_canopy_ndarray + + +def remove_nan_from_array_refactor(matrix, replacement_value=bt_const.BT_NODATA_COST): + # Use boolean indexing to replace nan values + matrix[np.isnan(matrix)] = replacement_value + + +def dyn_np_cc_map(in_chm, canopy_ht_threshold): + """ + Create a new canopy raster. + + MaskedArray based on the threshold comparison of in_chm (canopy height model) + with canopy_ht_threshold. It assigns 1.0 where the condition is True (canopy) + and 0.0 where the condition is False (non-canopy). + + """ + canopy_ndarray = np.ma.where(in_chm >= canopy_ht_threshold, 1.0, 0.0).astype(float) + return canopy_ndarray + + +def cost_focal_stats(canopy_ndarray, kernel): + mask = ( + canopy_ndarray.mask if np.ma.is_masked(canopy_ndarray) else np.zeros(canopy_ndarray.shape, dtype=bool) + ) + # Replace masked/nan values with 0 for convolution; track valid pixel counts + data = np.where(mask, 0.0, np.asarray(canopy_ndarray, dtype=float)) + valid = (~mask).astype(float) + + # Use fast C-level convolution instead of generic_filter with Python callbacks + kernel_f = kernel.astype(float) + sum_vals = scipy.ndimage.convolve(data, kernel_f, mode="nearest") + count = scipy.ndimage.convolve(valid, kernel_f, mode="nearest") + count = np.maximum(count, 1.0) # avoid division by zero + + mean_array = sum_vals / count + + # Var = E[X^2] - E[X]^2 + sum_sq = scipy.ndimage.convolve(data * data, kernel_f, mode="nearest") + variance = sum_sq / count - mean_array * mean_array + variance = np.maximum(variance, 0.0) # clamp numerical noise + std_array = np.sqrt(variance) + + return std_array, mean_array + + +def cost_norm_dist_transform(canopy_ndarray, max_line_dist, sampling): + """Compute a distance-based cost map based on the proximity of valid data points.""" + # Convert masked array to a regular array and fill the masked areas with np.nan + in_ndarray = canopy_ndarray.filled(np.nan) + + # Compute the Euclidean distance transform (edt) where the valid values are + euc_dist_array = scipy.ndimage.distance_transform_edt( + np.logical_not(np.isnan(in_ndarray)), sampling=sampling + ) + + # Apply the mask back to set the distances to np.nan + euc_dist_array[canopy_ndarray.mask] = np.nan + + # Calculate the smoothness (cost) array + normalized_cost = float(max_line_dist) - euc_dist_array + normalized_cost[normalized_cost <= 0.0] = 0.0 + smooth_cost_array = normalized_cost / float(max_line_dist) + + return smooth_cost_array + + +def dyn_np_cost_raster_refactor(canopy_ndarray, cc_mean, cc_std, cc_smooth, avoidance, cost_raster_exponent): + # Calculate the lower and upper bounds for canopy cover (mean ± std deviation) + lower_bound = cc_mean - cc_std + upper_bound = cc_mean + cc_std + + # Calculate the ratio between the lower and upper bounds + ratio_lower_upper = np.divide( + lower_bound, + upper_bound, + where=upper_bound != 0, + out=np.zeros(lower_bound.shape, dtype=float), + ) + + # Normalize the ratio to a scale between 0 and 1 + normalized_ratio = (1 + ratio_lower_upper) / 2 + + # Adjust where the sum of mean and std deviation is less than or equal to zero + adjusted_cover = cc_mean + cc_std + adjusted_ratio = np.where(adjusted_cover <= 0, 0, normalized_ratio) + + # Combine canopy cover ratio with smoothing, weighted by avoidance factor + weighted_cover = adjusted_ratio * (1 - avoidance) + (cc_smooth * avoidance) + + # Final cost modification based on canopy presence (masked by canopy_ndarray) + final_cost = np.where(canopy_ndarray.data == 1, 1, weighted_cover) + + # Apply the exponential transformation to the cost values + exponent_cost = np.exp(final_cost) + + # Raise the cost to the specified exponent + result_cost_raster = np.power(exponent_cost, float(cost_raster_exponent)) + + return result_cost_raster + + +def circle_kernel_refactor(size, radius): + """ + Create a circular kernel using Scipy. + + Args: + size : kernel size + radius : radius of the circle + + Returns: + kernel (ndarray): A circular kernel. + + Examples: + kernel_scipy = create_circle_kernel_scipy(17, 8) + will replicate xarray-spatial kernel + cell_x = 0.3 + cell_y = 0.3 + tree_radius = 2.5 + convolution.circle_kernel(cell_x, cell_y, tree_radius) + + """ + # Create grid points (mesh) + y, x = np.ogrid[:size, :size] + + # Center of the kernel + center_x, center_y = (size - 1) / 2, (size - 1) / 2 + + # Calculate the distance from the center + distance = np.sqrt((x - center_x) ** 2 + (y - center_y) ** 2) + + # Create a circular kernel + kernel = distance <= radius + return kernel.astype(float) + + +def alt_cost_raster( + in_raster, + meta, + tree_gaps, + tree_radius=2.5, + canopy_ht_threshold=2.5, + max_line_dist=2.5, + canopy_avoid=0.4, + cost_raster_exponent=1.5, +): + """Alternative version of cost_raster.""" + + def alt_dyn_np_cc_map(in_chm, canopy_ht_threshold, tree_gaps=None): + """ + Create a new canopy raster. + + MaskedArray based on the threshold comparison of in_chm (canopy height model) + with canopy_ht_threshold. It assigns 1.0 where the condition is True (canopy) + and 0.0 where the condition is False (non-canopy). + + """ + canopy_ndarray = np.ma.where(in_chm >= canopy_ht_threshold, 1.0, 0.0).astype(float) + canopy_ndarray = np.ma.where(tree_gaps.astype(bool), 0.0, canopy_ndarray) + + return canopy_ndarray + + def alt_cost_focal_stats(canopy_ndarray, kernel, tree_gaps=None): + mask = ( + canopy_ndarray.mask + if np.ma.is_masked(canopy_ndarray) + else np.zeros(canopy_ndarray.shape, dtype=bool) + ) + # Replace masked/nan values with 0 for convolution; track valid pixel counts + data = np.where(mask, 0.0, np.asarray(canopy_ndarray, dtype=float)) + data[tree_gaps.astype(bool)] = 0.0 + valid = (~mask).astype(float) + + # Use fast C-level convolution instead of generic_filter with Python callbacks + kernel_f = kernel.astype(float) + sum_vals = scipy.ndimage.convolve(data, kernel_f, mode="nearest") + count = scipy.ndimage.convolve(valid, kernel_f, mode="nearest") + count = np.maximum(count, 1.0) # avoid division by zero + + mean_array = sum_vals / count + + # Var = E[X^2] - E[X]^2 + sum_sq = scipy.ndimage.convolve(data * data, kernel_f, mode="nearest") + variance = sum_sq / count - mean_array * mean_array + variance = np.maximum(variance, 0.0) # clamp numerical noise + std_array = np.sqrt(variance) + + return std_array, mean_array + + def alt_cost_norm_dist_transform(canopy_ndarray, max_line_dist, sampling, tree_gaps=None): + """Compute a distance-based cost map based on the proximity of valid data points.""" + # Convert masked array to a regular array and fill the masked areas with np.nan + in_ndarray = canopy_ndarray.filled(np.nan) + in_ndarray[tree_gaps.astype(bool)] = 0.0 + # Compute the Euclidean distance transform (edt) where the valid values are + dist_transform_array = scipy.ndimage.distance_transform_edt(np.logical_not(np.isnan(in_ndarray)), + sampling=sampling + ) + + # Apply the mask back to set the distances to np.nan + dist_transform_array[canopy_ndarray.mask] = np.nan + # dist_transform_crown_array[canopy_ndarray.mask] = np.nan + + # Calculate the smoothness (cost) array + normalized_cost = float(max_line_dist) - dist_transform_array # *dist_transform_crown_array) + normalized_cost[normalized_cost <= 0.0] = 0.0 + smooth_cost_array = normalized_cost / float(max_line_dist) + + return smooth_cost_array + + def alt_dyn_np_cost_raster_refactor( + canopy_ndarray, cc_mean, cc_std, cc_smooth, avoidance, cost_raster_exponent, tree_gaps=None + ): + # Calculate the lower and upper bounds for canopy cover (mean ± std deviation) + lower_bound = cc_mean - cc_std + upper_bound = cc_mean + cc_std + + # Calculate the ratio between the lower and upper bounds + ratio_lower_upper = np.divide( + lower_bound, + upper_bound, + where=upper_bound != 0, + out=np.zeros(lower_bound.shape, dtype=float), + ) + + # Normalize the ratio to a scale between 0 and 1 + normalized_ratio = (1 + ratio_lower_upper) / 2 + + # Adjust where the sum of mean and std deviation is less than or equal to zero + adjusted_cover = cc_mean + cc_std + adjusted_ratio = np.where(adjusted_cover <= 0, 0, normalized_ratio) + + # Combine canopy cover ratio with smoothing, weighted by avoidance factor + weighted_cover = adjusted_ratio * (1 - avoidance) + (cc_smooth * avoidance) + + # Final cost modification based on canopy presence (masked by canopy_ndarray) + final_cost = np.where(canopy_ndarray.data == 1, 1, weighted_cover) + + # Apply the exponential transformation to the cost values + exponent_cost = np.exp(final_cost) + + # Raise the cost to the specified exponent + result_cost_raster = np.power(exponent_cost, float(cost_raster_exponent)) + result_cost_raster[tree_gaps == 1] = 1.0 + + return result_cost_raster + + if len(in_raster.shape) > 2: + in_raster = np.squeeze(in_raster, axis=0) + + # regulate canopy_avoid between 0 and 1 + avoidance = max(0, min(1, int(canopy_avoid))) + cell_x, cell_y = meta["transform"][0], -meta["transform"][4] + tree_gaps_=tree_gaps.copy() + tree_gaps_[tree_gaps<=canopy_ht_threshold]=0 + kernel_radius = int(tree_radius / cell_x) + kernel = circle_kernel_refactor(2 * kernel_radius + 1, kernel_radius) + dyn_canopy_ndarray = alt_dyn_np_cc_map(in_raster, canopy_ht_threshold, tree_gaps_) + + cc_std, cc_mean = alt_cost_focal_stats(dyn_canopy_ndarray, kernel, tree_gaps_) + cc_smooth = alt_cost_norm_dist_transform(dyn_canopy_ndarray, max_line_dist, [cell_x, cell_y],tree_gaps_) + + cost_clip = alt_dyn_np_cost_raster_refactor( + dyn_canopy_ndarray, cc_mean, cc_std, cc_smooth, avoidance, cost_raster_exponent,tree_gaps_ + ) + + # TODO use nan or BT_DATA? + cost_clip[in_raster == bt_const.BT_NODATA] = np.nan + dyn_canopy_ndarray[in_raster == bt_const.BT_NODATA] = np.nan + + return cost_clip, dyn_canopy_ndarray diff --git a/beratools/modules/mapping/algo_dijkstra.py b/beratools/modules/mapping/algo_dijkstra.py new file mode 100644 index 0000000..020ea2c --- /dev/null +++ b/beratools/modules/mapping/algo_dijkstra.py @@ -0,0 +1,500 @@ +""" +Least Cost Path Algorithm. + +This algorithm is adapted from the QGIS plugin: +Find the least cost path with given cost raster and points +Original author: FlowMap Group@SESS.PKU +Source code repository: https://github.com/Gooong/LeastCostPath + +Copyright (C) 2023 by AppliedGRG +Author: Richard Zeng +Date: 2023-03-01 + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" + +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = "$Format:%H$" + +import math +import queue +from collections import defaultdict + +import numpy as np +import rasterio +import shapely.geometry as sh_geom +import skimage.graph as sk_graph + +import beratools.core.constants as bt_const + +sqrt2 = math.sqrt(2) +USE_NUMPY_FOR_DIJKSTRA = True + + +class MinCostPathHelper: + """Helper class for the cost matrix.""" + + @staticmethod + def _point_to_row_col(point_xy, ras_transform): + col, row = ras_transform.rowcol(point_xy.x(), point_xy.y()) + + return row, col + + @staticmethod + def _row_col_to_point(row_col, ras_transform): + x, y = ras_transform.xy(row_col[0], row_col[1]) + return x, y + + @staticmethod + def create_points_from_path(ras_transform, min_cost_path, start_point, end_point): + path_points = list( + map( + lambda row_col: MinCostPathHelper._row_col_to_point(row_col, ras_transform), + min_cost_path, + ) + ) + path_points[0] = (start_point.x, start_point.y) + path_points[-1] = (end_point.x, end_point.y) + return path_points + + @staticmethod + def create_path_feature_from_points(path_points, attr_vals): + path_points_raw = [[pt.x, pt.y] for pt in path_points] + + return sh_geom.LineString(path_points_raw), attr_vals + + @staticmethod + def block2matrix_numpy(block, nodata): + contains_negative = False + with np.nditer(block, flags=["refs_ok"], op_flags=["readwrite"]) as it: + for x in it: + # TODO: this speeds up a lot, but need further inspection + # if np.isclose(x, nodata) or np.isnan(x): + if x <= nodata or np.isnan(x): + x[...] = 9999.0 + elif x < 0: + contains_negative = True + + return block, contains_negative + + @staticmethod + def block2matrix(block, nodata): + contains_negative = False + width, height = block.shape + # TODO: deal with nodata + matrix = [ + [ + None + if np.isclose(block[i][j], nodata) or np.isclose(block[i][j], bt_const.BT_NODATA) + else block[i][j] + for j in range(height) + ] + for i in range(width) + ] + + for row in matrix: + for v in row: + if v is not None: + if v < 0 and not np.isclose(v, bt_const.BT_NODATA): + contains_negative = True + + return matrix, contains_negative + + +def dijkstra(start_tuple, end_tuples, block, find_nearest, feedback=None): + class Grid: + def __init__(self, matrix): + self.map = matrix + self.h = len(matrix) + self.w = len(matrix[0]) + self.manhattan_boundary = None + self.curr_boundary = None + + def _in_bounds(self, id): + x, y = id + return 0 <= x < self.h and 0 <= y < self.w + + def _passable(self, id): + x, y = id + return self.map[x][y] is not None + + def is_valid(self, id): + return self._in_bounds(id) and self._passable(id) + + def neighbors(self, id): + x, y = id + results = [ + (x + 1, y), + (x, y - 1), + (x - 1, y), + (x, y + 1), + (x + 1, y - 1), + (x + 1, y + 1), + (x - 1, y - 1), + (x - 1, y + 1), + ] + results = list(filter(self.is_valid, results)) + return results + + @staticmethod + def manhattan_distance(id1, id2): + x1, y1 = id1 + x2, y2 = id2 + return abs(x1 - x2) + abs(y1 - y2) + + @staticmethod + def min_manhattan(curr_node, end_nodes): + return min(map(lambda node: Grid.manhattan_distance(curr_node, node), end_nodes)) + + @staticmethod + def max_manhattan(curr_node, end_nodes): + return max(map(lambda node: Grid.manhattan_distance(curr_node, node), end_nodes)) + + @staticmethod + def all_manhattan(curr_node, end_nodes): + return {end_node: Grid.manhattan_distance(curr_node, end_node) for end_node in end_nodes} + + def simple_cost(self, cur, nex): + cx, cy = cur + nx, ny = nex + currV = self.map[cx][cy] + offsetV = self.map[nx][ny] + if cx == nx or cy == ny: + return (currV + offsetV) / 2 + else: + return sqrt2 * (currV + offsetV) / 2 + + result = [] + grid = Grid(block) + + end_dict = defaultdict(list) + for end_tuple in end_tuples: + end_dict[end_tuple[0]].append(end_tuple) + end_row_cols = set(end_dict.keys()) + end_row_col_list = list(end_row_cols) + start_row_col = start_tuple[0] + + frontier = queue.PriorityQueue() + frontier.put((0, start_row_col)) + came_from = {} + cost_so_far = {} + decided = set() + + if not grid.is_valid(start_row_col): + return result + + # init progress + index = 0 + distance_dic = grid.all_manhattan(start_row_col, end_row_cols) + if find_nearest: + total_manhattan = min(distance_dic.values()) + else: + total_manhattan = sum(distance_dic.values()) + + total_manhattan = total_manhattan + 1 + bound = total_manhattan + if feedback: + feedback.setProgress(1 + 100 * (1 - bound / total_manhattan)) + + came_from[start_row_col] = None + cost_so_far[start_row_col] = 0 + + while not frontier.empty(): + _, current_node = frontier.get() + if current_node in decided: + continue + decided.add(current_node) + + # update the progress bar + if feedback: + if feedback.isCanceled(): + return None + + index = (index + 1) % len(end_row_col_list) + target_node = end_row_col_list[index] + new_manhattan = grid.manhattan_distance(current_node, target_node) + if new_manhattan < distance_dic[target_node]: + if find_nearest: + curr_bound = new_manhattan + else: + curr_bound = bound - (distance_dic[target_node] - new_manhattan) + + distance_dic[target_node] = new_manhattan + + if curr_bound < bound: + bound = curr_bound + if feedback: + feedback.setProgress( + 1 + 100 * (1 - bound / total_manhattan) * (1 - bound / total_manhattan) + ) + + # destination + if current_node in end_row_cols: + path = [] + costs = [] + traverse_node = current_node + while traverse_node is not None: + path.append(traverse_node) + costs.append(cost_so_far[traverse_node]) + traverse_node = came_from[traverse_node] + + # start point and end point overlaps + if len(path) == 1: + path.append(start_row_col) + costs.append(0.0) + path.reverse() + costs.reverse() + result.append((path, costs, end_dict[current_node])) + + end_row_cols.remove(current_node) + end_row_col_list.remove(current_node) + if len(end_row_cols) == 0 or find_nearest: + break + + # relax distance + for nex in grid.neighbors(current_node): + new_cost = cost_so_far[current_node] + grid.simple_cost(current_node, nex) + if nex not in cost_so_far or new_cost < cost_so_far[nex]: + cost_so_far[nex] = new_cost + frontier.put((new_cost, nex)) + came_from[nex] = current_node + + return result + + +def valid_node(node, size_of_grid): + """Check if node is within the grid boundaries.""" + if node[0] < 0 or node[0] >= size_of_grid: + return False + if node[1] < 0 or node[1] >= size_of_grid: + return False + return True + + +def up(node): + return node[0] - 1, node[1] + + +def down(node): + return node[0] + 1, node[1] + + +def left(node): + return node[0], node[1] - 1 + + +def right(node): + return node[0], node[1] + 1 + + +def backtrack(initial_node, desired_node, distances): + # idea start at the last node then choose the least number of steps to go back + # last node + path = [desired_node] + + size_of_grid = distances.shape[0] + + while True: + # check up down left right - choose the direction that has the least distance + potential_distances = [] + potential_nodes = [] + + directions = [up, down, left, right] + + for direction in directions: + node = direction(path[-1]) + if valid_node(node, size_of_grid): + potential_nodes.append(node) + potential_distances.append(distances[node[0], node[1]]) + + print(potential_nodes) + + least_distance_index = np.argsort(potential_distances) + + pt_added = False + for index in least_distance_index: + p_point = potential_nodes[index] + if p_point == (1, 6): + pass + if p_point not in path: + path.append(p_point) + pt_added = True + break + + if index >= len(potential_distances) - 1 and not pt_added: + print("No best path found.") + return + + if path[-1][0] == initial_node[0] and path[-1][1] == initial_node[1]: + break + + if len(path) == 0 or path[-1][0] != initial_node[0] or path[-1][1] != initial_node[1]: + return None + + return list(reversed(path)) + + +def dijkstra_np(start_tuple, end_tuple, matrix): + """ + Dijkstra's algorithm for finding the shortest path between two nodes in a graph. + + Args: + start_node (list): [row,col] coordinates of the initial node + end_node (list): [row,col] coordinates of the desired node + matrix (array 2d): numpy array that contains matrix as 1s and free space as 0s + + Returns: + list[list]: list of list of nodes that form the shortest path + + """ + # source and destination are free + start_node = start_tuple[0] + end_node = end_tuple[0] + path = None + costs = None + + try: + matrix[start_node[0], start_node[1]] = 0 + matrix[end_node[0], end_node[1]] = 0 + + path, cost = sk_graph.route_through_array(matrix, start_node, end_node) + costs = [0.0 for i in range(len(path))] + except Exception as e: + print(f"dijkstra_np: {e}") + return None + + return [(path, costs, end_tuple)] + + +def find_least_cost_path(out_image, in_meta, line, find_nearest=True, output_linear_reference=False): + default_return = None + ras_nodata = in_meta["nodata"] + + pt_start = line.coords[0] + pt_end = line.coords[-1] + + out_image = np.where(out_image < 0, np.nan, out_image) # set negative value to nan + if len(out_image.shape) > 2: + out_image = np.squeeze(out_image, axis=0) + + if USE_NUMPY_FOR_DIJKSTRA: + matrix, contains_negative = MinCostPathHelper.block2matrix_numpy(out_image, ras_nodata) + else: + matrix, contains_negative = MinCostPathHelper.block2matrix(out_image, ras_nodata) + + if contains_negative: + print("ERROR: Raster has negative values.") + return default_return + + transformer = rasterio.transform.AffineTransformer(in_meta["transform"]) + + if ( + type(pt_start[0]) is tuple + or type(pt_start[1]) is tuple + or type(pt_end[0]) is tuple + or type(pt_end[1]) is tuple + ): + print("Point initialization error. Input is tuple.") + return default_return + + start_tuples = [] + end_tuples = [] + start_tuple = [] + try: + start_tuples = [ + ( + transformer.rowcol(pt_start[0], pt_start[1]), + sh_geom.Point(pt_start[0], pt_start[1]), + 0, + ) + ] + end_tuples = [ + ( + transformer.rowcol(pt_end[0], pt_end[1]), + sh_geom.Point(pt_end[0], pt_end[1]), + 1, + ) + ] + start_tuple = start_tuples[0] + end_tuple = end_tuples[0] + + # clamp row/col to valid matrix bounds + rows, cols = matrix.shape + + def _clamp_row_col(row_col): + row = max(0, min(int(row_col[0]), rows - 1)) + col = max(0, min(int(row_col[1]), cols - 1)) + return row, col + + start_tuple = (_clamp_row_col(start_tuple[0]), start_tuple[1], start_tuple[2]) + end_tuple = (_clamp_row_col(end_tuple[0]), end_tuple[1], end_tuple[2]) + + except Exception as e: + print(f"find_least_cost_path: {e}") + + if USE_NUMPY_FOR_DIJKSTRA: + result = dijkstra_np(start_tuple, end_tuple, matrix) + else: + # TODO: change end_tuples to end_tuple + result = dijkstra(start_tuple, end_tuples, matrix, find_nearest) + + if result is None: + return default_return + + if len(result) == 0: + print("No result returned.") + return default_return + + path_points = None + for path, costs, end_tuple in result: + path_points = MinCostPathHelper.create_points_from_path( + transformer, path, start_tuple[1], end_tuple[1] + ) + if output_linear_reference: + # TODO: code not reached + # add linear reference + for point, cost in zip(path_points, costs): + point.addMValue(cost) + + # feat_attr = (start_tuple[2], end_tuple[2], total_cost) + lc_path = None + if len(path_points) >= 2: + lc_path = sh_geom.LineString(path_points) + + return lc_path + + +def find_least_cost_path_skimage(cost_clip, in_meta, seed_line): + lc_path_new = [] + if len(cost_clip.shape) > 2: + cost_clip = np.squeeze(cost_clip, axis=0) + + out_transform = in_meta["transform"] + transformer = rasterio.transform.AffineTransformer(out_transform) + + x1, y1 = list(seed_line.coords)[0][:2] + x2, y2 = list(seed_line.coords)[-1][:2] + row1, col1 = transformer.rowcol(x1, y1) + row2, col2 = transformer.rowcol(x2, y2) + + try: + path_new = sk_graph.route_through_array(cost_clip[0], [row1, col1], [row2, col2]) + except Exception as e: + print(f"find_least_cost_path_skimage: {e}") + return None + + if path_new[0]: + for row, col in path_new[0]: + x, y = transformer.xy(row, col) + lc_path_new.append((x, y)) + + if len(lc_path_new) < 2: + print("No least cost path detected, pass.") + return None + else: + lc_path_new = sh_geom.LineString(lc_path_new) + + return lc_path_new diff --git a/beratools/modules/mapping/algo_footprint_plots.py b/beratools/modules/mapping/algo_footprint_plots.py new file mode 100644 index 0000000..9406db9 --- /dev/null +++ b/beratools/modules/mapping/algo_footprint_plots.py @@ -0,0 +1,355 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Irina Terentieva (original SegLine code) + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + Split a line footprint into plots and subplots along its centerline. + Ported from SegLine by Irina Terentieva + (https://github.com/IrinaTerentieva/SegLine, src/fixed_area and + src/fixed_length). + + Two modes choose the plot and subplot lengths along the centerline: + fixed area derives them from target areas and the footprint width, fixed + length uses them directly. + + The footprint is cut by its extended centerline (left/right sides) and by + cross cuts at subplot stations along the centerline. Every resulting face is + labelled by its side and by the station interval it projects to, and faces + with the same label are dissolved. Labelling by geometry, not by split order, + keeps sides consistent and gives exactly one geometry per plot and subplot. +""" + +from __future__ import annotations + +import bisect +import logging +import math + +import numpy as np +import shapely +from shapely.geometry import LineString, Point +from shapely.ops import linemerge, polygonize, substring, unary_union + +LOGGER_NAME = "footprint_plots" +logger = logging.getLogger(LOGGER_NAME) + +MODE_AREA = "fixed_area" +MODE_LENGTH = "fixed_length" + +# SegLine stores side as 0/1; here 0 is left and 1 is right of the line direction +SIDE_LEFT = 0 +SIDE_RIGHT = 1 + +# A tail shorter than this fraction of the subplot spacing joins the last subplot +MIN_TAIL_FRACTION = 0.5 +TANGENT_STEP = 0.5 +# Pieces smaller than this (m2) left by cuts or by removing overlaps are dropped +MIN_PIECE_AREA = 1e-3 +# Pieces closer than this (m) count as touching after an overlay +TOUCH_TOLERANCE = 1e-6 +# Output coordinates are snapped to this grid (m); it removes zero-width spikes overlays leave +GRID_SIZE = 1e-6 +# A line within this angle (degrees) of north-south or east-west counts as cardinal +CARDINAL_TOLERANCE = 15.0 + + +def prepare_centerline(line, footprint): + """Merge line parts and trim the line to the stretch that overlaps the footprint.""" + if line is None or line.is_empty or footprint is None or footprint.is_empty: + return None + + line = shapely.force_2d(line) + if line.geom_type == "MultiLineString": + line = linemerge(line) + if line.geom_type == "MultiLineString": + line = max(line.geoms, key=lambda part: part.intersection(footprint).length) + if line.geom_type != "LineString": + return None + + inside = line.intersection(footprint) + if inside.is_empty: + return None + distances = [line.project(Point(xy)) for xy in shapely.get_coordinates(inside)] + start, end = min(distances), max(distances) + if end - start <= 0: + return None + return substring(line, start, end) + + +def estimate_width(footprint, centerline) -> float: + """ + Return the average footprint width: footprint area over trimmed centerline length. + + Using this width makes the mean subplot area match the target. + """ + return footprint.area / centerline.length if centerline.length > 0 else 0.0 + + +def area_mode_lengths(width, plot_area, subplot_area): + """ + Return (plot length, subplot length) along the line for fixed area mode. + + A plot covers both sides of the line, a subplot covers one side, so a subplot + is length * width / 2. Subplots per side is rounded so subplots nest in plots. + """ + subplots_per_side = max(1, round(plot_area / (2 * subplot_area))) + subplot_length = 2 * subplot_area / width + return subplots_per_side * subplot_length, subplot_length + + +def subplot_stations(length, plot_length, subplot_length): + """ + Return [(start distance, plot index)] of the subplots along a line. + + Plots start every plot_length and subplots restart at each plot start. A + piece shorter than MIN_TAIL_FRACTION of a subplot joins the previous subplot. + """ + stations = [] + for plot_idx in range(max(1, math.ceil(length / plot_length))): + plot_start = plot_idx * plot_length + plot_end = min(plot_start + plot_length, length) + count = max(1, math.ceil((plot_end - plot_start) / subplot_length)) + stations.extend((plot_start + k * subplot_length, plot_idx) for k in range(count)) + + ends = [start for start, _ in stations[1:]] + [length] + return [ + station + for i, (station, end) in enumerate(zip(stations, ends)) + if i == 0 or end - station[0] >= MIN_TAIL_FRACTION * subplot_length + ] + + +def split_footprint(footprint, centerline, plot_length, subplot_length): + """ + Split one footprint into plots and subplots. + + Args: + footprint: footprint Polygon or MultiPolygon + centerline: centerline of the footprint (trimmed with prepare_centerline) + plot_length: plot length along the centerline (m) + subplot_length: subplot length along the centerline (m) + + Returns: + (plots, subplots): plots is a list of (plot_idx, side, length, geometry), + subplots is a list of (plot_idx, side, subplot_idx, length, geometry). + length is measured along the centerline. Indexes count from 0 along the + line; subplot_idx restarts in each plot. + + """ + footprint = shapely.force_2d(footprint) + if plot_length <= 0 or subplot_length <= 0: + return [], [] + + stations = subplot_stations(centerline.length, plot_length, subplot_length) + starts = [start for start, _ in stations] + station_lengths = [end - start for start, end in zip(starts, [*starts[1:], centerline.length])] + subplot_idx = [] + for i, (_, plot_idx) in enumerate(stations): + first = i == 0 or stations[i - 1][1] != plot_idx + subplot_idx.append(0 if first else subplot_idx[-1] + 1) + + # Cuts must cross the whole footprint; extra cuts at bends are healed by the dissolve + width = estimate_width(footprint, centerline) + reach = footprint.hausdorff_distance(centerline) + width + 1.0 + cuts = [_cross_cut(centerline, start, reach) for start in starts[1:]] + edges = unary_union([footprint.boundary, _extend_line(centerline, reach), *cuts]) + + shapely.prepare(footprint) + pieces = {} + for face in polygonize(edges): + # crumbs where a cut clips the corner of a small footprint fragment + if face.area <= MIN_PIECE_AREA: + continue + point = face.representative_point() + if not footprint.contains(point): + continue + distance = centerline.project(point) + station = max(bisect.bisect_right(starts, distance) - 1, 0) + key = (_side_of(centerline, distance, point), station) + pieces.setdefault(key, []).append(face) + + subplots = [] + plot_pieces = {} + for (side, station), faces in sorted(pieces.items(), key=lambda item: (item[0][1], item[0][0])): + geom = unary_union(faces) + plot_idx = stations[station][1] + subplots.append((plot_idx, side, subplot_idx[station], station_lengths[station], geom)) + plot_pieces.setdefault((plot_idx, side), []).append((station_lengths[station], geom)) + + plots = [ + (plot_idx, side, sum(length for length, _ in parts), unary_union([geom for _, geom in parts])) + for (plot_idx, side), parts in plot_pieces.items() + ] + return plots, subplots + + +def line_orientation(line) -> float: + """ + Return the main direction of a line in degrees, 0 to 180 counter-clockwise from east. + + Segment directions are averaged as axes (angles doubled), weighted by length, + so a line and its reverse give the same result and short wiggles count little. + """ + coords = shapely.get_coordinates(line) + dx, dy = np.diff(coords[:, 0]), np.diff(coords[:, 1]) + weights = np.hypot(dx, dy) + doubled = 2 * np.arctan2(dy, dx) + angle = math.atan2((weights * np.sin(doubled)).sum(), (weights * np.cos(doubled)).sum()) + # rounding keeps an angle a hair below 0 from wrapping to 180 + return round(math.degrees(angle) / 2, 9) % 180 + + +def is_cardinal(line, tolerance=CARDINAL_TOLERANCE) -> bool: + """Return True if the line runs within tolerance degrees of north-south or east-west.""" + offset = line_orientation(line) % 90 + return min(offset, 90 - offset) <= tolerance + + +def trim_line_ends(footprint, centerline, claimed): + """ + Cut claimed area off the ends of a footprint and trim its centerline to match. + + Used where the centerline ends in an overlap another footprint keeps. The + centerline keeps its longest stretch outside the claimed area, in its + original direction. Footprint pieces that touch the claimed area but are not + crossed by that stretch, such as bits poking out beyond the other line, are + returned as leftovers. Other pieces, such as fragments of a multipart + footprint, are kept. + + Returns: + (footprint, centerline, leftovers). footprint and centerline are None if + nothing is left. + + """ + stretches = [ + part + for part in shapely.get_parts(centerline.difference(claimed)) + if part.geom_type == "LineString" and part.length > 0 + ] + if not stretches: + return None, None, polygon_parts(shapely.force_2d(footprint).difference(claimed)) + + trimmed = max(stretches, key=lambda part: part.length) + start, end = (centerline.project(Point(xy)) for xy in (trimmed.coords[0], trimmed.coords[-1])) + if start > end: + trimmed = trimmed.reverse() + + kept, leftovers = [], [] + for part in polygon_parts(shapely.force_2d(footprint).difference(claimed)): + cut_off = part.distance(claimed) <= TOUCH_TOLERANCE and not part.intersects(trimmed) + (leftovers if cut_off else kept).append(part) + if not kept: + return None, None, leftovers + return unary_union(kept), trimmed, leftovers + + +def remove_overlap(subplots, claimed): + """ + Cut the claimed area out of subplots. + + Subplots keep their place along the line: a subplot the claimed area cuts + in two keeps both pieces, one on each side of the crossing, so its edges + stay on the cross cuts. Subplots left empty are dropped. + + Args: + subplots: list of (plot_idx, side, subplot_idx, length, geometry) + claimed: area kept by other footprints, or None + + """ + if claimed is None or claimed.is_empty: + return subplots + + shapely.prepare(claimed) + result = [] + for plot_idx, side, subplot_idx, length, geom in subplots: + if claimed.intersects(geom): + parts = polygon_parts(geom.difference(claimed)) + if not parts: + continue + geom = unary_union(parts) + result.append((plot_idx, side, subplot_idx, length, geom)) + return result + + +def plots_from_subplots(plots, subplots): + """Rebuild plot geometries as the union of their subplots, keeping plot lengths.""" + lengths = {(plot_idx, side): length for plot_idx, side, length, _ in plots} + geoms = {} + for plot_idx, side, _, _, geom in subplots: + geoms.setdefault((plot_idx, side), []).append(geom) + return [ + (plot_idx, side, lengths[(plot_idx, side)], unary_union(parts)) + for (plot_idx, side), parts in geoms.items() + ] + + +def clean_polygon(geom): + """ + Snap geom to GRID_SIZE and keep its polygon parts, or None if nothing is left. + + Cutting and merging pieces whose edges almost coincide leaves zero-width + spikes in the outline; snapping to a fine grid removes them. Neighbouring + pieces snap to the same grid, so their shared edges still match. + """ + parts = polygon_parts(geom) + return unary_union(parts) if parts else None + + +def polygon_parts(geom): + """ + Return the polygon parts of an overlay result, dropping line-like and tiny leftovers. + + The result is snapped to GRID_SIZE first: cutting along an edge that almost + coincides with another leaves zero-width spikes, which would otherwise carry + into the plots and confuse the inside test when splitting. + """ + return [ + part + for part in shapely.get_parts(shapely.set_precision(geom, GRID_SIZE)) + if part.geom_type == "Polygon" and part.area > MIN_PIECE_AREA + ] + + +def _tangent(line, distance): + start = line.interpolate(max(distance - TANGENT_STEP, 0)) + end = line.interpolate(min(distance + TANGENT_STEP, line.length)) + dx, dy = end.x - start.x, end.y - start.y + norm = math.hypot(dx, dy) + return (dx / norm, dy / norm) if norm > 0 else (1.0, 0.0) + + +def _side_of(line, distance, point): + origin = line.interpolate(distance) + tx, ty = _tangent(line, distance) + cross = tx * (point.y - origin.y) - ty * (point.x - origin.x) + return SIDE_LEFT if cross > 0 else SIDE_RIGHT + + +def _cross_cut(line, distance, reach): + origin = line.interpolate(distance) + tx, ty = _tangent(line, distance) + return LineString( + [(origin.x + ty * reach, origin.y - tx * reach), (origin.x - ty * reach, origin.y + tx * reach)] + ) + + +def _extend_line(line, distance): + """Extend both ends straight along the end tangents so the line crosses the footprint.""" + start, end = line.interpolate(0), line.interpolate(line.length) + sx, sy = _tangent(line, 0) + ex, ey = _tangent(line, line.length) + coords = list(line.coords) + return LineString( + [ + (start.x - sx * distance, start.y - sy * distance), + *coords, + (end.x + ex * distance, end.y + ey * distance), + ] + ) diff --git a/beratools/modules/mapping/algo_geometry.py b/beratools/modules/mapping/algo_geometry.py new file mode 100644 index 0000000..bee1384 --- /dev/null +++ b/beratools/modules/mapping/algo_geometry.py @@ -0,0 +1,171 @@ +"""Reusable vector geometry post-processing helpers.""" + +from __future__ import annotations + +import logging +import math + +from shapely.geometry import LineString, MultiLineString, MultiPolygon, Point, Polygon +from shapely.ops import linemerge, substring + +LOGGER_NAME = "algo_geometry" +logger = logging.getLogger(LOGGER_NAME) + +def chaikin_smooth_line(line: LineString, *, iterations: int) -> LineString: + if line is None or line.is_empty or iterations <= 0 or len(line.coords) < 3: + return line + + points = [(float(x), float(y)) for x, y, *_ in line.coords] + for _ in range(iterations): + smoothed = [points[0]] + for point, next_point in zip(points, points[1:]): + smoothed.append((0.75 * point[0] + 0.25 * next_point[0], 0.75 * point[1] + 0.25 * next_point[1])) + smoothed.append((0.25 * point[0] + 0.75 * next_point[0], 0.25 * point[1] + 0.75 * next_point[1])) + smoothed.append(points[-1]) + points = smoothed + return LineString(points) + + +def vertex_interior_angle(p1, p2, p3) -> float: + """Return the interior angle in degrees at p2; 180 is straight, smaller is sharper.""" + dx1, dy1 = p1[0] - p2[0], p1[1] - p2[1] + dx2, dy2 = p3[0] - p2[0], p3[1] - p2[1] + magnitude1 = math.hypot(dx1, dy1) + magnitude2 = math.hypot(dx2, dy2) + if magnitude1 == 0 or magnitude2 == 0: + return 180.0 + + cos_angle = (dx1 * dx2 + dy1 * dy2) / (magnitude1 * magnitude2) + return math.degrees(math.acos(max(-1.0, min(1.0, cos_angle)))) + + +def smooth_sharp_vertices(line, *, angle_threshold: float, buffer_distance: float): + """ + Cut sharp corners of a line and leave the rest of the line unchanged. + + Each vertex with an interior angle below angle_threshold is replaced by a straight + chord between the points where the line enters and leaves a circle of radius + buffer_distance around that vertex. + + Ported from SegLine by Irina Terentieva + (https://github.com/IrinaTerentieva/SegLine, src/utils/smooth_centerline.py). + """ + if line is None or line.is_empty or buffer_distance <= 0: + return line + if line.geom_type == "MultiLineString": + line = linemerge(line) + if line.geom_type == "MultiLineString": + return MultiLineString( + [ + smooth_sharp_vertices( + part, angle_threshold=angle_threshold, buffer_distance=buffer_distance + ) + for part in line.geoms + ] + ) + if line.geom_type != "LineString" or len(line.coords) < 3: + return line + + coords = list(line.coords) + smoothed = line + next_index = 1 + for i in range(1, len(coords) - 1): + # Skip the vertex right after a cut corner to avoid over-smoothing + if i < next_index: + continue + if vertex_interior_angle(coords[i - 1], coords[i], coords[i + 1]) < angle_threshold: + smoothed = _cut_corner(smoothed, Point(coords[i]), buffer_distance) + next_index = i + 2 + return smoothed + + +def _cut_corner(line: LineString, vertex: Point, buffer_distance: float) -> LineString: + piece = line.intersection(vertex.buffer(buffer_distance)) + if piece.geom_type != "LineString" or piece.is_empty: + return line + + chord_start, chord_end = piece.coords[0], piece.coords[-1] + start_dist = line.project(Point(chord_start)) + end_dist = line.project(Point(chord_end)) + if start_dist >= end_dist: + return line + + new_coords = [] + if start_dist > 0: + new_coords.extend(substring(line, 0, start_dist).coords[:-1]) + new_coords.extend([chord_start, chord_end]) + if end_dist < line.length: + new_coords.extend(substring(line, end_dist, line.length).coords[1:]) + return LineString(new_coords) if len(new_coords) >= 2 else line + + +def chaikin_smooth_polygon(geometry, *, iterations: int): + if geometry is None or geometry.is_empty or iterations <= 0: + return geometry + if geometry.geom_type == "Polygon": + exterior = _chaikin_smooth_ring(geometry.exterior.coords, iterations=iterations) + interiors = [ + _chaikin_smooth_ring(interior.coords, iterations=iterations) for interior in geometry.interiors + ] + return Polygon(exterior, interiors) + if geometry.geom_type == "MultiPolygon": + return MultiPolygon([chaikin_smooth_polygon(part, iterations=iterations) for part in geometry.geoms]) + return geometry + + +def process_corridor_polygon( + polygon, + cid=None, + *, + delete_holes=False, + simplify=False, + simplify_length=0.0, + smooth=False, + smooth_iterations=0, +): + """Apply stage-8 style polygon cleanup, simplification, and smoothing.""" + if polygon is None or polygon.is_empty: + return polygon + + processed = polygon + if delete_holes: + processed = _delete_polygon_holes(processed) + processed = processed.buffer(0.5) + processed = processed.buffer(-0.5) + if simplify and float(simplify_length) > 0: + area_before = processed.area + processed = processed.simplify(float(simplify_length), preserve_topology=True) + logger.debug( + f"{cid} simplify " + f"area_change=" + f"{100 * (processed.area - area_before) / area_before:.2f}%") + if smooth and int(smooth_iterations) > 0: + processed = chaikin_smooth_polygon(processed, iterations=int(smooth_iterations)) + if processed is not None and not processed.is_valid: + processed = processed.buffer(0) + return processed + + +def _delete_polygon_holes(geometry): + if geometry.geom_type == "Polygon": + return Polygon(geometry.exterior) + if geometry.geom_type == "MultiPolygon": + return MultiPolygon([Polygon(poly.exterior) for poly in geometry.geoms]) + return geometry + + +def _chaikin_smooth_ring(coords, *, iterations: int) -> list[tuple[float, float]]: + points = [(float(x), float(y)) for x, y, *_ in coords] + if len(points) > 1 and points[0] == points[-1]: + points = points[:-1] + if len(points) < 3 or iterations <= 0: + return points + points[:1] + + for _ in range(iterations): + smoothed = [] + for index, point in enumerate(points): + next_point = points[(index + 1) % len(points)] + smoothed.append((0.75 * point[0] + 0.25 * next_point[0], 0.75 * point[1] + 0.25 * next_point[1])) + smoothed.append((0.25 * point[0] + 0.75 * next_point[0], 0.25 * point[1] + 0.75 * next_point[1])) + points = smoothed + return points + points[:1] diff --git a/beratools/modules/mapping/algo_line_grouping.py b/beratools/modules/mapping/algo_line_grouping.py new file mode 100644 index 0000000..136cd55 --- /dev/null +++ b/beratools/modules/mapping/algo_line_grouping.py @@ -0,0 +1,972 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng, Maverick Fong + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + This file hosts code to deal with line grouping and merging, cleanups. +""" + +import enum +from collections import defaultdict +from dataclasses import dataclass, field +from itertools import chain +from typing import Optional, Union + +import networkit as nk +import numpy as np +import shapely +import shapely.geometry as sh_geom + +import beratools.core.constants as bt_const +import beratools.modules.mapping.algo_common as algo_common +import beratools.modules.mapping.algo_merge_lines as algo_merge_lines + +TRIMMING_DISTANCE = 75 # meters +SMALL_BUFFER = 1 + + +@enum.unique +class VertexClass(enum.IntEnum): + """Enum class for vertex class.""" + + TWO_WAY_ZERO_PRIMARY_LINE = 1 + THREE_WAY_ZERO_PRIMARY_LINE = 2 + THREE_WAY_ONE_PRIMARY_LINE = 3 + FOUR_WAY_ZERO_PRIMARY_LINE = 4 + FOUR_WAY_ONE_PRIMARY_LINE = 5 + FOUR_WAY_TWO_PRIMARY_LINE = 6 + FIVE_WAY_ZERO_PRIMARY_LINE = 7 + FIVE_WAY_ONE_PRIMARY_LINE = 8 + FIVE_WAY_TWO_PRIMARY_LINE = 9 + SINGLE_WAY = 10 + + +CONCERN_CLASSES = ( + VertexClass.FIVE_WAY_ZERO_PRIMARY_LINE, + VertexClass.FIVE_WAY_ONE_PRIMARY_LINE, + VertexClass.FIVE_WAY_TWO_PRIMARY_LINE, + VertexClass.FOUR_WAY_ZERO_PRIMARY_LINE, + VertexClass.FOUR_WAY_ONE_PRIMARY_LINE, + VertexClass.FOUR_WAY_TWO_PRIMARY_LINE, + VertexClass.THREE_WAY_ZERO_PRIMARY_LINE, + VertexClass.THREE_WAY_ONE_PRIMARY_LINE, + VertexClass.TWO_WAY_ZERO_PRIMARY_LINE, + VertexClass.SINGLE_WAY, +) + +ANGLE_TOLERANCE = np.pi / 10 +TURN_ANGLE_TOLERANCE = np.pi * 0.5 # (little bigger than right angle) +TRIM_THRESHOLD = 0.15 +TRANSECT_LENGTH = 40 + + +def points_in_line(line): + """Get point list of line.""" + point_list = [] + try: + for point in list(line.coords): # loops through every point in a line + # loops through every vertex of every segment + if point: # adds all the vertices to segment_list, which creates an array + point_list.append(sh_geom.Point(point[0], point[1])) + except Exception as e: + print(e) + + return point_list + + +def get_angle(line, end_index): + """ + Calculate the angle of the first or last segment. + + Args: + line: sh_geom.LineString + end_index: 0 or -1 of the line vertices. Consider the multipart. + + """ + pts = points_in_line(line) + + if end_index == 0: + pt_1 = pts[0] + pt_2 = pts[1] + elif end_index == -1: + pt_1 = pts[-1] + pt_2 = pts[-2] + + delta_x = pt_2.x - pt_1.x + delta_y = pt_2.y - pt_1.y + angle = np.arctan2(delta_y, delta_x) + + return angle + + +@dataclass +class SingleLine: + """Class to store line and its simplified line.""" + + line_id: int = field(default=0) + line: Union[sh_geom.LineString, sh_geom.MultiLineString] = field(default=None) + sim_line: Union[sh_geom.LineString, sh_geom.MultiLineString] = field(default=None) + vertex_index: int = field(default=0) + group: int = field(default=0) + + def get_angle_for_line(self): + return get_angle(self.sim_line, self.vertex_index) + + def end_transect(self): + coords = self.sim_line.coords + end_seg = None + if self.vertex_index == 0: + end_seg = sh_geom.LineString([coords[0], coords[1]]) + elif self.vertex_index == -1: + end_seg = sh_geom.LineString([coords[-1], coords[-2]]) + + l_left = end_seg.offset_curve(TRANSECT_LENGTH) + l_right = end_seg.offset_curve(-TRANSECT_LENGTH) + + return sh_geom.LineString([l_left.coords[0], l_right.coords[0]]) + + def midpoint(self): + return shapely.force_2d(self.line.interpolate(0.5, normalized=True)) + + def update_line(self, line): + self.line = line + + +class VertexNode: + """Class to store vertex and lines connected to it.""" + + def __init__(self, line_id, line, sim_line, vertex_index, group=None) -> None: + self.vertex = None + self.line_list = [] + self.line_connected = [] # pairs of lines connected + self.line_not_connected = [] + self.vertex_class = None + + if line: + self.add_line(SingleLine(line_id, line, sim_line, vertex_index, group)) + + def set_vertex(self, line, vertex_index): + """Set vertex coordinates.""" + if line is None: + self.vertex = None + return + + if line.is_empty: + self.vertex = None + return + + try: + self.vertex = shapely.force_2d( + shapely.get_point(line, vertex_index) + ) + except Exception: + self.vertex = None + + def add_line(self, line_class): + """Add line when creating or merging other VertexNode.""" + self.line_list.append(line_class) + self.set_vertex(line_class.line, line_class.vertex_index) + + def get_line(self, line_id): + for line in self.line_list: + if line.line_id == line_id: + return line.line + + def get_line_obj(self, line_id): + for line in self.line_list: + if line.line_id == line_id: + return line + + def get_line_geom(self, line_id): + return self.get_line_obj(line_id).line + + def get_all_line_ids(self): + all_line_ids = {i.line_id for i in self.line_list} + return all_line_ids + + def update_line(self, line_id, line): + for i in self.line_list: + if i.line_id == line_id: + i.update_line(line) + + def merge(self, vertex): + """Merge other VertexNode if they have same vertex coords.""" + self.add_line(vertex.line_list[0]) + + def get_trim_transect(self, poly, line_indices): + if not poly: + return None + + internal_line = None + for line_idx in line_indices: + line = self.get_line_obj(line_idx) + if poly.contains(line.midpoint()): + internal_line = line + + if not internal_line: + # print("No line is retrieved") + return None + return internal_line.end_transect() + + def _trim_polygon(self, poly, trim_transect): + if not poly or not trim_transect: + return None + + split_poly = shapely.ops.split(poly, trim_transect) + + if len(split_poly.geoms) != 2: + return + + # check geom_type + none_poly = False + for geom in split_poly.geoms: + if geom.geom_type != "Polygon": + none_poly = True + + if none_poly: + return None + + # only two polygons in split_poly + if split_poly.geoms[0].area > split_poly.geoms[1].area: + poly = split_poly.geoms[0] + else: + poly = split_poly.geoms[1] + + return poly + + def trim_end_all(self, polys): + """ + Trim all unconnected lines in the vertex. + + Args: + polys: list of polygons returned by sindex.query + + """ + polys = polys.geometry + new_polys = [] + for idx, poly in polys.items(): + out_poly = self.trim_end(poly) + if out_poly: + new_polys.append((idx, out_poly)) + + return new_polys + + def trim_end(self, poly): + transect = self.get_trim_transect(poly, self.line_not_connected) + if not transect: + return None + + poly = self._trim_polygon(poly, transect) + return poly + # Helper to get the neighbor coordinate based on vertex_index. + + @staticmethod + def get_vertex(line_obj, index): + coords = list(line_obj.sim_line.coords) + # Normalize negative indices. + if index < 0: + index += len(coords) + if 0 <= index < len(coords): + return sh_geom.Point(coords[index]) + return None + + @staticmethod + def get_neighbor(line_obj): + index = 0 + + if line_obj.vertex_index == 0: + index = 1 + elif line_obj.vertex_index == -1: + index = -2 + + return VertexNode.get_vertex(line_obj, index) + + @staticmethod + def parallel_line_centered(p1, p2, center, length): + """Generate a parallel line.""" + # Compute the direction vector. + dx = p2.x - p1.x + dy = p2.y - p1.y + + # Normalize the direction vector. + magnitude = (dx**2 + dy**2) ** 0.5 + if magnitude == 0: + return None + dx /= magnitude + dy /= magnitude + + # Compute half-length shifts. + half_dx = (dx * length) / 2 + half_dy = (dy * length) / 2 + + # Compute the endpoints of the new parallel line. + new_p1 = sh_geom.Point(center.x - half_dx, center.y - half_dy) + new_p2 = sh_geom.Point(center.x + half_dx, center.y + half_dy) + + return sh_geom.LineString([new_p1, new_p2]) + + def get_transect_for_primary(self): + """ + Get a transect line from two primary connected lines. + + This method calculates a transect line that is perpendicular to the line segment + formed by the next vertex neighbors of these two lines and the current vertex. + + Return: + A transect line object if the conditions are met, otherwise None. + + """ + if not self.line_connected or len(self.line_connected[0]) != 2: + return None + + # Retrieve the two connected line objects from the first connectivity group. + line_ids = self.line_connected[0] + pt1 = None + pt1 = None + if line_ids[0] == line_ids[1]: # line ring + # TODO: check line ring when merging vertex nodes. + # TODO: change one end index to -1 + line_id = line_ids[0] + pt1 = self.get_vertex(self.get_line_obj(line_id), 1) + pt2 = self.get_vertex(self.get_line_obj(line_id), -2) + else: # two different lines + line_obj1 = self.get_line_obj(line_ids[0]) + line_obj2 = self.get_line_obj(line_ids[1]) + + pt1 = self.get_neighbor(line_obj1) + pt2 = self.get_neighbor(line_obj2) + + if pt1 is None or pt2 is None: + return None + + transect = algo_common.generate_perpendicular_line_precise([pt1, self.vertex, pt2], offset=40) + return transect + + def get_transect_for_primary_second(self): + """ + Get a transect line from the second primary connected line. + + For the second primary line, this method retrieves the neighbor point from + two lines in the second connectivity group, creates a reference line through the + vertex by mirroring the neighbor point about the vertex, and then generates a + parallel line centered at the vertex. + + Returns: + A LineString representing the transect if available, otherwise None. + + """ + # Ensure there is a second connectivity group. + if not self.line_connected or len(self.line_connected) < 2: + return None + + # Use the first line of the second connectivity group. + second_primary = self.line_connected[1] + line_obj1 = self.get_line_obj(second_primary[0]) + line_obj2 = self.get_line_obj(second_primary[1]) + if not line_obj1 or not line_obj2: + return None + + pt1 = self.get_neighbor(line_obj1) + pt2 = self.get_neighbor(line_obj2) + + if pt1 is None or pt2 is None: + return None + + center = self.vertex + transect = self.parallel_line_centered(pt1, pt2, center, TRANSECT_LENGTH) + return transect + + def trim_primary_end(self, polys): + """ + Trim first primary line in the vertex. + + Args: + polys: list of polygons returned by sindex.query + + """ + if len(self.line_connected) == 0: + return None + + new_polys = [] + line = self.line_connected[0] + + # use the first line to get transect + # transect = self.get_line_obj(line[0]).end_transect() + # if len(self.line_connected) == 1: + transect = self.get_transect_for_primary() + # elif len(self.line_connected) > 1: + # transect = self.get_transect_for_primary_second() + + idx_1 = line[0] + poly_1 = None + idx_1 = line[1] + poly_2 = None + + for idx, poly in polys.items(): + # TODO: no polygons + if not poly: + continue + + if poly.buffer(SMALL_BUFFER).contains(self.get_line_geom(line[0])): + poly_1 = poly + idx_1 = idx + elif poly.buffer(SMALL_BUFFER).contains(self.get_line_geom(line[1])): + poly_2 = poly + idx_2 = idx + + if poly_1: + poly_1 = self._trim_polygon(poly_1, transect) + new_polys.append([idx_1, poly_1]) + if poly_2: + poly_2 = self._trim_polygon(poly_2, transect) + new_polys.append([idx_2, poly_2]) + + return new_polys + + def trim_intersection(self, polys, merge_group=True): + """ + Trim intersection of lines and polygons. + + TODO: there are polygons of 0 zero. + + """ + + def get_poly_with_info(line, polys): + if polys.empty: + return None, None, None + + for idx, row in polys.iterrows(): + poly = row.geometry + if not poly: # TODO: no polygon + continue + + if poly.buffer(SMALL_BUFFER).contains(line): + return idx, poly, row["max_width"] + + return None, None, None + + poly_trim_list = [] + primary_lines = [] + p_primary_list = [] + + # retrieve primary lines + if len(self.line_connected) > 0: + for idx in self.line_connected[0]: # only one connected line is used + primary_lines.append(self.get_line(idx)) + _, poly, _ = get_poly_with_info(self.get_line(idx), polys) + + if poly: + p_primary_list.append(poly.buffer(bt_const.SMALL_BUFFER)) + else: + print("trim_intersection: No primary polygon found.") + + line_idx_to_trim = self.line_not_connected + poly_list = [] + if not merge_group: # add all remaining primary lines for trimming + if len(self.line_connected) > 1: + for line in self.line_connected[1:]: + line_idx_to_trim.extend(line) + + # sort line index to by footprint area + for line_idx in line_idx_to_trim: + line = self.get_line_geom(line_idx) + poly_idx, poly, max_width = get_poly_with_info(line, polys) + if poly_idx: + poly_list.append((line_idx, poly_idx, max_width)) + + poly_list = sorted(poly_list, key=lambda x: x[2]) + + # create PolygonTrimming object and trim all by primary line + for i, indices in enumerate(poly_list): + line_idx = indices[0] + poly_idx = indices[1] + line_cleanup = self.get_line(line_idx) + poly_cleanup = polys.loc[poly_idx].geometry + poly_trim = PolygonTrimming( + line_index=line_idx, + line_cleanup=line_cleanup, + poly_index=poly_idx, + poly_cleanup=poly_cleanup, + ) + + poly_trim_list.append(poly_trim) + if p_primary_list: + poly_trim.process(p_primary_list, self.vertex) + + # use poly_trim.poly_cleanup to update polys gdf's geometry + polys.at[poly_trim.poly_index, "geometry"] = poly_trim.poly_cleanup + + # further trimming overlaps by non-primary lines + # poly_list and poly_trim_list have same index + for i, indices in enumerate(poly_list): + p_list = [] + for p in poly_list[i + 1 :]: + p_list.append(polys.loc[p[1]].geometry) + + poly_trim = poly_trim_list[i] + poly_trim.process(p_list, self.vertex) + + return poly_trim_list + + def assign_vertex_class(self): + if len(self.line_list) == 5: + if len(self.line_connected) == 0: + self.vertex_class = VertexClass.FIVE_WAY_ZERO_PRIMARY_LINE + if len(self.line_connected) == 1: + self.vertex_class = VertexClass.FIVE_WAY_ONE_PRIMARY_LINE + if len(self.line_connected) == 2: + self.vertex_class = VertexClass.FIVE_WAY_TWO_PRIMARY_LINE + elif len(self.line_list) == 4: + if len(self.line_connected) == 0: + self.vertex_class = VertexClass.FOUR_WAY_ZERO_PRIMARY_LINE + if len(self.line_connected) == 1: + self.vertex_class = VertexClass.FOUR_WAY_ONE_PRIMARY_LINE + if len(self.line_connected) == 2: + self.vertex_class = VertexClass.FOUR_WAY_TWO_PRIMARY_LINE + elif len(self.line_list) == 3: + if len(self.line_connected) == 0: + self.vertex_class = VertexClass.THREE_WAY_ZERO_PRIMARY_LINE + if len(self.line_connected) == 1: + self.vertex_class = VertexClass.THREE_WAY_ONE_PRIMARY_LINE + elif len(self.line_list) == 2: + if len(self.line_connected) == 0: + self.vertex_class = VertexClass.TWO_WAY_ZERO_PRIMARY_LINE + elif len(self.line_list) == 1: + self.vertex_class = VertexClass.SINGLE_WAY + + def all_has_valid_group_attr(self): + """If all values in group list are valid value, return True.""" + # TODO: if some line has no group, give advice + for i in self.line_list: + if i.group is None: + return False + + return True + + def need_regrouping(self): + pass + + def check_connectivity(self, use_angle_grouping=True): + # Fill missing group with -1 + for line in self.line_list: + if line.group is None: + line.group = -1 + + if self.need_regrouping(): + self.group_regroup() + + if use_angle_grouping: + self.group_line_by_angle() + else: + self.update_connectivity_by_group() + + # record line not connected + all_line_ids = self.get_all_line_ids() + self.line_not_connected = list(all_line_ids - set(chain(*self.line_connected))) + + self.assign_vertex_class() + + def group_regroup(self): + pass + + def update_connectivity_by_group(self): + group_line = defaultdict(list) + for i in self.line_list: + group_line[i.group].append(i.line_id) + + for value in group_line.values(): + if len(value) > 1: + self.line_connected.append(value) + + def group_line_by_angle(self): + """Generate connectivity of all lines.""" + if len(self.line_list) == 1: + return + + # if there are 2 and more lines + new_angles = [i.get_angle_for_line() for i in self.line_list] + angle_visited = [False] * len(new_angles) + + if len(self.line_list) == 2: + angle_diff = abs(new_angles[0] - new_angles[1]) + angle_diff = angle_diff if angle_diff <= np.pi else angle_diff - np.pi + + # TODO: check if need to connect when turn angle < TURN_ANGLE_TOLERANCE + # if angle_diff >= TURN_ANGLE_TOLERANCE: + self.line_connected.append( + ( + self.line_list[0].line_id, + self.line_list[1].line_id, + ) + ) + return + + # three and more lines + for i, angle_1 in enumerate(new_angles): + for j, angle_2 in enumerate(new_angles[i + 1 :]): + if not angle_visited[i + j + 1]: + angle_diff = abs(angle_1 - angle_2) + angle_diff = angle_diff if angle_diff <= np.pi else angle_diff - np.pi + if ( + angle_diff < ANGLE_TOLERANCE + or np.pi - ANGLE_TOLERANCE < abs(angle_1 - angle_2) < np.pi + ANGLE_TOLERANCE + ): + angle_visited[j + i + 1] = True # tenth of PI + self.line_connected.append( + ( + self.line_list[i].line_id, + self.line_list[i + j + 1].line_id, + ) + ) + + +class LineGrouping: + """Class to group lines and merge them.""" + + def __init__(self, in_line_gdf, merge_group=True, use_angle_grouping=True) -> None: + if in_line_gdf is None: + raise ValueError("Line GeoDataFrame cannot be None") + self.use_angle_grouping = use_angle_grouping + + if in_line_gdf.empty: + raise ValueError("Line GeoDataFrame cannot be empty") + + self.lines = algo_common.clean_line_geometries(in_line_gdf) + self.lines.reset_index(inplace=True, drop=True) + self.merge_group = merge_group + + self.sim_geom = self.lines.simplify(1) + + self.G = nk.Graph(len(self.lines)) + self.merged_vertex_list = [] + self.has_group_attr = False + self.need_regrouping = False + self.groups = [None] * len(self.lines) + self.merged_lines_trimmed = None # merged trimmed lines + + self.vertex_list = [] + self.vertex_of_concern = [] + self.v_index = None # sindex of all vertices for vertex_list + + self.polys = None + + # invalid geoms in final geom list + self.valid_lines = None + self.valid_polys = None + self.invalid_lines = None + self.invalid_polys = None + + def create_vertex_list(self): + # check if data has group column + if bt_const.BT_GROUP in self.lines.keys(): + self.groups = self.lines[bt_const.BT_GROUP] + self.has_group_attr = True + if self.groups.hasnans: # Todo: check for other invalid values + self.need_regrouping = True + + for idx, s_geom, geom, group in zip(*zip(*self.sim_geom.items()), self.lines.geometry, self.groups): + self.vertex_list.append(VertexNode(idx, geom, s_geom, 0, group)) + self.vertex_list.append(VertexNode(idx, geom, s_geom, -1, group)) + + v_points = [] + for i in self.vertex_list: + if i.vertex is None: + print( + f"Vertex is None, skipping. " + f"line_id={i.line_list[0].line_id if i.line_list else 'NA'}" + ) + continue + + v_points.append(i.vertex.buffer(SMALL_BUFFER)) # small polygon + + # Spatial index of all vertices + self.v_index = shapely.STRtree(v_points) + + vertex_visited = [False] * len(self.vertex_list) + for i, pt in enumerate(v_points): + if vertex_visited[i]: + continue + + s_list = self.v_index.query(pt) + vertex = self.vertex_list[i] + if len(s_list) > 1: + for j in s_list: + if j != i: + # some short line will be very close to each other + if vertex.vertex.distance(self.vertex_list[j].vertex) > bt_const.SMALL_BUFFER: + continue + + vertex.merge(self.vertex_list[j]) + vertex_visited[j] = True + + self.merged_vertex_list.append(vertex) + vertex_visited[i] = True + + for i in self.merged_vertex_list: + i.check_connectivity(self.use_angle_grouping) + + for i in self.merged_vertex_list: + if i.line_connected: + for edge in i.line_connected: + self.G.addEdge(edge[0], edge[1]) + + def group_lines(self): + cc = nk.components.ConnectedComponents(self.G) + cc.run() + # print("number of components ", cc.numberOfComponents()) + + group = 0 + for i in range(cc.numberOfComponents()): + component = cc.getComponents()[i] + for id in component: + self.groups[id] = group + + group += 1 + + def update_line_in_vertex_node(self, line_id, line): + """Update line in VertexNode after trimming.""" + idx = self.v_index.query(line) + for i in idx: + v = self.vertex_list[i] + v.update_line(line_id, line) + + def run_line_merge(self): + return algo_merge_lines.run_line_merge(self.lines, self.merge_group) + + def find_vertex_for_poly_trimming(self): + self.vertex_of_concern = [i for i in self.merged_vertex_list if i.vertex_class in CONCERN_CLASSES] + + def line_and_poly_cleanup(self): + sindex_poly = self.polys.sindex + + for vertex in self.vertex_of_concern: + s_idx = sindex_poly.query(vertex.vertex, predicate="within") + if len(s_idx) == 0: + continue + + # Trim intersections of primary lines + polys = self.polys.loc[s_idx].geometry + if not self.merge_group: + if ( + vertex.vertex_class == VertexClass.FIVE_WAY_TWO_PRIMARY_LINE + or vertex.vertex_class == VertexClass.FIVE_WAY_ONE_PRIMARY_LINE + or vertex.vertex_class == VertexClass.FOUR_WAY_ONE_PRIMARY_LINE + or vertex.vertex_class == VertexClass.FOUR_WAY_TWO_PRIMARY_LINE + or vertex.vertex_class == VertexClass.THREE_WAY_ONE_PRIMARY_LINE + ): + out_polys = vertex.trim_primary_end(polys) + if len(out_polys) == 0: + continue + + # update polygon DataFrame + for idx, out_poly in out_polys: + if out_poly: + self.polys.at[idx, "geometry"] = out_poly + + # retrieve polygons again. Some polygons may be updated + polys = self.polys.loc[s_idx] + if ( + vertex.vertex_class == VertexClass.SINGLE_WAY + or vertex.vertex_class == VertexClass.TWO_WAY_ZERO_PRIMARY_LINE + or vertex.vertex_class == VertexClass.THREE_WAY_ZERO_PRIMARY_LINE + or vertex.vertex_class == VertexClass.FOUR_WAY_ZERO_PRIMARY_LINE + or vertex.vertex_class == VertexClass.FIVE_WAY_ZERO_PRIMARY_LINE + ): + if vertex.vertex_class == VertexClass.THREE_WAY_ZERO_PRIMARY_LINE: + pass + + out_polys = vertex.trim_end_all(polys) + if len(out_polys) == 0: + continue + + # update polygon DataFrame + for idx, out_poly in out_polys: + self.polys.at[idx, "geometry"] = out_poly + + polys = self.polys.loc[s_idx] + if vertex.vertex_class != VertexClass.SINGLE_WAY: + poly_trim_list = vertex.trim_intersection(polys, self.merge_group) + for p_trim in poly_trim_list: + # update main line and polygon DataFrame + self.polys.at[p_trim.poly_index, "geometry"] = p_trim.poly_cleanup + self.lines.at[p_trim.line_index, "geometry"] = p_trim.line_cleanup + + # update VertexNode's line + self.update_line_in_vertex_node(p_trim.line_index, p_trim.line_cleanup) + + def get_merged_lines_original(self): + return self.lines.dissolve(by=bt_const.BT_GROUP) + + def run_grouping(self): + self.create_vertex_list() + if not self.has_group_attr: + self.group_lines() + + self.find_vertex_for_poly_trimming() + self.lines[bt_const.BT_GROUP] = self.groups # assign group attribute + + def run_regrouping(self): + """ + Run this when new lines are added to grouped file. + + Some new lines has empty group attributes + """ + pass + + def run_cleanup(self, in_polys): + self.polys = in_polys.copy() + self.line_and_poly_cleanup() + self.run_line_merge_trimmed() + self.check_geom_validity() + + def run_line_merge_trimmed(self): + self.merged_lines_trimmed = self.run_line_merge() + + def check_geom_validity(self): + """ + Check MultiLineString and MultiPolygon in line and polygon dataframe. + + Save to separate layers for user to double check + """ + # remove null geometry + # TODO make sure lines and polygons match in pairs + # they should have same amount and spatial coverage + self.valid_polys = self.polys[~self.polys.geometry.isna() & ~self.polys.geometry.is_empty] + + # save sh_geom.MultiLineString and sh_geom.MultiPolygon + self.invalid_polys = self.polys[(self.polys.geometry.geom_type == "MultiPolygon")] + + # check lines + self.valid_lines = self.merged_lines_trimmed[ + ~self.merged_lines_trimmed.geometry.isna() & ~self.merged_lines_trimmed.geometry.is_empty + ] + self.valid_lines.reset_index(inplace=True, drop=True) + + self.invalid_lines = self.merged_lines_trimmed[ + (self.merged_lines_trimmed.geometry.geom_type == "MultiLineString") + ] + self.invalid_lines.reset_index(inplace=True, drop=True) + + def save_file(self, out_file, out_layer="ground_footprint"): + if not self.valid_lines.empty: + self.valid_lines = algo_common.clean_geometries( + self.valid_lines, + stage="output", + out_file=out_file, + layer="rejected_output_ground_trimmed_lines", + ) + self.valid_lines["length"] = self.valid_lines.length + self.valid_lines.to_file(out_file, layer="merged_lines") + + if not self.valid_polys.empty: + self.valid_polys = algo_common.clean_geometries( + self.valid_polys, + stage="output", + out_file=out_file, + layer="rejected_output_ground_trimmed_footprint", + ) + if "length" in self.valid_polys.columns: + self.valid_polys.drop(columns=["length"], inplace=True) + + self.valid_polys["area"] = self.valid_polys.area + layer_name = out_layer + self.valid_polys.to_file(out_file, layer=layer_name) + + if not self.invalid_lines.empty: + self.invalid_lines.to_file(out_file, layer="invalid_lines") + + if not self.invalid_polys.empty: + self.invalid_polys.to_file(out_file, layer="invalid_polygons") + + +@dataclass +class PolygonTrimming: + """Store polygon and line to trim. Primary polygon is used to trim both.""" + + poly_primary: Optional[sh_geom.MultiPolygon] = None + poly_index: int = field(default=-1) + poly_cleanup: Optional[sh_geom.Polygon] = None + line_index: int = field(default=-1) + line_cleanup: Optional[sh_geom.LineString] = None + + def process(self, primary_poly_list=None, vertex=None): + # prepare primary polygon + poly_primary = shapely.union_all(primary_poly_list) + trim_distance = TRIMMING_DISTANCE + + if self.line_cleanup.length < 100.0: + trim_distance = 50.0 + + poly_primary = poly_primary.intersection(vertex.buffer(trim_distance)) + + self.poly_primary = poly_primary + + # TODO: check why there is such cases + if self.poly_cleanup is None: + print("No polygon to trim.") + return + + midpoint = self.line_cleanup.interpolate(0.5, normalized=True) + if self.poly_primary is None or self.poly_primary.is_empty: + # print("Warning: No valid primary polygon for trimming; skipping difference operation.") + # TODO: handle this case + return + diff = self.poly_cleanup.difference(self.poly_primary) + if diff.geom_type == "Polygon": + self.poly_cleanup = diff + elif diff.geom_type == "MultiPolygon": + # area = self.poly_cleanup.area + reserved = [] + for i in diff.geoms: + # if i.area > TRIM_THRESHOLD * area: # small part + # reserved.append(i) + if i.contains(midpoint): + reserved.append(i) + + if len(reserved) == 0: + pass + elif len(reserved) == 1: + self.poly_cleanup = sh_geom.Polygon(*reserved) + else: + # TODO output all MultiPolygons which should be dealt with + # self.poly_cleanup = sh_geom.MultiPolygon(reserved) + print("trim: MultiPolygon detected, please check") + + diff = self.line_cleanup.intersection(self.poly_cleanup) + if diff.geom_type == "GeometryCollection": + geoms = [] + for item in diff.geoms: + if item.geom_type == "LineString": + geoms.append(item) + elif item.geom_type == "MultiLineString": + print("trim: sh_geom.MultiLineString detected, please check") + if len(geoms) == 0: + return + elif len(geoms) == 1: + diff = geoms[0] + else: + diff = sh_geom.MultiLineString(geoms) + + if diff.geom_type == "LineString": + self.line_cleanup = diff + elif diff.geom_type == "MultiLineString": + length = self.line_cleanup.length + reserved = [] + for i in diff.geoms: + if i.length > TRIM_THRESHOLD * length: # small part + reserved.append(i) + + if len(reserved) == 0: + pass + elif len(reserved) == 1: + self.line_cleanup = sh_geom.LineString(*reserved) + else: + # TODO output all MultiPolygons which should be dealt with + self.poly_cleanup = sh_geom.MultiLineString(reserved) diff --git a/beratools/modules/mapping/algo_merge_lines.py b/beratools/modules/mapping/algo_merge_lines.py new file mode 100644 index 0000000..22367dd --- /dev/null +++ b/beratools/modules/mapping/algo_merge_lines.py @@ -0,0 +1,276 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + This file is intended to be hosting algorithms and utility functions/classes + for merging lines. +""" + +from itertools import pairwise +from operator import itemgetter + +import networkit as nk +import shapely.geometry as sh_geom +from shapely.geometry import GeometryCollection, LineString, MultiLineString +from shapely.ops import linemerge + +import beratools.core.constants as bt_const +import beratools.modules.mapping.algo_common as algo_common + + +def safe_linemerge(geom): + if isinstance(geom, (MultiLineString, GeometryCollection)): + return linemerge(geom) + elif isinstance(geom, LineString): + return geom + else: + return geom + + +def custom_line_merge(geom): + if geom.geom_type == "MultiLineString": + # First try shapely's linemerge (fast) + merged = linemerge(geom) + # If still MultiLineString, use MergeLines for complex cases + if isinstance(merged, sh_geom.MultiLineString): + worker = MergeLines(merged) + merged = worker.merge_all_lines() + return merged if merged else geom + else: + return merged + elif geom.geom_type == "LineString": + return geom + else: + return geom + + +def run_line_merge(in_line_gdf, merge_group, group_field=bt_const.BT_GROUP): + """Merge lines sharing a group_field value into one line (BT_GROUP by default).""" + out_line_gdf = in_line_gdf + if merge_group: + if group_field not in in_line_gdf.columns: + in_line_gdf = in_line_gdf.copy() + in_line_gdf[group_field] = range(1, len(in_line_gdf) + 1) + out_line_gdf = in_line_gdf.dissolve(by=group_field, as_index=False) + + out_line_gdf.geometry = out_line_gdf.geometry.apply(safe_linemerge) + for i, row in enumerate(out_line_gdf.itertuples()): + if isinstance(row.geometry, sh_geom.MultiLineString): + worker = MergeLines(row.geometry) + merged_line = worker.merge_all_lines() + if merged_line: + out_line_gdf.at[row.Index, "geometry"] = merged_line + + out_line_gdf = algo_common.clean_line_geometries(out_line_gdf) + out_line_gdf.reset_index(inplace=True, drop=True) + out_line_gdf["length"] = out_line_gdf.geometry.length + return out_line_gdf + + +class MergeLines: + """Merge line segments in MultiLineString.""" + + def __init__(self, multi_line): + self.G = None + self.line_segs = None + self.multi_line = multi_line + self.node_poly = None + self.end = None + + self.create_graph() + + def create_graph(self): + self.line_segs = list(self.multi_line.geoms) + + # TODO: check empty line and null geoms + self.line_segs = [line for line in self.line_segs if line.length > 1e-3] + self.multi_line = sh_geom.MultiLineString(self.line_segs) + m = sh_geom.mapping(self.multi_line) + self.end = [(i[0], i[-1]) for i in m["coordinates"]] + + self.G = nk.Graph(edgesIndexed=True) + self.G.addNodes(2) + self.G.addEdge(0, 1) + + self.node_poly = [ + sh_geom.Point(self.end[0][0]).buffer(1), + sh_geom.Point(self.end[0][1]).buffer(1), + ] + + for i, line in enumerate(self.end[1:]): + node_exists = False + pt = sh_geom.Point(line[0]) + pt_buffer = pt.buffer(1) + + for node in self.G.iterNodes(): + if self.node_poly[node].contains(pt): + node_exists = True + node_start = node + if not node_exists: + node_start = self.G.addNode() + self.node_poly.append(pt_buffer) + + node_exists = False + pt = sh_geom.Point(line[1]) + pt_buffer = pt.buffer(1) + for node in self.G.iterNodes(): + if self.node_poly[node].contains(pt): + node_exists = True + node_end = node + if not node_exists: + node_end = self.G.addNode() + self.node_poly.append(pt_buffer) + + self.G.addEdge(node_start, node_end) + + def get_components(self): + cc = nk.components.ConnectedComponents(self.G) + cc.run() + components = cc.getComponents() + return components + + def is_single_path(self, component): + single_path = True + for node in component: + neighbors = list(self.G.iterNeighbors(node)) + if len(neighbors) > 2: + single_path = False + + return single_path + + def get_merged_line_for_component(self, component): + sub = nk.graphtools.subgraphFromNodes(self.G, component) + lines = None + if nk.graphtools.maxDegree(sub) >= 3: # not simple path + edges = [self.G.edgeId(i[0], i[1]) for i in list(sub.iterEdges())] + lines = itemgetter(*edges)(self.line_segs) + elif nk.graphtools.maxDegree(sub) == 2: + lines = self.merge_single_line(component) + + return lines + + def find_path_for_component(self, component): + if not component: + return [] + + neighbors = list(self.G.iterNeighbors(component[0])) + if not neighbors: + return [component[0]] + + path = [component[0]] + right = neighbors[0] + path.append(right) + + left = None + if len(neighbors) == 2: + left = neighbors[1] + path.insert(0, left) + + neighbors = list(self.G.iterNeighbors(right)) + right_safety = 0 + while len(neighbors) > 1: + right_safety += 1 + if right_safety > len(component) + 2: + break + + next_candidates = [n for n in neighbors if n not in path] + if not next_candidates: + break + + right = next_candidates[0] + path.append(right) + + neighbors = list(self.G.iterNeighbors(right)) + + # last node + if neighbors[0] not in path: + path.append(neighbors[0]) + + # process left side + if left: + neighbors = list(self.G.iterNeighbors(left)) + left_safety = 0 + while len(neighbors) > 1: + left_safety += 1 + if left_safety > len(component) + 2: + break + + next_candidates = [n for n in neighbors if n not in path] + if not next_candidates: + break + + left = next_candidates[0] + path.insert(0, left) + + neighbors = list(self.G.iterNeighbors(left)) + + # last node + if neighbors[0] not in path: + path.insert(0, neighbors[0]) + + return path + + def merge_single_line(self, component): + path = self.find_path_for_component(component) + if len(path) < 2: + return None + + pairs = list(pairwise(path)) + if not pairs: + return None + + line_list = [self.G.edgeId(i[0], i[1]) for i in pairs] + if not line_list: + return None + + vertices = [] + + for i, id in enumerate(line_list): + pair = pairs[i] + poly_t = self.node_poly[pair[0]] + point_t = sh_geom.Point(self.end[id][0]) + if poly_t.contains(point_t): + line = self.line_segs[id] + else: + # line = reverse(self.line_segs[id]) + line = self.line_segs[id].reverse() + + vertices.extend(list(line.coords)) + last_vertex = vertices.pop() + + vertices.append(last_vertex) + merged_line = sh_geom.LineString(vertices) + + return [merged_line] + + def merge_all_lines(self): + components = self.get_components() + lines = [] + for c in components: + line = self.get_merged_line_for_component(c) + if line: + if isinstance(line, tuple): + lines.extend(list(line)) + elif isinstance(line, list): + lines.extend(line) + else: + lines.append(line) + else: # TODO: check line + print(f"merge_all_lines: failed to merge: {self.multi_line.bounds}") + + # print('Merge lines done.') + + if len(lines) > 1: + return sh_geom.MultiLineString(lines) + elif len(lines) == 1: + return lines[0] + else: + return None diff --git a/beratools/modules/mapping/algo_seed_line_correction.py b/beratools/modules/mapping/algo_seed_line_correction.py new file mode 100644 index 0000000..98b18cb --- /dev/null +++ b/beratools/modules/mapping/algo_seed_line_correction.py @@ -0,0 +1,612 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + The purpose of this script is to move line vertices to the right + seismic line courses for improved alignment and analysis in + geospatial data processing. +""" + +import geopandas as gpd +import numpy as np +import pandas as pd +import shapely.geometry as sh_geom +from shapely import STRtree + +import beratools.core.constants as bt_const +import beratools.core.tool_base as bt_base +import beratools.modules.mapping.algo_common as algo_common +import beratools.modules.mapping.algo_cost as algo_cost +import beratools.utility.spatial_common as sp_common +from beratools.modules.mapping import algo_dijkstra +from beratools.modules.mapping.algo_check_seed_line import VertexPrecleaner + +try: + import rasterio +except Exception: + rasterio = None + + +def update_line_end_pt(line, index, new_vertex): + if not line: + return None + + if index >= len(line.coords) or index < -1: + return line + + coords = list(line.coords) + if len(coords[index]) == 2: + coords[index] = (new_vertex.x, new_vertex.y) + elif len(coords[index]) == 3: + coords[index] = (new_vertex.x, new_vertex.y, 0.0) + + return sh_geom.LineString(coords) + + +class _SingleLine: + """Single line object with anchor point.""" + + def __init__(self, line_gdf, line_no, end_no, search_distance): + self.line_gdf = line_gdf + self.line = self.line_gdf.geometry[0] + self.line_no = line_no + self.end_no = end_no + self.search_distance = search_distance + self.anchor = None + + self.add_anchors_to_line() + + def is_valid(self): + return self.line.is_valid + + def line_coord_list(self): + return algo_common.line_coord_list(self.line) + + def get_end_vertex(self): + return self.line_coord_list()[self.end_no] + + def touches_point(self, vertex): + return algo_common.points_are_close(vertex, self.get_end_vertex()) + + def get_angle(self): + return algo_common.get_angle(self.line, self.end_no) + + def add_anchors_to_line(self): + """ + Append new vertex to vertex group, by calculating distance to existing vertices. + + An anchor point will be added together with line + """ + # Calculate anchor point for each vertex + point = self.get_end_vertex() + line_string = self.line + index = self.end_no + pts = algo_common.line_coord_list(line_string) + + pt_1 = None + pt_2 = None + if index == 0: + pt_1 = point + pt_2 = pts[1] + elif index == -1: + pt_1 = point + pt_2 = pts[-2] + + # Calculate anchor point + dist_pt = 0.0 + if pt_1 and pt_2: + dist_pt = pt_1.distance(pt_2) + + # TODO: check why two points are the same + if np.isclose(dist_pt, 0.0): + print("Points are close, return") + return None + + X = pt_1.x + (pt_2.x - pt_1.x) * self.search_distance / dist_pt + Y = pt_1.y + (pt_2.y - pt_1.y) * self.search_distance / dist_pt + self.anchor = sh_geom.Point(X, Y) # add anchor point + + +class _Vertex: + """Vertex object with multiple lines.""" + + def __init__(self, line_obj, in_raster=None, line_radius=None, cost_footprint=None): + self.vertex = line_obj.get_end_vertex() + self.search_distance = line_obj.search_distance + + self.cost_footprint = cost_footprint + self.vertex_opt = None # optimized vertex + self.centerlines = None + self.anchors = None + self.in_raster = in_raster + self.line_radius = line_radius + self.lines = [] # SingleLine objects + + self.add_line(line_obj) + + def add_line(self, line_obj): + self.lines.append(line_obj) + + def generate_anchor_pairs(self): + """ + Extend line following outward direction to length of search_distance. + + Use the end point as anchor point. + + vertex: input intersection with all related lines + return: + one or two pairs of anchors according to numbers of lines + intersected. + two pairs anchors return when 3 or 4 lines intersected + one pair anchors return when 1 or 2 lines intersected. + """ + vertex = self.get_vertex() + slopes = [] + for line in self.lines: + slopes.append(line.get_angle()) + + index = 0 # the index of line which paired with first line. + pt_start_1 = None + pt_end_1 = None + pt_start_2 = None + pt_end_2 = None + + if len(slopes) == 4: + # get sort order of angles + index = np.argsort(slopes) + + # first anchor pair (first and third in the sorted array) + pt_start_1 = self.lines[index[0]].anchor + pt_end_1 = self.lines[index[2]].anchor + + pt_start_2 = self.lines[index[1]].anchor + pt_end_2 = self.lines[index[3]].anchor + elif len(slopes) == 3: + # find the largest difference between angles + angle_diff = [ + abs(slopes[0] - slopes[1]), + abs(slopes[0] - slopes[2]), + abs(slopes[1] - slopes[2]), + ] + angle_diff_norm = [2 * np.pi - i if i > np.pi else i for i in angle_diff] + index = np.argmax(angle_diff_norm) + pairs = [(0, 1), (0, 2), (1, 2)] + pair = pairs[index] + + # first anchor pair + pt_start_1 = self.lines[pair[0]].anchor + pt_end_1 = self.lines[pair[1]].anchor + + # the rest one index + remain = list({0, 1, 2} - set(pair))[0] # the remaining index + + try: + pt_start_2 = self.lines[remain].anchor + # symmetry point of pt_start_2 regarding vertex["point"] + X = vertex.x - (pt_start_2.x - vertex.x) + Y = vertex.y - (pt_start_2.y - vertex.y) + pt_end_2 = sh_geom.Point(X, Y) + except Exception as e: + print(e) + + # this scenario only use two anchors + # and find the closest point on least cost path + elif len(slopes) == 2: + pt_start_1 = self.lines[0].anchor + pt_end_1 = self.lines[1].anchor + elif len(slopes) == 1: + pt_start_1 = self.lines[0].anchor + # symmetry point of pt_start_1 regarding vertex["point"] + X = vertex.x - (pt_start_1.x - vertex.x) + Y = vertex.y - (pt_start_1.y - vertex.y) + pt_end_1 = sh_geom.Point(X, Y) + + if not pt_start_1 or not pt_end_1: + print("Anchors not found") + + # if points are outside of cost footprint, set to None + points = [pt_start_1, pt_end_1, pt_start_2, pt_end_2] + for index, pt in enumerate(points): + if pt: + if not self.cost_footprint.contains(sh_geom.Point(pt)): + points[index] = None + + if len(slopes) == 4 or len(slopes) == 3: + if None in points: + return None + else: + return points + elif len(slopes) == 2 or len(slopes) == 1: + if None in (pt_start_1, pt_end_1): + return None + else: + return pt_start_1, pt_end_1 + + def compute(self): + if self.cost_footprint is not None: + try: + if not self.cost_footprint.covers(self.get_vertex()): + return None + except Exception: + if not self.cost_footprint.contains(self.get_vertex()): + return None + + try: + self.anchors = self.generate_anchor_pairs() + except Exception as e: + print(e) + + if not self.anchors: + if bt_const.BT_DEBUGGING: + print("No anchors retrieved") + return None + + centerline_1 = None + centerline_2 = None + intersection = None + + if bt_const.CenterlineFlags.USE_SKIMAGE_GRAPH: + find_lc_path = algo_dijkstra.find_least_cost_path_skimage + else: + find_lc_path = algo_dijkstra.find_least_cost_path + + try: + if len(self.anchors) == 4: + seed_line = sh_geom.LineString(self.anchors[0:2]) + if not self._should_process_seed_line(seed_line): + return None + + raster_clip, out_meta = sp_common.clip_raster(self.in_raster, seed_line, self.line_radius) + raster_clip, _ = algo_cost.cost_raster(raster_clip, out_meta) + centerline_1 = find_lc_path(raster_clip, out_meta, seed_line) + seed_line = sh_geom.LineString(self.anchors[2:4]) + if not self._should_process_seed_line(seed_line): + return None + + raster_clip, out_meta = sp_common.clip_raster(self.in_raster, seed_line, self.line_radius) + raster_clip, _ = algo_cost.cost_raster(raster_clip, out_meta) + centerline_2 = find_lc_path(raster_clip, out_meta, seed_line) + + if centerline_1 and centerline_2: + intersection = algo_common.intersection_of_lines(centerline_1, centerline_2) + elif len(self.anchors) == 2: + seed_line = sh_geom.LineString(self.anchors) + if not self._should_process_seed_line(seed_line): + return None + + raster_clip, out_meta = sp_common.clip_raster(self.in_raster, seed_line, self.line_radius) + raster_clip, _ = algo_cost.cost_raster(raster_clip, out_meta) + centerline_1 = find_lc_path(raster_clip, out_meta, seed_line) + + if centerline_1: + intersection = algo_common.closest_point_to_line(self.get_vertex(), centerline_1) + except Exception as e: + print(e) + + # Update vertices according to intersection, new center lines are returned + if type(intersection) is sh_geom.MultiPoint: + intersection = intersection.centroid + + self.centerlines = [centerline_1, centerline_2] + self.vertex_opt = intersection + + def _should_process_seed_line(self, seed_line): + if seed_line is None or seed_line.length <= bt_const.SMALL_BUFFER: + return False + + if self.cost_footprint is not None: + try: + if not self.cost_footprint.intersects(seed_line.buffer(self.line_radius)): + return False + except Exception: + return False + + max_seed_length = max(float(self.search_distance) * 6.0, float(self.line_radius) * 10.0) + if seed_line.length > max_seed_length: + return False + + return True + + def get_lines(self): + lines = [item.line for item in self.lines] + return lines + + def get_vertex(self): + return self.vertex + + +class SeedLineCorrection: + """A class used to group vertices and perform seed line correction.""" + + process_label = "Seed line correction" + + def __init__( + self, + in_line, + in_raster, + search_distance, + line_radius, + processes, + call_mode, + layer=None, + optimize_internal_vertices=False, + close_distance=None, + min_segment_length=None, + angle_tol=10.0, + ): + self.in_line = in_line + self.in_layer = layer + self.in_raster = in_raster + self.line_radius = float(line_radius) + self.search_distance = float(search_distance) + self.processes = processes + self.call_mode = call_mode + self.optimize_internal_vertices = bool(optimize_internal_vertices) + + self.crs = None + self.vertex_grp = [] + self.sindex = None + + self.line_list = [] + self.line_visited = None + self.source_lines_gdf = None + + self.close_distance = close_distance + self.min_segment_length = min_segment_length + self.angle_tol = float(angle_tol) + + if self.close_distance is None: + self.close_distance = self._default_close_distance() + else: + self.close_distance = float(self.close_distance) + + if self.min_segment_length is None: + self.min_segment_length = self.close_distance + else: + self.min_segment_length = float(self.min_segment_length) + + # calculate cost raster footprint + self.cost_footprint = sp_common.generate_raster_footprint(self.in_raster, latlon=False) + + def _default_close_distance(self): + fallback = 2.0 + if rasterio is None: + return fallback + + try: + with rasterio.open(self.in_raster) as src: + transform = src.transform + cell_size = min(abs(transform.a), abs(transform.e)) + if np.isclose(cell_size, 0.0): + return fallback + return float(max(2.0, 1.5 * cell_size)) + except Exception: + return fallback + + def create_vertex_group(self, line_obj): + """ + Create a new vertex group. + + Args: + line_obj : _SingleLine + + """ + # all end points not added will stay with this vertex + vertex = line_obj.get_end_vertex() + vertex_obj = _Vertex( + line_obj, + in_raster=self.in_raster, + line_radius=self.line_radius, + cost_footprint=self.cost_footprint, + ) + search = self.sindex.query(vertex.buffer(bt_const.SMALL_BUFFER)) + + # add more vertices to the new group + for i in search: + line = self.line_list[i] + if i == line_obj.line_no: + continue + + if not self.line_visited[i][0]: + new_line = _SingleLine(line, i, 0, self.search_distance) + if new_line.touches_point(vertex): + vertex_obj.add_line(new_line) + self.line_visited[i][0] = True + + if not self.line_visited[i][-1]: + new_line = _SingleLine(line, i, -1, self.search_distance) + if new_line.touches_point(vertex): + vertex_obj.add_line(new_line) + self.line_visited[i][-1] = True + + self.vertex_grp.append(vertex_obj) + + def prepare_lines(self, lines_gdf=None): + print("Preparing lines...", flush=True) + print(f"in_file: {self.in_line}") + print(f"in_layer: {self.in_layer}") + + if lines_gdf is None: + lines_gdf = algo_common.read_geospatial_file(self.in_line, layer=self.in_layer) + + if lines_gdf is None: + self.source_lines_gdf = None + self.line_list = [] + self.sindex = None + self.line_visited = None + return + + # Keep in-memory and file-based paths consistent with shared input hygiene. + if "fid" in lines_gdf.columns: + lines_gdf = lines_gdf.rename(columns={"fid": "orig_fid"}) + + lines_gdf = algo_common.clean_geometries(lines_gdf, stage="input") + lines_gdf = lines_gdf.reset_index(drop=True) + if bt_const.BT_UID not in lines_gdf.columns: + lines_gdf[bt_const.BT_UID] = range(len(lines_gdf)) + + self.source_lines_gdf = lines_gdf.copy() + lines_gdf = VertexPrecleaner( + self.close_distance, + self.angle_tol, + ).remove_close_vertices(lines_gdf) + + self._index_lines(lines_gdf) + + def _index_lines(self, lines_gdf): + """Split prepared lines into line_list and build the spatial index.""" + if self.optimize_internal_vertices: + self.line_list = algo_common.split_lines_to_segments(algo_common.keep_source_seg(lines_gdf)) + else: + self.line_list = algo_common.lines_gdf_to_list(lines_gdf) + + if not self.line_list: + print(f"No lines available for {self.process_label.lower()}.") + self.sindex = None + self.line_visited = None + return + + self.sindex = STRtree([item.geometry[0] for item in self.line_list]) + self.line_visited = [{0: False, -1: False} for _ in range(len(self.line_list))] + + def group_vertices(self): + if not self.line_list or self.line_visited is None: + return + + for line_no in range(len(self.line_list)): + for end_no in [0, -1]: + if self.line_visited[line_no][end_no]: + continue + + line = _SingleLine(self.line_list[line_no], line_no, end_no, self.search_distance) + if not line.is_valid(): + print(f"Line {line.line_no} is invalid") + continue + + self.create_vertex_group(line) + self.line_visited[line_no][end_no] = True + + def create_all_vertex_groups(self): + self.prepare_lines() + self.group_vertices() + + def update_all_lines(self): + for vertex_obj in self.vertex_grp: + for line in vertex_obj.lines: + if not vertex_obj.vertex_opt: + continue + + old_line = self.line_list[line.line_no].geometry[0] + self.line_list[line.line_no].geometry = [ + update_line_end_pt(old_line, line.end_no, vertex_obj.vertex_opt) + ] + + def _post_update_vertex_cleanup(self, mode="endpoint_only"): + if not self.line_list or mode == "off": + return + + if mode not in VertexPrecleaner.VALID_MODES: + raise ValueError(f"Unsupported post-update vertex cleanup mode: {mode}") + + cleaned_lines = [] + precleaner = VertexPrecleaner(self.close_distance, self.angle_tol) + + for item in self.line_list: + line = item.geometry.iloc[0] + cleaned_line = precleaner.cleanup_line(line, mode=mode) + + if cleaned_line is None or cleaned_line.is_empty: + continue + + cleaned_item = item.copy() + cleaned_item.geometry = [cleaned_line] + cleaned_lines.append(cleaned_item) + + self.line_list = cleaned_lines + + def get_optimized_lines(self): + if not self.line_list: + if self.source_lines_gdf is None: + return None + + lines = self.source_lines_gdf.iloc[0:0] + return algo_common.clean_geometries( + lines, + stage="output", + layer="rejected_output_vertex_optimization_lines", + ) + + lines = pd.concat(self.line_list, ignore_index=True) + + if self.optimize_internal_vertices and bt_const.BT_UID in lines.columns: + import beratools.modules.mapping.algo_merge_lines as algo_merge_lines + + # join the segments back into their input rows, keeping each row's BT_GROUP + lines = algo_merge_lines.run_line_merge(lines, merge_group=True, group_field=bt_const.BT_UID) + lines = algo_common.restore_source_seg(lines) + + if "length" not in lines.columns: + lines["length"] = lines.geometry.length + + return algo_common.clean_geometries( + lines, + stage="output", + layer="rejected_output_vertex_optimization_lines", + ) + + def get_debug_layers(self): + lines = self.get_optimized_lines() + out_crs = None if lines is None else lines.crs + + lc_path_rows = [] + anchor_rows = [] + vertex_rows = [] + for group_id, item in enumerate(self.vertex_grp): + if item.centerlines: + for geom in item.centerlines: + if geom is not None: + lc_path_rows.append({"SLC_GROUP": int(group_id), "geometry": geom}) + if item.anchors: + for geom in item.anchors: + if geom is not None: + anchor_rows.append({"SLC_GROUP": int(group_id), "geometry": geom}) + if item.vertex_opt: + vertex_rows.append({"SLC_GROUP": int(group_id), "geometry": item.vertex_opt}) + + lc_paths = gpd.GeoDataFrame(lc_path_rows, columns=["SLC_GROUP", "geometry"], crs=out_crs) + anchors = gpd.GeoDataFrame(anchor_rows, columns=["SLC_GROUP", "geometry"], crs=out_crs) + vertices = gpd.GeoDataFrame(vertex_rows, columns=["SLC_GROUP", "geometry"], crs=out_crs) + + return { + "lc_paths": lc_paths, + "anchors": anchors, + "vertices": vertices, + } + + def optimize(self): + self.compute() + self.update_all_lines() + self._post_update_vertex_cleanup(mode="endpoint_only") + return self.get_optimized_lines() + + def _compute_processes(self): + return self.processes if self.processes is not None else 0 + + def compute(self): + vertex_grp = bt_base.execute_multiprocessing( + algo_common.process_single_item, + self.vertex_grp, + "Vertex Optimization", + self._compute_processes(), + self.call_mode, + ) + + self.vertex_grp = vertex_grp diff --git a/beratools/modules/mapping/algo_split_with_lines.py b/beratools/modules/mapping/algo_split_with_lines.py new file mode 100644 index 0000000..f0f1711 --- /dev/null +++ b/beratools/modules/mapping/algo_split_with_lines.py @@ -0,0 +1,291 @@ +"""Split lines at intersections using a class-based approach.""" + +from itertools import combinations + +import geopandas as gpd +from shapely import STRtree, snap +from shapely.geometry import LineString, MultiPoint, Point + +import beratools.modules.mapping.algo_common as algo_common + +EPSILON = 1e-5 +INTER_STATUS_COL = "INTER_STATUS" + + +def min_distance_in_multipoint(multipoint): + points = list(multipoint.geoms) + min_dist = float("inf") + for p1, p2 in combinations(points, 2): + dist = p1.distance(p2) + if dist < min_dist: + min_dist = dist + return min_dist + + +class LineSplitter: + """Split lines at intersections.""" + + def __init__(self, line_gdf): + """ + Initialize the LineSplitter with the input GeoPackage and layer name. + + Args: + input_gpkg (str): Path to the input GeoPackage file. + layer_name (str): Name of the layer to read from the GeoPackage. + + """ + # Explode if needed for multi-part geometries + self.line_gdf = line_gdf.explode() + self.line_gdf[INTER_STATUS_COL] = 1 # record line intersection status + self.inter_status = {} + self.sindex = self.line_gdf.sindex # Spatial index for faster operations + + self.intersection_gdf = [] + self.split_lines_gdf = None + + def cut_line_by_points(self, line, points): + """ + Cuts a LineString into segments based on the given points. + + Args: + line: A shapely LineString to be cut. + points: A list of Point objects where the LineString needs to be cut. + + Return: + A list of LineString segments after the cuts. + + """ + # Create a spatial index for the coordinates of the LineString + line_coords = [Point(x, y) for x, y in line.coords] + sindex = STRtree(line_coords) + + # Sort points based on their projected position along the line + sorted_points = sorted(points, key=lambda p: line.project(p)) + segments = [] + + # Process each point, inserting it into the correct location + start_idx = 0 + start_pt = None + end_pt = None + + for point in sorted_points: + # Find the closest segment on the line using the spatial index + nearest_pt_idx = sindex.nearest(point) + end_idx = nearest_pt_idx + end_pt = point + + dist1 = line.project(point) + dist2 = line.project(line_coords[nearest_pt_idx]) + + if dist1 > dist2: + end_idx = nearest_pt_idx + 1 + + # Create a new segment + new_coords = line_coords[start_idx:end_idx] + if start_pt: # Append start point + new_coords = [start_pt] + new_coords + + if end_pt: # Append end point + new_coords = new_coords + [end_pt] + + nearest_segment = LineString(new_coords) + start_idx = end_idx + start_pt = end_pt + + segments.append(nearest_segment) + + # Add remaining part of the line after the last point + if start_idx < len(line_coords): + # If last point is not close to end point of line + if start_pt.distance(line_coords[-1]) > EPSILON: + remaining_part = LineString([start_pt] + line_coords[end_idx:]) + segments.append(remaining_part) + + return segments + + def find_intersections(self): + """ + Find intersections between lines in the GeoDataFrame. + + Return: + List of Point geometries where the lines intersect. + + """ + visited_pairs = set() + intersection_points = [] + + # Iterate through each line geometry to find intersections + for idx, line1 in enumerate(self.line_gdf.geometry): + # Use spatial index to find candidates for intersection + indices = list(self.sindex.intersection(line1.bounds)) + indices.remove(idx) # Remove the current index from the list + + for match_idx in indices: + line2 = self.line_gdf.iloc[match_idx].geometry + + # Create an index pair where the smaller index comes first + pair = tuple(sorted([idx, match_idx])) + + # Skip if this pair has already been visited + if pair in visited_pairs: + continue + + # Mark the pair as visited + visited_pairs.add(pair) + + # Only check lines that are different and intersect + line1 = snap(line1, line2, tolerance=EPSILON) + if line1.intersects(line2): + # Find intersection points (can be multiple) + intersections = line1.intersection(line2) + + if intersections.is_empty: + continue + + # Intersection can be Point, MultiPoint, LineString + # or GeometryCollection + if isinstance(intersections, Point): + intersection_points.append(intersections) + else: + # record for further inspection + # GeometryCollection, MultiLineString + if isinstance(intersections, MultiPoint): + intersection_points.extend(intersections.geoms) + elif isinstance(intersections, LineString): + intersection_points.append(intersections.interpolate(0.5, normalized=True)) + + # if minimum distance between points is greater than threshold + # mark line as valid + if isinstance(intersections, MultiPoint): + if min_distance_in_multipoint(intersections) > algo_common.DISTANCE_THRESHOLD: + continue + # if intersection is a line, mark line as valid + if isinstance(intersections, LineString): + continue + + for item in pair: + self.inter_status[item] = 0 + + self.intersection_gdf = gpd.GeoDataFrame(geometry=intersection_points, crs=self.line_gdf.crs) + + def split_lines_at_intersections(self): + """ + Split lines at the given intersection points. + + Args: + intersection_points: List of Point geometries where the lines should be split. + + Returns: + A GeoDataFrame with the split lines. + + """ + # Create a spatial index for faster point-line intersection checks + sindex = self.intersection_gdf.sindex + + # List to hold the new split line segments + new_rows = [] + + # Iterate through each intersection point to split lines at that point + for row in self.line_gdf.itertuples(): + if not isinstance(row.geometry, LineString): + continue + + # Use spatial index to find possible line candidates for intersection + possible_matches = sindex.query(row.geometry.buffer(EPSILON)) + end_pts = MultiPoint([row.geometry.coords[0], row.geometry.coords[-1]]) + + pt_list = [] + new_segments = [row.geometry] + + for idx in possible_matches: + point = self.intersection_gdf.loc[idx].geometry + # Check if the point is on the line + if row.geometry.distance(point) < EPSILON: + if end_pts.distance(point) < EPSILON: + continue + else: + pt_list.append(point) + + if len(pt_list) > 0: + # Split the line at the intersection + new_segments = self.cut_line_by_points(row.geometry, pt_list) + + # If the line was split into multiple segments, create new rows + for segment in new_segments: + new_row = row._asdict() # Convert the original row into a dictionary + new_row["geometry"] = segment # Update the geometry with the split one + new_rows.append(new_row) + + self.split_lines_gdf = gpd.GeoDataFrame( + new_rows, columns=self.line_gdf.columns, crs=self.line_gdf.crs + ) + + self.split_lines_gdf = algo_common.clean_line_geometries(self.split_lines_gdf) + + # Debugging: print how many segments were created + print(f"Total new line segments created: {len(new_rows)}") + + def save_to_geopackage( + self, + input_gpkg, + line_layer="split_lines", + intersection_layer=None, + invalid_layer=None, + ): + """ + Save the split lines and intersection points to the GeoPackage. + + Args: + line_layer: split lines layer name in the GeoPackage. + intersection_layer: layer name for intersection points in the GeoPackage. + + """ + # Save intersection points and split lines to the GeoPackage + if self.split_lines_gdf is not None and intersection_layer: + if len(self.intersection_gdf) > 0: + self.intersection_gdf.to_file(input_gpkg, layer=intersection_layer, driver="GPKG") + + if self.split_lines_gdf is not None and line_layer: + if len(self.split_lines_gdf) > 0: + self.split_lines_gdf["length"] = self.split_lines_gdf.geometry.length + self.split_lines_gdf.to_file(input_gpkg, layer=line_layer, driver="GPKG") + + # save invalid splits + invalid_splits = self.line_gdf.loc[self.line_gdf[INTER_STATUS_COL] == 0] + if not invalid_splits.empty and invalid_layer: + if len(invalid_splits) > 0: + invalid_splits.to_file(input_gpkg, layer=invalid_layer, driver="GPKG") + + def process(self, intersection_gdf=None): + """ + Find intersection points, split lines at intersections. + + Args: + intersection_gdf: external GeoDataFrame with intersection points. + + """ + if intersection_gdf is not None: + self.intersection_gdf = intersection_gdf + else: + self.find_intersections() + + if self.inter_status: + for idx in self.inter_status.keys(): + self.line_gdf.loc[idx, INTER_STATUS_COL] = self.inter_status[idx] + + if not self.intersection_gdf.empty: + # Split the lines at intersection points + self.split_lines_at_intersections() + else: + print("No intersection points found, no lines to split.") + +if __name__ == "__main__": + input_gpkg = r"I:\Temp\footprint_final.gpkg" + layer_name = "merged_lines_original" + + gdf = gpd.read_file(input_gpkg, layer=layer_name) + if "fid" in gdf.columns: + gdf = gdf.rename(columns={"fid": "orig_fid"}) + splitter = LineSplitter(gdf) + splitter.process() + splitter.save_to_geopackage(input_gpkg) diff --git a/beratools/modules/mapping/algo_vertex_optimization.py b/beratools/modules/mapping/algo_vertex_optimization.py new file mode 100644 index 0000000..c27da89 --- /dev/null +++ b/beratools/modules/mapping/algo_vertex_optimization.py @@ -0,0 +1,117 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + The purpose of this script is to move line vertices to the right + seismic line courses for improved alignment and analysis in + geospatial data processing. + + The vertex grouping / anchor / least-cost-path machinery is shared with + seed line correction and lives in ``algo_seed_line_correction``. This + module only adds the file-based input pre-cleaning and output writing + used by the Vertex Optimization tool. +""" + +from pathlib import Path + +import geopandas as gpd +import pandas as pd + +import beratools.core.constants as bt_const +import beratools.modules.mapping.algo_common as algo_common +import beratools.modules.mapping.algo_merge_lines as algo_merge_lines +import beratools.modules.mapping.algo_vertex_preclean as algo_vertex_preclean +import beratools.utility.spatial_common as sp_common +from beratools.modules.mapping.algo_seed_line_correction import ( # noqa: F401 (re-exported) + SeedLineCorrection, + _SingleLine, + _Vertex, + update_line_end_pt, +) + + +class VertexGrouping(SeedLineCorrection): + """A class used to group vertices and perform vertex optimization.""" + + process_label = "Vertex optimization" + + def prepare_lines(self, lines_gdf=None): + print(f"Preparing lines...{self.in_line}", flush=True) + print(f"in_file: {self.in_line}, in_layer: {self.in_layer}") + + if lines_gdf is None: + lines_gdf = algo_common.read_geospatial_file(self.in_line, layer=self.in_layer) + + lines_gdf = algo_vertex_preclean.preclean_vertices( + lines_gdf, + self.close_distance, + self.min_segment_length, + self.angle_tol, + ) + self._index_lines(lines_gdf) + + def _compute_processes(self): + processes = self.processes + if self.optimize_internal_vertices and (processes is None or int(processes) <= 0): + processes = 1 + return processes + + def save_all_layers(self, line_file): + out_file, out_layer = sp_common.decode_file_layer(line_file) + line_file = Path(line_file) + + if not self.line_list: + lines = algo_common.read_geospatial_file(self.in_line, layer=self.in_layer) + if lines is None: + print(f"No output written to: {line_file} (failed to read input lines)", flush=True) + return + + lines = lines.iloc[0:0] + lines = algo_common.clean_geometries( + lines, + stage="output", + out_file=out_file, + layer="rejected_output_vertex_optimization_lines", + ) + lines.to_file(out_file, layer=out_layer) + print(f"Saved output to: {line_file}", flush=True) + return + + lines = pd.concat(self.line_list, ignore_index=True) + + if self.optimize_internal_vertices and bt_const.BT_UID in lines.columns: + # join the segments back into their input rows, keeping each row's BT_GROUP + lines = algo_merge_lines.run_line_merge(lines, merge_group=True, group_field=bt_const.BT_UID) + lines = algo_common.restore_source_seg(lines) + + lines = algo_common.clean_geometries( + lines, + stage="output", + out_file=out_file, + layer="rejected_output_vertex_optimization_lines", + ) + lines.to_file(out_file, layer=out_layer) + print(f"Saved output to: {line_file}", flush=True) + + if bt_const.BT_DEBUGGING: + aux_file = algo_common.get_aux_path(out_file) + lc_paths, anchors, vertices = [], [], [] + for item in self.vertex_grp: + if item.centerlines: + lc_paths.extend(g for g in item.centerlines if g is not None) + if item.anchors: + anchors.extend(g for g in item.anchors if g is not None) + if item.vertex_opt: + vertices.append(item.vertex_opt) + + gpd.GeoDataFrame(geometry=lc_paths, crs=lines.crs).to_file(aux_file, layer="lc_paths") + gpd.GeoDataFrame(geometry=anchors, crs=lines.crs).to_file(aux_file, layer="anchors") + gpd.GeoDataFrame(geometry=vertices, crs=lines.crs).to_file(aux_file, layer="vertices") diff --git a/beratools/modules/mapping/algo_vertex_preclean.py b/beratools/modules/mapping/algo_vertex_preclean.py new file mode 100644 index 0000000..4482275 --- /dev/null +++ b/beratools/modules/mapping/algo_vertex_preclean.py @@ -0,0 +1,175 @@ +"""Per-line vertex preclean helpers for vertex optimization.""" + +import math + +import geopandas as gpd +import numpy as np +import shapely as sh +import shapely.geometry as sh_geom + +import beratools.core.constants as bt_const + + +def _point_distance(coord_a, coord_b): + return sh_geom.Point(coord_a).distance(sh_geom.Point(coord_b)) + + +def _is_near_collinear(coord_a, coord_b, coord_c, angle_tol_deg): + v1x = coord_b[0] - coord_a[0] + v1y = coord_b[1] - coord_a[1] + v2x = coord_c[0] - coord_b[0] + v2y = coord_c[1] - coord_b[1] + + norm1 = math.hypot(v1x, v1y) + norm2 = math.hypot(v2x, v2y) + if norm1 <= bt_const.SMALL_BUFFER or norm2 <= bt_const.SMALL_BUFFER: + return True + + dot = v1x * v2x + v1y * v2y + cos_val = max(-1.0, min(1.0, dot / (norm1 * norm2))) + angle = math.degrees(math.acos(cos_val)) + + return angle <= angle_tol_deg or abs(angle - 180.0) <= angle_tol_deg + + +def _dedupe_consecutive_coords(coords): + if len(coords) <= 1: + return coords + + out = [coords[0]] + for coord in coords[1:]: + if _point_distance(coord, out[-1]) > bt_const.SMALL_BUFFER: + out.append(coord) + + return out + + +def _preclean_line(line, close_distance, min_segment_length, angle_tol): + coords = list(line.coords) + if len(coords) <= 2: + return line + + cleaned = [coords[0]] + + for i in range(1, len(coords) - 1): + prev_coord = cleaned[-1] + curr_coord = coords[i] + next_coord = coords[i + 1] + + prev_dist = _point_distance(prev_coord, curr_coord) + next_dist = _point_distance(curr_coord, next_coord) + + if prev_dist < close_distance or next_dist < close_distance: + continue + + if (prev_dist < min_segment_length or next_dist < min_segment_length) and _is_near_collinear( + prev_coord, curr_coord, next_coord, angle_tol + ): + continue + + cleaned.append(curr_coord) + + cleaned.append(coords[-1]) + cleaned = _dedupe_consecutive_coords(cleaned) + + while len(cleaned) > 2 and _point_distance(cleaned[0], cleaned[1]) < min_segment_length: + cleaned.pop(1) + + while len(cleaned) > 2 and _point_distance(cleaned[-2], cleaned[-1]) < min_segment_length: + cleaned.pop(-2) + + if len(cleaned) < 2: + return None + + if _point_distance(cleaned[0], cleaned[-1]) <= bt_const.SMALL_BUFFER: + return None + + return sh_geom.LineString(cleaned) + + +def _simplify_line_fr_dist_offset(line, close_distance, min_segment_length, angle_tol=None): + """ + 1) Remove repeated points from the input line, + 2) Remove vertices based on back and forward internal distances (e.g. < min_segment_length) and + offset constraints (e.g. perpendicular offset or collinearity < offset threshold). + + Return: + Simplified line + """ + line = sh.remove_repeated_points(line, tolerance=0.0) + vertices = np.array(line.coords) + if len(vertices) < 3: + return line + # Initialize with first point + simplified = [sh_geom.Point(vertices[0])] + skipped = False + for i in range(1, len(vertices) - 1): + prev = vertices[i - 1] + curr = vertices[i] + nxt = vertices[i + 1] + + # Calculate distances to previous and next vertex + dist_prev = np.linalg.norm(curr - prev) + dist_next = np.linalg.norm(nxt - curr) + # Calculate offset distances from curr point to previous and next vertex + current_p = sh_geom.Point(curr) + whole_l = sh_geom.LineString([prev, nxt]) + if skipped is False: + # Condition: either distances must be > 2 meters apart (example constraint) + if dist_prev > min_segment_length and dist_next > min_segment_length: + # perpendicular offset or collinearity > offset threshold, keep current point + if current_p.distance(whole_l) > close_distance: + simplified.append(current_p) + skipped = False + else: + # skip current when smaller + skipped = True + continue + + else: # Condition: distances < 2 meters apart, skip current + skipped = True + continue + else: + # if skipped in previous point, keep current point + simplified.append(current_p) + skipped = False + + # Always keep the last point + simplified.append(sh_geom.Point(vertices[-1])) + + return sh_geom.LineString(simplified) + + +def preclean_vertices(gdf, close_distance, min_segment_length, angle_tol): + """Remove redundant close internal vertices on each line independently.""" + if gdf is None or gdf.empty: + return gdf + + if isinstance(gdf, gpd.GeoSeries): + gdf = gpd.GeoDataFrame(geometry=gdf) + + out_gdf = gdf.copy() + + if any(geom.geom_type == "MultiLineString" for geom in out_gdf.geometry): + out_gdf = out_gdf.explode(index_parts=False) + + cleaned_geoms = [] + for geom in out_gdf.geometry: + if geom is None or geom.is_empty: + cleaned_geoms.append(None) + continue + + if geom.geom_type != "LineString": + cleaned_geoms.append(geom) + continue + + cleaned_geoms.append( + _simplify_line_fr_dist_offset(geom, close_distance, min_segment_length, angle_tol) + ) + + out_gdf.geometry = cleaned_geoms + out_gdf = out_gdf[~out_gdf.geometry.isna() & ~out_gdf.geometry.is_empty] + out_gdf = out_gdf[out_gdf.geometry.length > bt_const.SMALL_BUFFER] + out_gdf.reset_index(drop=True, inplace=True) + + return out_gdf diff --git a/beratools/modules/mapping/alt_spatial_common.py b/beratools/modules/mapping/alt_spatial_common.py new file mode 100644 index 0000000..13ec47e --- /dev/null +++ b/beratools/modules/mapping/alt_spatial_common.py @@ -0,0 +1,155 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng, Maverick Fong + +Description: + This file hosts alternate CHM clipping/filtering logic for centerline runs. +""" + +import math + +import numpy as np +import rasterio +import scipy.ndimage as ndimage +import shapely as shp +import skimage as ski +from rasterio import features + +import beratools.core.constants as bt_const + + +def alt_clip_and_filter_regional_maxima_wgap( + seedline_class, + in_raster_file, + clip_geom, + buffer=1.0, + default_nodata=bt_const.BT_NODATA, + ): + + def erose_all_labels(labels_array): + erose_array = np.zeros_like(labels_array) + unique_labels = np.unique(labels_array) + for label in unique_labels: + if label == 0: + continue # Skip background + + # Create a binary mask for the current label + mask = (labels_array == label) + + # Dilate the mask for this specific label + erose_mask = ski.morphology.erosion(mask) + + # Assign the dilated mask back into the new array with the correct label value + erose_array[erose_mask] = label + + return erose_array + + with rasterio.open(in_raster_file) as src: + + clip_geo_buffer = [shp.simplify(clip_geom,0.25).buffer(buffer)] + out_image, out_transform = rasterio.mask.mask(src, clip_geo_buffer, crop=True) + shapes = [(shp.simplify(clip_geom,0.25).buffer(buffer), 1)] # Burn value '1' into the raster + raster_array = features.rasterize(shapes, + out_shape=out_image.shape[1:], + transform=out_transform, + fill=0, + dtype=np.uint8, + all_touched=True, + + ) + valid_area=raster_array==1 + valid_area=valid_area[np.newaxis,...] + if src.nodata is not None: + out_image[out_image == src.nodata] = 0. + out_image[raster_array[np.newaxis,:] == 0] = default_nodata + ras_nodata = src.meta["nodata"] + if ras_nodata is None: + ras_nodata = default_nodata + + #generate mask for valid raster data + # data_mask = ~(np.ma.masked_equal(out_image, ras_nodata).mask) + data_mask = valid_area + #fill unmasked data with 0, otherwise keep the original value + data_filled = np.where(data_mask, out_image, 0) + data_filled = np.where(data_filled==ras_nodata,0, data_filled) + + + #calulate the gaussian_filter's sigma to remove sharp noise without removing small crowns. + sigma = math.ceil(seedline_class.tree_radius) * 0.5 + smoothed_data = ndimage.gaussian_filter(data_filled, sigma=sigma) + #generate search tree crown footprint + footprint = ski.morphology.disk(math.ceil(seedline_class.tree_radius)) + footprint = footprint.reshape(-1, footprint.shape[0], footprint.shape[1]) + + smooth_mask = ndimage.gaussian_filter(data_mask.astype(float), sigma=sigma) + mask_normalization = smoothed_data / smooth_mask + mask_normalization[~data_mask] = np.nan + mask_normalization = np.ma.masked_invalid(mask_normalization) + tree_tops_indices = ski.feature.peak_local_max( + mask_normalization, + min_distance=1, #find maximum number of tree tops + exclude_border=False, + num_peaks_per_label=1, + footprint=footprint, + ) + if len(tree_tops_indices) > 0: + mask_ = np.ma.zeros_like(mask_normalization) + for i, (_, row, col) in enumerate(tree_tops_indices): + mask_[_, row, col] = 1 + markers = ski.measure.label(mask_) + + markers_tree = ski.segmentation.expand_labels( + markers, distance=max(math.ceil(seedline_class.tree_radius), 1) + ) + markers_tree_=erose_all_labels(ski.segmentation.expand_labels(markers_tree,10)) + tree_area = markers_tree_.astype(bool) + new_chm = np.ma.zeros_like(mask_normalization) + new_chm[tree_area] = mask_normalization[tree_area] + new_chm[~valid_area] = np.nan + + new_chm_gaps = np.ma.zeros_like(mask_normalization) + new_chm_gaps=np.ma.where(markers_tree_==0,mask_normalization.data,0) + new_chm_gaps = np.ma.where(mask_normalization.mask , 0, new_chm_gaps) + + filtered_image = new_chm + + else: + filtered_image = mask_normalization # + markers = np.ma.zeros_like(mask_normalization) + tree_area = np.ma.zeros_like(mask_normalization, dtype=bool) + filtered_image[filtered_image < 0.0] = 0.0 + if np.ma.is_masked(filtered_image): + filtered_image.fill_value = default_nodata + else: + filtered_image = np.ma.masked_invalid(filtered_image) + filtered_image.fill_value = default_nodata + + ras_nodata = default_nodata + + # Update Metadata + out_meta = src.meta.copy() + out_meta.update({ + "driver": "GTiff", + "height": filtered_image.shape[1], + "width": filtered_image.shape[2], + "nodata": ras_nodata, + "transform": out_transform + }) + + tree_crown = ski.segmentation.watershed(-mask_normalization, markers, mask=~mask_normalization.mask, + watershed_line=True) + tree_crown_ = ski.morphology.erosion(tree_crown, footprint=ski.morphology.square(3)[np.newaxis,:] ) + tree_crown_area = tree_crown_.astype(bool) + new_crown = np.ma.zeros_like(mask_normalization) + new_crown[tree_crown_area] = mask_normalization[tree_crown_area] + new_crown[~tree_crown_area] = 0. + + return ( + filtered_image, + out_meta, + new_chm_gaps.squeeze(), + ) # ,markers.squeeze(),tree_area.squeeze(), new_crown.squeeze(), diff --git a/beratools/modules/mapping/canopy_footprint_absolute.py b/beratools/modules/mapping/canopy_footprint_absolute.py new file mode 100644 index 0000000..5f92a07 --- /dev/null +++ b/beratools/modules/mapping/canopy_footprint_absolute.py @@ -0,0 +1,278 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + The purpose of this script is to provide main interface for canopy footprint tool. +""" + +import logging +import time + +import geopandas as gpd +import pandas as pd + +import beratools.core.tool_base as bt_base +import beratools.utility.spatial_common as sp_common +import beratools.utility.unit_conversion as unit_conversion +from beratools.modules.mapping.algo_canopy_footprint_absolute import ( + CanopyFootprintRequest, + CanopyFootprintResult, + FootprintCanopyAdaptive, + cast_request_types, + generate_absolute_line_class_list, + merge_footprints_by_original_line, + process_single_absolute_line, + save_aux_layers, + save_main_footprint, +) +from beratools.utility.tool_args import CallMode + +LOGGER_NAME="canopy_footprint_abs" +logger = logging.getLogger(LOGGER_NAME) + + +def _is_valid_gdf(obj, attr): + """Check if obj has a non-empty GeoDataFrame attribute.""" + gdf = getattr(obj, attr, None) + return gdf is not None and hasattr(gdf, "empty") and not gdf.empty + + +def canopy_footprint_abs( + in_line, + in_chm, + corridor_thresh=3.0, + max_ln_width=32.0, + exp_shk_cell=0, + out_footprint=None, + footprint_mode="absolute", + tree_radius=1.5, + max_line_dist=1.5, + canopy_avoidance=0.0, + exponent=1.0, + canopy_thresh_percentage=50, + simplify_footprint_polygon=True, + footprint_simplify_length=0.5, + smooth_footprint_polygon=False, + footprint_polygon_smooth_iterations=1, + merge_by_original_line=False, + processes=0, + call_mode=CallMode.CLI, + log_level="INFO", +): + """Run canopy footprint in absolute or adaptive mode.""" + if not out_footprint: + raise ValueError("out_footprint is required") + + request = cast_request_types( + CanopyFootprintRequest( + in_line=in_line, + in_chm=in_chm, + out_footprint=out_footprint, + max_ln_width=max_ln_width, + corridor_thresh=corridor_thresh, + exp_shk_cell=exp_shk_cell, + tree_radius=tree_radius, + max_line_dist=max_line_dist, + canopy_avoidance=canopy_avoidance, + exponent=exponent, + canopy_thresh_percentage=canopy_thresh_percentage, + simplify_footprint_polygon=simplify_footprint_polygon, + footprint_simplify_length=footprint_simplify_length, + smooth_footprint_polygon=smooth_footprint_polygon, + footprint_polygon_smooth_iterations=footprint_polygon_smooth_iterations, + merge_by_original_line=merge_by_original_line, + processes=processes, + call_mode=call_mode, + log_level=log_level, + ) + ) + + mode = str(footprint_mode).strip().lower() + if mode not in {"absolute", "adaptive"}: + raise ValueError("footprint_mode must be 'absolute' or 'adaptive'") + + in_file, in_layer = sp_common.decode_file_layer(request.in_line) + vec_crs_osr = sp_common.vector_crs(in_file, in_layer) + request.max_ln_width = unit_conversion.convert_meters_param_projected_from_osr( + vec_crs_osr, + request.max_ln_width, + "Maximum Line Width (m)", + ) + request.footprint_simplify_length = unit_conversion.convert_meters_param_projected_from_osr( + vec_crs_osr, + request.footprint_simplify_length, + "Footprint Simplification Length (m)", + ) + + if not sp_common.compare_crs(vec_crs_osr, sp_common.raster_crs(request.in_chm)): + print("Line and CHM have different spatial references, please check.") + return + + if not sp_common.check_vector_raster_extent_overlap(in_file, in_layer, request.in_chm): + print("Input line extent does not overlap input raster extent.") + return + + line_gdf = gpd.read_file(in_file, layer=in_layer) + if not sp_common.check_vector_raster_overlap(line_gdf, request.in_chm): + print("Input line(s) do not overlap input raster.") + return + + if mode == "adaptive": + result = _run_adaptive_request(request) + rejected_layer_name = "rejected_output_canopy_footprint_adaptive" + else: + result = _run_absolute_request(request) + rejected_layer_name = "rejected_output_canopy_footprint_absolute" + + for message in result.messages: + print(message) + + # one footprint per input line, or per original line when merging, as in the centerline tool + if request.merge_by_original_line: + result.footprints_gdf = merge_footprints_by_original_line(result.footprints_gdf, printer=print) + + save_main_footprint( + result, + request.out_footprint, + rejected_layer_name=rejected_layer_name, + printer=print, + ) + if mode == "adaptive": + save_aux_layers(result, request.out_footprint, printer=print) + + +def _run_absolute_request(req: CanopyFootprintRequest) -> CanopyFootprintResult: + """Run absolute footprint workflow using shared request/result contracts.""" + in_file, in_layer = sp_common.decode_file_layer(req.in_line) + + corridor_thresh = req.corridor_thresh if req.corridor_thresh is not None else 3.0 + exp_shk_cell = req.exp_shk_cell if req.exp_shk_cell is not None else 0 + + footprint_list = [] + line_class_list = generate_absolute_line_class_list( + in_file, + req.in_chm, + corridor_thresh, + req.max_ln_width, + exp_shk_cell, + req.simplify_footprint_polygon, + req.footprint_simplify_length, + req.smooth_footprint_polygon, + req.footprint_polygon_smooth_iterations, + in_layer, + ) + + run_call_mode = req.call_mode + if isinstance(run_call_mode, str): + run_call_mode = CallMode(run_call_mode) + + feat_list = bt_base.execute_multiprocessing( + process_single_absolute_line, + line_class_list, + "Line footprint", + req.processes, + run_call_mode, + ) + + if feat_list: + for item in feat_list: + if item.footprint is not None: + footprint_list.append(item.footprint) + + result = CanopyFootprintResult( + stats={ + "line_count": len(line_class_list), + "success_count": len(footprint_list), + "fail_count": max(len(line_class_list) - len(footprint_list), 0), + } + ) + + if footprint_list: + result.footprints_gdf = gpd.GeoDataFrame(pd.concat(footprint_list)).reset_index(drop=True) + else: + result.messages.append("No footprints generated.") + + return result + + +def _run_adaptive_request(req: CanopyFootprintRequest) -> CanopyFootprintResult: + """Run adaptive footprint workflow using shared request/result contracts.""" + result = CanopyFootprintResult() + run_call_mode = req.call_mode + if isinstance(run_call_mode, str): + run_call_mode = CallMode(run_call_mode) + + try: + footprint = FootprintCanopyAdaptive( + req.in_line, + req.in_chm, + max_line_width=req.max_ln_width if req.max_ln_width is not None else 32.0, + tree_radius=req.tree_radius if req.tree_radius is not None else 1.5, + max_line_dist=req.max_line_dist if req.max_line_dist is not None else 1.5, + canopy_avoidance=req.canopy_avoidance if req.canopy_avoidance is not None else 0.0, + exponent=req.exponent if req.exponent is not None else 1.0, + canopy_thresh_percentage=req.canopy_thresh_percentage + if req.canopy_thresh_percentage is not None + else 50.0, + exp_shk_cell=req.exp_shk_cell if req.exp_shk_cell is not None else 0, + simplify_footprint_polygon=req.simplify_footprint_polygon, + footprint_simplify_length=req.footprint_simplify_length, + smooth_footprint_polygon=req.smooth_footprint_polygon, + footprint_polygon_smooth_iterations=req.footprint_polygon_smooth_iterations, + ) + except Exception as err: + result.messages.append(f"Failed to initialize FootprintCanopyAdaptive: {err}") + return result + + try: + footprint.compute(req.processes, run_call_mode) + except Exception as err: + result.messages.append(f"Error in compute(): {err}") + import traceback + + traceback.print_exc() + return result + + if _is_valid_gdf(footprint, "footprints"): + result.footprints_gdf = footprint.footprints + else: + result.messages.append("No valid footprints to save.") + + if _is_valid_gdf(footprint, "lines_percentile"): + result.aux_layers["lines_percentile"] = gpd.GeoDataFrame(footprint.lines_percentile) + + lines = getattr(footprint, "lines", []) or [] + line_count = len(lines) + + if line_count > 0: + success_count = sum( + 1 for line in lines if hasattr(line, "footprint") and getattr(line, "footprint") is not None + ) + else: + success_count = 0 if result.footprints_gdf is None else int(len(result.footprints_gdf)) + + result.stats = { + "line_count": int(line_count), + "success_count": int(success_count), + "fail_count": int(max(line_count - success_count, 0)), + } + + return result + + +if __name__ == "__main__": + from beratools.utility.tool_args import compose_tool_kwargs + + start_time = time.time() + print("Footprint processing started") + kwargs = compose_tool_kwargs("canopy_footprint_absolute") + canopy_footprint_abs(**kwargs) + print("Elapsed time: {}".format(time.time() - start_time)) diff --git a/beratools/modules/mapping/canopy_threshold_relative.py b/beratools/modules/mapping/canopy_threshold_relative.py new file mode 100644 index 0000000..5a9d7b8 --- /dev/null +++ b/beratools/modules/mapping/canopy_threshold_relative.py @@ -0,0 +1,655 @@ +import math +import os.path +from functools import partial +from multiprocessing.pool import Pool +from pathlib import Path + +import geopandas as gpd +import numpy as np +import pandas as pd +import shapely + +from beratools.core.constants import BT_DEBUGGING, BT_NODATA, ParallelMode +from beratools.core.tool_base import parallel_mode +from beratools.modules.mapping.algo_common import chk_df_multipart +from beratools.modules.mapping.common import PARALLEL_MODE +from beratools.utility.spatial_common import ( + clip_raster, + compare_crs, + decode_file_layer, + raster_crs, + vector_crs, +) + + +class OperationCancelledException(Exception): + pass + + +def multiringbuffer(geom, nrings: int, ringdist: int) -> list: + """ + Buffer an input geometry nrings (number of rings) times, ringdist apart. + + Returns a list of non-overlapping buffers. + """ + import numpy as np + rings = [] # A list to hold the individual buffers + for ring in np.arange(0, ringdist, nrings): # For each ring (1, 2, 3, ..., nrings) + big_ring = geom.buffer( + nrings + ring, single_sided=True, cap_style="flat" + ) # Create one big buffer + small_ring = geom.buffer( + ring, single_sided=True, cap_style="flat" + ) # Create one smaller one + the_ring = big_ring.difference(small_ring) # Difference the big with the small to create a ring + if ( + ~shapely.is_empty(the_ring) + or ~shapely.is_missing(the_ring) + or not None + or ~the_ring.area == 0 + ): + if isinstance(the_ring, shapely.MultiPolygon) or isinstance(the_ring, shapely.Polygon): + rings.append(the_ring) # Append the ring to the rings list + else: + if isinstance(the_ring, shapely.GeometryCollection): + for i in range(0, len(the_ring.geoms)): + if not isinstance(the_ring.geoms[i], shapely.LineString): + rings.append(the_ring.geoms[i]) + print(" {}% ".format((ring / ringdist) * 100)) + + return rings # return the list + + +def main_canopy_threshold_relative( + in_line: str, + in_chm: str, + canopy_percentile: int, + canopy_thresh_percentage: int, + full_step: bool, + processes:int, + out_dyn_centerline: str=None, #for Test tool only +)-> str | None: + """ + Find the approximate surrounding forest canopy height and forest edge distance from the input CHM. + + Args: + in_line: Path like string + in_chm: Path like string + canopy_percentile: Percentile as integer range 1-100 + canopy_thresh_percentage: Percentage as integer range 1-100 + + Returns: + Path like string of the saved centerlines with extra attributes + """ + file_path, in_file_name = os.path.split(Path(in_line)) + in_file, layer = decode_file_layer(in_line) + if out_dyn_centerline is None: + out_dyn_centerline = os.path.join(Path(file_path), "DynCanTh_" + in_file_name) + out_cl_file, out_layer = decode_file_layer(out_dyn_centerline) + line_seg = gpd.GeoDataFrame.from_file(in_file, layer=layer) + _,processes=parallel_mode(processes) + # check coordinate systems between line and raster features + # with rasterio.open(in_chm) as in_raster: + if compare_crs(vector_crs(in_file,layer), raster_crs(in_chm)): + pass + else: + print("Line and raster spatial references are not same, please check.") + exit() + + # Check the canopy threshold percent in 0-100 range. If it is not, 50% will be applied + if not 100 >= int(canopy_percentile) > 0: + canopy_percentile = 50 + + # Check the Dynamic Canopy threshold column in data. If it is not, new column will be created + if "DynCanTh" not in line_seg.columns.array: + print("New column created: {}".format("DynCanTh")) + line_seg["DynCanTh"] = np.nan + + # Check the OLnFID column in data. If it is not, column will be created + if "OLnFID" not in line_seg.columns.array: + print("New column created: {}".format("OLnFID")) + line_seg["OLnFID"] = line_seg.index + + # Check the OLnSEG column in data. If it is not, column will be created + if "OLnSEG" not in line_seg.columns.array: + print("New column created: {}".format("OLnSEG")) + line_seg["OLnSEG"] = 0 + + # Check input line for multipart + line_seg = chk_df_multipart(line_seg, "LineString")[0] + + #Not splitting lines + proc_segments = False + if proc_segments: + line_seg = split_into_segments(line_seg) + else: + pass + + # copy original line input to another GeoDataframe and simplify the line geometry for buffering + workln_df_c = gpd.GeoDataFrame.copy(line_seg, deep=True) + workln_df_c.geometry = workln_df_c.geometry.simplify(tolerance=0.5, preserve_topology=True) + + print("{}%".format(5)) + # copy simplified line input for ring buffer for two sides buffering + worklnbuffer_df_l_ring = gpd.GeoDataFrame.copy((workln_df_c),deep=True) + worklnbuffer_df_r_ring = gpd.GeoDataFrame.copy((workln_df_c),deep=True) + + print("Create ring buffer for input line to find the forest edge....") + + # Create a column with the rings as a list + print("Create rings buffer to forest edge on both side of centerlines....") + with Pool(processes) as pool: + worklnbuffer_df_l_ring["mgeometry"] = pool.map( + partial(multiringbuffer, nrings=1, ringdist=15), + worklnbuffer_df_l_ring.geometry, + chunksize=max(1, len(worklnbuffer_df_l_ring) // (processes * 4)), + ) + worklnbuffer_df_r_ring["mgeometry"] = pool.map( + partial(multiringbuffer, nrings=-1, ringdist=-15), + worklnbuffer_df_r_ring.geometry, + chunksize=max(1, len(worklnbuffer_df_r_ring) // (processes * 4)), + ) + + # Explode to create a row for each ring + worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.explode("mgeometry") + worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.set_geometry("mgeometry") + worklnbuffer_df_l_ring = ( + worklnbuffer_df_l_ring.drop(columns=["geometry"]).rename_geometry("geometry").set_crs(workln_df_c.crs) + ) + worklnbuffer_df_l_ring["iRing"] = worklnbuffer_df_l_ring.groupby(["OLnFID", "OLnSEG"]).cumcount() + worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.sort_values(by=["OLnFID", "OLnSEG", "iRing"]) + worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.reset_index(drop=True) + + worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.explode( + "mgeometry" + ) # Explode to create a row for each ring + worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.set_geometry("mgeometry") + worklnbuffer_df_r_ring = ( + worklnbuffer_df_r_ring.drop(columns=["geometry"]).rename_geometry("geometry").set_crs(workln_df_c.crs) + ) + worklnbuffer_df_r_ring["iRing"] = worklnbuffer_df_r_ring.groupby(["OLnFID", "OLnSEG"]).cumcount() + worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.sort_values(by=["OLnFID", "OLnSEG", "iRing"]) + worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.reset_index(drop=True) + + print("Create rings buffer.... done.") + print("{}%".format(20)) + + worklnbuffer_df_r_ring["Percentile_RRing"] = np.nan + worklnbuffer_df_l_ring["Percentile_LRing"] = np.nan + line_seg["CL_CutHt"] = np.nan + line_seg["CR_CutHt"] = np.nan + line_seg["RDist_Cut"] = np.nan + line_seg["LDist_Cut"] = np.nan + print("{}%".format(30)) + + # calculate the Height percentile for each parallel area using CHM + worklnbuffer_df_l_ring = multiprocessing_percentile( + worklnbuffer_df_l_ring, + int(canopy_percentile), + int(canopy_thresh_percentage), + in_chm, + processes, + side="LRing", + ) + + worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.sort_values(by=["OLnFID", "OLnSEG", "iRing"]) + worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.reset_index(drop=True) + print("{}%".format(60)) + worklnbuffer_df_r_ring = multiprocessing_percentile( + worklnbuffer_df_r_ring, + int(canopy_percentile), + int(canopy_thresh_percentage), + in_chm, + processes, + side="RRing", + ) + + worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.sort_values(by=["OLnFID", "OLnSEG", "iRing"]) + worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.reset_index(drop=True) + + result = multiprocessing_RofC(line_seg, worklnbuffer_df_l_ring, worklnbuffer_df_r_ring, processes) + print("{}%".format(80)) + print("Calculating forest population done.") + + print("Saving percentile information to input line ...") + gpd.GeoDataFrame.to_file(result, out_cl_file, layer=out_layer) + print("Saving percentile information to input line ...done.") + + if full_step: + return out_dyn_centerline # TODO: make sure this is correct + + print("{}%".format(100)) + + +def rate_of_change(in_arg): # ,max_chmht): + x = in_arg[0] + Olnfid = in_arg[1] + Olnseg = in_arg[2] + side = in_arg[3] + df = in_arg[4] + + # Since the x interval is 1 unit, the array 'diff' is the rate of change (slope) + diff = np.ediff1d(x) + cut_dist = len(x) / 5 + + median_percentile = np.nanmedian(x) + if not np.isnan(median_percentile): + cut_percentile = math.floor(median_percentile) + else: + cut_percentile = 0.5 + found = False + changes = 1.50 + Change = np.insert(diff, 0, 0) + scale_down = 1 + + # test the rate of change is > than 150% (1.5), if it is + # no result found then lower to 140% (1.4) until 110% (1.1) + try: + while not found and changes >= 1.1: + for ii in range(0, len(Change) - 1): + if x[ii] >= 0.5: + if (Change[ii]) >= changes: + cut_dist = (ii + 1) * scale_down + cut_percentile = math.floor(x[ii]) + # median_diff=(cut_percentile-median_percentile) + if 0.5 >= cut_percentile: + if cut_dist > 5: + cut_percentile = 2 + cut_dist = cut_dist * scale_down**3 + print( + "{}: OLnFID:{}, OLnSEG: {} @<0.5 found and modified".format( + side, Olnfid, Olnseg + ), + flush=True, + ) + elif 0.5 < cut_percentile <= 5.0: + if cut_dist > 6: + cut_dist = cut_dist * scale_down**3 # 4.0 + print( + "{}: OLnFID:{}, OLnSEG: {} @0.5-5.0 found and modified".format( + side, Olnfid, Olnseg + ), + flush=True, + ) + elif 5.0 < cut_percentile <= 10.0: + if cut_dist > 8: # 5 + cut_dist = cut_dist * scale_down**3 + print( + "{}: OLnFID:{}, OLnSEG: {} @5-10 found and modified".format( + side, Olnfid, Olnseg + ), + flush=True, + ) + elif 10.0 < cut_percentile <= 15: + if cut_dist > 5: + cut_dist = cut_dist * scale_down**3 # 5.5 + print( + "{}: OLnFID:{}, OLnSEG: {} @10-15 found and modified".format( + side, Olnfid, Olnseg + ), + flush=True, + ) + elif 15 < cut_percentile: + if cut_dist > 4: + cut_dist = cut_dist * scale_down**2 + cut_percentile = 15.5 + print( + "{}: OLnFID:{}, OLnSEG: {} @>15 found and modified".format( + side, Olnfid, Olnseg + ), + flush=True, + ) + found = True + print( + "{}: OLnFID:{}, OLnSEG: {} rate of change found".format(side, Olnfid, Olnseg), + flush=True, + ) + break + changes = changes - 0.1 + + except IndexError: + pass + + # if still is no result found, lower to 10% (1.1), if no result found then default is used + if not found: + if 0.5 >= median_percentile: + cut_dist = 4 * scale_down # 3 + cut_percentile = 0.5 + elif 0.5 < median_percentile <= 5.0: + cut_dist = 4.5 * scale_down # 4.0 + cut_percentile = math.floor(median_percentile) + elif 5.0 < median_percentile <= 10.0: + cut_dist = 5.5 * scale_down # 5 + cut_percentile = math.floor(median_percentile) + elif 10.0 < median_percentile <= 15: + cut_dist = 6 * scale_down # 5.5 + cut_percentile = math.floor(median_percentile) + elif 15 < median_percentile: + cut_dist = 5 * scale_down # 5 + cut_percentile = 15.5 + print( + "{}: OLnFID:{}, OLnSEG: {} Estimated".format(side, Olnfid, Olnseg), + flush=True, + ) + if side == "Right": + df["RDist_Cut"] = cut_dist + df["CR_CutHt"] = cut_percentile + elif side == "Left": + df["LDist_Cut"] = cut_dist + df["CL_CutHt"] = cut_percentile + + return df + + +def multiprocessing_RofC(line_seg, worklnbuffer_dfLRing, worklnbuffer_dfRRing, processes): + in_argsL = [] + in_argsR = [] + + for index in line_seg.index: + Olnfid = int(line_seg.OLnFID.iloc[index]) + Olnseg = int(line_seg.OLnSEG.iloc[index]) + sql_dfL = worklnbuffer_dfLRing.loc[ + (worklnbuffer_dfLRing["OLnFID"] == Olnfid) & (worklnbuffer_dfLRing["OLnSEG"] == Olnseg) + ].sort_values(by=["iRing"]) + PLRing = list(sql_dfL["Percentile_LRing"]) + sql_dfR = worklnbuffer_dfRRing.loc[ + (worklnbuffer_dfRRing["OLnFID"] == Olnfid) & (worklnbuffer_dfRRing["OLnSEG"] == Olnseg) + ].sort_values(by=["iRing"]) + PRRing = list(sql_dfR["Percentile_RRing"]) + in_argsL.append([PLRing, Olnfid, Olnseg, "Left", line_seg.loc[index], index]) + in_argsR.append([PRRing, Olnfid, Olnseg, "Right", line_seg.loc[index], index]) + print(' "PROGRESS_LABEL Preparing grouped buffer areas...." ', flush=True) + print(" {}% ".format(((index + 1) / len(line_seg)) * 100)) + + total_steps = len(in_argsL) + len(in_argsR) + featuresL = [] + featuresR = [] + + if PARALLEL_MODE == ParallelMode.MULTIPROCESSING: + with Pool(processes=int(processes)) as pool: + step = 0 + # execute tasks in order, process results out of order + try: + for resultL in pool.imap_unordered(rate_of_change, in_argsL): + if BT_DEBUGGING: + print("Got result: {}".format(resultL), flush=True) + featuresL.append(resultL) + step += 1 + print( + ' "PROGRESS_LABEL Calculate Rate of Change In Buffer Area {} of {}" '.format( + step, total_steps + ), + flush=True, + ) + print("{}%".format(step / total_steps * 100), flush=True) + except Exception: + print(Exception) + raise + + gpdL = gpd.GeoDataFrame(pd.concat(featuresL, axis=1).T) + with Pool(processes=int(processes)) as pool: + step=0 + try: + for resultR in pool.imap_unordered(rate_of_change, in_argsR): + if BT_DEBUGGING: + print("Got result: {}".format(resultR), flush=True) + featuresR.append(resultR) + step += 1 + print( + ' "PROGRESS_LABEL Calculate Rate of Change Area {} of {}" '.format( + step + len(in_argsL), total_steps + ), + flush=True, + ) + print( + "{}%".format((step + len(in_argsL)) / total_steps * 100), + flush=True, + ) + except Exception: + print(Exception) + raise + gpdR = gpd.GeoDataFrame(pd.concat(featuresR, axis=1).T) + else: + for rowL in in_argsL: + featuresL.append(rate_of_change(rowL)) + + for rowR in in_argsR: + featuresR.append(rate_of_change(rowR)) + + gpdL = gpd.GeoDataFrame(pd.concat(featuresL, axis=1).T) + gpdR = gpd.GeoDataFrame(pd.concat(featuresR, axis=1).T) + + line_seg = line_seg.set_index(['OLnFID', 'OLnSEG'], drop=True) + gpdL['geometry'] = gpdL['geometry'].normalize() + gpdL['wkt'] = gpdL['geometry'].apply(lambda x: x.wkt) + deduplicated_gpdL = gpdL.drop_duplicates(subset=['wkt'], keep='first') + deduplicated_gpdL = deduplicated_gpdL.drop(columns=['wkt']).reset_index(drop=True) + gpdR['geometry'] = gpdR['geometry'].normalize() + gpdR['wkt'] = gpdR['geometry'].apply(lambda x: x.wkt) + deduplicated_gpdR = gpdR.drop_duplicates(subset=['wkt'], keep='first') + deduplicated_gpdR = deduplicated_gpdR.drop(columns=['wkt']).reset_index(drop=True) + + mapping_left_ldist_cut = deduplicated_gpdL.set_index(['OLnFID', 'OLnSEG'])['LDist_Cut'] + mapping_left_rdist_cut = deduplicated_gpdR.set_index(['OLnFID', 'OLnSEG'])['RDist_Cut'] + mapping_left_lcl_cut = deduplicated_gpdL.set_index(['OLnFID', 'OLnSEG'])['CL_CutHt'] + mapping_left_rcl_cut = deduplicated_gpdR.set_index(['OLnFID', 'OLnSEG'])['CR_CutHt'] + + condition_ldist_cut = line_seg.index.isin(mapping_left_ldist_cut.index) + condition_rdist_cut = line_seg.index.isin(mapping_left_rdist_cut.index) + condition_lcl_cut = line_seg.index.isin(mapping_left_lcl_cut.index) + condition_rcl_cut = line_seg.index.isin(mapping_left_rcl_cut.index) + + line_seg.loc[condition_ldist_cut, "LDist_Cut"] = line_seg.index.map(mapping_left_ldist_cut) + line_seg.loc[condition_rdist_cut, "RDist_Cut"] = line_seg.index.map(mapping_left_rdist_cut) + line_seg.loc[condition_lcl_cut, "CL_CutHt"] = line_seg.index.map(mapping_left_lcl_cut) + line_seg.loc[condition_rcl_cut, "CR_CutHt"] = line_seg.index.map(mapping_left_rcl_cut) + line_seg["DynCanTh"] = (line_seg["CL_CutHt"] + line_seg["CR_CutHt"]) / 2 + line_seg=line_seg.reset_index(drop=False) + + + return line_seg + + +def split_line_fc(line): + if line: + return list(map(shapely.LineString, zip(line.coords[:-1], line.coords[1:]))) + else: + return None + + +def split_into_segments(df): + odf = df + crs = odf.crs + if "OLnSEG" not in odf.columns.array: + df["OLnSEG"] = np.nan + else: + pass + df = odf.assign(geometry=odf.apply(lambda x: split_line_fc(x.geometry), axis=1)) + df = df.explode() + + df["OLnSEG"] = df.groupby("OLnFID").cumcount() + gdf = gpd.GeoDataFrame(df, geometry=df.geometry, crs=crs) + gdf = gdf.sort_values(by=["OLnFID", "OLnSEG"]) + gdf = gdf.reset_index(drop=True) + return gdf + +def multiprocessing_percentile(df:gpd.GeoDataFrame, + can_percentile:int, + can_thr_percentage:int, + in_chm: str, + processes:int, + side:str)->gpd.GeoDataFrame | None: + try: + line_arg = [] + total_steps = len(df) + cal_percentile = cal_percentile_ring + which_side = side + per_col="Percentile_LRing" + if side == "LRing": + per_col = "Percentile_LRing" + which_side = "left" + elif side == "RRing": + per_col = "Percentile_RRing" + which_side = "right" + + print("Calculating surrounding ({}) forest population for buffer area ...".format(which_side)) + + for item in df.index: + item_list = [ + df.iloc[[item]], + can_percentile, + can_thr_percentage, + in_chm, + item, + per_col, + ] + line_arg.append(item_list) + print( + ' "PROGRESS_LABEL Preparing lines... {} of {}" '.format(item + 1, len(df)), + flush=True, + ) + print(" {}% ".format(item / len(df) * 100), flush=True) + + features = [] + + if PARALLEL_MODE == ParallelMode.MULTIPROCESSING: + with Pool(processes=int(processes)) as pool: + step = 0 + # execute tasks in order, process results out of order + try: + for result in pool.imap_unordered(cal_percentile, line_arg): + if BT_DEBUGGING: + print("Got result: {}".format(result), flush=True) + features.append(result) + step += 1 + print( + ' "PROGRESS_LABEL Calculate Percentile In Buffer Area {} of {}" '.format( + step, total_steps + ), + flush=True, + ) + print("{}%".format(step / total_steps * 100), flush=True) + except Exception: + print(Exception) + raise + del line_arg + + return gpd.GeoDataFrame(pd.concat(features)) + else: + verbose = False + total_steps = len(line_arg) + step = 0 + for row in line_arg: + features.append(cal_percentile(row)) + step += 1 + if verbose: + print( + ' "PROGRESS_LABEL Calculate Percentile on line {} of {}" '.format(step, total_steps), + flush=True, + ) + print(" {}% ".format(step / total_steps * 100), flush=True) + return gpd.GeoDataFrame(pd.concat(features)) + + except OperationCancelledException: + print("Operation cancelled") + return None + + +def cal_percentile_ring(line_arg): + import traceback + + from shapely import ops + + try: + df = line_arg[0] + can_percentile = line_arg[1] + can_thr_percentage = line_arg[2] + in_chm = line_arg[3] + row_index = line_arg[4] + per_col = line_arg[5] + + percentile = 1 + dyn_canopy_threshold = 1 + + line_buffer = df.loc[row_index, "geometry"] + if line_buffer.is_empty or shapely.is_missing(line_buffer): + return None + if line_buffer.has_z: + line_buffer = ops.transform(lambda x, y, z=None: (x, y), line_buffer) + + except Exception as e: + print(e) + print("Assigning variable on index:{} Error: ".format(line_arg) + traceback.format_exc()) + exit() + + if isinstance(can_percentile,int): + if 100>can_percentile>0: + pass + else: + can_percentile = 50 + else: + can_percentile =50 + + try: + + clipped_raster, out_meta = clip_raster(in_chm, line_buffer, 0) + clipped_raster = np.squeeze(clipped_raster, axis=0) + + # mask all -9999 (nodata) value cells + masked_raster = np.ma.masked_where(clipped_raster == BT_NODATA, clipped_raster) + filled_raster = np.ma.filled(masked_raster, np.nan) + + percentile = np.nanpercentile(filled_raster, can_percentile) + + if percentile > 1: + dyn_canopy_threshold = percentile * (can_thr_percentage/100) + else: + dyn_canopy_threshold = 1 + + del clipped_raster, out_meta + + # return the generated value + except Exception as e: + print(e) + print("Default values are used.") + + finally: + df.loc[row_index, per_col] = percentile + df.loc[row_index, "DynCanTh"] = dyn_canopy_threshold + return df + + +def copyparallel_lineLRC(line_arg): + dfL = line_arg[0] + dfR = line_arg[1] + + # Simplify input center lines + geom = dfL.loc[line_arg[6], "geometry"] + if not geom: + return None + + lineL = dfL.loc[line_arg[6], "geometry"].simplify(tolerance=0.05, preserve_topology=True) + lineR = dfR.loc[line_arg[6], "geometry"].simplify(tolerance=0.05, preserve_topology=True) + # lineC = dfC.loc[line_arg[6], 'geometry'].simplify(tolerance=0.05, preserve_topology=True) + offset_distL = float(line_arg[3]) + offset_distR = float(line_arg[4]) + + # Older alternative method to the offset_curve() method, + # but uses resolution instead of quad_segs and a side keyword (‘left’ or ‘right’) instead + # of sign of the distance. This method is kept for backwards compatibility for now, + # but it is recommended to use offset_curve() instead. + # (ref: https://shapely.readthedocs.io/en/stable/manual.html#object.offset_curve) + parallel_lineL = lineL.parallel_offset( + distance=offset_distL, side="left", join_style=shapely.BufferJoinStyle.mitre + ) + + parallel_lineR = lineR.parallel_offset( + distance=-offset_distR, side="right", join_style=shapely.BufferJoinStyle.mitre + ) + + if not parallel_lineL.is_empty: + dfL.loc[line_arg[6], "geometry"] = parallel_lineL + if not parallel_lineR.is_empty: + dfR.loc[line_arg[6], "geometry"] = parallel_lineR + + return dfL.iloc[[line_arg[6]]], dfR.iloc[[line_arg[6]]] diff --git a/beratools/modules/mapping/centerline.py b/beratools/modules/mapping/centerline.py new file mode 100644 index 0000000..67f0e74 --- /dev/null +++ b/beratools/modules/mapping/centerline.py @@ -0,0 +1,471 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + The purpose of this script is to provide main interface for centerline tool. +""" + +import logging +import os +from pathlib import Path + +import geopandas as gpd +import pandas as pd +import rasterio + +import beratools.core.constants as bt_const +import beratools.modules.mapping.algo_centerline as algo_centerline +import beratools.modules.mapping.algo_common as algo_common +import beratools.modules.mapping.tool_geo_simplify as tool_geo_simplify +import beratools.utility.spatial_common as sp_common +import beratools.utility.unit_conversion as unit_conversion +from beratools.core.tool_base import execute_multiprocessing +from beratools.utility.tool_args import CallMode, to_bool + +LOGGER_NAME="centerline" +logger = logging.getLogger(LOGGER_NAME) + + +def generate_line_class_list( + in_vector, + in_raster, + line_radius, + layer=None, + proc_segments=True, + guided_strategy=bt_const.CENTERLINE_GUIDED_STRATEGY.value, + centerline_method=bt_const.CENTERLINE_METHOD.value, + lcp_simplify_enabled=False, + lcp_simplify_diameter=10.0, + lcp_smooth_enabled=False, + lcp_smooth_iterations=1, + chm_mode=bt_const.CENTERLINE_CHM_MODE.value, + chm_buffer_width=5.0, + chm_buffer_multiplier=0.5, + astar_corridor_line_bias_weight=0.1, + astar_corridor_distance_penalty_weight=0.2, + corridor_simplify_polygon=False, + corridor_simplify_length=0.5, + corridor_smooth_polygon=False, + corridor_polygon_smooth_iterations=1, +) -> list: + line_classes = [] + line_list = algo_common.prepare_lines_gdf(in_vector, layer, proc_segments, tag_source_rows=True) + + for item in line_list: + line_classes.append( + algo_centerline.SeedLine( + item, + in_raster, + proc_segments, + line_radius, + guided_strategy=guided_strategy, + centerline_method=centerline_method, + lcp_simplify_enabled=lcp_simplify_enabled, + lcp_simplify_diameter=lcp_simplify_diameter, + lcp_smooth_enabled=lcp_smooth_enabled, + lcp_smooth_iterations=lcp_smooth_iterations, + chm_mode=chm_mode, + chm_buffer_width=chm_buffer_width, + chm_buffer_multiplier=chm_buffer_multiplier, + astar_corridor_line_bias_weight=astar_corridor_line_bias_weight, + astar_corridor_distance_penalty_weight=astar_corridor_distance_penalty_weight, + corridor_simplify_polygon=corridor_simplify_polygon, + corridor_simplify_length=corridor_simplify_length, + corridor_smooth_polygon=corridor_smooth_polygon, + corridor_polygon_smooth_iterations=corridor_polygon_smooth_iterations, + ) + ) + + return line_classes + + +MERGE_ORDER_FIELD = "BT_MERGE_ORDER" + + +def _add_merge_order(gdf, merge_by_original_line): + """Number the pieces in the order they join: by input row and vertex, or along the original line.""" + if gdf is None or gdf.empty: + return gdf + gdf = gdf.copy() + if merge_by_original_line: + group_field = "OLnFID" + sort_fields = [algo_common.SOURCE_SEG_FIELD, algo_common.SOURCE_ROW_FIELD, "OLnSEG"] + else: + group_field = algo_common.SOURCE_ROW_FIELD + sort_fields = ["OLnSEG"] + ordered = gdf.sort_values(sort_fields, kind="stable") + gdf[MERGE_ORDER_FIELD] = ordered.groupby(group_field, sort=False).cumcount() + return gdf + + +def _restore_merged_ids(gdf, merge_by_original_line): + """Give merged rows their input OLnSEG back (or -1 for a whole original line) and drop helper fields.""" + if gdf is None or gdf.empty: + return gdf + gdf = gdf.copy() + if merge_by_original_line: + gdf["OLnSEG"] = -1 + elif algo_common.SOURCE_SEG_FIELD in gdf.columns: + gdf["OLnSEG"] = gdf[algo_common.SOURCE_SEG_FIELD] + return _drop_helper_fields(gdf) + + +def _drop_helper_fields(gdf): + if gdf is None: + return gdf + helper_fields = [algo_common.SOURCE_ROW_FIELD, algo_common.SOURCE_SEG_FIELD, MERGE_ORDER_FIELD] + return gdf.drop(columns=[f for f in helper_fields if f in gdf.columns]) + + +def process_single_line_class(seed_line): + try: + # OLnFID and OLnSEG are added in previous QC stage. + cid=(f"{seed_line.line['OLnFID'].iloc[0]}_" + f"{seed_line.line['OLnSEG'].iloc[0]}") + seed_line.compute() + return seed_line + except Exception: + logger.exception(f"FAILED PID={os.getpid()} FID={cid}") + raise + + +def centerline( + in_line, + in_raster, + line_radius, + proc_segments, + out_line, + merge_by_original_line=False, + centerline_method=bt_const.CENTERLINE_METHOD.value, + guided_strategy=bt_const.CENTERLINE_GUIDED_STRATEGY.value, + simplify_centerline=False, + simplify_diameter=10.0, + lcp_simplify_enabled=False, + lcp_simplify_diameter=10.0, + lcp_smooth_enabled=False, + lcp_smooth_iterations=1, + chm_mode=bt_const.CENTERLINE_CHM_MODE.value, + chm_buffer_width=5.0, + chm_buffer_multiplier=0.5, + astar_corridor_line_bias_weight=0.1, + astar_corridor_distance_penalty_weight=0.2, + corridor_simplify_polygon=False, + corridor_simplify_length=0.5, + corridor_smooth_polygon=False, + corridor_polygon_smooth_iterations=1, + use_angle_grouping=True, + processes=0, + call_mode=CallMode.CLI, + log_level="INFO", +): + """ + Run centerline extraction. + + guided_strategy modes: + - MAIN_ROUTE: unguided main-route extraction. + - PAIRWISE: endpoint-guided search over endpoint node pairs. + - VIRTUAL_NODES: endpoint-guided search using virtual source/destination graph nodes. + - DIRECT_INSERT: endpoint-guided search by inserting endpoints directly into the Voronoi graph. + """ + if isinstance(guided_strategy, str): + guided_strategy = bt_const.CenterlineStrategy(guided_strategy) + if isinstance(centerline_method, str): + centerline_method = bt_const.CenterlineMethod(centerline_method) + if isinstance(chm_mode, str): + chm_mode = bt_const.CenterlineChmMode(chm_mode) + + guided_strategy_value = guided_strategy.value + centerline_method_value = centerline_method.value + chm_mode_value = chm_mode.value + proc_segments = to_bool(proc_segments) + merge_by_original_line = to_bool(merge_by_original_line) + + in_file, in_layer = sp_common.decode_file_layer(in_line) + out_file, out_layer = sp_common.decode_file_layer(out_line) + simplify_enabled = to_bool(simplify_centerline) + diameter = tool_geo_simplify.validate_diameter(simplify_diameter) + line_radius_m = float(line_radius) + + vec_crs_osr = sp_common.vector_crs(in_file, in_layer) + line_radius_native = unit_conversion.convert_meters_param_projected_from_osr( + vec_crs_osr, + line_radius_m, + "Line Processing Radius (m)", + ) + chm_buffer_width_native = unit_conversion.convert_meters_param_projected_from_osr( + vec_crs_osr, + float(chm_buffer_width), + "CHM Buffer Width (m)", + ) + + if not sp_common.compare_crs(vec_crs_osr, sp_common.raster_crs(in_raster)): + print("Line and CHM have different spatial references, please check.") + return + + with rasterio.open(in_raster) as src: + cell_size = max(abs(float(src.transform.a)), abs(float(src.transform.e)), ) + + if not sp_common.check_vector_raster_extent_overlap(in_file, in_layer, in_raster): + print("Input line extent does not overlap input raster extent.") + return + + line_gdf = gpd.read_file(in_file, layer=in_layer) + if not sp_common.check_vector_raster_overlap(line_gdf, in_raster): + print("Input line(s) do not overlap input raster.") + return + + line_class_list = generate_line_class_list( + in_file, + in_raster, + line_radius=line_radius_native, + layer=in_layer, + proc_segments=proc_segments, + guided_strategy=guided_strategy_value, + centerline_method=centerline_method_value, + lcp_simplify_enabled=to_bool(lcp_simplify_enabled), + lcp_simplify_diameter=tool_geo_simplify.validate_diameter(lcp_simplify_diameter), + lcp_smooth_enabled=to_bool(lcp_smooth_enabled), + lcp_smooth_iterations=int(lcp_smooth_iterations), + chm_mode=chm_mode_value, + chm_buffer_width=chm_buffer_width_native, + chm_buffer_multiplier=float(chm_buffer_multiplier), + astar_corridor_line_bias_weight=float(astar_corridor_line_bias_weight), + astar_corridor_distance_penalty_weight=float(astar_corridor_distance_penalty_weight), + corridor_simplify_polygon=to_bool(corridor_simplify_polygon), + corridor_simplify_length=float(corridor_simplify_length), + corridor_smooth_polygon=to_bool(corridor_smooth_polygon), + corridor_polygon_smooth_iterations=int(corridor_polygon_smooth_iterations), + ) + + print("{} lines to be processed.".format(len(line_class_list))) + + lc_path_list = [] + centerline_list = [] + corridor_poly_list = [] + result = execute_multiprocessing( + process_single_line_class, + line_class_list, + "Centerline", + processes, + call_mode, + logger_name = LOGGER_NAME) + if not result: + print("No centerlines found.") + return 1 + + for item in result: + lc_path_list.append(item.lc_path) + centerline_list.append(item.centerline) + corridor_poly_list.append(item.corridor_poly_gpd) + + # Concatenate the lists of GeoDataFrames into single GeoDataFrames + if len(lc_path_list) == 0 or len(centerline_list) == 0 or len(corridor_poly_list) == 0: + print("No centerline generated.") + return 1 + + lc_path_list = pd.concat(lc_path_list, ignore_index=True) + centerline_list = pd.concat(centerline_list, ignore_index=True) + corridor_polys = pd.concat(corridor_poly_list, ignore_index=True) + + # Make sure they remain GeoDataFrames: + lc_path_gdf = gpd.GeoDataFrame(lc_path_list, + geometry="geometry",crs=line_gdf.crs,) + + centerline_gdf = gpd.GeoDataFrame(centerline_list, + geometry="geometry",crs=line_gdf.crs,) + + corridor_gdf = gpd.GeoDataFrame(corridor_polys, + geometry="geometry",crs=line_gdf.crs,) + + # Save the concatenated GeoDataFrames to the shapefile/gpkg + logger.info("Clean geometries....") + centerline_gdf = algo_common.clean_geometries( + centerline_gdf, + stage="output", + out_file=out_file, + layer="rejected_output_centerlines",) + + lc_path_gdf = algo_common.clean_geometries( + lc_path_gdf, + stage="lcp_segments", + out_file=out_file, + layer="rejected_lcp_segments", + ) + + corridor_gdf = algo_common.clean_geometries( + corridor_gdf, + stage="corridor_segments", + out_file=out_file, + layer="rejected_corridor_segments", + ) + logger.info("Clean geometries....Done") + + dissolved_cl_orig=centerline_gdf + dissolved_lcp_orig=lc_path_gdf + dissolved_corridor_orig=corridor_gdf + # whole lines need no merging, so they are saved as they are + dissolved_cl = centerline_gdf + dissolved_lcp = lc_path_gdf + dissolved_corridor = corridor_gdf + aux_file = algo_common.get_aux_path(out_file) + if proc_segments or merge_by_original_line: + logger.info("Dissolving segments...") + dissolved_cl_orig, dissolved_lcp_orig, dissolved_corridor_orig = ( + _add_merge_order(gdf, merge_by_original_line) + for gdf in (centerline_gdf, lc_path_gdf, corridor_gdf) + ) + group_field = "OLnFID" if merge_by_original_line else algo_common.SOURCE_ROW_FIELD + + dissolved_cl = ( + algo_common.merge_lines_by_original_id( + line_gdf=dissolved_cl_orig, + group_field=group_field, + order_field=MERGE_ORDER_FIELD, + max_bridge_gap=max( + cell_size * 1.5, + 0.5, + ), + geometry_count_field=( + "merged_centerline_part_count" + ), + ) + ) + + dissolved_cl = algo_common.clean_geometries( + dissolved_cl, + stage="merged_centerlines", + out_file=out_file, + layer="rejected_merged_centerline_geometry", + ) + + dissolved_lcp = ( + algo_common.merge_lines_by_original_id( + line_gdf=dissolved_lcp_orig, + group_field=group_field, + order_field=MERGE_ORDER_FIELD, + max_bridge_gap=max( + cell_size * 0.75, + 0.05, + ), + geometry_count_field=( + "merged_lcp_part_count" + ), + ) + ) + + dissolved_corridor = ( + algo_common.merge_corridors_by_original_id( + dissolved_corridor_orig, + group_field=group_field, + order_field=MERGE_ORDER_FIELD, + ) + ) + + + if dissolved_cl is None or dissolved_cl.empty: + print("No centerlines remained after merging.") + return 1 + + valid_mask = dissolved_cl.geometry.apply( + lambda geom: not algo_common._is_degenerate_line( + geom, + min_length=max(cell_size, 1.0), + endpoint_tolerance=max(cell_size * 0.01,1e-6,), + min_straightness=0.10, + stage="final",)) + + rejected_final = dissolved_cl.loc[~valid_mask].copy() + dissolved_cl = dissolved_cl.loc[valid_mask].copy() + + if not rejected_final.empty: + rejected_final["BT_REJECT_REASON"] = ( + "degenerate_after_merge") + + rejected_final.to_file(aux_file, + layer="rejected_merged_centerlines",overwrite=True,) + + if dissolved_cl.empty: + print("All merged centerlines failed final QC.") + return 1 + + logger.info("Dissolving segments...Done") + + dissolved_cl, dissolved_lcp, dissolved_corridor = ( + _restore_merged_ids(gdf, merge_by_original_line) + for gdf in (dissolved_cl, dissolved_lcp, dissolved_corridor) + ) + centerline_gdf, lc_path_gdf, corridor_gdf = ( + _drop_helper_fields(gdf) for gdf in (centerline_gdf, lc_path_gdf, corridor_gdf) + ) + + if simplify_enabled and diameter > 0: + temp_file = tool_geo_simplify.build_temp_output_same_folder( + out_file, + prefix=f"{Path(out_file).stem}_centerline_tmp_", + ) + # geo-simplify recreates its --output file, so never point it at out_file + # directly or every other layer in the GeoPackage is wiped. + temp_out_file = tool_geo_simplify.build_temp_output_same_folder( + out_file, + prefix=f"{Path(out_file).stem}_centerline_simplified_tmp_", + ) + temp_layer = "centerline_temp" + try: + dissolved_cl.to_file(temp_file.as_posix(), layer=temp_layer,overwrite=True) + temp_out_file.unlink() + tool_geo_simplify.run_reduce_bend( + input_file=temp_file, + in_layer=temp_layer, + output_file=temp_out_file.as_posix(), + out_layer=out_layer, + diameter=diameter, + smooth_line=True, + ) + simplified_cl = gpd.read_file(temp_out_file, layer=out_layer) + algo_common.drop_layer_if_exists(out_file, out_layer) + simplified_cl.to_file(out_file, layer=out_layer) + finally: + for path in (temp_file, temp_out_file): + if path.exists(): + path.unlink() + else: + if simplify_enabled and diameter == 0: + print("Centerline simplify enabled with diameter 0; skipping simplify step.") + if Path(out_file).exists(): + algo_common.drop_layer_if_exists(out_file,out_layer) + dissolved_cl.to_file(out_file, layer=out_layer) + + print(f"Saved centerlines to: {out_file}") + + aux_file = algo_common.get_aux_path(out_file) + print(f"Saved auxiliary data to: {aux_file}") + + # Save lc_path_list and corridor_polys to the new GeoPackage with '_aux' suffix + if proc_segments: + centerline_gdf.to_file(aux_file,layer="centerline_segments",overwrite=True) + lc_path_gdf.to_file(aux_file,layer="least_cost_path_segments",overwrite=True) + corridor_gdf.to_file(aux_file,layer="corridor_polygon_segments",overwrite=True) + + dissolved_lcp.to_file(aux_file, layer="dissolved_lcp",overwrite=True) + dissolved_corridor.to_file(aux_file, layer="dissolved_corridor",overwrite=True) + + return 0 + + +if __name__ == "__main__": + import time + + from beratools.utility.tool_args import compose_tool_kwargs + + start_time = time.time() + kwargs = compose_tool_kwargs("centerline") + centerline(**kwargs) + print("Elapsed time: {}".format(time.time() - start_time)) diff --git a/beratools/modules/mapping/check_seed_line.py b/beratools/modules/mapping/check_seed_line.py new file mode 100644 index 0000000..7b41b1d --- /dev/null +++ b/beratools/modules/mapping/check_seed_line.py @@ -0,0 +1,886 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + The purpose of this script is to provide main interface for line grouping tool. +""" + +import logging +import time +from dataclasses import dataclass +from datetime import datetime, timezone +from typing import Optional + +import geopandas as gpd + +import beratools.core.constants as bt_const +import beratools.modules.mapping.algo_common as algo_common +import beratools.utility.spatial_common as sp_common +import beratools.utility.unit_conversion as unit_conversion +from beratools.modules.mapping.algo_check_seed_line import ( + _clean_line_geometries_min_length_m, + _clip_to_chm_footprint, + _default_close_distance_m, + _densify_long_lines, + _normalize_to_lines, + _preclean_lines_full, + _snap_close_endpoints, + _trim_short_terminal_segments, + qc_merge_multilinestring, + qc_split_lines_at_intersections, +) +from beratools.utility.tool_args import CallMode, to_bool + +LOGGER_NAME="check_seed_line" +logger = logging.getLogger(LOGGER_NAME) + +@dataclass +class SeedLineQCConfig: + chm_footprint_shrink: float = 15.0 + clip_to_chm_footprint: bool = True + remove_short_lines: bool = False + minimum_line_length: float = 5.0 + preclean_vertices: bool = True + preclean_close_distance: Optional[float] = None + preclean_angle_tolerance: float = 10.0 + snap_close_endpoints: bool = False + snap_tolerance: float = 5.0 + group_lines: bool = False + densify_long_lines: bool = False + max_segment_length: float = bt_const.LP_SEGMENT_LENGTH + use_angle_grouping: bool = True + warn_nodata_vertices: bool = True + nodata_vertex_search_radius: float = 10.0 + check_internal_vertices: bool = False + apply_seed_line_correction: bool = False + slc_search_distance: float = 5.0 + slc_line_radius: float = 15.0 + slc_optimize_internal_vertices: bool = False + + +def _write_output(gdf, out_file, out_layer): + to_file_kwargs = {} + if out_layer: + to_file_kwargs["layer"] = out_layer + gdf.to_file(out_file, **to_file_kwargs) + + +def _log_step( + step_idx, + step_name, + in_count, + out_count, + elapsed=None, + skipped_reason=None, + verbose=False, + skipped_steps=None, +): + label = step_name.ljust(34) + + if skipped_reason: + if verbose: + print(f"↷ {label} {in_count} -> {out_count}") + elif skipped_steps is not None: + _record_skipped_step(skipped_steps, step_idx, step_name, skipped_reason) + logger.debug( + "Step %s - %s skipped (%s): %s -> %s", + step_idx, + step_name, + skipped_reason, + in_count, + out_count, + ) + return + + if elapsed is None: + print(f"✓ {label} {in_count} -> {out_count}") + return + + print(f"✓ {label} {in_count} -> {out_count} {elapsed:.3f}s") + + +def _print_skipped_summary(skipped_steps): + if not skipped_steps: + return + + option_order = { + "Clip to CHM footprint": 0, + "Remove short lines": 1, + "Preclean vertices": 2, + "Snap close endpoints": 3, + "Group lines": 4, + "Densify long lines": 5, + "Apply Seed Line Correction": 6, + } + skipped_steps = sorted( + skipped_steps, + key=lambda item: (option_order.get(item[1], 99), item[0]), + ) + + lines = [] + for _, step_name, _ in skipped_steps: + label = step_name.ljust(34) + lines.append(f"↷ {label} skipped") + print("\n".join(lines)) + + +def _print_qc_summary(qc_summary, aux_file): + if qc_summary["total"] > 0: + print("QC Report Summary:") + print(f" Short lines: {qc_summary['short_line']} issues") + print(f" Close vertices: {qc_summary['close_vertices']} issues") + print(f" Unsnapped endpoints: {qc_summary['unsnapped_endpoint']} issues") + print(f" Self-crossing: {qc_summary['self_crossing']} issues") + print(f" Overlapping lines: {qc_summary['overlap']} issues") + print(f" CHM NoData vertices: {qc_summary.get('chm_nodata_vertex', 0)} issues") + print(f" {'-' * 35}") + print(f" Total issues: {qc_summary['total']}") + print(f" Details saved to: {aux_file} (layer: qc_report_issues)") + else: + print("QC Report: No issues found.") + + +def _record_skipped_step(skipped_steps, step_idx, step_name, reason): + if skipped_steps is None: + return + + if any(existing_step_name == step_name for _, existing_step_name, _ in skipped_steps): + return + + skipped_steps.append((step_idx, step_name, reason)) + + +def _bail_if_empty(gdf, step_name, out_file, out_layer, in_count, skipped_steps=None): + if not gdf.empty: + return False + + if skipped_steps: + _print_skipped_summary(skipped_steps) + + logger.warning( + "Seed line QC early return after '%s' produced empty output (%s -> 0).", + step_name, + in_count, + ) + print("QC Report skipped: output became empty before Step 12.") + _write_output(gdf.iloc[0:0].copy(), out_file, out_layer) + return True + + +def _step_timer(): + return time.perf_counter() + + +def _elapsed(start_t): + return time.perf_counter() - start_t + + +def _convert_slc_meter_params_to_native_units(lines_gdf, search_distance_m, line_radius_m): + """Convert SLC meter parameters to source CRS linear units.""" + search_distance_native = unit_conversion.convert_meters_param_projected( + lines_gdf, + search_distance_m, + "Apply Seed Line Correction search distance (m)", + min_value=bt_const.SMALL_BUFFER, + ) + line_radius_native = unit_conversion.convert_meters_param_projected( + lines_gdf, + line_radius_m, + "Apply Seed Line Correction line radius (m)", + min_value=bt_const.SMALL_BUFFER, + ) + return search_distance_native, line_radius_native + + +def check_seed_line( + in_line, + in_raster, + out_line, + chm_footprint_shrink=15.0, + clip_to_chm_footprint=True, + remove_short_lines=False, + minimum_line_length=5.0, + preclean_vertices=True, + preclean_close_distance=None, + preclean_angle_tolerance=10.0, + snap_close_endpoints=False, + snap_tolerance=5.0, + group_lines=False, + densify_long_lines=False, + max_segment_length=bt_const.LP_SEGMENT_LENGTH, + use_angle_grouping=True, + warn_nodata_vertices=True, + nodata_vertex_search_radius=10.0, + check_internal_vertices=False, + apply_seed_line_correction=False, + slc_search_distance=5.0, + slc_line_radius=15.0, + slc_optimize_internal_vertices=False, + processes=0, + call_mode=CallMode.CLI, + log_level="INFO", +): + from beratools.modules.mapping.algo_line_grouping import LineGrouping + + level_name = str(log_level).upper() + level_value = getattr(logging, level_name, logging.INFO) + verbose_steps = level_value <= logging.DEBUG + logger.setLevel(level_value) + for handler in logging.getLogger().handlers: + if isinstance(handler, logging.StreamHandler): + handler.setLevel(level_value) + + config = SeedLineQCConfig( + chm_footprint_shrink=float(chm_footprint_shrink), + clip_to_chm_footprint=to_bool(clip_to_chm_footprint), + remove_short_lines=to_bool(remove_short_lines), + minimum_line_length=float(minimum_line_length), + preclean_vertices=to_bool(preclean_vertices), + preclean_close_distance=None + if preclean_close_distance in (None, "", "none") + else float(preclean_close_distance), + preclean_angle_tolerance=float(preclean_angle_tolerance), + snap_close_endpoints=to_bool(snap_close_endpoints), + snap_tolerance=float(snap_tolerance), + group_lines=to_bool(group_lines), + densify_long_lines=to_bool(densify_long_lines), + max_segment_length=float(max_segment_length), + use_angle_grouping=to_bool(use_angle_grouping), + warn_nodata_vertices=to_bool(warn_nodata_vertices), + nodata_vertex_search_radius=float(nodata_vertex_search_radius), + check_internal_vertices=to_bool(check_internal_vertices), + apply_seed_line_correction=to_bool(apply_seed_line_correction), + slc_search_distance=float(slc_search_distance), + slc_line_radius=float(slc_line_radius), + slc_optimize_internal_vertices=to_bool(slc_optimize_internal_vertices), + ) + + skipped_steps = [] + + in_file, in_layer = sp_common.decode_file_layer(in_line) + out_file, out_layer = sp_common.decode_file_layer(out_line) + aux_file = algo_common.get_aux_path(out_file) + effective_preclean_close_distance = ( + _default_close_distance_m(in_raster) + if config.preclean_close_distance is None + else float(config.preclean_close_distance) + ) + + qc_manifest = { + "qc_removed_input_cleanup": { + "layer_name": "qc_removed_input_cleanup", + "step": 0, + "step_name": "input cleanup", + "reason": "Invalid, null, or empty geometries removed during input hygiene", + "feature_count": 0, + "written": 0, + "notes": "not triggered", + }, + "qc_removed_cleanup": { + "layer_name": "qc_removed_cleanup", + "step": 2, + "step_name": "geometry cleanup", + "reason": "Null, empty, or too-short lines removed in cleanup", + "feature_count": 0, + "written": 0, + "notes": "not triggered", + }, + "qc_removed_short": { + "layer_name": "qc_removed_short", + "step": 4, + "step_name": "short line removal", + "reason": "Lines below user minimum length", + "feature_count": 0, + "written": 0, + "notes": "disabled", + }, + "qc_removed_clipped": { + "layer_name": "qc_removed_clipped", + "step": 3, + "step_name": "CHM footprint clipping", + "reason": "Lines outside shrunken CHM footprint", + "feature_count": 0, + "written": 0, + "notes": "not triggered", + }, + "chm_footprint": { + "layer_name": "chm_footprint", + "step": 3, + "step_name": "CHM footprint clipping", + "reason": "Shrunken CHM footprint used for clipping", + "feature_count": 0, + "written": 0, + "notes": "not triggered", + }, + "qc_removed_post_clip": { + "layer_name": "qc_removed_post_clip", + "step": 5, + "step_name": "post-clip normalize + cleanup", + "reason": "Fragments removed after clipping and normalization", + "feature_count": 0, + "written": 0, + "notes": "not triggered", + }, + "qc_removed_preclean": { + "layer_name": "qc_removed_preclean", + "step": 6, + "step_name": "preclean vertices", + "reason": ( + "Removes near-duplicate endpoint vertices and simplifies close interior vertices with " + "angle-aware bend preservation." + ), + "feature_count": 0, + "written": 0, + "notes": "not triggered", + }, + "qc_removed_final": { + "layer_name": "qc_removed_final", + "step": 11, + "step_name": "final cleanup", + "reason": "Remaining invalid/empty/too-short lines", + "feature_count": 0, + "written": 0, + "notes": "not triggered", + }, + "qc_report_issues": { + "layer_name": "qc_report_issues", + "step": 12, + "step_name": "QC report", + "reason": "Post-processing QC check results (using 2x thresholds)", + "feature_count": 0, + "written": 0, + "notes": "not triggered", + }, + } + + def _mark_layer(layer_name, layer_gdf, notes=None): + if layer_name not in qc_manifest: + return + count = 0 if layer_gdf is None else len(layer_gdf) + qc_manifest[layer_name]["feature_count"] = int(count) + qc_manifest[layer_name]["written"] = 1 if count > 0 else 0 + qc_manifest[layer_name]["notes"] = notes or ("written" if count > 0 else "empty") + if count > 0: + algo_common.save_aux_layer(layer_gdf, out_file, layer_name) + + def _has_rows(layer_gdf): + return layer_gdf is not None and hasattr(layer_gdf, "empty") and not layer_gdf.empty + + def _ensure_gdf(obj, fallback_crs): + if isinstance(obj, gpd.GeoDataFrame): + return obj + return gpd.GeoDataFrame(obj, crs=fallback_crs) + + def _persist_qc_tables(input_count, output_count): + manifest_rows = [qc_manifest[key] for key in qc_manifest.keys()] + algo_common.save_aux_table(manifest_rows, out_file, "qc_manifest", overwrite=True) + summary_row = { + "tool_name": "check_seed_line", + "run_timestamp_utc": datetime.now(timezone.utc).isoformat(), + "input_line": in_line, + "input_raster": in_raster, + "output_line": out_line, + "aux_gpkg": aux_file, + "clip_to_chm_footprint": int(config.clip_to_chm_footprint), + "chm_footprint_shrink_m": float(config.chm_footprint_shrink), + "remove_short_lines": int(config.remove_short_lines), + "minimum_line_length_m": float(config.minimum_line_length), + "preclean_vertices": int(config.preclean_vertices), + "preclean_mode": "full", + "preclean_close_distance_m": float(effective_preclean_close_distance), + "preclean_angle_tolerance_deg": float(config.preclean_angle_tolerance), + "snap_close_endpoints": int(config.snap_close_endpoints), + "snap_tolerance_m": float(config.snap_tolerance), + "group_lines": int(config.group_lines), + "densify_long_lines": int(config.densify_long_lines), + "max_segment_length_m": float(config.max_segment_length), + "warn_nodata_vertices": int(config.warn_nodata_vertices), + "nodata_vertex_search_radius_m": float(config.nodata_vertex_search_radius), + "check_internal_vertices": int(config.check_internal_vertices), + "apply_seed_line_correction": int(config.apply_seed_line_correction), + "slc_search_distance": float(config.slc_search_distance), + "slc_line_radius": float(config.slc_line_radius), + "slc_optimize_internal_vertices": int(config.slc_optimize_internal_vertices), + "input_feature_count": int(input_count), + "output_feature_count": int(output_count), + } + algo_common.save_aux_table([summary_row], out_file, "qc_run_summary", overwrite=True) + + if in_raster: + if not sp_common.compare_crs( + sp_common.vector_crs(in_file, in_layer), sp_common.raster_crs(in_raster) + ): + raise ValueError("Input line and raster CRS do not match.") + + gdf = gpd.read_file(in_file, layer=in_layer) + if ( + config.clip_to_chm_footprint + and in_raster + and not sp_common.seedlines_within_chm_footprint(gdf, in_raster) + ): + raise ValueError("Input line(s) do not overlap input raster.") + if "fid" in gdf.columns: + gdf = gdf.rename(columns={"fid": "orig_fid"}) + input_count = len(gdf) + gdf = algo_common.clean_geometries( + gdf, + stage="input", + out_file=out_file, + layer="qc_removed_input_cleanup", + ).reset_index(drop=True) + input_cleanup_removed_count = input_count - len(gdf) + qc_manifest["qc_removed_input_cleanup"]["feature_count"] = int(max(input_cleanup_removed_count, 0)) + qc_manifest["qc_removed_input_cleanup"]["written"] = 1 if input_cleanup_removed_count > 0 else 0 + qc_manifest["qc_removed_input_cleanup"]["notes"] = ( + "written" if input_cleanup_removed_count > 0 else "empty" + ) + + logger.info( + "Seed line QC start: %s feature(s), input cleanup removed %s feature(s)", + len(gdf), + input_cleanup_removed_count, + ) + + step_name = "Normalize multiline seed lines" + in_count = len(gdf) + t0 = _step_timer() + gdf = qc_merge_multilinestring(gdf) + _log_step( + 1, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps + ) + if _bail_if_empty( + gdf, + step_name, + out_file, + out_layer, + in_count, + skipped_steps=skipped_steps, + ): + _persist_qc_tables(input_count, 0) + return + + step_name = "Geometry cleanup" + in_count = len(gdf) + t0 = _step_timer() + gdf, removed_gdf = _clean_line_geometries_min_length_m(gdf, bt_const.SMALL_BUFFER) + gdf = gdf.reset_index(drop=True) + _mark_layer("qc_removed_cleanup", removed_gdf, notes="written" if _has_rows(removed_gdf) else "empty") + _log_step( + 2, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps + ) + if _bail_if_empty( + gdf, + step_name, + out_file, + out_layer, + in_count, + skipped_steps=skipped_steps, + ): + _persist_qc_tables(input_count, 0) + return + + step_name = "Clip to CHM footprint" + in_count = len(gdf) + if config.clip_to_chm_footprint: + if in_raster: + t0 = _step_timer() + gdf, removed_gdf, footprint = _clip_to_chm_footprint(gdf, in_raster, config.chm_footprint_shrink) + _mark_layer( + "qc_removed_clipped", removed_gdf, notes="written" if _has_rows(removed_gdf) else "empty" + ) + footprint_gdf = gpd.GeoDataFrame( + [{"source": "chm_footprint_shrunken"}], geometry=[footprint], crs=gdf.crs + ) + _mark_layer("chm_footprint", footprint_gdf, notes="written") + _log_step( + 3, + step_name, + in_count, + len(gdf), + _elapsed(t0), + verbose=verbose_steps, + skipped_steps=skipped_steps, + ) + if _bail_if_empty( + gdf, + step_name, + out_file, + out_layer, + in_count, + skipped_steps=skipped_steps, + ): + _persist_qc_tables(input_count, 0) + return + else: + qc_manifest["qc_removed_clipped"]["notes"] = "enabled but missing in_raster" + qc_manifest["chm_footprint"]["notes"] = "enabled but missing in_raster" + logger.error( + "CHM footprint clipping enabled but 'in_raster' is missing; " + "continuing without footprint clip." + ) + _log_step( + 3, + step_name, + in_count, + in_count, + skipped_reason="enabled but missing in_raster", + verbose=verbose_steps, + skipped_steps=skipped_steps, + ) + else: + qc_manifest["qc_removed_clipped"]["notes"] = "disabled" + qc_manifest["chm_footprint"]["notes"] = "disabled" + _log_step( + 3, + step_name, + in_count, + in_count, + skipped_reason="disabled", + verbose=verbose_steps, + skipped_steps=skipped_steps, + ) + + step_name = "Remove short lines" + in_count = len(gdf) + if config.remove_short_lines: + t0 = _step_timer() + gdf, removed_gdf = _clean_line_geometries_min_length_m(gdf, config.minimum_line_length) + gdf = gdf.reset_index(drop=True) + _mark_layer("qc_removed_short", removed_gdf, notes="written" if _has_rows(removed_gdf) else "empty") + _log_step( + 4, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps + ) + if _bail_if_empty( + gdf, + step_name, + out_file, + out_layer, + in_count, + skipped_steps=skipped_steps, + ): + _persist_qc_tables(input_count, 0) + return + else: + qc_manifest["qc_removed_short"]["notes"] = "disabled" + _log_step( + 4, + step_name, + in_count, + in_count, + skipped_reason="disabled", + verbose=verbose_steps, + skipped_steps=skipped_steps, + ) + + step_name = "Post-clip cleanup" + in_count = len(gdf) + t0 = _step_timer() + gdf = _normalize_to_lines(gdf) + gdf, removed_gdf = _clean_line_geometries_min_length_m(gdf, bt_const.SMALL_BUFFER) + gdf = gdf.reset_index(drop=True) + _mark_layer("qc_removed_post_clip", removed_gdf, notes="written" if _has_rows(removed_gdf) else "empty") + _log_step( + 5, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps + ) + if _bail_if_empty( + gdf, + step_name, + out_file, + out_layer, + in_count, + skipped_steps=skipped_steps, + ): + _persist_qc_tables(input_count, 0) + return + + step_name = "Preclean vertices" + in_count = len(gdf) + if config.preclean_vertices: + t0 = _step_timer() + gdf, removed_gdf = _preclean_lines_full( + gdf, + close_distance_m=effective_preclean_close_distance, + angle_tol_deg=config.preclean_angle_tolerance, + ) + gdf.geometry = gdf.geometry.apply( + lambda g: _trim_short_terminal_segments( + g, + min_segment_length=config.minimum_line_length + ) + ) + gdf = gdf.reset_index(drop=True) + + _mark_layer( + "qc_removed_preclean", removed_gdf, notes="written" if _has_rows(removed_gdf) else "empty" + ) + _log_step( + 6, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps + ) + if _bail_if_empty( + gdf, + step_name, + out_file, + out_layer, + in_count, + skipped_steps=skipped_steps, + ): + _persist_qc_tables(input_count, 0) + return + else: + qc_manifest["qc_removed_preclean"]["notes"] = "disabled" + _log_step( + 6, + step_name, + in_count, + in_count, + skipped_reason="disabled", + verbose=verbose_steps, + skipped_steps=skipped_steps, + ) + + step_name = "Snap close endpoints" + in_count = len(gdf) + if config.snap_close_endpoints: + t0 = _step_timer() + effective_tolerance = config.snap_tolerance + if config.remove_short_lines: + effective_tolerance = max(effective_tolerance, config.minimum_line_length) + gdf = _snap_close_endpoints(gdf, effective_tolerance).reset_index(drop=True) + _log_step( + 7, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps + ) + if _bail_if_empty( + gdf, + step_name, + out_file, + out_layer, + in_count, + skipped_steps=skipped_steps, + ): + _persist_qc_tables(input_count, 0) + return + else: + _log_step( + 7, + step_name, + in_count, + in_count, + skipped_reason="disabled", + verbose=verbose_steps, + skipped_steps=skipped_steps, + ) + + step_name = "Split lines at intersections" + in_count = len(gdf) + t0 = _step_timer() + prev_crs = gdf.crs + split_out = qc_split_lines_at_intersections(gdf) + gdf = _ensure_gdf(split_out, prev_crs) + split_min_length = config.minimum_line_length if config.remove_short_lines else bt_const.SMALL_BUFFER + gdf, removed_gdf = _clean_line_geometries_min_length_m(gdf, split_min_length) + # pieces keep their line's OLnSEG, so number them along each original line + if "OLnFID" in gdf.columns and "OLnSEG" in gdf.columns: + gdf = gdf.sort_values(["OLnFID", "OLnSEG"], kind="stable").reset_index(drop=True) + gdf["OLnSEG"] = gdf.groupby("OLnFID").cumcount() + gdf = gdf.reset_index(drop=True) + _log_step( + 8, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps + ) + if _bail_if_empty( + gdf, + step_name, + out_file, + out_layer, + in_count, + skipped_steps=skipped_steps, + ): + _persist_qc_tables(input_count, 0) + return + + step_name = "Group lines" + in_count = len(gdf) + if config.group_lines: + t0 = _step_timer() + lg = LineGrouping(gdf, use_angle_grouping=config.use_angle_grouping) + lg.run_grouping() + gdf = _ensure_gdf(lg.lines, gdf.crs).reset_index(drop=True) + _log_step( + 9, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps + ) + if _bail_if_empty( + gdf, + step_name, + out_file, + out_layer, + in_count, + skipped_steps=skipped_steps, + ): + _persist_qc_tables(input_count, 0) + return + else: + gdf = _ensure_gdf(gdf, gdf.crs).reset_index(drop=True) + gdf[bt_const.BT_GROUP] = list(range(len(gdf))) + _log_step( + 9, + step_name, + in_count, + len(gdf), + skipped_reason="disabled; assigned unique BT_GROUP", + verbose=verbose_steps, + skipped_steps=skipped_steps, + ) + + step_name = "Densify long lines" + in_count = len(gdf) + if config.densify_long_lines: + t0 = _step_timer() + gdf = _densify_long_lines(gdf, config.max_segment_length).reset_index(drop=True) + _log_step( + 10, + step_name, + in_count, + len(gdf), + _elapsed(t0), + verbose=verbose_steps, + skipped_steps=skipped_steps, + ) + if _bail_if_empty( + gdf, + step_name, + out_file, + out_layer, + in_count, + skipped_steps=skipped_steps, + ): + _persist_qc_tables(input_count, 0) + return + else: + _log_step( + 10, + step_name, + in_count, + in_count, + skipped_reason="disabled", + verbose=verbose_steps, + skipped_steps=skipped_steps, + ) + + step_name = "Apply Seed Line Correction" + in_count = len(gdf) + if config.apply_seed_line_correction: + from beratools.modules.mapping.algo_seed_line_correction import SeedLineCorrection + + print("Starting Seed Line Correction...", flush=True) + + slc_search_distance_native, slc_line_radius_native = _convert_slc_meter_params_to_native_units( + gdf, + config.slc_search_distance, + config.slc_line_radius, + ) + + t0 = _step_timer() + try: + slc = SeedLineCorrection( + in_file, + in_raster, + slc_search_distance_native, + slc_line_radius_native, + processes, + call_mode, + layer=in_layer, + optimize_internal_vertices=config.slc_optimize_internal_vertices, + ) + slc.prepare_lines(lines_gdf=gdf) + slc.group_vertices() + gdf = _ensure_gdf(slc.optimize(), gdf.crs).reset_index(drop=True) + debug_layers = slc.get_debug_layers() + algo_common.save_aux_layer(debug_layers.get("lc_paths"), out_file, "lc_paths") + algo_common.save_aux_layer(debug_layers.get("anchors"), out_file, "anchors") + algo_common.save_aux_layer(debug_layers.get("vertices"), out_file, "vertices") + except Exception: + logger.exception("Apply Seed Line Correction failed; QC report step was not reached.") + raise + _log_step( + 11, + step_name, + in_count, + len(gdf), + _elapsed(t0), + verbose=verbose_steps, + skipped_steps=skipped_steps, + ) + if _bail_if_empty( + gdf, + step_name, + out_file, + out_layer, + in_count, + skipped_steps=skipped_steps, + ): + _persist_qc_tables(input_count, 0) + return + else: + _log_step( + 11, + step_name, + in_count, + in_count, + skipped_reason="disabled", + verbose=verbose_steps, + skipped_steps=skipped_steps, + ) + + gdf, removed_gdf = _clean_line_geometries_min_length_m(gdf, bt_const.SMALL_BUFFER) + gdf = gdf.reset_index(drop=True) + _mark_layer("qc_removed_final", removed_gdf, notes="written" if _has_rows(removed_gdf) else "empty") + + step_name = "Generate QC Report" + from beratools.modules.mapping.algo_check_seed_line_validate import generate_qc_report + + print("Running final validation pass to detect remaining issues after all previous steps...") + t0 = _step_timer() + qc_issues_gdf, qc_summary = generate_qc_report( + gdf, + min_length_m=config.minimum_line_length * 2.0, + close_distance_m=effective_preclean_close_distance * 2.0, + snap_tolerance_m=config.snap_tolerance * 2.0, + in_raster=in_raster, + warn_nodata_vertices=config.warn_nodata_vertices, + nodata_vertex_search_radius_m=config.nodata_vertex_search_radius, + check_internal_vertices=config.check_internal_vertices, + ) + _mark_layer("qc_report_issues", qc_issues_gdf) + _log_step( + 12, + step_name, + len(gdf), + qc_summary["total"], + _elapsed(t0), + verbose=verbose_steps, + skipped_steps=skipped_steps, + ) + _print_qc_summary(qc_summary, aux_file) + + if not verbose_steps and skipped_steps: + _print_skipped_summary(skipped_steps) + + _write_output(gdf, out_file, out_layer) + _persist_qc_tables(input_count, len(gdf)) + print(f"Output saved to file: {out_file}, layer: {out_layer}") + + +if __name__ == "__main__": + from beratools.utility.tool_args import compose_tool_kwargs + + start_time = time.time() + kwargs = compose_tool_kwargs("check_seed_line") + check_seed_line(**kwargs) + print("Elapsed time: {}".format(time.time() - start_time)) diff --git a/beratools/modules/mapping/common.py b/beratools/modules/mapping/common.py new file mode 100644 index 0000000..78ea311 --- /dev/null +++ b/beratools/modules/mapping/common.py @@ -0,0 +1,314 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng, Maverick Fong + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + This file is intended to be hosting common spatial classes/functions for BERA Tools +""" +import geopandas as gpd +import numpy as np +import shapely +import shapely.geometry as sh_geom +import shapely.ops as sh_ops +import xarray as xr +from scipy import ndimage + +from beratools.utility.faulthandler_pause import faulthandler_paused + +# xrspatial imports scipy.fft, whose import on Windows raises access violations that it catches +# itself; see faulthandler_pause +with faulthandler_paused(): + import xrspatial + +import beratools.core.constants as bt_const +from beratools.modules.mapping.algo_common import chk_df_multipart # noqa: F401 (re-exported) + +PARALLEL_MODE = bt_const.ParallelMode.MULTIPROCESSING + +def remove_nan_from_array(matrix): + with np.nditer(matrix, op_flags=["readwrite"]) as it: + for x in it: + if np.isnan(x[...]): + x[...] = bt_const.BT_NODATA_COST + +def split_into_equal_Nth_segments(df, seg_length): + odf = df + crs = odf.crs + if "OLnSEG" not in odf.columns.array: + df["OLnSEG"] = np.nan + df = odf.assign(geometry=odf.apply(lambda x: cut_line_by_length(x.geometry, seg_length), axis=1)) + df = df.explode() + + df["OLnSEG"] = df.groupby("OLnFID").cumcount() + gdf = gpd.GeoDataFrame(df, geometry=df.geometry, crs=crs) + gdf = gdf.sort_values(by=["OLnFID", "OLnSEG"]) + gdf = gdf.reset_index(drop=True) + + if "shape_leng" in gdf.columns.array: + gdf["shape_leng"] = gdf.geometry.length + elif "LENGTH" in gdf.columns.array: + gdf["LENGTH"] = gdf.geometry.length + else: + gdf["shape_leng"] = gdf.geometry.length + return gdf + + +def cut_line_by_length(line, length, merge_threshold=0.5): + """ + Split line into segments of equal length. + + Merge the last segment with the second-to-last if its length + is smaller than the given threshold. + + Args: + line : LineString + Line to be split by distance along the line. + length : float + Length of each segment to cut. + merge_threshold : float, optional + Threshold below which the last segment is merged with the previous one. Default is 0.5. + + Returns: + List of LineString objects + A list containing the resulting line segments. + + Example: + ">>> from shapely.geometry import LineString + ">>> line = LineString([(0, 0), (10, 0)]) + ">>> segments = cut_line_by_length(line, 3, merge_threshold=1) + ">>> for segment in segments: + ">>> print(f"Segment: {segment}, Length: {segment.length}") + + Output: + Segment: LINESTRING (0 0, 3 0), Length: 3.0 + Segment: LINESTRING (3 0, 6 0), Length: 3.0 + Segment: LINESTRING (6 0, 9 0), Length: 3.0 + Segment: LINESTRING (9 0, 10 0), Length: 1.0 + + After merging the last segment with the second-to-last segment: + + Output: + Segment: LINESTRING (0 0, 3 0), Length: 3.0 + Segment: LINESTRING (3 0, 6 0), Length: 3.0 + Segment: LINESTRING (6 0, 10 0), Length: 4.0 + + """ + if line.has_z: + # Remove the Z component of the line if it exists + line = sh_ops.transform(lambda x, y, z=None: (x, y), line) + + if shapely.is_empty(line): + return [] + + # Segment the line based on the specified distance + line = shapely.segmentize(line, length) + lines = [] + end_pt = None + + while line.length > length: + coords = list(line.coords) + + for i, p in enumerate(coords): + p_dist = line.project(sh_geom.Point(p)) + + # Check if the distance matches closely and split the line + if abs(p_dist - length) < 1e-9: # Use a small epsilon value + lines.append(sh_geom.LineString(coords[: i + 1])) + line = sh_geom.LineString(coords[i:]) + end_pt = None + break + elif p_dist > length: + end_pt = line.interpolate(length) + lines.append(sh_geom.LineString(coords[:i] + list(end_pt.coords))) + line = sh_geom.LineString(list(end_pt.coords) + coords[i:]) + break + + if end_pt: + lines.append(line) + + # Handle the threshold condition: merge the last segment if its length is below the threshold + if len(lines) > 1: + if lines[-1].length < merge_threshold: + # Merge the last segment with the second-to-last one + lines[-2] = sh_geom.LineString(list(lines[-2].coords) + list(lines[-1].coords)) + lines.pop() # Remove the last segment after merging + + return lines + +def dyn_fs_raster_stdmean(canopy_ndarray, kernel, nodata): + # This function uses xrspatial which can handle large data but slow + mask = canopy_ndarray.mask + in_ndarray = np.ma.where(mask, np.nan, canopy_ndarray) + result_ndarray = xrspatial.focal.focal_stats( + xr.DataArray(in_ndarray.data), kernel, stats_funcs=["std", "mean"] + ) + + # Assign std and mean ndarray (return array contain nan value) + reshape_std_ndarray = result_ndarray[0].data + reshape_mean_ndarray = result_ndarray[1].data + + return reshape_std_ndarray, reshape_mean_ndarray + + +def dyn_smooth_cost(canopy_ndarray, max_line_dist, sampling): + mask = canopy_ndarray.mask + in_ndarray = np.ma.where(mask, np.nan, canopy_ndarray) + # scipy way to do Euclidean distance transform + euc_dist_array = ndimage.distance_transform_edt( + np.logical_not(np.isnan(in_ndarray.data)), sampling=sampling + ) + euc_dist_array[mask] = np.nan + smooth1 = float(max_line_dist) - euc_dist_array + smooth1[smooth1 <= 0.0] = 0.0 + smooth_cost_array = smooth1 / float(max_line_dist) + + return smooth_cost_array + + +def dyn_np_cost_raster(canopy_ndarray, cc_mean, cc_std, cc_smooth, avoidance, cost_raster_exponent): + aM1a = cc_mean - cc_std + aM1b = cc_mean + cc_std + aM1 = np.divide(aM1a, aM1b, where=aM1b != 0, out=np.zeros(aM1a.shape, dtype=float)) + aM = (1 + aM1) / 2 + aaM = cc_mean + cc_std + bM = np.where(aaM <= 0, 0, aM) + cM = bM * (1 - avoidance) + (cc_smooth * avoidance) + dM = np.where(canopy_ndarray.data == 1, 1, cM) + eM = np.exp(dM) + result = np.power(eM, float(cost_raster_exponent)) + + return result + + +def dyn_np_cc_map(in_chm, canopy_ht_threshold, nodata): + canopy_ndarray = np.ma.where(in_chm >= canopy_ht_threshold, 1.0, 0.0).astype(float) + canopy_ndarray.fill_value = nodata + + return canopy_ndarray + + +def generate_line_args_DFP_NoClip( + line_seg, + work_in_bufferL, + work_in_bufferC, + in_chm_obj, + in_chm, + tree_radius, + max_line_dist, + canopy_avoidance, + exponent, + work_in_bufferR, + canopy_thresh_percentage, + exp_shk_cell +): + line_argsL = [] + line_argsR = [] + line_argsC = [] + line_id = 0 + total = len(work_in_bufferC)+len(work_in_bufferL)+len(work_in_bufferR) + for record in range(0, len(work_in_bufferC)): + line_bufferC = work_in_bufferC.loc[record, "geometry"] + nodata = bt_const.BT_NODATA + line_argsC.append( + [ + in_chm, + float(work_in_bufferC.loc[record, "DynCanTh"]), + float(tree_radius), + float(max_line_dist), + float(canopy_avoidance), + float(exponent), + in_chm_obj.res, + nodata, + line_seg.iloc[[record]], + in_chm_obj.meta.copy(), + line_id, + 10, + "Center", + canopy_thresh_percentage, + line_bufferC, + exp_shk_cell + ] + ) + + step = line_id + 1 + print(f' "PROGRESS_LABEL Preparing... {step} of {total}" ', flush=True) + print(f" {(step / total) * 100}% ", flush=True) + line_id += 1 + + line_id = 0 + + for record in range(0, len(work_in_bufferL)): + line_bufferL = work_in_bufferL.loc[record, "geometry"] + LCut = work_in_bufferL.loc[record, "LDist_Cut"] + + nodata = bt_const.BT_NODATA + line_argsL.append( + [ + in_chm, + float(work_in_bufferL.loc[record, "DynCanTh"]), + float(tree_radius), + float(max_line_dist), + float(canopy_avoidance), + float(exponent), + in_chm_obj.res, + nodata, + line_seg.iloc[[record]], + in_chm_obj.meta.copy(), + line_id, + LCut, + "Left", + canopy_thresh_percentage, + line_bufferL, + exp_shk_cell + ] + ) + + step = line_id + 1+ len(work_in_bufferC) + print(f' "PROGRESS_LABEL Preparing... {step} of {total}" ', flush=True) + print(f" {(step / total) * 100}% ", flush=True) + line_id += 1 + + line_id = 0 + for record in range(0, len(work_in_bufferR)): + line_bufferR = work_in_bufferR.loc[record, "geometry"] + RCut = work_in_bufferR.loc[record, "RDist_Cut"] + + nodata = bt_const.BT_NODATA + # TODO deal with inherited nodata and BT_NODATA_COST + # TODO convert nodata to BT_NODATA_COST + line_argsR.append( + [ + in_chm, + float(work_in_bufferR.loc[record, "DynCanTh"]), + float(tree_radius), + float(max_line_dist), + float(canopy_avoidance), + float(exponent), + in_chm_obj.res, + nodata, + line_seg.iloc[[record]], + in_chm_obj.meta.copy(), + line_id, + RCut, + "Right", + canopy_thresh_percentage, + line_bufferR, + exp_shk_cell + ] + ) + + step = line_id + 1 + len(work_in_bufferC)+len(work_in_bufferL) + print(f' "PROGRESS_LABEL Preparing... {step} of {total}" ', flush=True) + print(f" {(step / total) * 100}% ", flush=True) + + line_id += 1 + + return line_argsL, line_argsR, line_argsC + diff --git a/beratools/modules/mapping/docs/files/api.md b/beratools/modules/mapping/docs/files/api.md new file mode 100644 index 0000000..49d3e10 --- /dev/null +++ b/beratools/modules/mapping/docs/files/api.md @@ -0,0 +1,72 @@ +# Mapping API Reference + +## Tools API + +::: beratools.modules.mapping.check_seed_line +::: beratools.modules.mapping.vertex_optimization +::: beratools.modules.mapping.centerline +::: beratools.modules.mapping.canopy_footprint_absolute +::: beratools.modules.mapping.line_footprint_relative + options: + members: + - line_footprint_relative +::: beratools.modules.mapping.ground_footprint + +## Core Algorithms + +::: beratools.modules.mapping.algo_centerline + options: + members: + - CenterlineParams + - CenterlineStatus + - EndPointAnchorResult + - centerline_is_valid + - snap_end_to_end + - find_centerline + - find_corridor_polygon + - process_single_centerline + - find_centerlines + - regenerate_centerline + - SeedLine + - orient_to_split +::: beratools.modules.mapping.line_footprint_functions + options: + members: + - dyn_canopy_cost_raster + - split_line_fc + - split_line_npart + - split_into_segments + - split_into_equal_nth_segments + - generate_line_args + - find_corridor_threshold + - process_single_line_relative + - multiprocessing_footprint_relative + - main_line_footprint_relative +::: beratools.modules.mapping.canopy_threshold_relative + options: + members: + - OperationCancelledException + - main_canopy_threshold_relative + - rate_of_change + - multiprocessing_RofC + - split_line_fc + - split_into_segments + - multiprocessing_percentile + - cal_percentile_ring + - copyparallel_lineLRC + +## Common Tool Utilities + +::: beratools.modules.mapping.common + options: + members: + - remove_nan_from_array + - split_into_equal_Nth_segments + - cut_line_by_length + - chk_df_multipart + - dyn_fs_raster_stdmean + - dyn_smooth_cost + - dyn_np_cost_raster + - dyn_np_cc_map + - generate_line_args_DFP_NoClip + diff --git a/beratools/modules/mapping/docs/files/index.md b/beratools/modules/mapping/docs/files/index.md new file mode 100644 index 0000000..549dfeb --- /dev/null +++ b/beratools/modules/mapping/docs/files/index.md @@ -0,0 +1,18 @@ +# Mapping + +Tools for delineating and attributing forest linear disturbances: line quality control, +vertex optimization, centerlines and footprints. + +| Tool | `bt` subcommand | Details | +|------|-----------------|---------| +| [Check Seed Lines](user/check_seed_line.md) | `check_line` | Groups and splits input lines for seed line quality control. | +| [Vertex Optimization](user/vertex_optimization.md) | `vertex_opt` | Optimizes line vertices using raster data for improved delineation. | +| [Centerline](user/centerline.md) | `centerline` | Generates centerlines from input lines and raster data. | +| [Smooth Centerline](user/smooth_centerline.md) | `smooth_line` | Removes sharp corners from centerlines and keeps the rest of each line unchanged. | +| [Canopy Footprint (Absolute Threshold)](user/canopy_footprint_abs.md) | `footprint_abs` | Generates line footprints based on absolute canopy thresholds. | +| [Canopy Footprint (Relative Threshold)](user/canopy_footprint_rel.md) | `footprint_rel` | Creates dynamic line footprints using least-cost corridor and relative thresholds. | +| [Ground Footprint](user/ground_footprint.md) | `footprint_grd` | Computes fixed-width line footprints and associated statistics. | +| [Footprint Plots and Subplots](user/footprint_plots.md) | `footprint_plots` | Splits line footprints into plots and subplots along their centerlines. | + +This site covers the Mapping module. Installation, the GUI, the `bt` command and +pipelines are in the [BERA Tools Guide](https://beratool.github.io/beratools/). diff --git a/docs/files/screenshots/tool_canopy_abs.png b/beratools/modules/mapping/docs/files/screenshots/tool_canopy_abs.png similarity index 100% rename from docs/files/screenshots/tool_canopy_abs.png rename to beratools/modules/mapping/docs/files/screenshots/tool_canopy_abs.png diff --git a/docs/files/screenshots/tool_canopy_rel.png b/beratools/modules/mapping/docs/files/screenshots/tool_canopy_rel.png similarity index 100% rename from docs/files/screenshots/tool_canopy_rel.png rename to beratools/modules/mapping/docs/files/screenshots/tool_canopy_rel.png diff --git a/docs/files/screenshots/tool_centerline.png b/beratools/modules/mapping/docs/files/screenshots/tool_centerline.png similarity index 100% rename from docs/files/screenshots/tool_centerline.png rename to beratools/modules/mapping/docs/files/screenshots/tool_centerline.png diff --git a/docs/files/screenshots/tool_check_line.png b/beratools/modules/mapping/docs/files/screenshots/tool_check_line.png similarity index 100% rename from docs/files/screenshots/tool_check_line.png rename to beratools/modules/mapping/docs/files/screenshots/tool_check_line.png diff --git a/beratools/modules/mapping/docs/files/screenshots/tool_footprint_plots.png b/beratools/modules/mapping/docs/files/screenshots/tool_footprint_plots.png new file mode 100644 index 0000000..4f3c556 Binary files /dev/null and b/beratools/modules/mapping/docs/files/screenshots/tool_footprint_plots.png differ diff --git a/docs/files/screenshots/tool_ground_ft.png b/beratools/modules/mapping/docs/files/screenshots/tool_ground_ft.png similarity index 100% rename from docs/files/screenshots/tool_ground_ft.png rename to beratools/modules/mapping/docs/files/screenshots/tool_ground_ft.png diff --git a/beratools/modules/mapping/docs/files/screenshots/tool_smooth_centerline.png b/beratools/modules/mapping/docs/files/screenshots/tool_smooth_centerline.png new file mode 100644 index 0000000..8548361 Binary files /dev/null and b/beratools/modules/mapping/docs/files/screenshots/tool_smooth_centerline.png differ diff --git a/docs/files/screenshots/tool_vertex_opt.png b/beratools/modules/mapping/docs/files/screenshots/tool_vertex_opt.png similarity index 100% rename from docs/files/screenshots/tool_vertex_opt.png rename to beratools/modules/mapping/docs/files/screenshots/tool_vertex_opt.png diff --git a/docs/files/technical/algorithms/canopy_footprint_absolute.md b/beratools/modules/mapping/docs/files/technical/algorithms/canopy_footprint_absolute.md similarity index 100% rename from docs/files/technical/algorithms/canopy_footprint_absolute.md rename to beratools/modules/mapping/docs/files/technical/algorithms/canopy_footprint_absolute.md diff --git a/docs/files/technical/algorithms/canopy_footprint_relative.md b/beratools/modules/mapping/docs/files/technical/algorithms/canopy_footprint_relative.md similarity index 100% rename from docs/files/technical/algorithms/canopy_footprint_relative.md rename to beratools/modules/mapping/docs/files/technical/algorithms/canopy_footprint_relative.md diff --git a/docs/files/technical/algorithms/centerline.md b/beratools/modules/mapping/docs/files/technical/algorithms/centerline.md similarity index 100% rename from docs/files/technical/algorithms/centerline.md rename to beratools/modules/mapping/docs/files/technical/algorithms/centerline.md diff --git a/docs/files/technical/algorithms/check_seed_line.md b/beratools/modules/mapping/docs/files/technical/algorithms/check_seed_line.md similarity index 100% rename from docs/files/technical/algorithms/check_seed_line.md rename to beratools/modules/mapping/docs/files/technical/algorithms/check_seed_line.md diff --git a/beratools/modules/mapping/docs/files/technical/algorithms/footprint_plots.md b/beratools/modules/mapping/docs/files/technical/algorithms/footprint_plots.md new file mode 100644 index 0000000..1cfc8e7 --- /dev/null +++ b/beratools/modules/mapping/docs/files/technical/algorithms/footprint_plots.md @@ -0,0 +1,87 @@ +# Footprint Plots and Subplots — Algorithm Notes + +Related user page: [Footprint Plots and Subplots](../../user/footprint_plots.md) + +## Purpose + +Split line footprints into plots and subplots along their centerlines, labelled by side, plot and subplot. Ported from [SegLine](https://github.com/IrinaTerentieva/SegLine) (`src/fixed_area` and `src/fixed_length`) by Irina Terentieva. + +## Inputs and outputs + +- Inputs: footprint polygons, centerlines, `mode` (`fixed_area` default or `fixed_length`), plot/subplot sizes, `remove_overlap` (default `false`) +- Outputs: plot layer (one feature per plot side) and subplot layer, with the SegLine columns `UniqueID`, `side`, `plot_id`, `subplot_id`, `area`, `length`, `perimeter`, `plot_area`, `subplot_area`, plus `est_width` + +## Method summary + +1. Check the sizes: subplot size `> 0`; in fixed area, plot area `>= 2 x` subplot area; in fixed length, plot length `>=` subplot length. Footprints and centerlines must share a CRS. +2. Keep an existing unique `UniqueID` column, otherwise generate random 6-character IDs. +3. Match each footprint to the centerline with the longest overlap inside it (spatial index query, then intersection length). +4. With `remove_overlap`, decide who keeps each overlap and trim lines that end in one (see [Overlap removal](#overlap-removal)). +5. In a worker per footprint: + 1. Prepare the centerline (`prepare_centerline`): merge parts and trim it to the stretch that overlaps the footprint. + 2. Estimate the width as footprint area / centerline length (`estimate_width`). + 3. Get the plot and subplot lengths along the line (`area_mode_lengths` or the fixed lengths). + 4. Split the footprint (`split_footprint`), then cut out overlaps it gives up at crossings. + 5. Snap the pieces to a `1e-6` m grid and drop zero-width spikes and crumbs of `0.001` m² or less. +6. Number plots and subplots across the output, add the measure columns and write both layers. + +The core logic is in `beratools/modules/mapping/algo_footprint_plots.py`; matching and overlap decisions are in `beratools/modules/mapping/footprint_plots.py`. + +## Plot and subplot lengths + +- **Fixed area**: a subplot covers one side, so its area is `length x width / 2`. + - Subplot length = `2 x subplot_area / width` + - Subplots per side = `round(plot_area / (2 x subplot_area))`, at least 1 + - Plot length = subplots per side `x` subplot length +- **Fixed length**: `plot_length` and `subplot_length` are used directly. + +Because the width is the footprint's average, the mean subplot area matches the target; locally wider or narrower parts give larger or smaller subplots. + +## Stations + +`subplot_stations` places subplot starts along the centerline: + +- Plots start every plot length; subplots restart at each plot start, so a plot length that isn't a multiple of the subplot length leaves a shorter last subplot in each plot. +- A piece shorter than half a subplot length (`MIN_TAIL_FRACTION`) joins the previous subplot. + +## Splitting by labelled faces + +`split_footprint` cuts by geometry, not by split order: + +1. Extend the centerline straight along its end tangents, so it crosses the whole footprint. +2. Draw a cross cut perpendicular to the line at every station after the first. Cuts reach the footprint's Hausdorff distance from the centerline plus its width plus 1 m. +3. Polygonize the footprint boundary, the extended centerline and the cuts into faces. +4. For each face inside the footprint, project its representative point onto the centerline: + - the station interval it falls in gives the subplot; + - the sign of the cross product with the local tangent gives the side (`0` left, `1` right of the line direction). +5. Dissolve faces with the same side and station into one subplot, and the subplots of a plot side into one plot. + +Labelling faces by position keeps sides consistent along the line and gives exactly one geometry per plot side and subplot, even where cross cuts at bends cross each other. Plots and subplots cover the footprint without gaps or overlaps. + +## Overlap removal + +Each overlap between two matched footprints (polygon parts larger than `0.001` m²) is decided on its own: + +1. A line that ends in the overlap loses it to one that passes through. A line ends in it if a centerline end is within half the footprint width (at least `0.5` m) of the overlap. +2. Otherwise a cardinal line keeps it over a non-cardinal one. A line is cardinal if its main direction is within `15°` of north-south or east-west. The main direction is the length-weighted mean of the segment directions, averaged as axes (angles doubled), so a line and its reverse agree and short bends count little. +3. Then the longer centerline (inside its footprint) keeps it, then the lower input index. + +The loser gives up the overlap in one of two ways: + +- **Ends in the overlap** (`trim_line_ends`, before splitting): the overlap is cut off the footprint and the centerline keeps its longest stretch outside it, in its original direction. Footprint pieces touching the overlap but not crossed by that stretch (bits beyond the other footprint) are dropped; other parts of a multipart footprint are kept. A footprint with nothing left is skipped. +- **Passes through** (`remove_overlap`, after splitting): the overlap is cut out of the subplots, which keep their stations and `length`. A subplot split in two keeps both pieces; a subplot entirely inside the overlap is dropped. Plots are rebuilt as the union of their subplots. + +## Numbering + +As in SegLine, `plot_id` and `subplot_id` are unique across the output. Subplots are sorted by footprint, plot, side and position along the line, so IDs increase along each line. `length` is measured along the centerline; `area`, `perimeter` and `plot_area` are measured on the final geometry, after any overlap removal. + +## Assumptions + +- Footprints and centerlines use the same projected CRS (metres). +- Each footprint has one main centerline running along it. + +## Edge cases + +- Footprints with no overlapping centerline, or whose centerline has no length inside the footprint, are skipped. +- A start trimmed off a line in overlap removal shifts every plot along that line by the trimmed amount; trimming the far end doesn't move plots. +- Plots and subplots the crossing runs through can end up as two pieces, one on each side of the other line. diff --git a/docs/files/technical/algorithms/ground_footprint.md b/beratools/modules/mapping/docs/files/technical/algorithms/ground_footprint.md similarity index 100% rename from docs/files/technical/algorithms/ground_footprint.md rename to beratools/modules/mapping/docs/files/technical/algorithms/ground_footprint.md diff --git a/beratools/modules/mapping/docs/files/technical/algorithms/smooth_centerline.md b/beratools/modules/mapping/docs/files/technical/algorithms/smooth_centerline.md new file mode 100644 index 0000000..128f59e --- /dev/null +++ b/beratools/modules/mapping/docs/files/technical/algorithms/smooth_centerline.md @@ -0,0 +1,44 @@ +# Smooth Centerline — Algorithm Notes + +Related user page: [Smooth Centerline](../../user/smooth_centerline.md) + +## Purpose + +Cut off sharp corners of centerlines and leave every other vertex unchanged. Ported from [SegLine](https://github.com/IrinaTerentieva/SegLine) (`src/utils/smooth_centerline.py`) by Irina Terentieva. + +## Inputs and outputs + +- Inputs: centerline vector, `angle_threshold` (degrees, default `130`), `buffer_distance` (m, default `2.0`) +- Outputs: smoothed centerline vector with the input attributes and line order + +## Method summary + +1. Read the lines and send each line to a worker (`smooth_worker` in `beratools/modules/mapping/smooth_centerline.py`). +2. Merge a `MultiLineString` with `linemerge`; parts that stay separate are smoothed one by one. +3. Walk the interior vertices of the line and compute the interior angle at each one from its two neighbours (`vertex_interior_angle`). `180°` is straight, smaller is sharper. +4. For a vertex with an angle below `angle_threshold`, cut the corner (`_cut_corner`): + 1. Intersect the line with a circle of radius `buffer_distance` around the vertex. + 2. Take the points where the line enters and leaves the circle. + 3. Replace the stretch between them with a straight chord; the line before and after keeps its vertices. +5. Skip the vertex right after a cut corner, so two neighbouring vertices aren't both cut. +6. Restore the input order, count the changed lines and write the output. + +The core logic is `smooth_sharp_vertices` in `beratools/modules/mapping/algo_geometry.py`. + +## Comparison with other smoothing + +- Centerline's **Smooth LCP** smooths every vertex of the least-cost path. +- Centerline's **Simplify Centerline** (`geo-simplify reduce-bend`) reduces bends along the whole line. +- Smooth Centerline changes only the sharp vertices and keeps the rest of the line exactly. + +## Assumptions + +- Lines are in a projected CRS, so `buffer_distance` is in metres. +- `buffer_distance` is small compared with the segment lengths and the footprint width. + +## Edge cases + +- Lines with fewer than three vertices, empty lines and `buffer_distance <= 0` are returned unchanged. +- A corner is left as is when the line crosses the circle more than once (the intersection isn't a single line), for example where the line loops back near the vertex. +- Angles are measured on the input vertices, so a corner next to one already cut is judged by its original shape. +- A vertex within `buffer_distance` of a line end cuts the line from that end. diff --git a/docs/files/technical/algorithms/vertex_optimization.md b/beratools/modules/mapping/docs/files/technical/algorithms/vertex_optimization.md similarity index 100% rename from docs/files/technical/algorithms/vertex_optimization.md rename to beratools/modules/mapping/docs/files/technical/algorithms/vertex_optimization.md diff --git a/docs/files/user/canopy_footprint_abs.md b/beratools/modules/mapping/docs/files/user/canopy_footprint_abs.md similarity index 100% rename from docs/files/user/canopy_footprint_abs.md rename to beratools/modules/mapping/docs/files/user/canopy_footprint_abs.md diff --git a/docs/files/user/canopy_footprint_rel.md b/beratools/modules/mapping/docs/files/user/canopy_footprint_rel.md similarity index 100% rename from docs/files/user/canopy_footprint_rel.md rename to beratools/modules/mapping/docs/files/user/canopy_footprint_rel.md diff --git a/docs/files/user/centerline.md b/beratools/modules/mapping/docs/files/user/centerline.md similarity index 100% rename from docs/files/user/centerline.md rename to beratools/modules/mapping/docs/files/user/centerline.md diff --git a/docs/files/user/check_seed_line.md b/beratools/modules/mapping/docs/files/user/check_seed_line.md similarity index 100% rename from docs/files/user/check_seed_line.md rename to beratools/modules/mapping/docs/files/user/check_seed_line.md diff --git a/beratools/modules/mapping/docs/files/user/footprint_plots.md b/beratools/modules/mapping/docs/files/user/footprint_plots.md new file mode 100644 index 0000000..fbe4c08 --- /dev/null +++ b/beratools/modules/mapping/docs/files/user/footprint_plots.md @@ -0,0 +1,147 @@ +# Footprint Plots and Subplots + +## What does this tool do? + +**Footprint Plots and Subplots** splits line footprints into plots and subplots along their centerlines. This is useful for field sampling or for summarizing data along a line in equal-area or equal-length units. + +- A **plot** covers both sides of the line. Each side is a separate feature, labelled `0` (left) or `1` (right) relative to the line direction. +- A **subplot** is a smaller unit on one side of the line. Subplots nest inside plots. + +The tool is ported from [SegLine](https://github.com/IrinaTerentieva/SegLine) by Irina Terentieva and supports both SegLine segmentation modes: + +| | **Fixed area** (`fixed_area`) | **Fixed length** (`fixed_length`) | +|---|---|---| +| **Plots** | Target area, e.g. 100 m² | Fixed spacing along the centerline, e.g. every 50 m | +| **Subplots** | Target area, e.g. 10 m² | Fixed spacing, e.g. every 10 m | +| **Wide vs. narrow lines** | Same area; plots get shorter as the line gets wider | Same length; plot area grows with line width | +| **Use when** | Plots must be comparable by area (e.g. stocking or density per m²) | Plots must line up with distance along the line (e.g. matching field transects) | + +## How do I use it? + +### Quick Start + +1. **Prepare your input files**: footprint polygons, for example the output of [Canopy Footprint](canopy_footprint_abs.md) or [Ground Footprint](ground_footprint.md), and the centerlines of those footprints. +2. **Run the tool** from GUI. The mode and size options are under **Show Advanced Options**: + + ![Footprint Plots and Subplots](../screenshots/tool_footprint_plots.png) + +3. **Open the two output files** in your GIS software. Symbolize by `plot_id` and `side` to see the plots. + +## What options can I set? + +- **Input Footprint**: Path to your input footprint polygon file +- **Input Centerline**: Path to the centerlines of the footprints. Each footprint uses the centerline that overlaps it the most, so the two files don't need a shared ID field. +- **Segmentation mode**: `fixed_area` or `fixed_length` (default: `fixed_area`) +- **Plot area (m2)**: Fixed area mode. Target plot area covering both sides of the line (default: `100`) +- **Subplot area (m2)**: Fixed area mode. Target subplot area on one side of the line (default: `10`) +- **Plot length (m)**: Fixed length mode. Distance between plot boundaries along the centerline (default: `50`) +- **Subplot length (m)**: Fixed length mode. Distance between subplot boundaries along the centerline (default: `10`) +- **Remove overlaps**: Cut overlaps between footprints, such as at line crossings, out of all but one footprint (default: `false`). See [Overlapping footprints](#overlapping-footprints) +- **Output Plots**: Path for the output plots, one feature per plot side +- **Output Subplots**: Path for the output subplots + +## How are plots sized? + +### Fixed area + +The tool estimates the average width of each footprint as its area divided by the length of the centerline inside it. It then spaces cuts along the centerline so that subplots get close to the target area: + +- Subplot length along the line = 2 × subplot area ÷ width +- Subplots per side of a plot = plot area ÷ (2 × subplot area), rounded to a whole number + +The plot area must be at least 2 × the subplot area. Where the footprint is wider or narrower than average, those subplots are larger or smaller. The mean subplot area still matches the target. + +### Fixed length + +Plots start every **plot length** along the centerline, and subplots start every **subplot length** within each plot. Subplots restart at each plot boundary, so a plot length that is not a multiple of the subplot length leaves a shorter last subplot in each plot. + +In both modes, a piece shorter than half a subplot length joins the previous subplot, for example at the end of a line. + +## Overlapping footprints + +Footprints often overlap where lines cross. By default, each footprint is split on its own, so plots and subplots of different lines overlap there. Any metric summed or averaged over subplots then counts the crossing twice. + +Turn on **Remove overlaps** to count each area only once. One footprint keeps each overlap and the other gives it up. Each overlap is decided on its own, so two lines that cross in one place and meet in another can be decided differently. The footprint that keeps it is chosen in this order: + +1. **A line that ends in the overlap always loses it**, as at a T-junction. A line counts as ending in the overlap if its centerline end is within half its footprint width of it (at least 0.5 m), so an end that stops just short of the other line counts too. +2. Where both lines pass through (a crossing) or both end there (a corner), a line running **north-south or east-west** keeps the overlap over a line running in any other direction. A line counts as north-south or east-west if its main direction is within 15° of one of them. +3. Otherwise, for two north-south or east-west lines, or two lines in other directions, the **longer centerline** keeps it. Only the part of the centerline inside its footprint counts. +4. If the lengths are equal, the footprint that comes first in the input keeps it. + +The main direction of a line is its length-weighted average direction, so a short bend doesn't change it. + +How the losing footprint gives up the overlap depends on whether its line ends there: + +- **Line ends in the overlap** (T-junction or corner): the footprint and its centerline are **trimmed** back to the other footprint before splitting. Plots and subplots start or stop at the cut, and `length` covers only the trimmed centerline. Bits of the footprint that poke out beyond the far side of the other footprint are dropped, so no plot holds part of another line's footprint. Fragments of a multipart footprint away from the overlap are kept. +- **Line passes through** (crossing): plot and subplot positions along the line don't change. The overlap is cut out of the pieces at the crossing, which get smaller. If the cut splits a subplot in two, the subplot keeps both pieces, one on each side of the crossing, so every subplot stays between its own cross cuts and both sides of the line are cut at the same places. A subplot that lies entirely inside the overlap is dropped. A plot or subplot the crossing runs through can end up in two pieces, one on each side of the other line. `length` is not changed. + +!!! note "Trimming shifts plots when the start of a line is trimmed" + Line ends are trimmed **before** plots and subplots are created, so the last subplot is a normal size, `length` matches the trimmed centerline, and pieces poking out beyond the other line are cut off cleanly. Plots are laid out from the start of the centerline, so when the trimmed end is the **start** of the line, every plot along it shifts by the trimmed amount (typically a few metres) compared with a run without **Remove overlaps**. Trimming the far end of a line doesn't move any plots. + +`area`, `perimeter` and `plot_area` are always measured after the overlap is removed. + +## Output attributes + +Both outputs keep the footprint attributes, plus any centerline attributes the footprint doesn't already have. The subplot output is the one to use downstream. Its key columns have the same names as in the [SegLine](https://github.com/IrinaTerentieva/SegLine) subplot layer. Some of them are computed differently, see [Differences from SegLine](#differences-from-segline). + +| Field | Description | +|---|---| +| `UniqueID` | Line (footprint polygon) ID. An existing unique `UniqueID` column in the footprints is kept; otherwise random IDs are generated, as in SegLine | +| `side` | Side of the centerline: `0` left, `1` right, relative to the line direction | +| `plot_id` | Plot ID. Unique across the output and increasing along each line | +| `subplot_id` | Subplot ID. Unique across the output and increasing along each line (subplots only) | +| `area` | Area of the feature (m²) | +| `length` | Length of the feature along the centerline (m) | +| `perimeter` | Perimeter of the feature (m) | +| `plot_area` | Area of the plot side the feature belongs to (m²) | +| `subplot_area` | Area of the subplot (m², subplots only) | +| `est_width` | Estimated average footprint width (m) | + +The plot output has one feature per plot side, with the same columns except `subplot_id` and `subplot_area`. + +## Differences from SegLine + +The tool follows SegLine's two modes and output columns, but it is not a line-by-line copy. Compared with the output of SegLine's own scripts: + +### Output columns + +| Column | SegLine | This tool | +|---|---|---| +| `UniqueID` | Always generated as a random ID (4 characters with the default config) | Kept from the footprints if they already have a unique `UniqueID` column; otherwise a random 6-character ID | +| `side` | `0`/`1` from pairing plot pieces, not tied to the line direction | `0` is always left and `1` always right of the line direction | +| `plot_id` | Unique across the output, but not always in order along the line | Unique across the output and increasing from the start of each line | +| `subplot_id` | Unique across the output; all of side `0` along a line, then all of side `1` | Unique across the output; ordered by plot, then side, then along the line | +| `length` | Polygon perimeter (same value as `perimeter`) | Length along the centerline | +| `plot_area` | Fixed area: area of the plot side. Fixed length: the configured `plot_area` value, the same for every feature | Area of the plot side in both modes | +| `subplot_area` | Fixed area: subplot area. Fixed length: the configured `subplot_area` value, the same for every feature | Subplot area in both modes | +| `width` | Input width column, required | Not required. The estimated width is written as `est_width` | +| Temporary columns | `PartID`, `segment_id`, `SubplotPartID`, `centroid_x`, `centroid_y`, `edge_points` | Not written | + +### Processing + +- **One tool instead of a pipeline.** SegLine runs separate scripts (assign IDs, clean centerlines, smooth, plots, sides, subplots) and writes a file after each step. This tool writes only the plots and the subplots. +- **Centerline cleaning and smoothing are not included.** SegLine's fixed-area mode removes duplicate and overlapping centerlines and can smooth them. Clean the centerlines first, or use [Smooth Centerline](smooth_centerline.md). +- **Matching footprints to centerlines.** SegLine links them with sample points along the centerline. This tool uses the centerline with the longest overlap with each footprint. +- **Width.** SegLine reads the width from a footprint column. This tool estimates it as footprint area divided by centerline length inside the footprint. +- **Sides.** SegLine splits each line into pieces and then pairs them into sides by shared edge points. This tool cuts along the centerline and labels each piece by which side of the line it lies on, so every plot has a consistent left and right side. +- **Overlaps.** SegLine keeps overlaps between footprints. This tool keeps them too by default, and can remove them with **Remove overlaps**. +- **Small pieces.** SegLine merges small fragments and subplots by area (fixed area) or drops pieces smaller than `min_area` (fixed length). This tool joins any piece shorter than half a subplot length to the previous subplot and never drops area: plots and subplots cover each footprint exactly. The only exception is with **Remove overlaps**, where bits of a trimmed footprint that poke out beyond the other footprint are dropped. + +### Results on the SegLine sample data + +With the default options in both tools: + +| | SegLine | This tool | +|---|---|---| +| Fixed area subplots | 1,971, mean 10.0 m², std 0.43 m² | 1,974, mean 10.0 m², std 0.57 m² | +| Fixed area plot sides | 394 | 400 | +| Fixed length subplots | 1,001, median 20.0 m² | 998, median 20.0 m² | +| Fixed length plot sides | 206 | 204 | + +Exact geometries differ, because SegLine places cuts from the width column and this tool from the estimated width. + +## Tips + +- Footprints and centerlines must use the same coordinate reference system (CRS). +- Footprints with no overlapping centerline are skipped. The tool prints how many footprints it matched. +- Plots and subplots cover each footprint exactly, without gaps or overlaps. With **Remove overlaps** on, they cover the union of the footprints instead. Crumbs of 0.001 m² or less, where a cut clips the corner of a tiny footprint fragment, are dropped. diff --git a/docs/files/user/ground_footprint.md b/beratools/modules/mapping/docs/files/user/ground_footprint.md similarity index 100% rename from docs/files/user/ground_footprint.md rename to beratools/modules/mapping/docs/files/user/ground_footprint.md diff --git a/beratools/modules/mapping/docs/files/user/smooth_centerline.md b/beratools/modules/mapping/docs/files/user/smooth_centerline.md new file mode 100644 index 0000000..e2322b0 --- /dev/null +++ b/beratools/modules/mapping/docs/files/user/smooth_centerline.md @@ -0,0 +1,33 @@ +# Smooth Centerline + +## What does this tool do? + +**Smooth Centerline** removes sharp corners from centerlines. It changes only the vertices where the line turns sharply. Each sharp corner is cut off with a straight segment, and the rest of the line keeps its original vertices. + +This differs from the smoothing options in [Centerline](centerline.md): **Smooth LCP** smooths every vertex of the line, and **Simplify Centerline** reduces bends along the whole line. Use this tool when the line is mostly right and only a few corners, such as zig-zags or spikes from the least-cost path, need fixing. + +The tool is ported from [SegLine](https://github.com/IrinaTerentieva/SegLine) by Irina Terentieva. + +## How do I use it? + +### Quick Start + +1. **Prepare your input file**: a centerline vector file (GeoPackage or Shapefile), for example the output of [Centerline](centerline.md). +2. **Run the tool** from GUI. The angle and buffer options are under **Show Advanced Options**: + + ![Smooth Centerline](../screenshots/tool_smooth_centerline.png) + +3. **Open the output file** in your GIS software and compare it with the input lines. + +## What options can I set? + +- **Input Centerline**: Path to your input line file +- **Angle threshold (degrees)**: Vertices with an interior angle below this value are smoothed (default: `130`). An angle of 180° is a straight line and smaller angles are sharper corners, so a higher threshold smooths more vertices. +- **Buffer distance (m)**: Radius around a sharp vertex that is replaced by a straight cut (default: `2.0`). Larger values give a stronger cut. +- **Smoothed Centerline**: Path for the output file + +## Tips + +- All attributes and the input order of the lines are kept. +- The tool prints how many lines it changed. If it changed none, raise the angle threshold. +- Keep the buffer distance small compared with the line width, so cuts stay inside the footprint. diff --git a/docs/files/user/vertex_optimization.md b/beratools/modules/mapping/docs/files/user/vertex_optimization.md similarity index 100% rename from docs/files/user/vertex_optimization.md rename to beratools/modules/mapping/docs/files/user/vertex_optimization.md diff --git a/beratools/modules/mapping/docs/mkdocs.yml b/beratools/modules/mapping/docs/mkdocs.yml new file mode 100644 index 0000000..5c3a047 --- /dev/null +++ b/beratools/modules/mapping/docs/mkdocs.yml @@ -0,0 +1,30 @@ +# The Mapping module's docs site. Shared settings are in docs/base.yml at the repo root. +# Build with `zensical`, not `mkdocs`. +INHERIT: ../../../../docs/base.yml + +site_name: BERA Tools Mapping +site_url: https://beratool.github.io/beratools/mapping/ +edit_uri: edit/main/beratools/modules/mapping/docs/files/ + +nav: + - Home: index.md + - User Guide: + - user/check_seed_line.md + - user/vertex_optimization.md + - user/centerline.md + - user/smooth_centerline.md + - user/canopy_footprint_abs.md + - user/canopy_footprint_rel.md + - user/ground_footprint.md + - user/footprint_plots.md + - Technical Guide: + - technical/algorithms/check_seed_line.md + - technical/algorithms/vertex_optimization.md + - technical/algorithms/centerline.md + - technical/algorithms/smooth_centerline.md + - technical/algorithms/canopy_footprint_absolute.md + - technical/algorithms/canopy_footprint_relative.md + - technical/algorithms/ground_footprint.md + - technical/algorithms/footprint_plots.md + - API Reference: api.md + - BERA Tools Guide: https://beratool.github.io/beratools/ diff --git a/beratools/modules/mapping/footprint_plots.py b/beratools/modules/mapping/footprint_plots.py new file mode 100644 index 0000000..86a4d26 --- /dev/null +++ b/beratools/modules/mapping/footprint_plots.py @@ -0,0 +1,371 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Irina Terentieva (original SegLine code) + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + The purpose of this script is to split line footprints into plots and + subplots along their centerlines, with plot, side and subplot IDs. + + Ported from SegLine by Irina Terentieva + (https://github.com/IrinaTerentieva/SegLine, fixed area and fixed length + modes). Output columns follow the SegLine subplot layer: UniqueID, side, + plot_id, subplot_id, area, length, perimeter, plot_area and subplot_area. +""" + +import logging +import secrets +import string + +import geopandas as gpd +import numpy as np +import shapely + +import beratools.modules.mapping.algo_footprint_plots as algo_fp +import beratools.utility.spatial_common as sp_common +from beratools.core.tool_base import execute_multiprocessing +from beratools.utility.tool_args import CallMode, to_bool + +LOGGER_NAME = "footprint_plots" +logger = logging.getLogger(LOGGER_NAME) + +UNIQUE_ID = "UniqueID" +UNIQUE_ID_LENGTH = 6 +# Smallest distance (m) a centerline end may be from an overlap to count as ending in it +MIN_END_TOLERANCE = 0.5 + + +def footprint_plots( + in_footprint, + in_line, + out_plot, + out_subplot, + mode=algo_fp.MODE_AREA, + plot_area=100.0, + subplot_area=10.0, + plot_length=50.0, + subplot_length=10.0, + remove_overlap=False, + processes=0, + call_mode=CallMode.CLI, + log_level="INFO", +): + """ + Define tool entry point. + + Args: + in_footprint: input footprint polygons (encoded as "file|layer") + in_line: input centerlines (encoded as "file|layer") + out_plot: output plots, one feature per plot side (encoded as "file|layer") + out_subplot: output subplots (encoded as "file|layer") + mode: "fixed_area" or "fixed_length" + plot_area: fixed area, target plot area covering both sides of the line (m2) + subplot_area: fixed area, target subplot area on one side of the line (m2) + plot_length: fixed length, plot length along the centerline (m) + subplot_length: fixed length, subplot length along the centerline (m) + remove_overlap: cut overlaps between footprints so each area is counted once; + a line ending in an overlap always loses it and is trimmed back, otherwise + north-south and east-west lines keep it, then the longer centerline + processes: number of processes to use + call_mode: CLI or GUI + log_level: logging level + + """ + if mode == algo_fp.MODE_AREA: + size = (float(plot_area), float(subplot_area)) + if size[1] <= 0 or size[0] < 2 * size[1]: + raise ValueError("subplot_area must be > 0 and plot_area must be at least 2 x subplot_area.") + elif mode == algo_fp.MODE_LENGTH: + size = (float(plot_length), float(subplot_length)) + if size[1] <= 0 or size[0] < size[1]: + raise ValueError("subplot_length must be > 0 and plot_length must be at least subplot_length.") + else: + raise ValueError(f"mode must be '{algo_fp.MODE_AREA}' or '{algo_fp.MODE_LENGTH}', got '{mode}'.") + + fp_file, fp_layer = sp_common.decode_file_layer(in_footprint) + line_file, line_layer = sp_common.decode_file_layer(in_line) + footprints = gpd.read_file(fp_file, layer=fp_layer) + lines = gpd.read_file(line_file, layer=line_layer) + if footprints.crs != lines.crs: + raise ValueError("Footprint and centerline must use the same coordinate reference system.") + footprints = _rename_fid(footprints).reset_index(drop=True) + lines = _rename_fid(lines).reset_index(drop=True) + footprints[UNIQUE_ID] = assign_unique_ids(footprints) + + matches = match_lines_to_footprints(footprints, lines) + print(f"Matched {len(matches)} of {len(footprints)} footprints to centerlines.", flush=True) + + end_claims, cut_claims = {}, {} + if to_bool(remove_overlap): + end_claims, cut_claims = overlap_claims(footprints, lines, matches) + if end_claims or cut_claims: + print( + f"Removing overlaps: {len(end_claims)} footprints trimmed at line ends, " + f"{len(cut_claims)} cut at crossings.", + flush=True, + ) + + fp_geoms, line_geoms = footprints.geometry, lines.geometry + inputs = { + fp_idx: (fp_geoms.iloc[fp_idx], line_geoms.iloc[line_idx]) + for fp_idx, line_idx in matches.items() + } + if end_claims: + inputs = trim_ending_lines(inputs, end_claims) + + line_columns = [col for col in lines.columns if col != "geometry" and col not in footprints.columns] + tasks = [] + for fp_idx, line_idx in matches.items(): + footprint, line = inputs[fp_idx] + if footprint is None: + uid = footprints.at[fp_idx, UNIQUE_ID] + logger.info(f"Footprint {uid}: lies inside overlaps it gives up, skipped.") + continue + attrs = footprints.iloc[fp_idx].drop("geometry").to_dict() + attrs.update(lines.iloc[line_idx][line_columns].to_dict()) + attrs["_fp"] = int(fp_idx) + tasks.append((attrs, footprint, line, mode, size, cut_claims.get(fp_idx))) + + results = execute_multiprocessing( + footprint_plots_worker, tasks, "footprint_plots", processes, call_mode, logger_name=LOGGER_NAME + ) + if not results: + raise RuntimeError("Footprint plots produced no output.") + + plot_records = [rec for plots, _ in results for rec in plots] + subplot_records = [rec for _, subplots in results for rec in subplots] + plot_gdf, subplot_gdf = _to_segline_layers(plot_records, subplot_records, footprints.crs) + + out_file, out_layer = sp_common.decode_file_layer(out_plot) + plot_gdf.to_file(out_file, layer=out_layer) + out_file, out_layer = sp_common.decode_file_layer(out_subplot) + subplot_gdf.to_file(out_file, layer=out_layer) + print( + f"Created {len(plot_gdf)} plot sides and {len(subplot_gdf)} subplots ({mode}, " + f"mean subplot area {subplot_gdf['area'].mean():.1f} m2).", + flush=True, + ) + + +def assign_unique_ids(footprints): + """Keep an existing unique UniqueID column, otherwise generate random IDs like SegLine.""" + if UNIQUE_ID in footprints.columns: + ids = footprints[UNIQUE_ID] + if ids.notna().all() and ids.is_unique: + return ids.astype(str) + logger.warning(f"{UNIQUE_ID} column is missing values or not unique, new IDs are generated.") + + alphabet = string.ascii_letters + string.digits + ids = set() + while len(ids) < len(footprints): + ids.add("".join(secrets.choice(alphabet) for _ in range(UNIQUE_ID_LENGTH))) + return list(ids) + + +def match_lines_to_footprints(footprints, lines): + """Return {footprint index: line index} using the line with the longest overlap.""" + fp_idx, line_idx = lines.sindex.query(footprints.geometry, predicate="intersects") + if len(fp_idx) == 0: + return {} + + overlap = shapely.length( + shapely.intersection(footprints.geometry.values[fp_idx], lines.geometry.values[line_idx]) + ) + best = {} + for order in np.argsort(-overlap, kind="stable"): + if overlap[order] > 0: + best.setdefault(int(fp_idx[order]), int(line_idx[order])) + return dict(sorted(best.items())) + + +def overlap_claims(footprints, lines, matches): + """ + Return (end_claims, cut_claims), each {footprint index: overlap area it gives up}. + + Each overlap between two footprints is decided on its own: + + - a line that ends in the overlap gives it up to a line that passes through; + - otherwise a north-south or east-west line keeps it over a line in another + direction, then the longer centerline (inside its footprint), then the + lower index. + + A loser that ends in the overlap is trimmed back before splitting + (end_claims); a loser that passes through has the overlap cut out of its + plots and subplots after splitting (cut_claims). + """ + idx = sorted(matches) + if not idx: + return {}, {} + geoms = shapely.force_2d(footprints.geometry.values[idx]) + line_geoms = lines.geometry + info = [_overlap_line_info(geoms[k], line_geoms.iloc[matches[i]], i) for k, i in enumerate(idx)] + left, right = shapely.STRtree(geoms).query(geoms, predicate="intersects") + + end_claims, cut_claims = {}, {} + for i, j in zip(left, right): + if i >= j: + continue + for part in shapely.get_parts(shapely.intersection(geoms[i], geoms[j])): + if part.geom_type != "Polygon" or part.area <= algo_fp.MIN_PIECE_AREA: + continue + i_ends, j_ends = _ends_in(info[i], part), _ends_in(info[j], part) + if i_ends != j_ends: + loser, loser_ends = (i if i_ends else j), True + else: + loser, loser_ends = (j if info[i][2] < info[j][2] else i), i_ends + claims = end_claims if loser_ends else cut_claims + claims.setdefault(int(idx[loser]), []).append(part) + return _union_claims(end_claims), _union_claims(cut_claims) + + +def trim_ending_lines(inputs, end_claims): + """ + Trim footprints and centerlines that end in overlaps they give up. + + Args: + inputs: {footprint index: (footprint, line)} + end_claims: {footprint index: overlap area it gives up at its line ends} + + Returns: + inputs with trimmed footprints and centerlines; footprint is None when + nothing is left. Pieces cut off beyond the far side of the other + footprint are dropped, so every plot holds only its own footprint. + + """ + trimmed = dict(inputs) + for fp_idx, claim in end_claims.items(): + footprint, line = inputs[fp_idx] + centerline = algo_fp.prepare_centerline(line, footprint) + if centerline is None: + continue + footprint, centerline, leftovers = algo_fp.trim_line_ends(footprint, centerline, claim) + trimmed[fp_idx] = (footprint, centerline) + if leftovers: + area = sum(piece.area for piece in leftovers) + logger.info(f"Footprint {fp_idx}: dropped {area:.2f} m2 beyond the overlap it gives up.") + return trimmed + + +def _union_claims(claims): + return {fp_idx: shapely.union_all(parts) for fp_idx, parts in claims.items()} + + +def _overlap_line_info(footprint, line, fp_idx): + """Return (centerline end points, end tolerance, priority key) of one footprint for overlap_claims.""" + centerline = algo_fp.prepare_centerline(line, footprint) + if centerline is None: + return [], 0.0, (True, 0.0, int(fp_idx)) + + ends = [shapely.Point(centerline.coords[0]), shapely.Point(centerline.coords[-1])] + # a footprint reaches about half its width past the centerline end + tolerance = max(algo_fp.estimate_width(footprint, centerline) / 2, MIN_END_TOLERANCE) + priority = (not algo_fp.is_cardinal(centerline), -centerline.length, int(fp_idx)) + return ends, tolerance, priority + + +def _ends_in(line_info, part): + ends, tolerance, _ = line_info + return any(part.distance(end) <= tolerance for end in ends) + + +# task executed in a worker process +def footprint_plots_worker(in_args): + attrs, footprint, line, mode, size, cut_claim = in_args + centerline = algo_fp.prepare_centerline(line, footprint) + if centerline is None: + logger.warning(f"Footprint {attrs[UNIQUE_ID]}: no usable centerline inside footprint, skipped.") + return [], [] + + width = algo_fp.estimate_width(footprint, centerline) + if width <= 0: + return [], [] + lengths = algo_fp.area_mode_lengths(width, *size) if mode == algo_fp.MODE_AREA else size + + plots, subplots = algo_fp.split_footprint(footprint, centerline, *lengths) + if cut_claim is not None: + subplots = algo_fp.remove_overlap(subplots, cut_claim) + plots = algo_fp.plots_from_subplots(plots, subplots) + plots = _clean_pieces(plots) + subplots = _clean_pieces(subplots) + plot_records = [ + {**attrs, "side": side, "plot_id": plot_idx, "length": length, "est_width": width, "geometry": geom} + for plot_idx, side, length, geom in plots + ] + subplot_records = [ + { + **attrs, + "side": side, + "plot_id": plot_idx, + "subplot_id": subplot_idx, + "length": length, + "est_width": width, + "geometry": geom, + } + for plot_idx, side, subplot_idx, length, geom in subplots + ] + return plot_records, subplot_records + + +def _clean_pieces(pieces): + """Remove zero-width spikes from plot or subplot geometries (the last tuple item).""" + cleaned = [] + for *keys, geom in pieces: + geom = algo_fp.clean_polygon(geom) + if geom is not None: + cleaned.append((*keys, geom)) + return cleaned + + +def _rename_fid(gdf): + return gdf.rename(columns={"fid": "orig_fid"}) if "fid" in gdf.columns else gdf + + +def _to_segline_layers(plot_records, subplot_records, crs): + """ + Number plots and subplots and add the SegLine measure columns. + + As in SegLine, plot_id and subplot_id are unique across the whole output and + increase along each line. length is measured along the centerline, perimeter + is the polygon perimeter, plot_area is the area of the plot side and + subplot_area the subplot's own area. + """ + plots = gpd.GeoDataFrame(plot_records, geometry="geometry", crs=crs) + subplots = gpd.GeoDataFrame(subplot_records, geometry="geometry", crs=crs) + if subplots.empty: + return plots, subplots + + plot_keys = ["_fp", "plot_id"] + subplots = subplots.sort_values([*plot_keys, "side", "subplot_id"]).reset_index(drop=True) + plot_ids = {key: i for i, key in enumerate(subplots[plot_keys].drop_duplicates().itertuples(index=False))} + subplots["plot_id"] = [plot_ids[key] for key in subplots[plot_keys].itertuples(index=False)] + subplots["subplot_id"] = subplots.index + plots["plot_id"] = [plot_ids[key] for key in plots[plot_keys].itertuples(index=False)] + plots = plots.sort_values(["plot_id", "side"]).reset_index(drop=True) + + for gdf in (plots, subplots): + gdf["area"] = gdf.geometry.area.round(1) + gdf["length"] = gdf["length"].round(1) + gdf["perimeter"] = gdf.geometry.length.round(1) + gdf["est_width"] = gdf["est_width"].round(2) + plots["plot_area"] = plots["area"] + subplots["plot_area"] = subplots.groupby([UNIQUE_ID, "plot_id", "side"])["area"].transform("sum").round(1) + subplots["subplot_area"] = subplots["area"] + + return plots.drop(columns="_fp"), subplots.drop(columns="_fp") + + +if __name__ == "__main__": + import time + + from beratools.utility.tool_args import compose_tool_kwargs + + start_time = time.time() + kwargs = compose_tool_kwargs("footprint_plots") + footprint_plots(**kwargs) + print("Elapsed time: {}".format(time.time() - start_time)) diff --git a/beratools/modules/mapping/ground_footprint.py b/beratools/modules/mapping/ground_footprint.py new file mode 100644 index 0000000..3c38a6d --- /dev/null +++ b/beratools/modules/mapping/ground_footprint.py @@ -0,0 +1,516 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng, Maverick Fong + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + This file hosts the ground_footprint tool. +""" + +import logging +import math +from itertools import chain + +import geopandas as gpd +import numpy as np +import pandas as pd +import pyogrio.errors +import shapely.geometry as sh_geom +import shapely.ops as sh_ops + +import beratools.core.constants as bt_const +import beratools.modules.mapping.algo_common as algo_common +import beratools.utility.spatial_common as sp_common +import beratools.utility.unit_conversion as unit_conversion +from beratools.core.tool_base import execute_multiprocessing +from beratools.modules.mapping.algo_line_grouping import LineGrouping +from beratools.modules.mapping.algo_merge_lines import custom_line_merge +from beratools.modules.mapping.algo_split_with_lines import LineSplitter +from beratools.utility.tool_args import CallMode + +LOGGER_NAME="ground_footprint" +logger = logging.getLogger(LOGGER_NAME) + +FP_FIXED_WIDTH_DEFAULT = 5.0 + + +def prepare_line_args(line_gdf, poly_gdf, n_samples, offset, width_percentile): + """ + Generate arguments for each line in the GeoDataFrame. + + Args: + line_gdf + poly_gdf + n_samples + offset + + Returns: + line_args : list + row : + inter_poly : + n_samples : + offset : + width_percentile : + + """ + spatial_index = poly_gdf.sindex + line_args = [] + + for idx in line_gdf.index: + row = line_gdf.loc[[idx]] + line = row.geometry.iloc[0] + + # Skip rows where geometry is None + if line is None: + print(row) + continue + + inter_poly = poly_gdf.loc[spatial_index.query(line)] + if bt_const.BT_GROUP in inter_poly.columns: + inter_poly = inter_poly[inter_poly[bt_const.BT_GROUP] == row[bt_const.BT_GROUP].values[0]] + + try: + line_args.append([row, inter_poly, n_samples, offset, width_percentile]) + except Exception as e: + print(e) + + return line_args + + +# Calculating Line Widths +def generate_sample_points(line, n_samples=10): + """ + Generate evenly spaced points along a line. + + Args: + line (LineString): The line along which to generate points. + n_samples (int): The number of points to generate (default is 10). + + Returns: + list: List of shapely Point objects. + + """ + # TODO: determine line type + try: + pts = line.coords + except Exception as e: # TODO: check the code + print(e) + line = sh_ops.linemerge(line) + tuple_coord = sh_geom.mapping(line)["coordinates"] + pts = list(chain(*tuple_coord)) + + return [sh_geom.Point(item) for item in pts] + + +def process_single_line(line_arg): + row = line_arg[0] + inter_poly = line_arg[1] + n_samples = line_arg[2] + offset = line_arg[3] + width_percentile = line_arg[4] + + # TODO: deal with case when inter_poly is empty + try: + widths, line, perp_lines, perp_lines_original = calculate_average_width( + row.iloc[0].geometry, inter_poly, offset, n_samples + ) + except Exception as e: + print(e) + return None + + # Calculate the 75th percentile width + # filter zeros in width array + arr_filter = [False if math.isclose(i, 0.0) else True for i in widths] + widths = widths[arr_filter] + + q3_width = FP_FIXED_WIDTH_DEFAULT + q4_width = FP_FIXED_WIDTH_DEFAULT + try: + # TODO: check the code. widths is empty + if len(widths) > 0: + q3_width = np.percentile(widths, width_percentile) + q4_width = np.percentile(widths, 90) + except Exception as e: + print(e) + + # Store the 75th percentile width as a new attribute + row["avg_width"] = q3_width + row["max_width"] = q4_width + + row["geometry"] = line + try: + row["perp_lines"] = perp_lines + row["perp_lines_original"] = perp_lines_original + except Exception as e: + print(e) + + return row + + +def generate_fixed_width_footprint(line_gdf, max_width=False): + """ + Create a buffer around each line. + + In the GeoDataFrame using its 'max_width' attribute and + saves the resulting polygons in a new shapefile. + + Args: + line_gdf: GeoDataFrame containing LineString with 'max_width' attribute. + max_width: Use max width or not to produce buffer. + + """ + # Create a new GeoDataFrame with the buffer polygons + buffer_gdf = line_gdf.copy(deep=True) + + mean_avg_width = line_gdf["avg_width"].mean() + mean_max_width = line_gdf["max_width"].mean() + + # Use .loc to avoid chained assignment + line_gdf.loc[line_gdf["avg_width"].isna(), "avg_width"] = mean_avg_width + line_gdf.loc[line_gdf["max_width"].isna(), "max_width"] = mean_max_width + + line_gdf.loc[line_gdf["avg_width"] == 0.0, "avg_width"] = mean_avg_width + line_gdf.loc[line_gdf["max_width"] == 0.0, "max_width"] = mean_max_width + + if not max_width: + print("Using quantile 75% width") + buffer_gdf["geometry"] = line_gdf.apply( + lambda row: row.geometry.buffer(row.avg_width / 2) if row.geometry is not None else None, + axis=1, + ) + else: + print("Using quantile 90% + 20% width") + buffer_gdf["geometry"] = line_gdf.apply( + lambda row: row.geometry.buffer(row.max_width * 1.2 / 2) if row.geometry is not None else None, + axis=1, + ) + + return buffer_gdf + + +def calculate_average_width(line, in_poly, offset, n_samples): + """Calculate the average width of a polygon perpendicular to the given line.""" + # Smooth the line + try: + line = line.simplify(0.1) + + valid_widths = 0 + sample_points = generate_sample_points(line, n_samples=n_samples) + sample_points_pairs = list(zip(sample_points[:-2], sample_points[1:-1], sample_points[2:])) + widths = np.zeros(len(sample_points_pairs)) + perp_lines = [] + perp_lines_original = [] + except Exception as e: + print(e) + + try: + for i, points in enumerate(sample_points_pairs): + try: + perp_line = algo_common.generate_perpendicular_line_precise(points, offset=offset) + perp_lines_original.append(perp_line) + except Exception as e: + print(f"Failed to generate perpendicular at index {i}: {e}") + perp_lines_original.append(None) + continue + + try: + polygon_intersect = in_poly.iloc[in_poly.sindex.query(perp_line)] + intersections = polygon_intersect.intersection(perp_line) + except Exception as e: + print(f"Failed intersection at index {i}: {e}") + intersections = [] + + line_list = [] + for inter in intersections: + if inter.is_empty: + continue + + if isinstance(inter, sh_geom.GeometryCollection): + for item in inter.geoms: + if isinstance(item, sh_geom.LineString): + line_list.append(item) + elif isinstance(inter, sh_geom.MultiLineString): + line_list += list(inter.geoms) + else: + line_list.append(inter) + + perp_lines += line_list + + if isinstance(line_list, sh_geom.GeometryCollection): + print("Found 2: GeometryCollection") + + for item in line_list: + widths[i] = max(widths[i], item.length) + valid_widths += 1 + + # Todo: check missing perpendicular lines + # if len(perp_lines_original) < len(sample_points_pairs): + # print(f"Missing perpendicular at index {i}") + + except Exception as e: + print(f"loop: {e}") + + return ( + widths, + line, + sh_geom.MultiLineString(perp_lines), + sh_geom.MultiLineString(perp_lines_original), + ) + + +def ground_footprint( + in_line, + in_footprint, + n_samples, + offset, + max_width, + out_footprint, + in_layer_lc_path="least_cost_path", + merge_group=True, + merge_by_original_line=False, + width_percentile=75, + trim_output=True, + processes=0, + call_mode=CallMode.CLI, + log_level="INFO", +): + in_file, in_layer = sp_common.decode_file_layer(in_line) + in_fp_file, in_layer_fp = sp_common.decode_file_layer(in_footprint) + out_file, out_layer = sp_common.decode_file_layer(out_footprint) + + n_samples = int(n_samples) + offset = float(offset) + width_percentile = int(width_percentile) + + if not sp_common.check_vector_vector_extent_overlap(in_file, in_layer, in_fp_file, in_layer_fp): + print("Input line extent does not overlap input footprint extent.") + return + + # TODO: refactor this code for better line quality check + line_gdf = gpd.read_file(in_file, layer=in_layer) + if "fid" in line_gdf.columns: + line_gdf = line_gdf.rename(columns={"fid": "orig_fid"}) + line_gdf = algo_common.clean_geometries(line_gdf, stage="input") + line_gdf = line_gdf.reset_index(drop=True) + offset = unit_conversion.convert_meters_param_projected( + line_gdf, + offset, + "Perpendicular line length (m)", + min_value=bt_const.SMALL_BUFFER, + ) + + # group by original line, as the centerline tool merges, so pieces share one footprint + merge_by_original_line = str(merge_by_original_line).strip().lower() in ("true", "1", "yes") + if merge_by_original_line and "OLnFID" not in line_gdf.columns: + print("[Warning]: OLnFID not found in input lines; lines are not merged by original line.") + merge_by_original_line = False + if merge_by_original_line: + line_gdf[bt_const.BT_GROUP] = line_gdf["OLnFID"] + + if bt_const.BT_GROUP not in line_gdf.columns: + line_gdf[bt_const.BT_GROUP] = range(1, len(line_gdf) + 1) + + use_least_cost_path = True + try: + lc_path_gdf = gpd.read_file(in_file, layer=in_layer_lc_path) + if "fid" in lc_path_gdf.columns: + lc_path_gdf = lc_path_gdf.rename(columns={"fid": "orig_fid"}) + lc_path_gdf = algo_common.clean_geometries(lc_path_gdf, stage="input") + lc_path_gdf = lc_path_gdf.reset_index(drop=True) + if merge_by_original_line and "OLnFID" in lc_path_gdf.columns: + lc_path_gdf[bt_const.BT_GROUP] = lc_path_gdf["OLnFID"] + except (ValueError, OSError, pyogrio.errors.DataLayerError): + print(f"Layer '{in_layer_lc_path}' not found in {in_file}, skipping least cost path logic.") + use_least_cost_path = False + + if not merge_group: + line_gdf["geometry"] = line_gdf.geometry.apply(custom_line_merge) + if use_least_cost_path: + lc_path_gdf["geometry"] = lc_path_gdf.geometry.apply(custom_line_merge) + + # read footprints and remove holes + poly_gdf = gpd.read_file(in_fp_file, layer=in_layer_fp) + if "fid" in poly_gdf.columns: + poly_gdf = poly_gdf.rename(columns={"fid": "orig_fid"}) + poly_gdf = algo_common.clean_geometries(poly_gdf, stage="input") + poly_gdf = poly_gdf.reset_index(drop=True) + poly_gdf["geometry"] = poly_gdf["geometry"].apply(algo_common.remove_holes) + # polygons are matched to lines by BT_GROUP, so keep their groups the same as the lines' + if merge_by_original_line and "OLnFID" in poly_gdf.columns: + poly_gdf[bt_const.BT_GROUP] = poly_gdf["OLnFID"] + + if not sp_common.compare_crs( + sp_common.vector_crs(in_file, in_layer), sp_common.vector_crs(in_fp_file, in_layer_fp) + ): + print("Input line and footprint have different spatial references, please check.") + return + + if not sp_common.check_vector_vector_overlap(line_gdf, poly_gdf): + print("Input line(s) do not overlap input footprint.") + return + + # merge group and/or split lines at intersections + merged_line_gdf = line_gdf.copy(deep=True) + if merge_group: + lg = LineGrouping(line_gdf, merge_group) + lg.run_grouping() + merged_line_gdf = lg.run_line_merge() + else: + try: + lg = LineGrouping(line_gdf, not merge_group) + lg.run_grouping() + merged_line_gdf = lg.run_line_merge() + splitter = LineSplitter(merged_line_gdf) + splitter.process() + splitter.save_to_geopackage( + out_footprint, + line_layer="split_centerline", + intersection_layer="inter_points", + invalid_layer="invalid_splits", + ) + + # least cost path merge and split + if use_least_cost_path: + lg_leastcost = LineGrouping(lc_path_gdf, not merge_group) + lg_leastcost.run_grouping() + merged_lc_path_gdf = lg_leastcost.run_line_merge() + splitter_leastcost = LineSplitter(merged_lc_path_gdf) + splitter_leastcost.process(splitter.intersection_gdf) + + splitter_leastcost.save_to_geopackage( + out_footprint, + line_layer="split_leastcost", + ) + + lg = LineGrouping(splitter.split_lines_gdf, merge_group) + lg.run_grouping() + merged_line_gdf = lg.run_line_merge() + except ValueError as e: + print(f"Exception: ground_footprint: {e}") + + # save original merged lines + merged_line_gdf = algo_common.clean_geometries( + merged_line_gdf, + stage="output", + out_file=out_file, + layer="rejected_output_ground_merged_lines", + ) + merged_line_gdf.to_file(out_file, layer="merged_lines_original") + + # prepare line arguments + line_args = prepare_line_args(merged_line_gdf, poly_gdf, n_samples, offset, width_percentile) + + out_lines = execute_multiprocessing( + process_single_line, line_args, "Fixed footprint", processes, call_mode + ) + line_attr = pd.concat(out_lines) + + # Ensure BT_GROUP is present in line_attr + if bt_const.BT_GROUP not in line_attr.columns: + raise ValueError("BT_GROUP column is required in line_attr but is missing.") + + # update avg_width and max_width by max value of group + if not merge_group: + group_max = ( + line_attr.groupby(bt_const.BT_GROUP).agg({"avg_width": "max", "max_width": "max"}).reset_index() + ) + + # Merge the result back to the original dataframe based on 'group' + line_attr = line_attr.merge(group_max, on=bt_const.BT_GROUP, suffixes=("", "_max")) + + # Overwrite the original columns directly with the max values + line_attr["avg_width"] = line_attr["avg_width_max"] + line_attr["max_width"] = line_attr["max_width_max"] + + # Drop the temporary max columns + line_attr.drop(columns=["avg_width_max", "max_width_max"], inplace=True) + + # create fixed width footprint (always assign buffer_gdf) + print("Step: Generating fixed width footprints") + buffer_gdf = generate_fixed_width_footprint(line_attr, max_width=max_width) + + # reserve all layers for output + perp_lines_gdf = buffer_gdf.copy(deep=True) + perp_lines_original_gdf = buffer_gdf.copy(deep=True) + + # Save untrimmed fixed width footprint + buffer_gdf = buffer_gdf.drop(columns=["perp_lines"]) + buffer_gdf = buffer_gdf.drop(columns=["perp_lines_original"]) + buffer_gdf = buffer_gdf.set_crs(perp_lines_gdf.crs, allow_override=True) + buffer_gdf.reset_index(inplace=True, drop=True) + + untrimmed_footprint = "untrimmed_footprint" + buffer_gdf = algo_common.clean_geometries( + buffer_gdf, + stage="output", + out_file=out_file, + layer="rejected_output_ground_untrimmed_footprint", + ) + buffer_gdf.to_file(out_file, layer=untrimmed_footprint) + print(f"Untrimmed fixed width footprint saved as '{untrimmed_footprint}'") + + # trim lines and footprints + if trim_output: + lg.run_cleanup(buffer_gdf) + + # Ensure only polygons are saved in clean_footprint + def ensure_polygons(gdf, buffer_width=0.01): + gdf["geometry"] = gdf["geometry"].apply( + lambda geom: geom.buffer(buffer_width) + if geom.geom_type in ["LineString", "MultiLineString"] + else geom + ) + gdf = gdf[gdf.geometry.type.isin(["Polygon", "MultiPolygon"])] + return gdf + + # Patch: after trimming, ensure polygons in clean_footprint layer + if hasattr(lg, "merged_lines_trimmed") and lg.merged_lines_trimmed is not None: + lg.merged_lines_trimmed = ensure_polygons(lg.merged_lines_trimmed) + print("Step: Saving trimmed outputs") + lg.save_file(out_file, out_layer) + else: + print("Skipping line and footprint trimming per user option.") + + # perpendicular lines + layer = "perp_lines" + out_aux_gpkg = algo_common.get_aux_path(out_file) + perp_lines_gdf = perp_lines_gdf.set_geometry("perp_lines") + perp_lines_gdf = perp_lines_gdf.drop(columns=["perp_lines_original"]) + perp_lines_gdf = perp_lines_gdf.drop(columns=["geometry"]) + perp_lines_gdf = perp_lines_gdf.set_crs(buffer_gdf.crs, allow_override=True) + perp_lines_gdf.to_file(out_aux_gpkg, layer=layer) + + layer = "perp_lines_original" + perp_lines_original_gdf = perp_lines_original_gdf.set_geometry("perp_lines_original") + perp_lines_original_gdf = perp_lines_original_gdf.drop(columns=["perp_lines"]) + perp_lines_original_gdf = perp_lines_original_gdf.drop(columns=["geometry"]) + perp_lines_original_gdf = perp_lines_original_gdf.set_crs(buffer_gdf.crs, allow_override=True) + perp_lines_original_gdf.to_file(out_aux_gpkg, layer=layer) + + layer = "centerline_simplified" + # Drop perp_lines_original column if present to avoid export warnings + if "perp_lines_original" in line_attr.columns: + line_attr = line_attr.drop(columns=["perp_lines_original"]) + line_attr = line_attr.drop(columns="perp_lines") + line_attr.to_file(out_aux_gpkg, layer=layer) + + # save footprints without holes + poly_gdf.to_file(out_aux_gpkg, layer="footprint_no_holes") + print("Step: Finished fixed width footprint tool") + + +if __name__ == "__main__": + import time + + from beratools.utility.tool_args import compose_tool_kwargs + + start_time = time.time() + kwargs = compose_tool_kwargs("ground_footprint") + ground_footprint(**kwargs) + print("Elapsed time: {}".format(time.time() - start_time)) diff --git a/beratools/modules/mapping/line_footprint_functions.py b/beratools/modules/mapping/line_footprint_functions.py new file mode 100644 index 0000000..e4d8b28 --- /dev/null +++ b/beratools/modules/mapping/line_footprint_functions.py @@ -0,0 +1,933 @@ +# --------------------------------------------------------------------------- +# Copyright (C) 2021 Applied Geospatial Research Group +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +# --------------------------------------------------------------------------- +# +# Refactor to use for produce dynamic footprint from dynamic canopy and cost raster with open source libraries +# Prerequisite: Line feature class must have the attribute Fields:"CorridorTh" "DynCanTh" "OLnFID" +# line_footprint_function.py +# Maverick Fong +# Date: 2023-Dec +# This script is part of the BERA toolset +# Webpage: https://github.com/ +# +# Purpose: Creates dynamic footprint polygons for each input line based on a least +# cost corridor method and individual line thresholds. +# +# --------------------------------------------------------------------------- + +from multiprocessing.pool import Pool +from pathlib import Path + +import numpy as np +import pandas as pd +import rasterio +from geopandas import GeoDataFrame +from rasterio import features +from rasterio.mask import mask +from scipy import ndimage +from shapely import LineString, MultiPolygon, Point, buffer +from shapely.geometry import shape +from skimage.graph import MCP_Flexible + +from beratools.utility.faulthandler_pause import faulthandler_paused + +# xrspatial imports scipy.fft, whose import on Windows raises access violations that it catches +# itself; see faulthandler_pause +with faulthandler_paused(): + from xrspatial import convolution + +import beratools.modules.mapping.algo_common as algo_common +from beratools.core.constants import ( + BT_DEBUGGING, + BT_NODATA, + FP_CORRIDOR_THRESHOLD, + LP_SEGMENT_LENGTH, + ParallelMode, +) +from beratools.core.tool_base import parallel_mode +from beratools.modules.mapping.algo_centerline import find_centerlines, find_corridor_polygon +from beratools.modules.mapping.canopy_threshold_relative import OperationCancelledException +from beratools.modules.mapping.common import ( + PARALLEL_MODE, + dyn_fs_raster_stdmean, + dyn_np_cc_map, + dyn_np_cost_raster, + dyn_smooth_cost, + generate_line_args_DFP_NoClip, + remove_nan_from_array, + split_into_equal_Nth_segments, +) +from beratools.utility.spatial_common import ( + clip_raster, + compare_crs, + decode_file_layer, + raster_crs, + vector_crs, +) + + +def dyn_canopy_cost_raster(args): + in_chm_raster = args[0] + DynCanTh = args[1] + tree_radius = args[2] + max_line_dist = args[3] + canopy_avoid = args[4] + exponent = args[5] + nodata = args[7] + line_df = args[8] + out_meta = args[9] + line_id = args[10] + Cut_Dist = args[11] + Side = args[12] + canopy_thresh_percentage = float(args[13]) / 100 + line_buffer = args[14] + exp_shk_cell=args[15] + + if Side == "Left": + canopy_ht_threshold = line_df.CL_CutHt.iloc[0] * canopy_thresh_percentage + elif Side == "Right": + canopy_ht_threshold = line_df.CR_CutHt.iloc[0] * canopy_thresh_percentage + elif Side == "Center": + canopy_ht_threshold = DynCanTh * canopy_thresh_percentage + else: + canopy_ht_threshold = 0.5 + + canopy_ht_threshold = float(canopy_ht_threshold) + if canopy_ht_threshold <= 0: + canopy_ht_threshold = 0.5 + tree_radius = float(tree_radius) # get the round up integer number for tree search radius + max_line_dist = float(max_line_dist) + canopy_avoid = float(canopy_avoid) + cost_raster_exponent = float(exponent) + + try: + clipped_rasterC, out_meta = clip_raster(in_chm_raster, line_buffer, 0) + + in_chm = np.squeeze(clipped_rasterC, axis=0) + if BT_DEBUGGING: + print('[Debug]: Loading CHM ...') + cell_x, cell_y = out_meta["transform"][0], -out_meta["transform"][4] + + if BT_DEBUGGING: + print('[Debug]: Preparing Kernel window ...') + kernel = convolution.circle_kernel(cell_x, cell_y, int(tree_radius)) + + # Generate Canopy Raster and return the Canopy array + if BT_DEBUGGING: + print('[Debug]: Generate Canopy Raster ...') + dyn_canopy_ndarray = dyn_np_cc_map(in_chm, canopy_ht_threshold, BT_NODATA) + + # Calculating focal statistic from canopy raster + if BT_DEBUGGING: + print('[Debug]: Calculating focal statistic from Canopy Raster ...') + cc_std, cc_mean = dyn_fs_raster_stdmean(dyn_canopy_ndarray, kernel, BT_NODATA) + + # Smoothing raster + if BT_DEBUGGING: + print('[Debug]: Generating smoothed cost raster ...') + cc_smooth = dyn_smooth_cost(dyn_canopy_ndarray, max_line_dist, [cell_x, cell_y]) + avoidance = max(min(float(canopy_avoid), 1), 0) + cost_clip = dyn_np_cost_raster( + dyn_canopy_ndarray, + cc_mean, + cc_std, + cc_smooth, + avoidance, + cost_raster_exponent, + ) + negative_cost_clip = np.where( + np.isnan(cost_clip), -9999, cost_clip + ) # TODO was nodata, changed to BT_NODATA_COST + return ( + line_df, + dyn_canopy_ndarray, + negative_cost_clip, + out_meta, + max_line_dist, + nodata, + line_id, + Cut_Dist, + line_buffer, + exp_shk_cell + ) + + except Exception as e: + print("[Error]: Error in creating (dynamic) cost raster @ {}: {}".format(line_id, e)) + return None + + +def split_line_fc(line): + return list(map(LineString, zip(line.coords[:-1], line.coords[1:]))) + + +def split_line_npart(line): + # Work out n parts for each line (divided by LP_SEGMENT_LENGTH) + n = int(np.ceil(line.length / LP_SEGMENT_LENGTH)) + if n > 1: + # divided line into n-1 equal parts; + distances = np.linspace(0, line.length, n) + points = [line.interpolate(distance) for distance in distances] + line = LineString(points) + mline = split_line_fc(line) + else: + mline = line + return mline + + +def split_into_segments(df): + odf = df + crs = odf.crs + if "OLnSEG" not in odf.columns.array: + df["OLnSEG"] = np.nan + + df = odf.assign(geometry=odf.apply(lambda x: split_line_fc(x.geometry), axis=1)) + df = df.explode() + + df["OLnSEG"] = df.groupby("OLnFID").cumcount() + gdf = GeoDataFrame(df, geometry=df.geometry, crs=crs) + gdf = gdf.sort_values(by=["OLnFID", "OLnSEG"]) + gdf = gdf.reset_index(drop=True) + return gdf + + +def split_into_equal_nth_segments(df): + odf = df + crs = odf.crs + if "OLnSEG" not in odf.columns.array: + df["OLnSEG"] = np.nan + df = odf.assign(geometry=odf.apply(lambda x: split_line_npart(x.geometry), axis=1)) + df = df.explode(index_parts=True) + + df["OLnSEG"] = df.groupby("OLnFID").cumcount() + gdf = GeoDataFrame(df, geometry=df.geometry, crs=crs) + gdf = gdf.sort_values(by=["OLnFID", "OLnSEG"]) + gdf = gdf.reset_index(drop=True) + return gdf + + +def generate_line_args( + line_seg, + work_in_bufferL, + work_in_bufferC, + raster, + tree_radius, + max_line_dist, + canopy_avoidance, + exponent, + work_in_bufferR, + canopy_thresh_percentage, +): + line_argsL = [] + line_argsR = [] + line_argsC = [] + line_id = 0 + for record in range(0, len(work_in_bufferL)): + line_bufferL = work_in_bufferL.loc[record, "geometry"] + line_bufferC = work_in_bufferC.loc[record, "geometry"] + LCut = work_in_bufferL.loc[record, "LDist_Cut"] + + clipped_rasterL, out_transformL = mask( + raster, [line_bufferL], crop=True, nodata=BT_NODATA, filled=True + ) + clipped_rasterL = np.squeeze(clipped_rasterL, axis=0) + + clipped_rasterC, out_transformC = mask( + raster, [line_bufferC], crop=True, nodata=BT_NODATA, filled=True + ) + + clipped_rasterC = np.squeeze(clipped_rasterC, axis=0) + + # make rasterio meta for saving raster later + out_metaL = raster.meta.copy() + out_metaL.update( + { + "driver": "GTiff", + "height": clipped_rasterL.shape[0], + "width": clipped_rasterL.shape[1], + "nodata": BT_NODATA, + "transform": out_transformL, + } + ) + + out_metaC = raster.meta.copy() + out_metaC.update( + { + "driver": "GTiff", + "height": clipped_rasterC.shape[0], + "width": clipped_rasterC.shape[1], + "nodata": BT_NODATA, + "transform": out_transformC, + } + ) + + nodata = BT_NODATA + line_argsL.append( + [ + clipped_rasterL, + float(work_in_bufferL.loc[record, "DynCanTh"]), + float(tree_radius), + float(max_line_dist), + float(canopy_avoidance), + float(exponent), + raster.res, + nodata, + line_seg.iloc[[record]], + out_metaL, + line_id, + LCut, + "Left", + canopy_thresh_percentage, + line_bufferC, + ] + ) + + line_argsC.append( + [ + clipped_rasterC, + float(work_in_bufferC.loc[record, "DynCanTh"]), + float(tree_radius), + float(max_line_dist), + float(canopy_avoidance), + float(exponent), + raster.res, + nodata, + line_seg.iloc[[record]], + out_metaC, + line_id, + 10, + "Center", + canopy_thresh_percentage, + line_bufferC, + ] + ) + + print(' "PROGRESS_LABEL Preparing line arguments... {} of {}" '.format( + line_id ,len(work_in_bufferL) + len(work_in_bufferR)), + flush=True ) + print(" {}% ".format( + (line_id / (len(work_in_bufferL) + len(work_in_bufferR))) * 100) + ,flush=True ) + + line_id += 1 + + line_id = 0 + for record in range(0, len(work_in_bufferR)): + line_bufferR = work_in_bufferR.loc[record, "geometry"] + RCut = work_in_bufferR.loc[record, "RDist_Cut"] + clipped_rasterR, out_transformR = mask( + raster, [line_bufferR], crop=True, nodata=BT_NODATA, filled=True + ) + clipped_rasterR = np.squeeze(clipped_rasterR, axis=0) + + # make rasterio meta for saving raster later + out_metaR = raster.meta.copy() + out_metaR.update( + { + "driver": "GTiff", + "height": clipped_rasterR.shape[0], + "width": clipped_rasterR.shape[1], + "nodata": BT_NODATA, + "transform": out_transformR, + } + ) + line_bufferC = work_in_bufferC.loc[record, "geometry"] + clipped_rasterC, out_transformC = mask( + raster, [line_bufferC], crop=True, nodata=BT_NODATA, filled=True + ) + + clipped_rasterC = np.squeeze(clipped_rasterC, axis=0) + out_metaC = raster.meta.copy() + out_metaC.update( + { + "driver": "GTiff", + "height": clipped_rasterC.shape[0], + "width": clipped_rasterC.shape[1], + "nodata": BT_NODATA, + "transform": out_transformC, + } + ) + + nodata = BT_NODATA + # TODO deal with inherited nodata and BT_NODATA_COST + # TODO convert nodata to BT_NODATA_COST + line_argsR.append( + [ + clipped_rasterR, + float(work_in_bufferR.loc[record, "DynCanTh"]), + float(tree_radius), + float(max_line_dist), + float(canopy_avoidance), + float(exponent), + raster.res, + nodata, + line_seg.iloc[[record]], + out_metaR, + line_id, + RCut, + "Right", + canopy_thresh_percentage, + line_bufferC, + ] + ) + + print( + ' "PROGRESS_LABEL Preparing line arguments... {} of {}" '.format( + line_id + 1 + len(work_in_bufferL), + len(work_in_bufferL) + len(work_in_bufferR), + ), + flush=True, + ) + print( + " {}% ".format( + (line_id + 1 + len(work_in_bufferL)) / (len(work_in_bufferL) + len(work_in_bufferR)) * 100 + ), + flush=True, + ) + + line_id += 1 + + return line_argsL, line_argsR, line_argsC + + +# +# def find_corridor_threshold_boundary(canopy_clip, least_cost_path, corridor_raster): +# threshold = -1 +# thresholds = [-1] * 10 +# +# # morphological filters to get polygons from canopy raster +# canopy_bin = np.where(np.isclose(canopy_clip, 1.0), True, False) +# clean_holes = remove_small_holes(canopy_bin) +# clean_obj = remove_small_objects(clean_holes) +# +# polys = features.shapes(skimage.img_as_ubyte(clean_obj), mask=clean_obj) +# polys = [shape(poly).segmentize(FP_SEGMENTIZE_LENGTH) for poly, _ in polys] +# +# # perpendicular segments intersections with polygons +# size = corridor_raster.shape +# pts = [] +# for poly in polys: +# pts.extend(list(poly.exterior.coords)) +# +# index_0 = [] +# index_1 = [] +# for pt in pts: +# if int(pt[0]) < size[1] and int(pt[1]) < size[0]: +# index_0.append(int(pt[0])) +# index_1.append(int(pt[1])) +# +# try: +# thresholds = corridor_raster[index_1, index_0] +# except Exception as e: +# print(e) +# +# # trimmed mean of values at intersections +# threshold = stats.trim_mean(thresholds, 0.3) +# +# return threshold + + +def find_corridor_threshold(raster): + """ + Find the optimal corridor threshold by raster histogram. + + Parameters + ---------- + raster : corridor raster + + Returns + ------- + corridor_threshold : float + + """ + corridor_threshold = -1.0 + hist, bins = np.histogram(raster.flatten(), bins=100, range=(0, 100)) + half_count = np.sum(hist) / 2 + sub_count = 0 + + for count, bin_no in zip(hist, bins): + sub_count += count + if sub_count > half_count: + break + + corridor_threshold = bin_no + + return corridor_threshold + + +def process_single_line_relative(segment): + # this function takes single line to generate the line footprint + # Input segment arguments: + # [in_chm, float(work_in_bufferR.loc[record, 'DynCanTh']), float(tree_radius), + # float(max_line_dist), float(canopy_avoidance), float(exponent), raster.res, nodata, + # line_seg.iloc[[record]], out_meta, line_id,RCut,Side,canopy_thresh_percentage,line_buffer] + + # this will change segment content, and parameters will be changed + segment = dyn_canopy_cost_raster(segment) + if segment is None: + return None + # segment: + """ + 0:line_df, + 1:dyn_canopy_ndarray, + 2:negative_cost_clip, + 3:out_meta, + 4:max_line_dist, + 5:nodata, + 6:line_id, + 7:Cut_Dist, + 8: line_buffer, + 9: exp_shk_cell + """ + + # (regardless it process the whole line or individual segment) + df = segment[0] + in_canopy_r = segment[1] + in_cost_r = segment[2] + in_meta = segment[3] + no_data = segment[5] + Cut_Dist = segment[7] + exp_shk_cell=segment[9] + shapefile_proj = df.crs + in_transform = in_meta["transform"] + + if np.isnan(in_canopy_r).all(): + print("Canopy raster empty") + + if np.isnan(in_cost_r).all(): + print("Cost raster empty") + + FID = df["OLnSEG"] # segment line feature ID + OID = df["OLnFID"] # original line ID for segment line + + segment_list = [] + + feat = df.geometry.iloc[0] + for coord in feat.coords: + segment_list.append(coord) + + cell_size_x = in_transform[0] + cell_size_y = -in_transform[4] + + # Work out the corridor from both end of the centerline + try: + # TODO: further investigate and submit issue to skimage + # There is a severe bug in skimage find_costs + # when nan is present in clip_cost_r, find_costs cause access violation + # no message/exception will be caught + # change all nan to BT_NODATA_COST for workaround + if len(in_cost_r.shape) > 2: + in_cost_r = np.squeeze(in_cost_r, axis=0) + remove_nan_from_array(in_cost_r) + in_cost_r[in_cost_r == no_data] = np.inf + + # generate 1m interval points along line + distance_delta = 1 + distances = np.arange(0, feat.length, distance_delta) + multipoint_along_line = [feat.interpolate(distance) for distance in distances] + multipoint_along_line.append(Point(segment_list[-1])) + # Rasterize points along line + rasterized_points_Alongln = features.rasterize( + multipoint_along_line, + out_shape=in_cost_r.shape, + transform=in_transform, + fill=0, + all_touched=True, + default_value=1, + ) + points_Alongln = np.transpose(np.nonzero(rasterized_points_Alongln)) + + # Find minimum cost paths through an N-d costs array. + mcp_flexible1 = MCP_Flexible(in_cost_r, sampling=(cell_size_x, cell_size_y), fully_connected=True) + flex_cost_alongLn, flex_back_alongLn = mcp_flexible1.find_costs(starts=points_Alongln) + + # Generate corridor + corridor = flex_cost_alongLn # +flex_cost_dest #cum_cost_tosource+cum_cost_todestination + corridor = np.ma.masked_invalid(corridor) + + # Calculate minimum value of corridor raster + if np.ma.min(corridor) is not None: + corr_min = float(np.ma.min(corridor)) + else: + corr_min = 0.5 + + # normalize corridor raster by deducting corr_min + corridor_norm = corridor - corr_min + + # Set minimum as zero and save minimum file + # corridor_th_value = find_corridor_threshold(corridor_norm) + corridor_th_value = Cut_Dist / cell_size_x + if corridor_th_value < 0: # if no threshold found, use default value + corridor_th_value = FP_CORRIDOR_THRESHOLD / cell_size_x + + # corridor_th_value = FP_CORRIDOR_THRESHOLD + corridor_thresh = np.ma.where(corridor_norm >= corridor_th_value, 1.0, 0.0) + corridor_thresh_cl = np.ma.where(corridor_norm >= (corridor_th_value + (5 / cell_size_x)), 1.0, 0.0) + + # find contiguous corridor polygon for centerline + corridor_poly_gpd = find_corridor_polygon(corridor_thresh_cl, in_transform, df) + + # Process: Stamp CC and Max Line Width + # Original code here + # RasterClass = SetNull(IsNull(CorridorMin),((CorridorMin) + ((Canopy_Raster) >= 1)) > 0) + temp1 = corridor_thresh + in_canopy_r + raster_class = np.ma.where(temp1 == 0, 1, 0).data + + # BERA proposed Binary morphology + # RasterClass_binary=np.where(RasterClass==0,False,True) + if exp_shk_cell > 0 and cell_size_x < 1: + # Process: Expand + # FLM original Expand equivalent + cell_size = int(exp_shk_cell * 2 + 1) + + expanded = ndimage.grey_dilation(raster_class, size=(cell_size, cell_size)) + + # BERA proposed Binary morphology Expand + # Expanded = ndimage.binary_dilation(RasterClass_binary, iterations=exp_shk_cell,border_value=1) + + # Process: Shrink + # FLM original Shrink equivalent + file_shrink = ndimage.grey_erosion(expanded, size=(cell_size, cell_size)) + + # BERA proposed Binary morphology Shrink + # fileShrink = ndimage.binary_erosion((Expanded),iterations=Exp_Shk_cell,border_value=1) + else: + + file_shrink = raster_class + + # Process: Boundary Clean + clean_raster = ndimage.gaussian_filter(file_shrink, sigma=0, mode="nearest") + + # creat mask for non-polygon area + polygon_mask = np.where(clean_raster == 1, True, False) + if clean_raster.dtype == np.int64: + clean_raster = clean_raster.astype(np.int32) + + # Process: ndarray to shapely Polygon + out_polygon = features.shapes(clean_raster, mask=polygon_mask, transform=in_transform) + + # create a shapely multipolygon + multi_polygon = [] + for poly, value in out_polygon: + multi_polygon.append(shape(poly)) + poly = MultiPolygon(multi_polygon) + + # create a pandas dataframe for the FP + out_data = pd.DataFrame( + { + "OLnFID": OID, + "OLnSEG": FID, + "CorriThresh": corridor_th_value, + "geometry": poly, + } + ) + out_gdata = GeoDataFrame(out_data, geometry="geometry", crs=shapefile_proj) + + return out_gdata, corridor_poly_gpd + + except Exception as e: + print("Exception: {}".format(e)) + + +def multiprocessing_footprint_relative(line_args, processes): + try: + total_steps = len(line_args) + + feats = [] + with Pool(processes=processes) as pool: + step = 0 + # execute tasks in order, process results out of order + for result in pool.imap_unordered(process_single_line_relative, line_args): + if BT_DEBUGGING: + print("Got result: {}".format(result), flush=True) + if result is not None: + feats.append(result) + step += 1 + print( + ' "PROGRESS_LABEL Dynamic Segment Line Footprint {} of {}" '.format(step, total_steps), + flush=True, + ) + print(" {}% ".format(step / total_steps * 100), flush=True) + return feats + except OperationCancelledException: + print("Operation cancelled") + return None + + +def main_line_footprint_relative( + in_line:str, + in_chm: str, + max_ln_width: float, + out_footprint:str, + out_centerline:str, + exp_shk_cell:int, + tree_radius:float, + max_line_dist:float, + canopy_avoidance:float, + exponent:float, + full_step:bool, + canopy_thresh_percentage:int, + processes:int, + debug_mode:bool=BT_DEBUGGING, + merge_by_original_line:bool=False, +)-> None: + """ + Generate dynamic footprints from the input CHM. + + Uses the centerlines with forest canopy height and distance to edge. Optionally, smoothed + centerlines are generated too. + + Args: + in_line: Path like string for input centerlines + in_chm: Path like string input CHM + max_ln_width: Maximum processing width for input lines + out_footprint: Path like string output footprint + out_centerline: (Option) Path like string output centerline + exp_shk_cell: Range as integer used for cell erosion + tree_radius: Radius of trees influence in the cost raster + max_line_dist: Maximum Euclidean distance from canopy + canopy_avoidance: 0 < Ratio < 1 of importance between canopy search radius and Euclidean distance + exponent: Affects the cost of vegetated areas in an exponential fashion + canopy_thresh_percentage: Percentage as integer range 1-100 + merge_by_original_line: Merge outputs sharing an OLnFID into one feature, otherwise + keep one footprint and centerline per input line (OLnFID, OLnSEG) + + Returns: + New saved footprints and/or with smoothed centerlines dataset(s). + """ + in_file, layer = decode_file_layer(in_line) + line_seg = GeoDataFrame.from_file(in_file, layer=layer) + _, processes = parallel_mode(processes) + + # If Dynamic canopy threshold column not found, create one + if "DynCanTh" not in line_seg.columns.array: + print("[Warning]: Field {} is not found and will be populated default values.".format("DynCanTh")) + line_seg['DynCanTh']=3.0 + + if not float(canopy_thresh_percentage): + canopy_thresh_percentage = 50 + else: + canopy_thresh_percentage = float(canopy_thresh_percentage) + + if float(canopy_avoidance) <= 0.0: + canopy_avoidance = 0.0 + if float(exponent) <= 0.0: + exponent = 1.0 + # If OLnFID column is not found, column will be created + if "OLnFID" not in line_seg.columns.array: + print("[info]: Created {} column in input line data.".format("OLnFID")) + line_seg["OLnFID"] = line_seg.index + + if "OLnSEG" not in line_seg.columns.array: + line_seg["OLnSEG"] = 0 + + print("{}%".format(10)) + + # check coordinate systems between line and raster features + with rasterio.open(in_chm) as raster: + if compare_crs(vector_crs(in_file,layer), raster_crs(in_chm)): + proc_segments = False + if proc_segments: + print("[Info]: Splitting lines into segments...") + line_seg_split = split_into_segments(line_seg) + print("[info]: Splitting lines into segments...Done") + else: + if full_step: + print("[info]: Tool runs on input lines......") + line_seg_split = line_seg + else: + print("[info]: Tool runs on input segment lines......") + line_seg_split = split_into_equal_Nth_segments(line_seg, 250) + + print("{}%".format(20)) + + work_in_bufferL1 = GeoDataFrame.copy(line_seg_split) + work_in_bufferL2 = GeoDataFrame.copy(line_seg_split) + work_in_bufferR1 = GeoDataFrame.copy(line_seg_split) + work_in_bufferR2 = GeoDataFrame.copy(line_seg_split) + work_in_bufferC = GeoDataFrame.copy(line_seg_split) + work_in_bufferL1["geometry"] = buffer( + work_in_bufferL1["geometry"], + distance=float(max_ln_width) + 1, + cap_style=3, + single_sided=True, + ) + + work_in_bufferL2["geometry"] = buffer( + work_in_bufferL2["geometry"], + distance=-1, + cap_style=3, + single_sided=True, + ) + + work_in_bufferL = GeoDataFrame(pd.concat([work_in_bufferL1, work_in_bufferL2])) + work_in_bufferL = work_in_bufferL.dissolve(by=["OLnFID", "OLnSEG"], as_index=False) + + work_in_bufferR1["geometry"] = buffer( + work_in_bufferR1["geometry"], + distance=-float(max_ln_width) - 1, + cap_style=3, + single_sided=True, + ) + work_in_bufferR2["geometry"] = buffer( + work_in_bufferR2["geometry"], distance=1, cap_style=3, single_sided=True + ) + + work_in_bufferR = GeoDataFrame(pd.concat([work_in_bufferR1, work_in_bufferR2])) + work_in_bufferR = work_in_bufferR.dissolve(by=["OLnFID", "OLnSEG"], as_index=False) + + work_in_bufferC["geometry"] = buffer( + work_in_bufferC["geometry"], + distance=float(max_ln_width), + cap_style=3, + single_sided=False, + ) + print("[info]: Prepare arguments for Dynamic FP ...") + # Just prepare arguments for multiprocessing + line_argsL, line_argsR, line_argsC = generate_line_args_DFP_NoClip( + line_seg_split, + work_in_bufferL, + work_in_bufferC, + raster, + in_chm, + tree_radius, + max_line_dist, + canopy_avoidance, + exponent, + work_in_bufferR, + canopy_thresh_percentage, + exp_shk_cell, + ) + + else: + print("[info]: Line and canopy raster spatial references are not same, please check.") + exit() + # pass center lines for footprint + print("[info]: Generating Dynamic footprint ...") + + feat_listL = [] + feat_listR = [] + poly_listL = [] + poly_listR = [] + footprint_listL = [] + footprint_listR = [] + if PARALLEL_MODE == ParallelMode.MULTIPROCESSING: + feat_listL = multiprocessing_footprint_relative(line_argsL, processes) + feat_listR = multiprocessing_footprint_relative(line_argsR, processes) + + elif PARALLEL_MODE == ParallelMode.SEQUENTIAL: + step = 1 + total_steps = len(line_argsL) + print("[info]: There are {} result to process.".format(total_steps)) + for row in line_argsL: + feat_listL.append(process_single_line_relative(row)) + print("[info]: Footprint (left side) for line {} is done".format(step)) + print( + ' "PROGRESS_LABEL Dynamic Line Footprint {} of {}" '.format(step, total_steps), + flush=True, + ) + print(" {}% ".format((step / total_steps) * 100)) + step += 1 + step = 1 + total_steps = len(line_argsR) + for row in line_argsR: + feat_listR.append(process_single_line_relative(row)) + print("[info]: Footprint for (right side) line {} is done".format(step)) + print( + ' "PROGRESS_LABEL Dynamic Line Footprint {} of {}" '.format(step, total_steps), + flush=True, + ) + print(" {}% ".format((step / total_steps) * 100)) + step += 1 + + print("{}%".format(80)) + + + for feat in feat_listL: + if feat: + footprint_listL.append(feat[0]) + poly_listL.append(feat[1]) + + for feat in feat_listR: + if feat: + footprint_listR.append(feat[0]) + poly_listR.append(feat[1]) + + resultsL = GeoDataFrame(pd.concat(footprint_listL,ignore_index=True)) + resultsL["geometry"] = resultsL["geometry"].buffer(0.005) + resultsR = GeoDataFrame(pd.concat(footprint_listR,ignore_index=True)) + resultsR["geometry"] = resultsR["geometry"].buffer(0.005) + resultsL = resultsL.sort_values(by=["OLnFID", "OLnSEG"]) + resultsR = resultsR.sort_values(by=["OLnFID", "OLnSEG"]) + resultsL = resultsL.reset_index(drop=True) + resultsR = resultsR.reset_index(drop=True) + # + + # one output per input line, or per original line when merging, as in the centerline tool + dissolve_keys = ["OLnFID"] if merge_by_original_line else ["OLnFID", "OLnSEG"] + resultsAll = GeoDataFrame(pd.concat([resultsL, resultsR],ignore_index=True)) + dissolved_results = resultsAll.dissolve(by=dissolve_keys, as_index=False) + dissolved_results["geometry"] = dissolved_results["geometry"].buffer(-0.005) + if merge_by_original_line: + dissolved_results["OLnSEG"] = -1 + print("[info]: Saving output ...") + out_ft_file, layer = decode_file_layer(out_footprint) + dissolved_results.to_file(out_ft_file, layer=layer) + print("[info]: Footprint file saved") + + # dissolved polygon group by column 'OLnFID' + print("[info]: Generating centerlines from corridor polygons ...") + resultsCL = GeoDataFrame(pd.concat(poly_listL)) + resultsCL["geometry"] = resultsCL["geometry"].buffer(0.005) + resultsCR = GeoDataFrame(pd.concat(poly_listR)) + resultsCR["geometry"] = resultsCR["geometry"].buffer(0.005) + + resultsCLR = GeoDataFrame(pd.concat([resultsCL, resultsCR])) + resultsCLR = resultsCLR.dissolve(by=dissolve_keys, as_index=False) + resultsCLR = resultsCLR.sort_values(by=["OLnFID", "OLnSEG"]) + resultsCLR = resultsCLR.reset_index(drop=True) + resultsCLR["geometry"] = resultsCLR["geometry"].buffer(-0.005) + + # save lines to file + if out_centerline: + out_cl_file, layer = decode_file_layer(out_centerline) + guide_lines = line_seg + if merge_by_original_line: + # corridor polygons are dissolved per OLnFID, so guide each by all pieces of its original line + guide_lines = algo_common.merge_lines_by_original_id( + line_seg, group_field="OLnFID", order_field="OLnSEG" + ).drop(columns="OLnSEG") + poly_centerline_gpd = find_centerlines(resultsCLR, guide_lines, processes) + poly_gpd = poly_centerline_gpd.copy() + centerline_gpd = poly_centerline_gpd.copy() + + centerline_gpd = centerline_gpd.set_geometry("centerline") + centerline_gpd = centerline_gpd.drop(columns=["geometry"]) + centerline_gpd.crs = poly_centerline_gpd.crs + if merge_by_original_line: + centerline_gpd["OLnSEG"] = -1 + + # save polygons from smooth centerline for debug + if debug_mode: + path = Path(out_cl_file) + path = path.with_stem(path.stem + "_poly") + poly_gpd = poly_gpd.drop(columns=["centerline"]) + poly_gpd.to_file(path,layer='smoothedCL_poly') + print("[info]: Polygon from smoothed centerline file saved") + + centerline_gpd.to_file(out_cl_file, layer=layer) + print("[info]: Smoothed centerline file saved") + + print("{}%".format(100)) diff --git a/beratools/modules/mapping/line_footprint_relative.py b/beratools/modules/mapping/line_footprint_relative.py new file mode 100644 index 0000000..ee9172f --- /dev/null +++ b/beratools/modules/mapping/line_footprint_relative.py @@ -0,0 +1,156 @@ +# --------------------------------------------------------------------------- +# Copyright (C) 2021 Applied Geospatial Research Group +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, version 3. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +# --------------------------------------------------------------------------- +# +# line_footprint_relative.py +# Script Author: Maverick Fong +# Date: 2023-May +# Use open sources python library for produce dynamic footprint +# from dynamic canopy and cost raster with lines and CHM input. +# Prerequisite: Line feature class must have the attribute Fields: "OLnFID" adn CHM raster +# line_footprint_relative.py +# This script is part of the BERA toolset +# Webpage: https://github.com/ +# +# Purpose: Creates dynamic footprint polygons for each input line based on a least +# cost corridor method and individual line thresholds. +# +# --------------------------------------------------------------------------- + +import time +from pathlib import Path + +from beratools.modules.mapping.canopy_threshold_relative import main_canopy_threshold_relative +from beratools.modules.mapping.line_footprint_functions import main_line_footprint_relative +from beratools.utility.spatial_common import decode_file_layer + + +def line_footprint_relative( + in_line, + in_chm, + max_ln_width, + exp_shk_cell, + out_footprint, + out_centerline, + off_ln_dist, + canopy_percentile, + canopy_thresh_percentage, + tree_radius, + max_line_dist, + canopy_avoidance, + exponent, + processes, + call_mode, + log_level, + merge_by_original_line=False, +): + """ + Create canopy footprint polygons using per-line relative canopy thresholds. + + Runs in two steps. First, `main_canopy_threshold_relative` samples the CHM on + both sides of each input line and derives an individual canopy threshold + height from the surrounding forest. Second, `main_line_footprint_relative` + builds a canopy and cost raster per line and traces a least cost corridor + to produce the footprint polygons and, optionally, centerlines. Results are + written to `out_footprint` and `out_centerline`; if the threshold step + fails, an error is printed and nothing is written. + + Numeric arguments may be passed as strings (as they are from the GUI) and + are converted before use. + + Args: + in_line: Input line file. + in_chm: CHM raster used to calculate the surrounding forest percentile + and to build the canopy and cost rasters. + max_ln_width: Maximum processing width for input lines. A large value + increases processing time; a small value may clip the footprint. + exp_shk_cell: Cell range used to expand and shrink the corridor before + polygons are generated, to remove small artifacts. Use 0 when the + cell size is 1 m or larger. + out_footprint: Output footprint polygon file. + out_centerline: Optional output centerline file. + off_ln_dist: Offset distance from input lines. Currently not used. + canopy_percentile: Nth percentile of the surrounding forest height. + canopy_thresh_percentage: Percentage of the canopy percentile height + used as the canopy threshold. + tree_radius: Radius of canopy influence in the cost raster. Smooths the + canopy so gaps in sparse vegetation are not taken as footprint. + max_line_dist: Maximum euclidean distance from canopy, a second + smoothing factor that centers the line in the footprint. + canopy_avoidance: Weight between tree search radius (near 0) and + euclidean distance (near 1) in the cost raster. + exponent: Exponent applied to the cost of vegetated areas. + processes: Number of parallel processes. + call_mode: How the tool was invoked (see `CallMode`). + log_level: Logging level. Currently not used. + merge_by_original_line: Merge footprints and centerlines sharing an original + line ID (OLnFID) into one feature; otherwise keep one per input line. + """ + # Write the intermediate dynamic centerline as a layer in the output footprint's file, + # so no extra file is created and input data folders are never written to. + in_file, in_layer = decode_file_layer(in_line) + out_ft_file = decode_file_layer(out_footprint)[0] + dyn_layer = "DynCanTh_" + (in_layer or Path(in_file).stem) + if Path(out_ft_file).suffix.lower() != ".gpkg": + # a shapefile holds one layer, so use a GeoPackage beside it + out_ft_file = Path(out_ft_file).with_name(dyn_layer + ".gpkg").as_posix() + out_dyn_centerline = f"{out_ft_file}|{dyn_layer}" + + dy_cl_line = main_canopy_threshold_relative( + in_line=in_line, + in_chm=in_chm, + canopy_percentile=int(float(canopy_percentile)), + canopy_thresh_percentage=int(float(canopy_thresh_percentage)), + full_step=bool(True), + processes=int(float(processes)), + out_dyn_centerline=out_dyn_centerline, + ) + + if not dy_cl_line: + print("[error]: main_canopy_threshold_relative did not return a valid path. Aborting footprint step.") + return + + main_line_footprint_relative( + in_line=dy_cl_line, + in_chm=in_chm, + max_ln_width=float(max_ln_width), + out_footprint=out_footprint or "", + out_centerline=out_centerline or "", + exp_shk_cell=int(float(exp_shk_cell)), + tree_radius=float(tree_radius), + max_line_dist=float(max_line_dist), + canopy_avoidance=float(canopy_avoidance), + exponent=float(exponent), + full_step=bool(True), + canopy_thresh_percentage=int(float(canopy_thresh_percentage)), + processes=int(float(processes)), + merge_by_original_line=str(merge_by_original_line).strip().lower() in ("true", "1", "yes"), + ) + +if __name__ == "__main__": + from beratools.utility.tool_args import compose_tool_kwargs + start_time = time.time() + print("[info]: Dynamic CC and Footprint processing started") + print("[info]: Current time: {}".format(time.strftime("%d %b %Y %H:%M:%S", time.localtime()))) + + args=compose_tool_kwargs("line_footprint_relative") + + line_footprint_relative(**args) + + print("{}%".format(100)) + print("[info]: Dynamic CC and Footprint processes finished") + print("[info]: Current time: {}".format(time.strftime("%d %b %Y %H:%M:%S", time.localtime()))) + print("[info]: Total processing time (seconds): {}".format(round(time.time() - start_time, 3))) diff --git a/beratools/modules/mapping/smooth_centerline.py b/beratools/modules/mapping/smooth_centerline.py new file mode 100644 index 0000000..21197f5 --- /dev/null +++ b/beratools/modules/mapping/smooth_centerline.py @@ -0,0 +1,99 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Irina Terentieva (original SegLine code) + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + The purpose of this script is to smooth sharp vertices of centerlines. + Only vertices with an interior angle below the threshold are changed, + the rest of each line is kept as is. + + Ported from SegLine by Irina Terentieva + (https://github.com/IrinaTerentieva/SegLine, src/utils/smooth_centerline.py). +""" + +import logging + +import geopandas as gpd +import pandas as pd + +import beratools.utility.spatial_common as sp_common +from beratools.core.tool_base import execute_multiprocessing +from beratools.modules.mapping.algo_geometry import smooth_sharp_vertices +from beratools.utility.tool_args import CallMode + +LOGGER_NAME = "smooth_centerline" +logger = logging.getLogger(LOGGER_NAME) + + +def smooth_centerline( + in_line, + out_line, + angle_threshold=130.0, + buffer_distance=2.0, + processes=0, + call_mode=CallMode.CLI, + log_level="INFO", +): + """ + Define tool entry point. + + Args: + in_line: input centerlines (encoded as "file|layer") + out_line: output smoothed centerlines (encoded as "file|layer") + angle_threshold: vertices with interior angle (degrees) below this are smoothed + buffer_distance: radius (m) around a sharp vertex that is replaced by a straight cut + processes: number of processes to use + call_mode: CLI or GUI + log_level: logging level + + """ + in_file, in_layer = sp_common.decode_file_layer(in_line) + out_file, out_layer = sp_common.decode_file_layer(out_line) + + angle_threshold = float(angle_threshold) + buffer_distance = float(buffer_distance) + gdf = gpd.read_file(in_file, layer=in_layer) + if "fid" in gdf.columns: + gdf = gdf.rename(columns={"fid": "orig_fid"}) + gdf_list = [(gdf.iloc[[i]], angle_threshold, buffer_distance) for i in range(len(gdf))] + + results = execute_multiprocessing( + smooth_worker, gdf_list, "smooth_centerline", processes, call_mode, logger_name=LOGGER_NAME + ) + if not results: + raise RuntimeError("Smooth centerline produced no output.") + + # Workers finish out of order, restore the input order + smoothed_gdf = gpd.GeoDataFrame(pd.concat(results).sort_index(), crs=gdf.crs) + changed = int((~smoothed_gdf.geometry.geom_equals(gdf.geometry)).sum()) + print(f"Smoothed {changed} of {len(smoothed_gdf)} lines.", flush=True) + smoothed_gdf.to_file(out_file, layer=out_layer) + + +# task executed in a worker process +def smooth_worker(in_args): + smoothed = in_args[0].copy() + angle_threshold = in_args[1] + buffer_distance = in_args[2] + smoothed["geometry"] = smoothed.geometry.apply( + smooth_sharp_vertices, angle_threshold=angle_threshold, buffer_distance=buffer_distance + ) + return smoothed + + +if __name__ == "__main__": + import time + + from beratools.utility.tool_args import compose_tool_kwargs + + start_time = time.time() + kwargs = compose_tool_kwargs("smooth_centerline") + smooth_centerline(**kwargs) + print("Elapsed time: {}".format(time.time() - start_time)) diff --git a/beratools/modules/mapping/tests/conftest.py b/beratools/modules/mapping/tests/conftest.py new file mode 100644 index 0000000..b23cbc1 --- /dev/null +++ b/beratools/modules/mapping/tests/conftest.py @@ -0,0 +1,290 @@ +"""Test configuration for the Mapping tests.""" + +import logging +import os +import time +import warnings +from pathlib import Path + +import pytest + +# Test the work-in-progress modules and tools too (see core/registry.py) +os.environ["BERATOOLS_WIP"] = "1" + +# This module's sample data, in tests/data next to this file +DATA_DIR = Path(__file__).resolve().parent / "data" + + +def pytest_configure(config): + warnings.simplefilter("ignore", category=FutureWarning) + warnings.simplefilter("ignore", category=DeprecationWarning) + # Set the global logging level to ERROR to suppress DEBUG and INFO logs + logging.basicConfig(level=logging.ERROR) + + # Set logger to ERROR to suppress debug logs + logging.getLogger("pyogrio").setLevel(logging.ERROR) + logging.getLogger("rasterio").setLevel(logging.ERROR) + logging.getLogger("rasterio.env").setLevel(logging.ERROR) + logging.getLogger("beratools.external.polygon_centerline._src").setLevel(logging.ERROR) + logging.getLogger("pyproj").setLevel(logging.WARNING) + + +@pytest.fixture +def testdata_dir(): + return DATA_DIR + + +@pytest.fixture(scope="session") +def available_cpu_cores(): + return os.cpu_count() + +# Integration arguments: each tool uses original inputs +@pytest.fixture +def tool_arguments_integration(testdata_dir, available_cpu_cores): + return { + "args_check_seed_line": { + "in_line": f"{testdata_dir.joinpath('seed_lines_aoi.gpkg').as_posix()}|seed_lines", + "in_raster": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "out_line": f"{testdata_dir.joinpath('integration_inter.gpkg').as_posix()}|seed_lines_checked", + }, + "args_vertex_optimization": { + "in_line": f"{testdata_dir.joinpath('integration_aoi.gpkg').as_posix()}|seed_lines_checked", + "in_raster": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "search_distance": 5.0, + "line_radius": 15, + "out_line": f"{testdata_dir.joinpath('integration_inter.gpkg').as_posix()}|seed_lines_vo", + }, + "args_centerline": { + "in_line": f"{testdata_dir.joinpath('integration_aoi.gpkg').as_posix()}|seed_lines_vo", + "in_raster": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "line_radius": 15, + "proc_segments": True, + "merge_by_original_line": True, + "out_line": f"{testdata_dir.joinpath('integration_inter.gpkg').as_posix()}|centerline", + "chm_mode": "current", + "centerline_method": "astar", + }, + "args_centerline_pairwise": { + "in_line": f"{testdata_dir.joinpath('integration_aoi.gpkg').as_posix()}|seed_lines_vo", + "in_raster": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "line_radius": 15, + "proc_segments": True, + "guided_strategy": "pairwise", + "out_line": f"{testdata_dir.joinpath('integration_inter.gpkg').as_posix()}|centerline_pairwise", + }, + "args_footprint_abs": { + "in_line": f"{testdata_dir.joinpath('integration_aoi.gpkg').as_posix()}|centerline", + "in_chm": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "corridor_thresh": 3.0, + "max_ln_width": 32.0, + "exp_shk_cell": 0, + "out_footprint": f"{testdata_dir.joinpath('integration_inter.gpkg').as_posix()}|footprint_abs", + }, + "args_footprint_exp": { + "in_line": f"{testdata_dir.joinpath('integration_aoi.gpkg').as_posix()}|centerline", + "in_chm": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "out_footprint": f"{testdata_dir.joinpath('integration_inter.gpkg').as_posix()}|footprint_exp", + "max_ln_width": 32, + "tree_radius": 1.5, + "max_line_dist": 1.5, + "canopy_avoidance": 0.0, + "exponent": 0, + "canopy_thresh_percentage": 50, + }, + "args_footprint_adaptive_via_absolute": { + "in_line": f"{testdata_dir.joinpath('integration_aoi.gpkg').as_posix()}|centerline", + "in_chm": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "out_footprint": ( + f"{testdata_dir.joinpath('integration_inter.gpkg').as_posix()}|footprint_adaptive_abs" + ), + "footprint_mode": "adaptive", + "max_ln_width": 32, + "tree_radius": 1.5, + "max_line_dist": 1.5, + "canopy_avoidance": 0.0, + "exponent": 0, + "canopy_thresh_percentage": 50, + }, + "args_ground_footprint": { + "in_line": f"{testdata_dir.joinpath('integration_aoi.gpkg').as_posix()}|centerline", + "in_footprint": f"{testdata_dir.joinpath('integration_aoi.gpkg').as_posix()}|footprint_abs", + "n_samples": 15, + "offset": 30, + "max_width": True, + "out_footprint": f"{testdata_dir.joinpath('integration_inter.gpkg').as_posix()}|footprint_ground", + }, + "arg_main_canopy_threshold_relative": { + "in_line": f"{testdata_dir.joinpath('integration_aoi.gpkg').as_posix()}|centerline", + "in_chm": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "canopy_percentile": 90, + "canopy_thresh_percentage": 50, + "full_step": "True", + "processes": available_cpu_cores, + "out_dyn_centerline": ( + f"{testdata_dir.joinpath('DynCanTh_integration.gpkg').as_posix()}|centerline" + ), + }, + "arg_main_line_footprint_relative": { + "in_line": f"{testdata_dir.joinpath('DynCanTh_integration.gpkg').as_posix()}|centerline", + "in_chm": f"{testdata_dir.joinpath('chm_aoi.tif').as_posix()}", + "max_ln_width": 32, + "out_footprint": f"{testdata_dir.joinpath('integration_inter.gpkg').as_posix()}|footprint_rel", + "out_centerline": ( + f"{testdata_dir.joinpath('integration_inter.gpkg').as_posix()}|smooth_centerline" + ), + "exp_shk_cell": 5, + "tree_radius": 1.5, + "max_line_dist": 1.5, + "canopy_avoidance": 1.0, + "exponent": 1, + "full_step": "True", + "canopy_thresh_percentage": 50, + "processes": available_cpu_cores, + "debug_mode": False, + }, + "args_smooth_centerline": { + "in_line": f"{testdata_dir.joinpath('Seg_Plot/sample_centerlines.gpkg').as_posix()}|centerlines", + "angle_threshold": 130, + "buffer_distance": 2, + "processes": available_cpu_cores, + "out_line": f"{testdata_dir.joinpath('integration_inter.gpkg').as_posix()}|seg_plot_smooth", + }, + "args_footprint_plots": { + "in_footprint": f"{testdata_dir.joinpath('Seg_Plot/sample_footprint.gpkg').as_posix()}|footprint", + "in_line": f"{testdata_dir.joinpath('Seg_Plot/sample_centerlines.gpkg').as_posix()}|centerlines", + "mode": "fixed_area", + "plot_area": 100, + "subplot_area": 10, + "remove_overlap": True, + "processes": available_cpu_cores, + "out_plot": f"{testdata_dir.joinpath('integration_inter.gpkg').as_posix()}|seg_plot_plots", + "out_subplot": f"{testdata_dir.joinpath('integration_inter.gpkg').as_posix()}|seg_plot_subplots", + }, + } + + +# Workflow arguments: chained outputs +@pytest.fixture +def tool_arguments_workflow(testdata_dir, available_cpu_cores): + return { + "args_check_seed_line": { + "in_line": f"{testdata_dir.joinpath('seed_lines_aoi.gpkg').as_posix()}|seed_lines", + "in_raster": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "out_line": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|seed_lines_checked", + }, + "args_vertex_optimization": { + "in_line": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|seed_lines_checked", + "in_raster": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "search_distance": 5.0, + "line_radius": 15, + "out_line": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|seed_lines_vo", + }, + "args_centerline": { + "in_line": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|seed_lines_vo", + "in_raster": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "line_radius": 15, + "proc_segments": True, + "merge_by_original_line": True, + "out_line": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|centerline", + }, + "args_centerline_pairwise": { + "in_line": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|seed_lines_vo", + "in_raster": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "line_radius": 15, + "proc_segments": True, + "guided_strategy": "pairwise", + "out_line": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|centerline_pairwise", + }, + "args_footprint_abs": { + "in_line": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|centerline", + "in_chm": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "corridor_thresh": 3.0, + "max_ln_width": 32.0, + "exp_shk_cell": 0, + "out_footprint": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|footprint_abs", + }, + "args_footprint_exp": { + "in_line": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|centerline", + "in_chm": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "out_footprint": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|footprint_exp", + "max_ln_width": 32, + "tree_radius": 1.5, + "max_line_dist": 1.5, + "canopy_avoidance": 0.0, + "exponent": 0, + "canopy_thresh_percentage": 50, + }, + "args_footprint_adaptive_via_absolute": { + "in_line": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|centerline", + "in_chm": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "out_footprint": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|footprint_adaptive_abs", + "footprint_mode": "adaptive", + "max_ln_width": 32, + "tree_radius": 1.5, + "max_line_dist": 1.5, + "canopy_avoidance": 0.0, + "exponent": 0, + "canopy_thresh_percentage": 50, + }, + "args_ground_footprint": { + "in_line": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|centerline", + "in_footprint": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|footprint_abs", + "n_samples": 15, + "offset": 30, + "max_width": True, + "out_footprint": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|footprint_ground", + }, + "arg_main_canopy_threshold_relative": { + "in_line": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|centerline", + "in_chm": testdata_dir.joinpath("chm_aoi.tif").as_posix(), + "canopy_percentile": 90, + "canopy_thresh_percentage": 50, + "full_step": "True", + "processes": available_cpu_cores, + "out_dyn_centerline": f"{testdata_dir.joinpath('DynCanTh_workflow.gpkg').as_posix()}|centerline", + }, + "arg_main_line_footprint_relative": { + "in_line": f"{testdata_dir.joinpath('DynCanTh_workflow.gpkg').as_posix()}|centerline", + "in_chm": f"{testdata_dir.joinpath('chm_aoi.tif').as_posix()}", + "max_ln_width": 32, + "out_footprint": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|footprint_rel", + "out_centerline": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|smooth_centerline", + "exp_shk_cell": 5, + "tree_radius": 1.5, + "max_line_dist": 1.5, + "canopy_avoidance": 1.0, + "exponent": 1, + "full_step": "True", + "canopy_thresh_percentage": 50, + "processes": available_cpu_cores, + "debug_mode": False, + }, + } + + +# A test for cleaning up test output files +@pytest.fixture +def test_output_files(testdata_dir): + return [ + testdata_dir.joinpath("integration_inter.gpkg"), + testdata_dir.joinpath("integration_inter_aux.gpkg"), + testdata_dir.joinpath("DynCanTh_integration.gpkg"), + testdata_dir.joinpath("DynCanTh_integration_inter.gpkg"), + testdata_dir.joinpath("workflow.gpkg"), + testdata_dir.joinpath("workflow_aux.gpkg"), + testdata_dir.joinpath("DynCanTh_workflow.gpkg"), + testdata_dir.joinpath("smooth_centerline.gpkg"), + testdata_dir.joinpath("footprint_rel.gpkg"), + ] + + +@pytest.fixture +def cleanup_output_files(test_output_files): + """Fixture to clean up generated output files after the test.""" + yield # Yield here allows the test to run first + time.sleep(1) # Wait a little to allow file system operations to complete + for file_path in test_output_files: + if file_path.exists(): + file_path.unlink() + assert not file_path.exists(), f"Failed to remove {file_path}" + diff --git a/beratools/modules/mapping/tests/data/Seg_Plot/LICENSE b/beratools/modules/mapping/tests/data/Seg_Plot/LICENSE new file mode 100644 index 0000000..57bc88a --- /dev/null +++ b/beratools/modules/mapping/tests/data/Seg_Plot/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/beratools/modules/mapping/tests/data/Seg_Plot/README.md b/beratools/modules/mapping/tests/data/Seg_Plot/README.md new file mode 100644 index 0000000..97653a6 --- /dev/null +++ b/beratools/modules/mapping/tests/data/Seg_Plot/README.md @@ -0,0 +1,19 @@ +# Seg_Plot sample data + +Sample data from [SegLine](https://github.com/IrinaTerentieva/SegLine) by Irina Terentieva, +copied unchanged from its `sample_data/` folder at commit +[`470de9d`](https://github.com/IrinaTerentieva/SegLine/tree/470de9d015560112fd54ce6a88188bb0542fe591/sample_data). + +SegLine is licensed under the Apache License 2.0. A copy is in [LICENSE](LICENSE). + +| File | Layer | Contents | +|---|---|---| +| `sample_centerlines.gpkg` | `centerlines` | 8 seismic line centerlines in a 1 × 1 km area, EPSG:2956 | +| `sample_footprint.gpkg` | `footprint` | 8 footprint polygons, one per centerline, with a `width` column (3 to 5 m) | + +The lines cross each other in several places and some end on another line, so the data +covers overlap removal as well as plain splitting. + +Used by `test_footprint_plots.py`, `test_smooth_centerline.py` and `test_tools.py` +in the Mapping tests to test the Footprint Plots and Smooth Centerline tools, which are +ported from SegLine. diff --git a/beratools/modules/mapping/tests/data/Seg_Plot/sample_centerlines.gpkg b/beratools/modules/mapping/tests/data/Seg_Plot/sample_centerlines.gpkg new file mode 100644 index 0000000..7964176 Binary files /dev/null and b/beratools/modules/mapping/tests/data/Seg_Plot/sample_centerlines.gpkg differ diff --git a/beratools/modules/mapping/tests/data/Seg_Plot/sample_footprint.gpkg b/beratools/modules/mapping/tests/data/Seg_Plot/sample_footprint.gpkg new file mode 100644 index 0000000..118cc44 Binary files /dev/null and b/beratools/modules/mapping/tests/data/Seg_Plot/sample_footprint.gpkg differ diff --git a/tests/data/chm_aoi.tif b/beratools/modules/mapping/tests/data/chm_aoi.tif similarity index 100% rename from tests/data/chm_aoi.tif rename to beratools/modules/mapping/tests/data/chm_aoi.tif diff --git a/tests/data/integration_aoi.gpkg b/beratools/modules/mapping/tests/data/integration_aoi.gpkg similarity index 100% rename from tests/data/integration_aoi.gpkg rename to beratools/modules/mapping/tests/data/integration_aoi.gpkg diff --git a/tests/data/seed_lines_aoi.gpkg b/beratools/modules/mapping/tests/data/seed_lines_aoi.gpkg similarity index 100% rename from tests/data/seed_lines_aoi.gpkg rename to beratools/modules/mapping/tests/data/seed_lines_aoi.gpkg diff --git a/tests/utils.py b/beratools/modules/mapping/tests/mapping_test_utils.py similarity index 91% rename from tests/utils.py rename to beratools/modules/mapping/tests/mapping_test_utils.py index e6834dc..b3297a7 100644 --- a/tests/utils.py +++ b/beratools/modules/mapping/tests/mapping_test_utils.py @@ -1,5 +1,3 @@ -"""Helper functions for testing.""" - from pathlib import Path @@ -11,7 +9,8 @@ def check_file_exists(file_path, layer=None): if layer is None: return True - + import pyogrio + layers = pyogrio.list_layers(file_path) return layer in layers \ No newline at end of file diff --git a/tests/test_algo_astar.py b/beratools/modules/mapping/tests/test_algo_astar.py similarity index 98% rename from tests/test_algo_astar.py rename to beratools/modules/mapping/tests/test_algo_astar.py index 55be017..091fbb8 100644 --- a/tests/test_algo_astar.py +++ b/beratools/modules/mapping/tests/test_algo_astar.py @@ -4,7 +4,7 @@ from rasterio.transform import from_origin from shapely.geometry import LineString -from beratools.core.algo_astar import ( +from beratools.modules.mapping.algo_astar import ( astar_accumulation_corridor_raster, find_least_cost_path_astar_closest_line, ) diff --git a/tests/test_algo_centerline_modes.py b/beratools/modules/mapping/tests/test_algo_centerline_modes.py similarity index 86% rename from tests/test_algo_centerline_modes.py rename to beratools/modules/mapping/tests/test_algo_centerline_modes.py index cc22f7e..71ae594 100644 --- a/tests/test_algo_centerline_modes.py +++ b/beratools/modules/mapping/tests/test_algo_centerline_modes.py @@ -1,11 +1,12 @@ -import pytest from pathlib import Path + import geopandas as gpd import pyproj +import pytest from rasterio.transform import from_origin from shapely.geometry import LineString, Point, Polygon -import beratools.core.algo_centerline as algo_centerline +import beratools.modules.mapping.algo_centerline as algo_centerline def _seed_gdf(seed): @@ -24,7 +25,10 @@ def __enter__(self): def __exit__(self, *_args): return False - monkeypatch.setattr("beratools.tools.centerline.rasterio.open", lambda *_args, **_kwargs: _FakeRaster()) + monkeypatch.setattr( + "beratools.modules.mapping.centerline.rasterio.open", + lambda *_args, **_kwargs: _FakeRaster() + ) def test_is_endpoint_anchored_detects_direct_and_reverse(): @@ -227,7 +231,10 @@ def test_seedline_compute_uses_seedline_fallback_when_lcp_returns_none(monkeypat assert seed_line.centerline.geometry.iloc[0].equals(seed) assert seed_line.lc_path.geometry.iloc[0].equals(seed) - assert seed_line.centerline["cl_status"].iloc[0] == algo_centerline.CenterlineStatus.LCP_FAILED_SEED_FALLBACK.value + assert ( + seed_line.centerline["cl_status"].iloc[0] + == algo_centerline.CenterlineStatus.LCP_FAILED_SEED_FALLBACK.value + ) assert seed_line.centerline["cl_status_name"].iloc[0] == "LCP_FAILED_SEED_FALLBACK" @@ -254,7 +261,10 @@ def raise_lcp(*_args, **_kwargs): seed_line.compute() assert seed_line.centerline.geometry.iloc[0].equals(seed) - assert seed_line.centerline["cl_status"].iloc[0] == algo_centerline.CenterlineStatus.LCP_FAILED_SEED_FALLBACK.value + assert ( + seed_line.centerline["cl_status"].iloc[0] + == algo_centerline.CenterlineStatus.LCP_FAILED_SEED_FALLBACK.value + ) assert seed_line.centerline["cl_status_name"].iloc[0] == "LCP_FAILED_SEED_FALLBACK" @@ -288,7 +298,10 @@ def raise_corridor(*_args, **_kwargs): assert seed_line.centerline.geometry.iloc[0].equals(lcp) assert seed_line.lc_path.geometry.iloc[0].equals(lcp) - assert seed_line.centerline["cl_status"].iloc[0] == algo_centerline.CenterlineStatus.CENTERLINE_FAILED_LCP_FALLBACK.value + assert ( + seed_line.centerline["cl_status"].iloc[0] + == algo_centerline.CenterlineStatus.CENTERLINE_FAILED_LCP_FALLBACK.value + ) assert seed_line.centerline["cl_status_name"].iloc[0] == "CENTERLINE_FAILED_LCP_FALLBACK" @@ -333,7 +346,10 @@ def test_seedline_compute_uses_lcp_fallback_when_find_centerline_fails(monkeypat seed_line.compute() assert seed_line.centerline.geometry.iloc[0].equals(lcp) - assert seed_line.centerline["cl_status"].iloc[0] == algo_centerline.CenterlineStatus.CENTERLINE_FAILED_LCP_FALLBACK.value + assert ( + seed_line.centerline["cl_status"].iloc[0] + == algo_centerline.CenterlineStatus.CENTERLINE_FAILED_LCP_FALLBACK.value + ) assert seed_line.centerline["cl_status_name"].iloc[0] == "CENTERLINE_FAILED_LCP_FALLBACK" @@ -385,7 +401,10 @@ def fake_find_centerline(poly, *_args, **_kwargs): assert len(calls) == 2 assert seed_line.centerline.geometry.iloc[0].equals(absolute_centerline) - assert seed_line.centerline["cl_status"].iloc[0] == algo_centerline.CenterlineStatus.ABSOLUTE_FOOTPRINT_SUCCESS.value + assert ( + seed_line.centerline["cl_status"].iloc[0] + == algo_centerline.CenterlineStatus.ABSOLUTE_FOOTPRINT_SUCCESS.value + ) assert seed_line.centerline["cl_status_name"].iloc[0] == "ABSOLUTE_FOOTPRINT_SUCCESS" @@ -400,7 +419,7 @@ def test_snap_end_to_end_respects_max_snap_distance(): def test_centerline_tool_rejects_unknown_guided_strategy(): - from beratools.tools.centerline import centerline + from beratools.modules.mapping.centerline import centerline with pytest.raises(ValueError, match="not a valid CenterlineStrategy"): centerline( @@ -414,7 +433,7 @@ def test_centerline_tool_rejects_unknown_guided_strategy(): def test_centerline_tool_rejects_unknown_centerline_method(): - from beratools.tools.centerline import centerline + from beratools.modules.mapping.centerline import centerline with pytest.raises(ValueError, match="not a valid CenterlineMethod"): centerline( @@ -428,7 +447,7 @@ def test_centerline_tool_rejects_unknown_centerline_method(): def test_generate_line_class_list_forwards_astar_options(monkeypatch): - from beratools.tools import centerline as centerline_tool + from beratools.modules.mapping import centerline as centerline_tool line_gdf = gpd.GeoDataFrame(geometry=[LineString([(0, 0), (1, 0)])], crs="EPSG:3857") captured = {} @@ -438,7 +457,9 @@ def __init__(self, *args, **kwargs): captured["args"] = args captured["kwargs"] = kwargs - monkeypatch.setattr(centerline_tool.algo_common, "prepare_lines_gdf", lambda *_args, **_kwargs: [line_gdf]) + monkeypatch.setattr( + centerline_tool.algo_common, "prepare_lines_gdf", lambda *_args, **_kwargs: [line_gdf] + ) monkeypatch.setattr(centerline_tool.algo_centerline, "SeedLine", FakeSeedLine) line_classes = centerline_tool.generate_line_class_list( @@ -470,7 +491,7 @@ def __init__(self, *args, **kwargs): def test_centerline_tool_rejects_unknown_chm_mode(): - from beratools.tools.centerline import centerline + from beratools.modules.mapping.centerline import centerline with pytest.raises(ValueError, match="not a valid CenterlineChmMode"): centerline( @@ -658,20 +679,20 @@ def fake_simplify(line, *, crs, diameter, smooth_line): def test_validate_simplify_diameter_accepts_zero(): - from beratools.core import tool_geo_simplify + from beratools.modules.mapping import tool_geo_simplify assert tool_geo_simplify.validate_diameter(0) == 0.0 def test_validate_simplify_diameter_rejects_negative(): - from beratools.core import tool_geo_simplify + from beratools.modules.mapping import tool_geo_simplify with pytest.raises(ValueError, match=">= 0"): tool_geo_simplify.validate_diameter(-1) def test_run_geo_simplify_reduce_bend_builds_expected_command(monkeypatch, tmp_path): - from beratools.core import tool_geo_simplify + from beratools.modules.mapping import tool_geo_simplify captured = {} @@ -718,7 +739,7 @@ def _fake_run(command, capture_output, text): def test_run_geo_simplify_reduce_bend_omits_out_layer_when_empty(monkeypatch, tmp_path): - from beratools.core import tool_geo_simplify + from beratools.modules.mapping import tool_geo_simplify captured = {} @@ -749,7 +770,7 @@ def _fake_run(command, capture_output, text): def test_centerline_tool_converts_line_radius_meters_to_projected_native_units(monkeypatch): _patch_raster_open(monkeypatch) - from beratools.tools.centerline import centerline + from beratools.modules.mapping.centerline import centerline captured = {} @@ -763,24 +784,27 @@ def ExportToWkt(self): feet_crs_wkt = pyproj.CRS.from_epsg(2263).to_wkt() monkeypatch.setattr( - "beratools.tools.centerline.sp_common.vector_crs", + "beratools.modules.mapping.centerline.sp_common.vector_crs", lambda *_args, **_kwargs: _FakeOSR(feet_crs_wkt), ) monkeypatch.setattr( - "beratools.tools.centerline.sp_common.raster_crs", + "beratools.modules.mapping.centerline.sp_common.raster_crs", lambda *_args, **_kwargs: object(), ) - monkeypatch.setattr("beratools.tools.centerline.sp_common.compare_crs", lambda *_args, **_kwargs: True) monkeypatch.setattr( - "beratools.tools.centerline.gpd.read_file", + "beratools.modules.mapping.centerline.sp_common.compare_crs", + lambda *_args, **_kwargs: True, + ) + monkeypatch.setattr( + "beratools.modules.mapping.centerline.gpd.read_file", lambda *_args, **_kwargs: gpd.GeoDataFrame(geometry=[LineString([(0, 0), (1, 0)])], crs="EPSG:2263"), ) monkeypatch.setattr( - "beratools.tools.centerline.sp_common.check_vector_raster_overlap", + "beratools.modules.mapping.centerline.sp_common.check_vector_raster_overlap", lambda *_args, **_kwargs: True, ) monkeypatch.setattr( - "beratools.tools.centerline.sp_common.check_vector_raster_extent_overlap", + "beratools.modules.mapping.centerline.sp_common.check_vector_raster_extent_overlap", lambda *_args, **_kwargs: True, ) @@ -790,7 +814,10 @@ def _fake_generate( captured["line_radius"] = line_radius return [] - monkeypatch.setattr("beratools.tools.centerline.generate_line_class_list", _fake_generate) + monkeypatch.setattr( + "beratools.modules.mapping.centerline.generate_line_class_list", + _fake_generate, + ) result = centerline( in_line="dummy.gpkg|line", @@ -805,7 +832,7 @@ def _fake_generate( def test_centerline_tool_rejects_geographic_crs_for_meter_radius(monkeypatch): - from beratools.tools.centerline import centerline + from beratools.modules.mapping.centerline import centerline class _FakeOSR: def __init__(self, crs_text): @@ -817,7 +844,7 @@ def ExportToWkt(self): geo_crs_wkt = pyproj.CRS.from_epsg(4326).to_wkt() monkeypatch.setattr( - "beratools.tools.centerline.sp_common.vector_crs", + "beratools.modules.mapping.centerline.sp_common.vector_crs", lambda *_args, **_kwargs: _FakeOSR(geo_crs_wkt), ) @@ -833,27 +860,34 @@ def ExportToWkt(self): def test_centerline_tool_terminates_when_lines_do_not_overlap_raster(monkeypatch): _patch_raster_open(monkeypatch) - from beratools.tools.centerline import centerline + from beratools.modules.mapping.centerline import centerline class _FakeOSR: def ExportToWkt(self): return pyproj.CRS.from_epsg(2263).to_wkt() monkeypatch.setattr( - "beratools.tools.centerline.sp_common.vector_crs", lambda *_args, **_kwargs: _FakeOSR() + "beratools.modules.mapping.centerline.sp_common.vector_crs", + lambda *_args, **_kwargs: _FakeOSR(), ) - monkeypatch.setattr("beratools.tools.centerline.sp_common.raster_crs", lambda *_args, **_kwargs: object()) - monkeypatch.setattr("beratools.tools.centerline.sp_common.compare_crs", lambda *_args, **_kwargs: True) monkeypatch.setattr( - "beratools.tools.centerline.gpd.read_file", + "beratools.modules.mapping.centerline.sp_common.raster_crs", + lambda *_args, **_kwargs: object(), + ) + monkeypatch.setattr( + "beratools.modules.mapping.centerline.sp_common.compare_crs", + lambda *_args, **_kwargs: True, + ) + monkeypatch.setattr( + "beratools.modules.mapping.centerline.gpd.read_file", lambda *_args, **_kwargs: gpd.GeoDataFrame(geometry=[LineString([(0, 0), (1, 0)])], crs="EPSG:2263"), ) monkeypatch.setattr( - "beratools.tools.centerline.sp_common.check_vector_raster_overlap", + "beratools.modules.mapping.centerline.sp_common.check_vector_raster_overlap", lambda *_args, **_kwargs: False, ) monkeypatch.setattr( - "beratools.tools.centerline.sp_common.check_vector_raster_extent_overlap", + "beratools.modules.mapping.centerline.sp_common.check_vector_raster_extent_overlap", lambda *_args, **_kwargs: True, ) @@ -863,7 +897,10 @@ def _fake_generate(*_args, **_kwargs): called["generate"] += 1 raise RuntimeError("should-not-be-called") - monkeypatch.setattr("beratools.tools.centerline.generate_line_class_list", _fake_generate) + monkeypatch.setattr( + "beratools.modules.mapping.centerline.generate_line_class_list", + _fake_generate, + ) result = centerline( in_line="dummy.gpkg|line", @@ -879,27 +916,34 @@ def _fake_generate(*_args, **_kwargs): def test_centerline_tool_continues_when_lines_partially_overlap_raster(monkeypatch): _patch_raster_open(monkeypatch) - from beratools.tools.centerline import centerline + from beratools.modules.mapping.centerline import centerline class _FakeOSR: def ExportToWkt(self): return pyproj.CRS.from_epsg(2263).to_wkt() monkeypatch.setattr( - "beratools.tools.centerline.sp_common.vector_crs", lambda *_args, **_kwargs: _FakeOSR() + "beratools.modules.mapping.centerline.sp_common.vector_crs", + lambda *_args, **_kwargs: _FakeOSR(), + ) + monkeypatch.setattr( + "beratools.modules.mapping.centerline.sp_common.raster_crs", + lambda *_args, **_kwargs: object(), + ) + monkeypatch.setattr( + "beratools.modules.mapping.centerline.sp_common.compare_crs", + lambda *_args, **_kwargs: True, ) - monkeypatch.setattr("beratools.tools.centerline.sp_common.raster_crs", lambda *_args, **_kwargs: object()) - monkeypatch.setattr("beratools.tools.centerline.sp_common.compare_crs", lambda *_args, **_kwargs: True) monkeypatch.setattr( - "beratools.tools.centerline.gpd.read_file", + "beratools.modules.mapping.centerline.gpd.read_file", lambda *_args, **_kwargs: gpd.GeoDataFrame(geometry=[LineString([(0, 0), (1, 0)])], crs="EPSG:2263"), ) monkeypatch.setattr( - "beratools.tools.centerline.sp_common.check_vector_raster_overlap", + "beratools.modules.mapping.centerline.sp_common.check_vector_raster_overlap", lambda *_args, **_kwargs: True, ) monkeypatch.setattr( - "beratools.tools.centerline.sp_common.check_vector_raster_extent_overlap", + "beratools.modules.mapping.centerline.sp_common.check_vector_raster_extent_overlap", lambda *_args, **_kwargs: True, ) @@ -909,7 +953,10 @@ def _fake_generate(*_args, **_kwargs): called["generate"] += 1 return [] - monkeypatch.setattr("beratools.tools.centerline.generate_line_class_list", _fake_generate) + monkeypatch.setattr( + "beratools.modules.mapping.centerline.generate_line_class_list", + _fake_generate, + ) result = centerline( in_line="dummy.gpkg|line", @@ -925,19 +972,26 @@ def _fake_generate(*_args, **_kwargs): def test_centerline_tool_terminates_on_extent_precheck_without_loading_features(monkeypatch): _patch_raster_open(monkeypatch) - from beratools.tools.centerline import centerline + from beratools.modules.mapping.centerline import centerline class _FakeOSR: def ExportToWkt(self): return pyproj.CRS.from_epsg(2263).to_wkt() monkeypatch.setattr( - "beratools.tools.centerline.sp_common.vector_crs", lambda *_args, **_kwargs: _FakeOSR() + "beratools.modules.mapping.centerline.sp_common.vector_crs", + lambda *_args, **_kwargs: _FakeOSR(), + ) + monkeypatch.setattr( + "beratools.modules.mapping.centerline.sp_common.raster_crs", + lambda *_args, **_kwargs: object(), + ) + monkeypatch.setattr( + "beratools.modules.mapping.centerline.sp_common.compare_crs", + lambda *_args, **_kwargs: True, ) - monkeypatch.setattr("beratools.tools.centerline.sp_common.raster_crs", lambda *_args, **_kwargs: object()) - monkeypatch.setattr("beratools.tools.centerline.sp_common.compare_crs", lambda *_args, **_kwargs: True) monkeypatch.setattr( - "beratools.tools.centerline.sp_common.check_vector_raster_extent_overlap", + "beratools.modules.mapping.centerline.sp_common.check_vector_raster_extent_overlap", lambda *_args, **_kwargs: False, ) @@ -947,7 +1001,10 @@ def _fake_read(*_args, **_kwargs): called["read"] += 1 raise RuntimeError("should-not-read") - monkeypatch.setattr("beratools.tools.centerline.gpd.read_file", _fake_read) + monkeypatch.setattr( + "beratools.modules.mapping.centerline.gpd.read_file", + _fake_read + ) result = centerline( in_line="dummy.gpkg|line", diff --git a/tests/test_algo_cost.py b/beratools/modules/mapping/tests/test_algo_cost.py similarity index 96% rename from tests/test_algo_cost.py rename to beratools/modules/mapping/tests/test_algo_cost.py index b6d8806..ef9f086 100644 --- a/tests/test_algo_cost.py +++ b/beratools/modules/mapping/tests/test_algo_cost.py @@ -5,7 +5,7 @@ from rasterio.transform import from_origin from shapely.geometry import LineString -from beratools.core.algo_cost import reduce_chm_in_line_buffer +from beratools.modules.mapping.algo_cost import reduce_chm_in_line_buffer @pytest.mark.parametrize("add_band", [False, True]) diff --git a/tests/test_algo_geometry.py b/beratools/modules/mapping/tests/test_algo_geometry.py similarity index 96% rename from tests/test_algo_geometry.py rename to beratools/modules/mapping/tests/test_algo_geometry.py index 99ae7a5..d86c050 100644 --- a/tests/test_algo_geometry.py +++ b/beratools/modules/mapping/tests/test_algo_geometry.py @@ -1,6 +1,6 @@ from shapely.geometry import LineString, Polygon -from beratools.core.algo_geometry import ( +from beratools.modules.mapping.algo_geometry import ( chaikin_smooth_line, chaikin_smooth_polygon, process_corridor_polygon, diff --git a/tests/test_canopy_footprint_absolute_tool.py b/beratools/modules/mapping/tests/test_canopy_footprint_absolute_tool.py similarity index 97% rename from tests/test_canopy_footprint_absolute_tool.py rename to beratools/modules/mapping/tests/test_canopy_footprint_absolute_tool.py index 02ed423..3ffd680 100644 --- a/tests/test_canopy_footprint_absolute_tool.py +++ b/beratools/modules/mapping/tests/test_canopy_footprint_absolute_tool.py @@ -3,7 +3,7 @@ import pytest from shapely.geometry import LineString, Polygon -import beratools.tools.canopy_footprint_absolute as cfa +import beratools.modules.mapping.canopy_footprint_absolute as cfa class _FakeOSR: @@ -125,7 +125,7 @@ def _fake_run(req): def test_process_footprint_polygon_gdf_simplifies_and_smooths(): - from beratools.core.algo_canopy_footprint_absolute import process_footprint_polygon_gdf + from beratools.modules.mapping.algo_canopy_footprint_absolute import process_footprint_polygon_gdf polygon = Polygon([(0, 0), (4, 0), (4, 2), (0, 2), (0, 0)]) gdf = gpd.GeoDataFrame(geometry=[polygon], crs="EPSG:3857") diff --git a/tests/test_canopy_footprint_adapters.py b/beratools/modules/mapping/tests/test_canopy_footprint_adapters.py similarity index 81% rename from tests/test_canopy_footprint_adapters.py rename to beratools/modules/mapping/tests/test_canopy_footprint_adapters.py index ef268d6..590cd95 100644 --- a/tests/test_canopy_footprint_adapters.py +++ b/beratools/modules/mapping/tests/test_canopy_footprint_adapters.py @@ -3,12 +3,15 @@ from types import SimpleNamespace import geopandas as gpd -import shapely.geometry as sh_geom -import pytest import pyproj +import pytest +import shapely.geometry as sh_geom -from beratools.core.algo_canopy_footprint_absolute import CanopyFootprintRequest, cast_request_types -from beratools.tools.canopy_footprint_absolute import ( +from beratools.modules.mapping.algo_canopy_footprint_absolute import ( + CanopyFootprintRequest, + cast_request_types, +) +from beratools.modules.mapping.canopy_footprint_absolute import ( _run_absolute_request, _run_adaptive_request, canopy_footprint_abs, @@ -29,11 +32,11 @@ def test_run_absolute_request_returns_contract_shape(monkeypatch): fake_items = [SimpleNamespace(footprint=_single_poly_gdf()), SimpleNamespace(footprint=None)] monkeypatch.setattr( - "beratools.tools.canopy_footprint_absolute.generate_absolute_line_class_list", + "beratools.modules.mapping.canopy_footprint_absolute.generate_absolute_line_class_list", lambda *args, **kwargs: fake_line_classes, ) monkeypatch.setattr( - "beratools.tools.canopy_footprint_absolute.bt_base.execute_multiprocessing", + "beratools.modules.mapping.canopy_footprint_absolute.bt_base.execute_multiprocessing", lambda *args, **kwargs: fake_items, ) @@ -78,7 +81,10 @@ def __init__(self, *args, **kwargs): def compute(self, processes, call_mode=CallMode.CLI): return None - monkeypatch.setattr("beratools.tools.canopy_footprint_absolute.FootprintCanopyAdaptive", FakeAdaptive) + monkeypatch.setattr( + "beratools.modules.mapping.canopy_footprint_absolute.FootprintCanopyAdaptive", + FakeAdaptive + ) req = cast_request_types( CanopyFootprintRequest( @@ -124,30 +130,30 @@ def ExportToWkt(self): return self._crs_text monkeypatch.setattr( - "beratools.tools.canopy_footprint_absolute.sp_common.vector_crs", + "beratools.modules.mapping.canopy_footprint_absolute.sp_common.vector_crs", lambda *_args, **_kwargs: _FakeOSR(pyproj.CRS.from_epsg(2263).to_wkt()), ) monkeypatch.setattr( - "beratools.tools.canopy_footprint_absolute.sp_common.raster_crs", + "beratools.modules.mapping.canopy_footprint_absolute.sp_common.raster_crs", lambda *_args, **_kwargs: object(), ) monkeypatch.setattr( - "beratools.tools.canopy_footprint_absolute.sp_common.compare_crs", + "beratools.modules.mapping.canopy_footprint_absolute.sp_common.compare_crs", lambda *_args, **_kwargs: True, ) monkeypatch.setattr( - "beratools.tools.canopy_footprint_absolute.sp_common.check_vector_raster_extent_overlap", + "beratools.modules.mapping.canopy_footprint_absolute.sp_common.check_vector_raster_extent_overlap", lambda *_args, **_kwargs: True, ) monkeypatch.setattr( - "beratools.tools.canopy_footprint_absolute.gpd.read_file", + "beratools.modules.mapping.canopy_footprint_absolute.gpd.read_file", lambda *_args, **_kwargs: gpd.GeoDataFrame( geometry=[sh_geom.LineString([(0.0, 0.0), (1.0, 0.0)])], crs="EPSG:2263", ), ) monkeypatch.setattr( - "beratools.tools.canopy_footprint_absolute.sp_common.check_vector_raster_overlap", + "beratools.modules.mapping.canopy_footprint_absolute.sp_common.check_vector_raster_overlap", lambda *_args, **_kwargs: True, ) @@ -156,11 +162,11 @@ def _fake_run_absolute(req): return SimpleNamespace(messages=[], footprints_gdf=gpd.GeoDataFrame(), aux_layers={}, stats={}) monkeypatch.setattr( - "beratools.tools.canopy_footprint_absolute._run_absolute_request", + "beratools.modules.mapping.canopy_footprint_absolute._run_absolute_request", _fake_run_absolute, ) monkeypatch.setattr( - "beratools.tools.canopy_footprint_absolute.save_main_footprint", + "beratools.modules.mapping.canopy_footprint_absolute.save_main_footprint", lambda *_args, **_kwargs: True, ) @@ -184,7 +190,7 @@ def ExportToWkt(self): return self._crs_text monkeypatch.setattr( - "beratools.tools.canopy_footprint_absolute.sp_common.vector_crs", + "beratools.modules.mapping.canopy_footprint_absolute.sp_common.vector_crs", lambda *_args, **_kwargs: _FakeOSR(pyproj.CRS.from_epsg(4326).to_wkt()), ) @@ -211,7 +217,10 @@ def __init__(self, *args, **kwargs): def compute(self, processes, call_mode=CallMode.CLI): return None - monkeypatch.setattr("beratools.tools.canopy_footprint_absolute.FootprintCanopyAdaptive", FakeAdaptive) + monkeypatch.setattr( + "beratools.modules.mapping.canopy_footprint_absolute.FootprintCanopyAdaptive", + FakeAdaptive, + ) req = cast_request_types( CanopyFootprintRequest( @@ -245,7 +254,10 @@ def compute(self, processes, call_mode=CallMode.CLI): captured["processes"] = processes captured["call_mode"] = call_mode - monkeypatch.setattr("beratools.tools.canopy_footprint_absolute.FootprintCanopyAdaptive", FakeAdaptive) + monkeypatch.setattr( + "beratools.modules.mapping.canopy_footprint_absolute.FootprintCanopyAdaptive", + FakeAdaptive, + ) req = cast_request_types( CanopyFootprintRequest( diff --git a/tests/test_canopy_footprint_common.py b/beratools/modules/mapping/tests/test_canopy_footprint_common.py similarity index 96% rename from tests/test_canopy_footprint_common.py rename to beratools/modules/mapping/tests/test_canopy_footprint_common.py index eee1be5..ae0b769 100644 --- a/tests/test_canopy_footprint_common.py +++ b/beratools/modules/mapping/tests/test_canopy_footprint_common.py @@ -2,7 +2,7 @@ import geopandas as gpd -from beratools.core.algo_canopy_footprint_absolute import ( +from beratools.modules.mapping.algo_canopy_footprint_absolute import ( CanopyFootprintRequest, CanopyFootprintResult, cast_request_types, diff --git a/tests/test_check_seed_line_qc.py b/beratools/modules/mapping/tests/test_check_seed_line_qc.py similarity index 98% rename from tests/test_check_seed_line_qc.py rename to beratools/modules/mapping/tests/test_check_seed_line_qc.py index 2c73948..aa33de6 100644 --- a/tests/test_check_seed_line_qc.py +++ b/beratools/modules/mapping/tests/test_check_seed_line_qc.py @@ -1,16 +1,16 @@ +import sqlite3 + import geopandas as gpd import numpy as np import pytest from shapely.geometry import GeometryCollection, LineString, MultiLineString, Point, Polygon, box -import json -import sqlite3 -from pathlib import Path import beratools.core.constants as bt_const -import beratools.core.algo_check_seed_line as acsl -import beratools.core.algo_check_seed_line_validate as acsl_report -from beratools.core.algo_common import clean_line_geometries -import beratools.tools.check_seed_line as csl +import beratools.modules.mapping.algo_check_seed_line as acsl +import beratools.modules.mapping.algo_check_seed_line_validate as acsl_report +import beratools.modules.mapping.check_seed_line as csl +from beratools.core.registry import get_registry +from beratools.modules.mapping.algo_common import clean_line_geometries def _write_seed_input(tmp_path, geoms, data=None, layer="seed_lines", crs="EPSG:3857"): @@ -650,7 +650,7 @@ def test_qc_merge_multilinestring_mixed_geometry_types(monkeypatch): ) monkeypatch.setattr( - "beratools.core.algo_merge_lines.custom_line_merge", + "beratools.modules.mapping.algo_merge_lines.custom_line_merge", lambda geom: MultiLineString(getattr(geom, "geoms", [])), ) @@ -698,7 +698,7 @@ def test_check_seed_line_raises_when_seedlines_do_not_overlap_raster(tmp_path, m monkeypatch.setattr(csl.sp_common, "raster_crs", lambda *_args, **_kwargs: object()) monkeypatch.setattr(csl.sp_common, "compare_crs", lambda *_args, **_kwargs: True) monkeypatch.setattr( - csl.algo_common, + csl.sp_common, "generate_raster_footprint", lambda *_args, **_kwargs: Point(100.0, 100.0).buffer(100.0), ) @@ -751,7 +751,7 @@ def test_check_seed_line_assigns_unique_bt_group_when_grouping_disabled(tmp_path monkeypatch.setattr(csl.sp_common, "raster_crs", lambda *_args, **_kwargs: object()) monkeypatch.setattr(csl.sp_common, "compare_crs", lambda *_args, **_kwargs: True) monkeypatch.setattr( - csl.algo_common, + csl.sp_common, "generate_raster_footprint", lambda *_args, **_kwargs: Point(0.0, 0.0).buffer(50.0), ) @@ -777,7 +777,7 @@ def test_clip_to_chm_footprint_shrink_is_meters_for_geographic_crs(monkeypatch): ) monkeypatch.setattr( - csl.algo_common, + csl.sp_common, "generate_raster_footprint", lambda *_args, **_kwargs: box(-0.001, -0.001, 0.001, 0.001), ) @@ -801,7 +801,7 @@ def test_clip_to_chm_footprint_geographic_overshrink_raises(monkeypatch): ) monkeypatch.setattr( - csl.algo_common, + csl.sp_common, "generate_raster_footprint", lambda *_args, **_kwargs: box(-0.00005, -0.00005, 0.00005, 0.00005), ) @@ -1003,7 +1003,7 @@ def test_check_seed_line_grouping_and_densify_enabled_paths(tmp_path, monkeypatc ) out_gpkg = tmp_path / "seed_output.gpkg" - import beratools.core.algo_line_grouping as alg_lg + import beratools.modules.mapping.algo_line_grouping as alg_lg densify_calls = [] @@ -1049,7 +1049,7 @@ def test_check_seed_line_runs_seed_line_correction_branch(tmp_path, monkeypatch) in_gpkg = _write_seed_input(tmp_path, [LineString([(0.0, 0.0), (5.0, 0.0)])]) out_gpkg = tmp_path / "seed_output.gpkg" - import beratools.core.algo_seed_line_correction as asc + import beratools.modules.mapping.algo_seed_line_correction as asc init_args = {} saved_layers = [] @@ -1216,7 +1216,7 @@ def test_check_seed_line_writes_qc_doc_tables(tmp_path, monkeypatch): monkeypatch.setattr(csl.sp_common, "raster_crs", lambda *_args, **_kwargs: object()) monkeypatch.setattr(csl.sp_common, "compare_crs", lambda *_args, **_kwargs: True) monkeypatch.setattr( - csl.algo_common, + csl.sp_common, "generate_raster_footprint", lambda *_args, **_kwargs: box(-20.0, -20.0, 20.0, 20.0), ) @@ -1290,7 +1290,7 @@ def test_check_seed_line_overwrites_qc_tables_on_rerun(tmp_path, monkeypatch): monkeypatch.setattr(csl.sp_common, "raster_crs", lambda *_args, **_kwargs: object()) monkeypatch.setattr(csl.sp_common, "compare_crs", lambda *_args, **_kwargs: True) monkeypatch.setattr( - csl.algo_common, + csl.sp_common, "generate_raster_footprint", lambda *_args, **_kwargs: box(-20.0, -20.0, 20.0, 20.0), ) @@ -1327,8 +1327,7 @@ def test_check_seed_line_overwrites_qc_tables_on_rerun(tmp_path, monkeypatch): def test_schema_marks_chm_shrink_as_optional(): - schema_path = Path(__file__).resolve().parents[1] / "beratools" / "gui" / "assets" / "beratools.json" - data = json.loads(schema_path.read_text(encoding="utf-8")) + data = get_registry().as_dict() check_tool = None for category in data.get("toolbox", []): @@ -1386,8 +1385,7 @@ def test_schema_marks_chm_shrink_as_optional(): def test_schema_centerline_exposes_guided_strategy_parameter(): - schema_path = Path(__file__).resolve().parents[1] / "beratools" / "gui" / "assets" / "beratools.json" - data = json.loads(schema_path.read_text(encoding="utf-8")) + data = get_registry().as_dict() centerline_tool = None for category in data.get("toolbox", []): diff --git a/tests/test_corridor_raster_generalization.py b/beratools/modules/mapping/tests/test_corridor_raster_generalization.py similarity index 96% rename from tests/test_corridor_raster_generalization.py rename to beratools/modules/mapping/tests/test_corridor_raster_generalization.py index 9989455..cb64cf2 100644 --- a/tests/test_corridor_raster_generalization.py +++ b/beratools/modules/mapping/tests/test_corridor_raster_generalization.py @@ -1,10 +1,9 @@ -import numpy as np import geopandas as gpd +import numpy as np from rasterio.transform import Affine from shapely.geometry import LineString -from beratools.core import algo_centerline -from beratools.core import algo_common +from beratools.modules.mapping import algo_centerline, algo_common def test_corridor_threshold_to_mask_uses_zero_as_inside_corridor(): diff --git a/beratools/modules/mapping/tests/test_footprint_plots.py b/beratools/modules/mapping/tests/test_footprint_plots.py new file mode 100644 index 0000000..c7b3fa6 --- /dev/null +++ b/beratools/modules/mapping/tests/test_footprint_plots.py @@ -0,0 +1,620 @@ +"""Tests for the Footprint Plots and Subplots tool (ported from SegLine).""" + +import math +from pathlib import Path + +import geopandas as gpd +import pytest +import shapely +from shapely.geometry import GeometryCollection, LineString, Point, Polygon +from shapely.ops import unary_union + +from beratools.modules.mapping.algo_footprint_plots import ( + SIDE_LEFT, + SIDE_RIGHT, + area_mode_lengths, + clean_polygon, + estimate_width, + is_cardinal, + line_orientation, + polygon_parts, + prepare_centerline, + remove_overlap, + split_footprint, + subplot_stations, + trim_line_ends, +) +from beratools.modules.mapping.footprint_plots import ( + footprint_plots, + match_lines_to_footprints, + overlap_claims, +) + +WIDTH = 5.0 +SEGLINE_COLUMNS = [ + "UniqueID", + "side", + "plot_id", + "subplot_id", + "area", + "length", + "perimeter", + "plot_area", + "subplot_area", +] + + +def _split_area(line, footprint, plot_area=100, subplot_area=10): + centerline = prepare_centerline(line, footprint) + lengths = area_mode_lengths(estimate_width(footprint, centerline), plot_area, subplot_area) + return split_footprint(footprint, centerline, *lengths) + + +def _split_length(line, footprint, plot_length=50, subplot_length=10): + return split_footprint(footprint, prepare_centerline(line, footprint), plot_length, subplot_length) + + +def _assert_partition(footprint, subplots): + geoms = [geom for *_, geom in subplots] + union = unary_union(geoms) + assert union.area == pytest.approx(footprint.area, abs=1e-3) + assert sum(geom.area for geom in geoms) == pytest.approx(union.area, abs=1e-3) + keys = [(plot_id, side, subplot_id) for plot_id, side, subplot_id, *_ in subplots] + assert len(keys) == len(set(keys)) + + +def test_straight_footprint_gives_equal_plots_and_subplots(): + line = LineString([(0, 0), (200, 0)]) + footprint = line.buffer(WIDTH / 2, cap_style="flat") + + plots, subplots = _split_area(line, footprint) + + assert len(plots) == 20 + assert len(subplots) == 100 + assert all(geom.area == pytest.approx(50) for *_, geom in plots) + assert all(geom.area == pytest.approx(10) for *_, geom in subplots) + assert {subplot_id for _, _, subplot_id, *_ in subplots} == {0, 1, 2, 3, 4} + assert all(length == pytest.approx(4) for *_, length, _ in subplots) + assert all(length == pytest.approx(20) for *_, length, _ in plots) + _assert_partition(footprint, subplots) + + +def test_fixed_length_plots_keep_length_on_wider_line(): + line = LineString([(0, 0), (200, 0)]) + footprint = line.buffer(4.0, cap_style="flat") + + plots, subplots = _split_length(line, footprint) + + assert len(plots) == 8 + assert len(subplots) == 40 + assert all(geom.area == pytest.approx(200) for *_, geom in plots) + assert all(geom.area == pytest.approx(40) for *_, geom in subplots) + assert all(length == pytest.approx(10) for *_, length, _ in subplots) + _assert_partition(footprint, subplots) + + +def test_subplots_restart_at_each_plot_boundary(): + stations = subplot_stations(100, 50, 20) + + assert stations == [(0, 0), (20, 0), (40, 0), (50, 1), (70, 1), (90, 1)] + + +def test_short_pieces_join_previous_subplot(): + # 4 m pieces after 45 m and 95 m are shorter than half a subplot + stations = subplot_stations(99, 49, 15) + + assert stations == [(0, 0), (15, 0), (30, 0), (49, 1), (64, 1), (79, 1)] + + +def test_sides_follow_line_direction_with_uneven_footprint(): + line = LineString([(0, 0), (200, 0)]) + lobe = LineString([(60, 0), (60, 8)]).buffer(1.5, cap_style="flat") + footprint = line.buffer(WIDTH / 2, cap_style="flat").union(lobe) + + plots, subplots = _split_area(line, footprint) + + assert all(geom.centroid.y > 0 for _, side, _, geom in plots if side == SIDE_LEFT) + assert all(geom.centroid.y < 0 for _, side, _, geom in plots if side == SIDE_RIGHT) + _assert_partition(footprint, subplots) + + +@pytest.mark.parametrize( + "coords", + [ + [(0, 0), (100, 0), (160, 60)], + [(0, 0), (100, 0), (100, 12), (0, 12)], + ], +) +def test_bent_footprint_is_partitioned(coords): + line = LineString(coords) + footprint = line.buffer(WIDTH / 2, cap_style="flat", join_style="mitre") + + _, subplots = _split_area(line, footprint) + _assert_partition(footprint, subplots) + for side in (SIDE_LEFT, SIDE_RIGHT): + side_length = sum(length for _, s, _, length, _ in subplots if s == side) + assert side_length == pytest.approx(line.length) + mean_area = sum(geom.area for *_, geom in subplots) / len(subplots) + assert mean_area == pytest.approx(10, rel=0.05) + + _, subplots = _split_length(line, footprint) + _assert_partition(footprint, subplots) + + +def test_short_tail_joins_last_subplot(): + line = LineString([(0, 0), (203, 0)]) + footprint = line.buffer(WIDTH / 2, cap_style="flat") + + _, subplots = _split_area(line, footprint) + + assert min(geom.area for *_, geom in subplots) >= 5 + _assert_partition(footprint, subplots) + + +def test_centerline_longer_than_footprint_is_trimmed(): + line = LineString([(-500, 0), (700, 0)]) + footprint = LineString([(0, 0), (100, 0)]).buffer(WIDTH / 2, cap_style="flat") + + plots, subplots = _split_area(line, footprint) + + assert min(plot_id for plot_id, *_ in plots) == 0 + assert len(subplots) == 50 + + +def test_match_lines_to_footprints_uses_longest_overlap(): + footprints = gpd.GeoDataFrame(geometry=[LineString([(0, 0), (100, 0)]).buffer(2.5, cap_style="flat")]) + lines = gpd.GeoDataFrame( + geometry=[ + LineString([(50, -10), (50, 10)]), + LineString([(0, 0), (100, 0)]), + LineString([(0, 50), (9, 50)]), + ] + ) + + assert match_lines_to_footprints(footprints, lines) == {0: 1} + + +@pytest.mark.parametrize( + ("coords", "angle", "cardinal"), + [ + ([(0, 0), (100, 0)], 0, True), + ([(100, 0), (0, 0)], 0, True), + ([(0, 0), (0, 100)], 90, True), + ([(0, 0), (100, 10)], 5.71, True), + ([(0, 0), (100, 100)], 45, False), + ([(0, 0), (100, -60)], 149.04, False), + ], +) +def test_line_orientation(coords, angle, cardinal): + line = LineString(coords) + assert line_orientation(line) == pytest.approx(angle, abs=0.01) + assert is_cardinal(line) is cardinal + + +def _claims(lines): + footprints = gpd.GeoDataFrame(geometry=[line.buffer(WIDTH / 2, cap_style="flat") for line in lines]) + end_claims, cut_claims = overlap_claims( + footprints, gpd.GeoDataFrame(geometry=lines), {i: i for i in range(len(lines))} + ) + return footprints, end_claims, cut_claims + + +def _overlap_area(footprints): + return footprints.geometry[0].intersection(footprints.geometry[1]).area + + +def test_cardinal_line_keeps_overlap_over_longer_diagonal(): + short_east_west = LineString([(0, 0), (100, 0)]) + long_diagonal = LineString([(-50, -150), (150, 150)]) + footprints, end_claims, cut_claims = _claims([long_diagonal, short_east_west]) + + assert not end_claims + assert set(cut_claims) == {0} + assert cut_claims[0].area == pytest.approx(_overlap_area(footprints)) + + +@pytest.mark.parametrize( + "lines", + [ + # both cardinal + [LineString([(100, -40), (100, 40)]), LineString([(0, 0), (200, 0)])], + # both diagonal + [LineString([(80, -20), (120, 20)]), LineString([(0, 100), (200, -100)])], + ], +) +def test_longer_centerline_keeps_overlap_in_same_direction_class(lines): + footprints, end_claims, cut_claims = _claims(lines) + + assert not end_claims + assert set(cut_claims) == {0} + assert cut_claims[0].area == pytest.approx(_overlap_area(footprints)) + + +def test_line_ending_in_overlap_always_loses(): + # a short north-south line ends on a long diagonal line, which would lose a crossing + ending_north_south = LineString([(100, 0), (100, 100)]) + through_diagonal = LineString([(0, 0), (200, 200)]) + footprints, end_claims, cut_claims = _claims([ending_north_south, through_diagonal]) + + assert set(end_claims) == {0} + assert not cut_claims + assert end_claims[0].area == pytest.approx(_overlap_area(footprints)) + + +def test_line_end_just_short_of_other_line_counts_as_ending(): + ending_north_south = LineString([(100, 0), (100, 95)]) + through_diagonal = LineString([(0, 0), (200, 200)]) + _, end_claims, _ = _claims([ending_north_south, through_diagonal]) + + assert set(end_claims) == {0} + + +def test_rule_decides_at_corner_and_loser_is_trimmed(): + # both lines end at the corner, so the east-west line keeps it + diagonal = LineString([(0, 0), (100, 100)]) + east_west = LineString([(100, 100), (300, 100)]) + _, end_claims, cut_claims = _claims([diagonal, east_west]) + + assert set(end_claims) == {0} + assert not cut_claims + + +def test_footprint_inside_another_loses_overlap(): + footprints, end_claims, _ = _claims([LineString([(10, 0), (20, 0)]), LineString([(0, 0), (200, 0)])]) + + assert end_claims[0].equals(footprints.geometry[0]) + + +def test_trim_line_ends_cuts_footprint_and_centerline(): + centerline = LineString([(100, 0), (100, 105)]) + footprint = centerline.buffer(WIDTH / 2, cap_style="flat") + # an east-west line footprint across the end, the centerline pokes 2.5 m past it + claimed = LineString([(0, 100), (200, 100)]).buffer(WIDTH / 2, cap_style="flat").intersection(footprint) + + trimmed_fp, trimmed_line, leftovers = trim_line_ends(footprint, centerline, claimed) + + assert trimmed_line.length == pytest.approx(97.5) + assert trimmed_line.coords[0] == (100, 0) + assert trimmed_fp.area == pytest.approx(97.5 * WIDTH) + assert trimmed_fp.intersection(claimed).area == pytest.approx(0, abs=1e-6) + # the 2.5 m poking out beyond the other line is cut off, not kept + assert [piece.area for piece in leftovers] == pytest.approx([2.5 * WIDTH]) + + +def test_trim_line_ends_keeps_fragments_away_from_overlap(): + centerline = LineString([(100, 0), (100, 100)]) + fragment = Point(110, 50).buffer(1) + footprint = centerline.buffer(WIDTH / 2, cap_style="flat").union(fragment) + claimed = LineString([(0, 100), (200, 100)]).buffer(WIDTH / 2, cap_style="flat").intersection(footprint) + + trimmed_fp, _, leftovers = trim_line_ends(footprint, centerline, claimed) + + assert trimmed_fp.contains(fragment.buffer(-0.01)) + assert not leftovers + + +def test_crossing_cut_keeps_pieces_in_their_subplot(): + # an east-west line with 10 m subplots, crossed by a 3 m wide north-south footprint + line = LineString([(0, 0), (100, 0)]) + footprint = line.buffer(WIDTH / 2, cap_style="flat") + _, subplots = _split_length(line, footprint, plot_length=50, subplot_length=10) + # the crossing leaves a 0.1 m strip of the 20-30 m subplot before it + claimed = LineString([(21.6, -10), (21.6, 10)]).buffer(1.5, cap_style="flat").intersection(footprint) + + result = remove_overlap(subplots, claimed) + + by_key = {(plot_idx, side, subplot_idx): geom for plot_idx, side, subplot_idx, _, geom in result} + for side in (SIDE_LEFT, SIDE_RIGHT): + # the 20-30 m subplot keeps both pieces and stays between its cross cuts + pieces = shapely.get_parts(by_key[(0, side, 2)]) + assert sorted(piece.area for piece in pieces) == pytest.approx([0.1 * WIDTH / 2, 6.9 * WIDTH / 2]) + assert by_key[(0, side, 2)].bounds[0] == pytest.approx(20) + assert by_key[(0, side, 2)].bounds[2] == pytest.approx(30) + assert by_key[(0, side, 1)].area == pytest.approx(10 * WIDTH / 2) + total = sum(geom.area for geom in by_key.values()) + assert total == pytest.approx(footprint.area - claimed.area) + + +def test_clean_polygon_removes_zero_width_spike(): + # a square with a 5 m spike that runs out and straight back + spiky = Polygon([(0, 0), (2, 0), (2, 1), (7, 1), (2, 1.0000000001), (2, 2), (0, 2)]) + + cleaned = clean_polygon(spiky) + + assert cleaned.area == pytest.approx(4) + assert cleaned.length == pytest.approx(8, abs=1e-5) + + +def _spikes(geoms): + """Count polygon parts whose outline has zero-width spikes (outline lost by a tiny opening).""" + count = 0 + for geom in geoms: + for part in shapely.get_parts(geom): + opened = part.buffer(-0.01, join_style="mitre").buffer(0.01, join_style="mitre") + if part.length - opened.length > 0.2 and part.area - opened.area < 0.01: + count += 1 + return count + + +@pytest.mark.parametrize("mode", ["fixed_area", "fixed_length"]) +@pytest.mark.parametrize("angle", [20, 35, 60]) +def test_remove_overlap_leaves_no_spikes_at_shallow_angles(tmp_path, mode, angle): + # a through line, a line crossing it and a line ending on it, both at a shallow angle + dx, dy = math.cos(math.radians(angle)), math.sin(math.radians(angle)) + through = LineString([(0, 0), (300, 0)]) + crossing = LineString([(60 - 40 * dx, -40 * dy), (60 + 40 * dx, 40 * dy)]) + ending = LineString([(200 - 60 * dx, -60 * dy), (200, 0)]) + lines = [through, crossing, ending] + line_gdf = gpd.GeoDataFrame({"line_id": [1, 2, 3]}, geometry=lines, crs="EPSG:2956") + footprints = [line.buffer(WIDTH / 2, cap_style="flat") for line in lines] + fp_gdf = gpd.GeoDataFrame(geometry=footprints, crs="EPSG:2956") + in_file = tmp_path / "input.gpkg" + line_gdf.to_file(in_file, layer="centerline") + fp_gdf.to_file(in_file, layer="footprint") + + plots, subplots = _run(tmp_path, in_file, mode=mode, remove_overlap=True) + + assert _spikes(subplots.geometry) == 0 + assert _spikes(plots.geometry) == 0 + assert subplots.area.sum() == pytest.approx(fp_gdf.union_all().area, abs=1e-2) + # the trimmed end keeps a subplot on both sides + ending_plots = subplots.loc[subplots["line_id"] == 3].groupby("plot_id")["side"].nunique() + assert (ending_plots == 2).all() + + +def test_polygon_parts_drops_line_like_leftovers(): + square = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]) + sliver = Polygon([(2, 0), (5, 0), (5, 1e-9), (2, 1e-9)]) + mixed = GeometryCollection([square, sliver, LineString([(0, 5), (3, 5)])]) + + parts = polygon_parts(mixed) + assert len(parts) == 1 + assert parts[0].equals(square) + + +@pytest.mark.filterwarnings("ignore:invalid value encountered:RuntimeWarning") +@pytest.mark.parametrize("mode", ["fixed_area", "fixed_length"]) +def test_remove_overlap_drops_piece_where_line_end_pokes_through(tmp_path, mode): + # the north-south line runs 1 m past the far side of the east-west footprint + lines = [LineString([(0, 100), (200, 100)]), LineString([(100, 0), (100, 103.5)])] + line_gdf = gpd.GeoDataFrame({"line_id": [1, 2]}, geometry=lines, crs="EPSG:2956") + footprints = [line.buffer(WIDTH / 2, cap_style="flat") for line in lines] + fp_gdf = gpd.GeoDataFrame(geometry=footprints, crs="EPSG:2956") + in_file = tmp_path / "input.gpkg" + line_gdf.to_file(in_file, layer="centerline") + fp_gdf.to_file(in_file, layer="footprint") + + _, subplots = _run(tmp_path, in_file, mode=mode, remove_overlap=True) + + # the 1 m poke-through piece is dropped, it doesn't join the east-west line + union_area = fp_gdf.union_all().area + assert subplots.area.sum() == pytest.approx(union_area - 1.0 * WIDTH, abs=1e-2) + assert subplots.union_all().area == pytest.approx(subplots.area.sum(), abs=1e-2) + through = subplots.loc[subplots["line_id"] == 1] + assert through.area.sum() == pytest.approx(fp_gdf.area[0], abs=1e-2) + assert through.union_all().difference(fp_gdf.geometry[0]).area == pytest.approx(0, abs=1e-3) + parts = [part for geom in subplots.geometry for part in shapely.get_parts(geom)] + assert min(part.area for part in parts) > 1e-3 + + +def _run(tmp_path, in_file, **kwargs): + out_file = tmp_path / "output.gpkg" + footprint_plots( + in_footprint=f"{in_file.as_posix()}|footprint", + in_line=f"{in_file.as_posix()}|centerline", + out_plot=f"{out_file.as_posix()}|plots", + out_subplot=f"{out_file.as_posix()}|subplots", + processes=1, + **kwargs, + ) + return gpd.read_file(out_file, layer="plots"), gpd.read_file(out_file, layer="subplots") + + +# SegLine sample lines and footprints (see data/Seg_Plot/README.md): footprint i belongs to centerline i +SEG_PLOT_DIR = Path(__file__).parent / "data" / "Seg_Plot" +SAMPLE_FOOTPRINT = f"{(SEG_PLOT_DIR / 'sample_footprint.gpkg').as_posix()}|footprint" +SAMPLE_CENTERLINE = f"{(SEG_PLOT_DIR / 'sample_centerlines.gpkg').as_posix()}|centerlines" +SAMPLE_IDS = [f"fp{i}" for i in range(8)] +# lines that end in another line's footprint, and lines that keep crossings with others +SAMPLE_ENDING = {2, 4, 5, 6, 7} +SAMPLE_CUTTING = {0, 3, 4} +MODES = ["fixed_area", "fixed_length"] + + +@pytest.fixture(scope="module") +def sample(): + footprints = gpd.read_file(SEG_PLOT_DIR / "sample_footprint.gpkg", layer="footprint") + lines = gpd.read_file(SEG_PLOT_DIR / "sample_centerlines.gpkg", layer="centerlines") + return footprints, lines + + +@pytest.fixture(scope="module") +def run_sample(tmp_path_factory, sample): + """Run the tool on the sample once per option set, with UniqueIDs fp0-fp7 to map outputs back.""" + in_file = tmp_path_factory.mktemp("seg_plot_in") / "footprint.gpkg" + sample[0].assign(UniqueID=SAMPLE_IDS).to_file(in_file, layer="footprint") + cache = {} + + def run(mode="fixed_area", remove_overlap=False): + if (mode, remove_overlap) not in cache: + out_file = tmp_path_factory.mktemp("seg_plot_out") / "output.gpkg" + footprint_plots( + in_footprint=f"{in_file.as_posix()}|footprint", + in_line=SAMPLE_CENTERLINE, + out_plot=f"{out_file.as_posix()}|plots", + out_subplot=f"{out_file.as_posix()}|subplots", + mode=mode, + remove_overlap=remove_overlap, + processes=1, + ) + cache[(mode, remove_overlap)] = ( + gpd.read_file(out_file, layer="plots"), + gpd.read_file(out_file, layer="subplots"), + ) + return cache[(mode, remove_overlap)] + + return run + + +def _assert_plot_areas_add_up(subplots): + by_plot = subplots.groupby(["plot_id", "side"]) + assert by_plot["plot_area"].first().values == pytest.approx(by_plot["area"].sum().values, abs=0.1) + + +def test_sample_lines_match_their_footprints(sample): + footprints, lines = sample + + assert match_lines_to_footprints(footprints, lines) == {i: i for i in range(8)} + + +def test_sample_overlap_claims(sample): + footprints, lines = sample + + end_claims, cut_claims = overlap_claims(footprints, lines, {i: i for i in range(8)}) + + assert set(end_claims) == SAMPLE_ENDING + assert set(cut_claims) == SAMPLE_CUTTING + for idx, claim in {**end_claims, **cut_claims}.items(): + assert claim.area > 0 + assert claim.difference(footprints.geometry[idx]).area == pytest.approx(0, abs=1e-6) + + +@pytest.mark.parametrize("mode", MODES) +def test_footprint_plots_writes_segline_columns(sample, run_sample, mode): + footprints, lines = sample + + plots, subplots = run_sample(mode) + + assert set(SEGLINE_COLUMNS) <= set(subplots.columns) + assert sorted(subplots["UniqueID"].unique()) == SAMPLE_IDS + assert set(plots["UniqueID"]) == set(SAMPLE_IDS) + assert set(subplots["side"]) == {0, 1} + assert subplots["subplot_id"].is_unique + assert not plots.duplicated(["plot_id", "side"]).any() + assert subplots.groupby("plot_id")["UniqueID"].nunique().max() == 1 + assert (subplots["subplot_area"] == subplots["area"]).all() + assert subplots["area"].values == pytest.approx(subplots.area.values, abs=0.05) + assert subplots["perimeter"].values == pytest.approx(subplots.geometry.length.values, abs=0.05) + assert subplots.is_valid.all() and plots.is_valid.all() + _assert_plot_areas_add_up(subplots) + line_length = dict(zip(SAMPLE_IDS, lines.length)) + for side in (0, 1): + plot_length = plots.loc[plots["side"] == side].groupby("UniqueID")["length"].sum() + assert plot_length.values == pytest.approx([line_length[uid] for uid in plot_length.index], rel=0.005) + # each length is rounded to 0.1 m, so the error grows with the number of pieces + side_subplots = subplots.loc[subplots["side"] == side].groupby("UniqueID")["length"] + rounding = 0.05 * (side_subplots.size() + plots.loc[plots["side"] == side].groupby("UniqueID").size()) + assert (side_subplots.sum() - plot_length).abs().le(rounding).all() + + +@pytest.mark.parametrize("mode", MODES) +def test_overlap_is_kept_by_default(sample, run_sample, mode): + footprints, _ = sample + + _, subplots = run_sample(mode) + + fp_area = dict(zip(SAMPLE_IDS, footprints.area)) + by_fp = subplots.area.groupby(subplots["UniqueID"]).sum() + assert by_fp.values == pytest.approx([fp_area[uid] for uid in by_fp.index], abs=1e-2) + assert subplots.union_all().area == pytest.approx(footprints.union_all().area, abs=1e-2) + + +def test_fixed_area_subplots_hit_target_area(run_sample): + plots, subplots = run_sample("fixed_area") + + assert subplots.area.median() == pytest.approx(10, abs=0.01) + assert subplots.area.mean() == pytest.approx(10, rel=0.01) + # full plots hold 100 m2 over both sides + assert plots.groupby("plot_id")["plot_area"].sum().median() == pytest.approx(100, abs=0.1) + + +def test_fixed_length_subplots_hit_target_length(run_sample): + plots, subplots = run_sample("fixed_length") + + assert subplots["length"].median() == pytest.approx(10, abs=0.01) + assert plots["length"].median() == pytest.approx(50, abs=0.01) + # pieces shorter than half a subplot join the one before + assert subplots["length"].min() >= 5 + + +@pytest.mark.parametrize("mode", MODES) +def test_remove_overlap_counts_each_area_once(sample, run_sample, mode): + footprints, _ = sample + + plots, subplots = run_sample(mode, remove_overlap=True) + + union_area = footprints.union_all().area + assert subplots.union_all().area == pytest.approx(subplots.area.sum(), abs=1e-2) + assert plots.area.sum() == pytest.approx(subplots.area.sum(), abs=1e-2) + # only the small pieces where line ends poke through another footprint are dropped + assert union_area - 2 < subplots.area.sum() <= union_area + 1e-2 + _assert_plot_areas_add_up(subplots) + assert _spikes(subplots.geometry) == 0 + assert _spikes(plots.geometry) == 0 + # line 1 loses no overlap, so it keeps its whole footprint + line_1 = subplots.loc[subplots["UniqueID"] == "fp1"] + assert line_1.area.sum() == pytest.approx(footprints.area[1], abs=1e-2) + + +@pytest.mark.parametrize("mode", MODES) +def test_remove_overlap_trims_lines_ending_in_overlap(sample, run_sample, mode): + footprints, lines = sample + end_claims, _ = overlap_claims(footprints, lines, {i: i for i in range(8)}) + + _, subplots = run_sample(mode, remove_overlap=True) + + for idx, claim in end_claims.items(): + ending = subplots.loc[subplots["UniqueID"] == SAMPLE_IDS[idx]] + assert ending.union_all().intersection(claim).area == pytest.approx(0, abs=1e-3) + for side in (0, 1): + assert ending.loc[ending["side"] == side, "length"].sum() < lines.length[idx] + # the trimmed end keeps a subplot on both sides + assert (ending.groupby("plot_id")["side"].nunique() == 2).all() + + +@pytest.mark.parametrize("mode", MODES) +def test_remove_overlap_keeps_subplots_in_their_slot_at_crossings(sample, run_sample, mode): + footprints, lines = sample + + _, subplots = run_sample(mode, remove_overlap=True) + + for idx in SAMPLE_CUTTING - SAMPLE_ENDING: + crossed = subplots.loc[subplots["UniqueID"] == SAMPLE_IDS[idx]] + line = lines.geometry[idx] + for geom, length in zip(crossed.geometry, crossed["length"]): + along = [line.project(Point(xy)) for xy in shapely.get_coordinates(geom)] + assert max(along) - min(along) <= length + 0.5 + assert crossed.groupby("plot_id")["side"].nunique().min() == 2 + + +def test_footprint_plots_generates_unique_ids(tmp_path): + out_file = tmp_path / "output.gpkg" + + footprint_plots( + in_footprint=SAMPLE_FOOTPRINT, + in_line=SAMPLE_CENTERLINE, + out_plot=f"{out_file.as_posix()}|plots", + out_subplot=f"{out_file.as_posix()}|subplots", + mode="fixed_length", + processes=1, + ) + + subplots = gpd.read_file(out_file, layer="subplots") + ids = subplots["UniqueID"].unique() + assert len(ids) == 8 + assert all(len(uid) == 6 for uid in ids) + # input columns are carried over + assert set(subplots["width"]) == {3.0, 4.0, 5.0} + + +@pytest.mark.parametrize( + "kwargs", + [ + {"plot_area": 10, "subplot_area": 10}, + {"mode": "fixed_length", "plot_length": 5, "subplot_length": 10}, + {"mode": "fixed_volume"}, + ], +) +def test_footprint_plots_rejects_bad_options(kwargs): + with pytest.raises(ValueError): + footprint_plots("a.gpkg|fp", "a.gpkg|cl", "o.gpkg|p", "o.gpkg|s", **kwargs) diff --git a/tests/test_ground_footprint_units.py b/beratools/modules/mapping/tests/test_ground_footprint_units.py similarity index 99% rename from tests/test_ground_footprint_units.py rename to beratools/modules/mapping/tests/test_ground_footprint_units.py index b13eb17..780eb4a 100644 --- a/tests/test_ground_footprint_units.py +++ b/beratools/modules/mapping/tests/test_ground_footprint_units.py @@ -3,7 +3,7 @@ import pytest from shapely.geometry import LineString, Polygon -import beratools.tools.ground_footprint as gf +import beratools.modules.mapping.ground_footprint as gf class _DummyLineGrouping: diff --git a/beratools/modules/mapping/tests/test_mapping_tools_json.py b/beratools/modules/mapping/tests/test_mapping_tools_json.py new file mode 100644 index 0000000..cc83385 --- /dev/null +++ b/beratools/modules/mapping/tests/test_mapping_tools_json.py @@ -0,0 +1,34 @@ +"""The Mapping module's tools.json, as the frame loads it.""" + +from beratools.core import registry + +MODULE = "mapping" + +# The bt subcommands of this module's tools; they must not change +CLI_NAMES = { + "check_line": "check_seed_line", + "vertex_opt": "vertex_optimization", + "centerline": "centerline", + "smooth_line": "smooth_centerline", + "footprint_abs": "canopy_footprint_absolute", + "footprint_rel": "line_footprint_relative", + "footprint_grd": "ground_footprint", + "footprint_plots": "footprint_plots", +} + + +def _box(): + return next(box for box in registry.get_registry().toolbox if box["module"] == MODULE) + + +def test_module_loads_without_errors(): + assert [e for e in registry.get_registry().errors if e.startswith(f"{MODULE}:")] == [] + assert _box()["category"] == "Mapping" + + +def test_cli_names_are_unchanged(): + assert {tool["cli_name"]: tool["tool_api"] for tool in _box()["tools"]} == CLI_NAMES + + +def test_no_tool_is_wip(): + assert all(tool["status"] == "released" for tool in _box()["tools"]) diff --git a/tests/test_seed_line_correction.py b/beratools/modules/mapping/tests/test_seed_line_correction.py similarity index 98% rename from tests/test_seed_line_correction.py rename to beratools/modules/mapping/tests/test_seed_line_correction.py index c460924..a80410d 100644 --- a/tests/test_seed_line_correction.py +++ b/beratools/modules/mapping/tests/test_seed_line_correction.py @@ -3,10 +3,10 @@ import pandas as pd import shapely.geometry as sh_geom -import beratools.core.algo_common as algo_common import beratools.core.constants as bt_const -import beratools.core.algo_seed_line_correction as asc -from beratools.core.algo_seed_line_correction import SeedLineCorrection +import beratools.modules.mapping.algo_seed_line_correction as asc +import beratools.utility.spatial_common as sp_common +from beratools.modules.mapping.algo_seed_line_correction import SeedLineCorrection from beratools.utility.spatial_common import decode_file_layer @@ -59,7 +59,7 @@ def _make_slc(args, in_file, in_layer): def _make_local_slc(monkeypatch, *, close_distance=0.5, angle_tol=10.0): monkeypatch.setattr( - algo_common, + sp_common, "generate_raster_footprint", lambda *_args, **_kwargs: sh_geom.box(-100.0, -100.0, 100.0, 100.0), ) diff --git a/beratools/modules/mapping/tests/test_smooth_centerline.py b/beratools/modules/mapping/tests/test_smooth_centerline.py new file mode 100644 index 0000000..430ec0c --- /dev/null +++ b/beratools/modules/mapping/tests/test_smooth_centerline.py @@ -0,0 +1,90 @@ +"""Tests for the Smooth Centerline tool (ported from SegLine).""" + +from pathlib import Path + +import geopandas as gpd +import pytest +from shapely.geometry import LineString, MultiLineString + +from beratools.modules.mapping.algo_geometry import smooth_sharp_vertices, vertex_interior_angle +from beratools.modules.mapping.smooth_centerline import smooth_centerline + + +def test_vertex_interior_angle_straight_and_right_angle(): + assert vertex_interior_angle((0, 0), (1, 0), (2, 0)) == pytest.approx(180.0) + assert vertex_interior_angle((0, 0), (1, 0), (1, 1)) == pytest.approx(90.0) + + +def test_smooth_sharp_vertices_cuts_hairpin(): + line = LineString([(0, 0), (50, 0), (5, 25)]) + + smoothed = smooth_sharp_vertices(line, angle_threshold=130, buffer_distance=2) + + assert not smoothed.equals(line) + assert smoothed.is_valid + assert smoothed.hausdorff_distance(line) <= 2 + assert smoothed.coords[0] == line.coords[0] + assert smoothed.coords[-1] == line.coords[-1] + + +def test_smooth_sharp_vertices_keeps_gentle_bend(): + line = LineString([(0, 0), (50, 0), (100, 18)]) + + smoothed = smooth_sharp_vertices(line, angle_threshold=130, buffer_distance=2) + + assert smoothed.equals(line) + + +def test_smooth_sharp_vertices_only_changes_area_near_corner(): + line = LineString([(0, 0), (50, 0), (50, 50)]) + + smoothed = smooth_sharp_vertices(line, angle_threshold=130, buffer_distance=2) + + assert len(smoothed.coords) == 4 + assert smoothed.coords[1] == pytest.approx((48, 0)) + assert smoothed.coords[2] == pytest.approx((50, 2)) + + +def test_smooth_sharp_vertices_keeps_z(): + line = LineString([(0, 0, 5), (50, 0, 6), (50, 50, 7)]) + + smoothed = smooth_sharp_vertices(line, angle_threshold=130, buffer_distance=2) + + assert smoothed.has_z + + +def test_smooth_sharp_vertices_handles_disjoint_multilinestring(): + line = MultiLineString([[(0, 0), (50, 0), (50, 50)], [(100, 0), (150, 0)]]) + + smoothed = smooth_sharp_vertices(line, angle_threshold=130, buffer_distance=2) + + assert smoothed.geom_type == "MultiLineString" + assert len(smoothed.geoms) == 2 + assert not smoothed.geoms[0].equals(line.geoms[0]) + + +def test_smooth_centerline_tool_on_sample_lines(tmp_path): + in_file = Path(__file__).parent / "data" / "Seg_Plot" / "sample_centerlines.gpkg" + lines = gpd.read_file(in_file, layer="centerlines").assign(line_id=range(10, 18)) + lines.to_file(tmp_path / "lines.gpkg", layer="centerline") + out_file = tmp_path / "smoothed.gpkg" + + smooth_centerline( + in_line=f"{(tmp_path / 'lines.gpkg').as_posix()}|centerline", + out_line=f"{out_file.as_posix()}|centerline_smooth", + angle_threshold=130, + buffer_distance=2, + processes=1, + ) + + out = gpd.read_file(out_file, layer="centerline_smooth") + assert out.crs == lines.crs + assert list(out["line_id"]) == list(range(10, 18)) + # only lines 2, 4 and 6 have vertices sharper than 130 degrees + changed = [not geom.equals(src) for geom, src in zip(out.geometry, lines.geometry)] + assert changed == [False, False, True, False, True, False, True, False] + for geom, src in zip(out.geometry, lines.geometry): + assert geom.is_valid + assert geom.hausdorff_distance(src) <= 2 + assert geom.coords[0] == src.coords[0] + assert geom.coords[-1] == src.coords[-1] diff --git a/tests/test_tool_geo_simplify_single_geometry.py b/beratools/modules/mapping/tests/test_tool_geo_simplify_single_geometry.py similarity index 73% rename from tests/test_tool_geo_simplify_single_geometry.py rename to beratools/modules/mapping/tests/test_tool_geo_simplify_single_geometry.py index db7ca8d..af21fc0 100644 --- a/tests/test_tool_geo_simplify_single_geometry.py +++ b/beratools/modules/mapping/tests/test_tool_geo_simplify_single_geometry.py @@ -2,7 +2,7 @@ def test_simplify_line_reduce_bend_returns_input_when_diameter_zero(): - from beratools.core.tool_geo_simplify import simplify_line_reduce_bend + from beratools.modules.mapping.tool_geo_simplify import simplify_line_reduce_bend line = LineString([(0, 0), (1, 1), (2, 0)]) diff --git a/tests/test_tools.py b/beratools/modules/mapping/tests/test_tools.py similarity index 73% rename from tests/test_tools.py rename to beratools/modules/mapping/tests/test_tools.py index effd19c..c17db5b 100644 --- a/tests/test_tools.py +++ b/beratools/modules/mapping/tests/test_tools.py @@ -2,15 +2,17 @@ from pprint import pprint -from utils import check_file_exists - -from beratools.core.canopy_threshold_relative import main_canopy_threshold_relative -from beratools.core.line_footprint_functions import main_line_footprint_relative -from beratools.tools.canopy_footprint_absolute import canopy_footprint_abs -from beratools.tools.centerline import centerline -from beratools.tools.check_seed_line import check_seed_line -from beratools.tools.ground_footprint import ground_footprint -from beratools.tools.vertex_optimization import vertex_optimization +from mapping_test_utils import check_file_exists + +from beratools.modules.mapping.canopy_footprint_absolute import canopy_footprint_abs +from beratools.modules.mapping.canopy_threshold_relative import main_canopy_threshold_relative +from beratools.modules.mapping.centerline import centerline +from beratools.modules.mapping.check_seed_line import check_seed_line +from beratools.modules.mapping.footprint_plots import footprint_plots +from beratools.modules.mapping.ground_footprint import ground_footprint +from beratools.modules.mapping.line_footprint_functions import main_line_footprint_relative +from beratools.modules.mapping.smooth_centerline import smooth_centerline +from beratools.modules.mapping.vertex_optimization import vertex_optimization from beratools.utility.spatial_common import decode_file_layer @@ -117,6 +119,27 @@ def test_ground_footprint_tool(tool_arguments_integration): assert check_file_exists(out_file, layer), "Ground footprint no output!" +def test_smooth_centerline_tool(tool_arguments_integration): + """Test for the smooth_centerline tool on the Seg_Plot sample lines.""" + args_smooth_centerline = tool_arguments_integration["args_smooth_centerline"] + pprint(args_smooth_centerline) + smooth_centerline(**args_smooth_centerline) + + out_file, layer = decode_file_layer(args_smooth_centerline["out_line"]) + assert check_file_exists(out_file, layer), "Smooth Centerline no output!" + + +def test_footprint_plots_tool(tool_arguments_integration): + """Test for the footprint_plots tool on the Seg_Plot sample footprints.""" + args_footprint_plots = tool_arguments_integration["args_footprint_plots"] + pprint(args_footprint_plots) + footprint_plots(**args_footprint_plots) + + for key in ("out_plot", "out_subplot"): + out_file, layer = decode_file_layer(args_footprint_plots[key]) + assert check_file_exists(out_file, layer), f"Footprint Plots no {key} output!" + + # CLEANUP TESTS def test_cleanup_output_files(cleanup_output_files): # Your test code goes here diff --git a/tests/test_vertex_preclean.py b/beratools/modules/mapping/tests/test_vertex_preclean.py similarity index 92% rename from tests/test_vertex_preclean.py rename to beratools/modules/mapping/tests/test_vertex_preclean.py index 2c12655..22b07e7 100644 --- a/tests/test_vertex_preclean.py +++ b/beratools/modules/mapping/tests/test_vertex_preclean.py @@ -3,10 +3,11 @@ import pandas as pd import shapely.geometry as sh_geom -import beratools.core.algo_common as algo_common -import beratools.core.algo_vertex_optimization as algo_vertex_optimization -from beratools.core.algo_canopy_footprint_absolute import FootprintCanopyAdaptive -from beratools.core.algo_vertex_preclean import preclean_vertices +import beratools.modules.mapping.algo_common as algo_common +import beratools.modules.mapping.algo_vertex_optimization as algo_vertex_optimization +import beratools.utility.spatial_common as sp_common +from beratools.modules.mapping.algo_canopy_footprint_absolute import FootprintCanopyAdaptive +from beratools.modules.mapping.algo_vertex_preclean import preclean_vertices def test_preclean_removes_close_internal_vertex(): @@ -52,7 +53,7 @@ def test_endpoint_mode_applies_preclean(monkeypatch): lines_gdf = gpd.GeoDataFrame({"id": [1]}, geometry=[line], crs="EPSG:3857") monkeypatch.setattr(algo_common, "read_geospatial_file", lambda *args, **kwargs: lines_gdf) - monkeypatch.setattr(algo_common, "generate_raster_footprint", lambda *args, **kwargs: footprint) + monkeypatch.setattr(sp_common, "generate_raster_footprint", lambda *args, **kwargs: footprint) vg = algo_vertex_optimization.VertexGrouping( in_line="dummy.gpkg", @@ -82,7 +83,7 @@ def test_internal_vertex_mode_keeps_segments_outside_raster(monkeypatch): lines_gdf = gpd.GeoDataFrame({"BT_UID": [7]}, geometry=[line], crs="EPSG:3857") monkeypatch.setattr(algo_common, "read_geospatial_file", lambda *args, **kwargs: lines_gdf) - monkeypatch.setattr(algo_common, "generate_raster_footprint", lambda *args, **kwargs: footprint) + monkeypatch.setattr(sp_common, "generate_raster_footprint", lambda *args, **kwargs: footprint) monkeypatch.setattr( algo_vertex_optimization.algo_vertex_preclean, "preclean_vertices", lambda gdf, *_: gdf ) @@ -108,7 +109,7 @@ def test_internal_vertex_mode_keeps_segments_outside_raster(monkeypatch): def _build_vertex_grouping(monkeypatch): monkeypatch.setattr( - algo_common, "generate_raster_footprint", lambda *args, **kwargs: sh_geom.box(0, 0, 1, 1) + sp_common, "generate_raster_footprint", lambda *args, **kwargs: sh_geom.box(0, 0, 1, 1) ) return algo_vertex_optimization.VertexGrouping( in_line="dummy.gpkg", diff --git a/tests/test_workflow.py b/beratools/modules/mapping/tests/test_workflow.py similarity index 84% rename from tests/test_workflow.py rename to beratools/modules/mapping/tests/test_workflow.py index f989fb3..c65fa3d 100644 --- a/tests/test_workflow.py +++ b/beratools/modules/mapping/tests/test_workflow.py @@ -1,14 +1,14 @@ """Test script for the tools in the beratools package.""" -from utils import check_file_exists +from mapping_test_utils import check_file_exists -from beratools.core.canopy_threshold_relative import main_canopy_threshold_relative -from beratools.core.line_footprint_functions import main_line_footprint_relative -from beratools.tools.canopy_footprint_absolute import canopy_footprint_abs -from beratools.tools.centerline import centerline -from beratools.tools.check_seed_line import check_seed_line -from beratools.tools.ground_footprint import ground_footprint -from beratools.tools.vertex_optimization import vertex_optimization +from beratools.modules.mapping.canopy_footprint_absolute import canopy_footprint_abs +from beratools.modules.mapping.canopy_threshold_relative import main_canopy_threshold_relative +from beratools.modules.mapping.centerline import centerline +from beratools.modules.mapping.check_seed_line import check_seed_line +from beratools.modules.mapping.ground_footprint import ground_footprint +from beratools.modules.mapping.line_footprint_functions import main_line_footprint_relative +from beratools.modules.mapping.vertex_optimization import vertex_optimization from beratools.utility.spatial_common import decode_file_layer diff --git a/beratools/modules/mapping/tool_geo_simplify.py b/beratools/modules/mapping/tool_geo_simplify.py new file mode 100644 index 0000000..31139c5 --- /dev/null +++ b/beratools/modules/mapping/tool_geo_simplify.py @@ -0,0 +1,127 @@ +"""Tooling helpers for invoking geo-simplify binaries.""" + +from __future__ import annotations + +import os +import platform +import stat +import subprocess +import tempfile +from pathlib import Path + +import geopandas as gpd +from shapely.geometry import LineString + +import beratools.external + + +def validate_diameter(value): + try: + diameter = float(value) + except (TypeError, ValueError): + raise ValueError("simplify_diameter must be a number >= 0.") + + if diameter < 0: + raise ValueError("simplify_diameter must be >= 0.") + + return diameter + + +def build_temp_output_same_folder(out_file, suffix=".gpkg", prefix="centerline_tmp_"): + out_path = Path(out_file) + out_dir = out_path.parent if out_path.parent else Path(".") + out_dir.mkdir(parents=True, exist_ok=True) + fd, temp_path = tempfile.mkstemp(prefix=prefix, suffix=suffix, dir=out_dir) + os.close(fd) + return Path(temp_path) + + +def simplify_line_reduce_bend(line: LineString, *, crs, diameter: float, smooth_line=True) -> LineString: + if diameter <= 0: + return line + + with tempfile.TemporaryDirectory(prefix="beratools_line_simplify_") as temp_dir: + temp_path = Path(temp_dir) + input_file = temp_path / "input.gpkg" + output_file = temp_path / "output.gpkg" + in_layer = "line_temp" + out_layer = "line_simplified" + gdf = gpd.GeoDataFrame([{}], geometry=[line], crs=crs) + gdf.to_file(input_file, layer=in_layer) + run_reduce_bend( + input_file=input_file, + in_layer=in_layer, + output_file=output_file.as_posix(), + out_layer=out_layer, + diameter=diameter, + smooth_line=smooth_line, + ) + simplified = gpd.read_file(output_file, layer=out_layer) + if simplified.empty: + raise RuntimeError("geo-simplify returned no features") + geom = simplified.geometry.iloc[0] + if geom is None or geom.is_empty: + raise RuntimeError("geo-simplify returned empty geometry") + if geom.geom_type == "MultiLineString" and len(geom.geoms) == 1: + geom = geom.geoms[0] + if not isinstance(geom, LineString): + raise RuntimeError(f"geo-simplify returned unsupported geometry: {geom.geom_type}") + return geom + + +def run_reduce_bend(input_file, in_layer, output_file, out_layer, diameter, smooth_line=True): + binary_path = _geo_simplify_resolve_binary_path() + command = [ + str(binary_path), + "reduce-bend", + "--input", + str(input_file), + "--in-layer", + in_layer, + "--output", + output_file, + "--diameter", + str(diameter), + ] + + if smooth_line: + command.append("--smooth-line") + + if out_layer: + command.extend(["--out-layer", out_layer]) + + result = subprocess.run(command, capture_output=True, text=True) + if result.returncode != 0: + raise RuntimeError( + "geo-simplify reduce-bend failed " + f"(exit code {result.returncode})\n" + f"Command: {' '.join(command)}\n" + f"stdout:\n{result.stdout}\n" + f"stderr:\n{result.stderr}" + ) + + +def _geo_simplify_resolve_binary_path(): + external_dir = Path(beratools.external.__file__).resolve().parent / "geo_simplify" + system_name = platform.system() + + if system_name == "Windows": + binary_path = external_dir / "geo-simplify-win-x64.exe" + elif system_name == "Linux": + binary_path = external_dir / "geo-simplify-linux-x64" + else: + raise RuntimeError(f"Centerline simplify is not supported on OS: {system_name}") + + if not binary_path.exists(): + raise FileNotFoundError(f"Missing geo-simplify binary: {binary_path}") + + if system_name == "Linux": + _geo_simplify_ensure_executable(binary_path) + + return binary_path + + +def _geo_simplify_ensure_executable(binary_path): + mode = binary_path.stat().st_mode + if not (mode & stat.S_IXUSR): + binary_path.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) diff --git a/beratools/modules/mapping/tools.json b/beratools/modules/mapping/tools.json new file mode 100644 index 0000000..f10db0a --- /dev/null +++ b/beratools/modules/mapping/tools.json @@ -0,0 +1,1442 @@ +{ + "$schema": "../../gui/assets/module.schema.json", + "module": "mapping", + "version": "0.7.0", + "requires_frame": ">=0.7", + "category": "Mapping", + "description": "Tools used to map centerlines and footprint polygons of linear disturbances in forests using a Canopy Height Model (CHM) as reference.", + "docs_url": "https://beratool.github.io/beratools/mapping/", + "tools": [ + { + "name": "Check Seed Lines", + "info": "Check seed line quality and fix issues if present.", + "tool_type": "python", + "tool_api": "check_seed_line", + "cli_name": "check_line", + "entry": "beratools.modules.mapping.check_seed_line:check_seed_line", + "icon": "check_seed_line.gif", + "tech_link": "user/check_seed_line/", + "parameters": [ + { + "variable": "in_line", + "accepts": "line", + "label": "Seed Line", + "description": "Input seed line file.", + "type": "file", + "subtype": "vector|line", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "in_raster", + "accepts": "chm", + "label": "CHM Raster", + "description": "Input CHM raster used for seed line QC clipping.", + "type": "file", + "subtype": "raster", + "default": "", + "output": false, + "optional": true, + "depends_on": { + "logic": "or", + "conditions": [ + { + "variable": "clip_to_chm_footprint", + "condition": true + }, + { + "variable": "apply_seed_line_correction", + "condition": true + }, + { + "variable": "warn_nodata_vertices", + "condition": true + } + ], + "mode": "hide" + } + }, + { + "variable": "out_line", + "produces": { + "line": [] + }, + "label": "Output Seed Line", + "description": "Output Seed Line file.", + "type": "file", + "subtype": "vector", + "default": "", + "output": true, + "optional": false + }, + { + "variable": "clip_to_chm_footprint", + "label": "Clip to CHM footprint", + "description": "Clip seed lines to CHM footprint after inward shrink.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": true, + "output": false, + "optional": true + }, + { + "variable": "chm_footprint_shrink", + "label": "CHM footprint shrink (m)", + "description": "Inward buffer distance applied to CHM footprint before clipping seed lines.", + "type": "number", + "subtype": "float", + "default": 15.0, + "output": false, + "optional": true, + "unit": "m", + "depends_on": { + "variable": "clip_to_chm_footprint", + "condition": true, + "mode": "inline" + } + }, + { + "variable": "remove_short_lines", + "label": "Remove short lines", + "description": "Remove lines shorter than the configured minimum line length.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "minimum_line_length", + "label": "Minimum line length (m)", + "description": "Minimum length threshold used when short line removal is enabled.", + "type": "number", + "subtype": "float", + "default": 5.0, + "output": false, + "optional": true, + "unit": "m", + "depends_on": { + "variable": "remove_short_lines", + "condition": true, + "mode": "inline" + } + }, + { + "variable": "warn_nodata_vertices", + "label": "Warn CHM NoData vertices", + "description": "Report seed-line endpoints on or surrounded by CHM NoData in the QC report without changing geometry.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": true, + "output": false, + "optional": true + }, + { + "variable": "nodata_vertex_search_radius", + "label": "NoData vertex search radius (m)", + "description": "Search radius used to report the nearest valid CHM cell for NoData endpoint/vertex warnings.", + "type": "number", + "subtype": "float", + "default": 10.0, + "output": false, + "optional": true, + "unit": "m", + "depends_on": { + "variable": "warn_nodata_vertices", + "condition": true, + "mode": "hide" + } + }, + { + "variable": "check_internal_vertices", + "label": "Check internal NoData vertices", + "description": "Also report internal seed-line vertices on or surrounded by CHM NoData. Endpoints are always checked when NoData vertex warnings are enabled.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true, + "depends_on": { + "variable": "warn_nodata_vertices", + "condition": true, + "mode": "hide" + } + }, + { + "variable": "preclean_vertices", + "label": "Preclean vertices", + "description": "Removes near-duplicate endpoint vertices and simplifies close interior vertices with angle-aware bend preservation.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": true, + "output": false, + "optional": true + }, + { + "variable": "preclean_close_distance", + "label": "Preclean close distance (m)", + "description": "Distance threshold for remove vertices too close to endpoint.", + "type": "number", + "subtype": "float", + "default": 2.0, + "output": false, + "optional": true, + "unit": "m", + "depends_on": { + "variable": "preclean_vertices", + "condition": true, + "mode": "hide" + } + }, + { + "variable": "preclean_angle_tolerance", + "label": "Preclean angle tolerance (deg)", + "description": "Angle tolerance used by vertex precleaning decisions to reserve line shape.", + "type": "number", + "subtype": "float", + "default": 10.0, + "output": false, + "optional": true, + "unit": "deg", + "depends_on": { + "variable": "preclean_vertices", + "condition": true, + "mode": "hide" + } + }, + { + "variable": "snap_close_endpoints", + "label": "Snap close endpoints", + "description": "Snap close line endpoints together using directed endpoint snapping.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "snap_tolerance", + "label": "Snap tolerance (m)", + "description": "Distance threshold used to snap close line endpoints.", + "type": "number", + "subtype": "float", + "default": 5.0, + "output": false, + "optional": true, + "unit": "m", + "depends_on": { + "variable": "snap_close_endpoints", + "condition": true, + "mode": "inline" + } + }, + { + "variable": "group_lines", + "label": "Group lines", + "description": "Group lines by endpoint connectivity (and optional angle compatibility) and assign shared BT_GROUP IDs.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "densify_long_lines", + "label": "Densify long lines", + "description": "Insert equalized internal vertices for lines longer than max segment length.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "max_segment_length", + "label": "Max segment length (m)", + "description": "Maximum segment length used by long line densification.", + "type": "number", + "subtype": "float", + "default": 500.0, + "output": false, + "optional": true, + "unit": "m", + "depends_on": { + "variable": "densify_long_lines", + "condition": true, + "mode": "inline" + } + }, + { + "variable": "apply_seed_line_correction", + "label": "Apply Seed Line Correction", + "description": "Run optional in-memory seed line correction after QC steps.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "slc_search_distance", + "label": "SLC search distance (m)", + "description": "Vertex search distance for optional seed line correction.", + "type": "number", + "subtype": "float", + "default": 5.0, + "output": false, + "optional": true, + "unit": "m", + "depends_on": { + "variable": "apply_seed_line_correction", + "condition": true, + "mode": "hide" + } + }, + { + "variable": "slc_line_radius", + "label": "SLC line radius (m)", + "description": "Line processing radius for optional seed line correction.", + "type": "number", + "subtype": "float", + "default": 15.0, + "output": false, + "optional": true, + "unit": "m", + "depends_on": { + "variable": "apply_seed_line_correction", + "condition": true, + "mode": "hide" + } + }, + { + "variable": "slc_optimize_internal_vertices", + "label": "SLC optimize internal vertices", + "description": "Enable split/merge workflow for internal vertex optimization in optional seed line correction.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true, + "depends_on": { + "variable": "apply_seed_line_correction", + "condition": true, + "mode": "hide" + } + } + ] + }, + { + "name": "Vertex Optimization", + "info": "Relocating line intersections to seismic line paths", + "tool_type": "python", + "tool_api": "vertex_optimization", + "cli_name": "vertex_opt", + "entry": "beratools.modules.mapping.vertex_optimization:vertex_optimization", + "icon": "vertex_optimization.gif", + "tech_link": "user/vertex_optimization/", + "parameters": [ + { + "variable": "in_line", + "accepts": "line", + "label": "Input Line", + "description": "Input lines to optimize.", + "type": "file", + "subtype": "vector|line", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "in_raster", + "accepts": "chm", + "label": "CHM Raster", + "description": "Input CHM raster used to optimize vertices.", + "type": "file", + "subtype": "raster", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "search_distance", + "label": "Vertex searching distance (m)", + "description": "Bigger value will let tool enlarge searching area for better vertex location.", + "type": "number", + "subtype": "float", + "default": 30, + "output": false, + "optional": false + }, + { + "variable": "line_radius", + "label": "Line Processing Radius", + "description": "Maximum processing distance from input lines. A large search radius may increase processing times whereas a small radius may cause undesired clipping.", + "type": "number", + "subtype": "int", + "default": 35, + "output": false, + "optional": true + }, + { + "variable": "optimize_internal_vertices", + "label": "Optimize Internal Vertices", + "description": "Enable split/merge workflow to optimize internal vertices in addition to endpoints.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "out_line", + "produces": { + "line": [] + }, + "label": "Optimized Line", + "description": "Output optimized line file.", + "type": "file", + "subtype": "vector", + "default": "", + "output": true, + "optional": false + } + ] + }, + { + "name": "Centerline", + "info": "Extract the least cost path and smooth centerline between vertices of the seed lines.", + "tool_type": "python", + "tool_api": "centerline", + "cli_name": "centerline", + "entry": "beratools.modules.mapping.centerline:centerline", + "icon": "centerline.gif", + "tech_link": "user/centerline/", + "parameters": [ + { + "variable": "in_line", + "accepts": "line", + "label": "Seed Line", + "description": "Input seed lines.", + "type": "file", + "subtype": "vector|line", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "in_raster", + "accepts": "chm", + "label": "CHM Raster", + "description": "Input raster image used to calculate the centerline.", + "type": "file", + "subtype": "raster", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "line_radius", + "label": "Line Processing Radius", + "description": "Maximum processing distance from input lines. A large search radius may increase processing times whereas a small radius may cause undesired clipping.", + "type": "number", + "subtype": "float", + "default": 15.0, + "output": false, + "optional": true + }, + { + "variable": "chm_mode", + "label": "CHM Mode", + "description": "CHM preprocessing mode. 'current' uses existing raster clipping; 'alt' applies local-maxima filtering; 'buffer' reduces raw CHM values around the input line before initial path generation.", + "type": "list", + "subtype": "string", + "data": [ + "current", + "alt", + "buffer" + ], + "default": "current", + "output": false, + "optional": true + }, + { + "variable": "chm_buffer_width", + "label": "CHM Buffer Width (m)", + "description": "Distance from the input line where raw CHM values are reduced before initial path generation.", + "type": "number", + "subtype": "float", + "default": 5.0, + "output": false, + "optional": true, + "unit": "m", + "depends_on": { + "variable": "chm_mode", + "condition": "buffer" + } + }, + { + "variable": "chm_buffer_multiplier", + "label": "CHM Buffer Multiplier", + "description": "Multiplier applied to valid raw CHM values inside the input-line buffer.", + "type": "number", + "subtype": "float", + "default": 0.5, + "output": false, + "optional": true, + "depends_on": { + "variable": "chm_mode", + "condition": "buffer" + } + }, + { + "variable": "proc_segments", + "label": "Process Segments", + "description": "Process each segment between vertices separately", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": true, + "output": false, + "optional": false + }, + { + "variable": "centerline_method", + "label": "Centerline Method", + "description": "Least-cost path and corridor raster method. 'bera' uses the existing BERA Tools workflow; 'astar' uses the A* LCP and A* accumulation corridor workflow.", + "type": "list", + "subtype": "string", + "data": [ + "bera", + "astar" + ], + "default": "bera", + "output": false, + "optional": true + }, + { + "variable": "guided_strategy", + "label": "Guided Strategy", + "description": "Centerline extraction strategy. 'pairwise': endpoint-guided pair scoring (default). 'main_route': unguided extraction from corridor graph.", + "type": "list", + "subtype": "string", + "data": [ + "pairwise", + "main_route" + ], + "default": "pairwise", + "output": false, + "optional": true + }, + { + "variable": "lcp_simplify_enabled", + "label": "Simplify LCP", + "description": "Run geo-simplify reduce-bend on the least-cost path before corridor generation.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "lcp_simplify_diameter", + "label": "LCP Simplify Diameter (m)", + "description": "Diameter used by reduce-bend for the least-cost path before corridor generation.", + "type": "number", + "subtype": "float", + "default": 10.0, + "output": false, + "optional": true, + "unit": "m", + "depends_on": { + "variable": "lcp_simplify_enabled", + "condition": true + } + }, + { + "variable": "lcp_smooth_enabled", + "label": "Smooth LCP", + "description": "Apply Chaikin smoothing to the least-cost path before corridor generation.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "lcp_smooth_iterations", + "label": "LCP Smooth Iterations", + "description": "Number of Chaikin smoothing iterations for the least-cost path.", + "type": "number", + "subtype": "int", + "default": 1, + "output": false, + "optional": true, + "depends_on": { + "variable": "lcp_smooth_enabled", + "condition": true + } + }, + { + "variable": "astar_corridor_line_bias_weight", + "label": "A* Corridor Line Bias", + "description": "Tie-breaking weight that biases A* accumulation toward the endpoint direction.", + "type": "number", + "subtype": "float", + "default": 0.1, + "output": false, + "optional": true, + "depends_on": { + "variable": "centerline_method", + "condition": "astar" + } + }, + { + "variable": "astar_corridor_distance_penalty_weight", + "label": "A* Corridor Distance Penalty", + "description": "Penalty applied by distance from the A* path when building the A* accumulation corridor.", + "type": "number", + "subtype": "float", + "default": 0.2, + "output": false, + "optional": true, + "depends_on": { + "variable": "centerline_method", + "condition": "astar" + } + }, + { + "variable": "corridor_simplify_polygon", + "label": "Simplify Corridor Polygon", + "description": "Simplify the corridor polygon before extracting the final centerline.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "corridor_simplify_length", + "label": "Corridor Simplify Length (m)", + "description": "Topology-preserving simplification tolerance for the corridor polygon.", + "type": "number", + "subtype": "float", + "default": 0.5, + "output": false, + "optional": true, + "unit": "m", + "depends_on": { + "variable": "corridor_simplify_polygon", + "condition": true + } + }, + { + "variable": "corridor_smooth_polygon", + "label": "Smooth Corridor Polygon", + "description": "Apply Chaikin smoothing to the corridor polygon before centerline extraction.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "corridor_polygon_smooth_iterations", + "label": "Corridor Smooth Iterations", + "description": "Number of Chaikin smoothing iterations for the corridor polygon.", + "type": "number", + "subtype": "int", + "default": 1, + "output": false, + "optional": true, + "depends_on": { + "variable": "corridor_smooth_polygon", + "condition": true + } + }, + { + "variable": "simplify_centerline", + "label": "Simplify Centerline", + "description": "Run geo-simplify reduce-bend on extracted centerlines.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "simplify_diameter", + "label": "Simplify Diameter (m)", + "description": "Diameter used by simplify reduce-bend. Uses layer CRS units (metres in projected CRS).", + "type": "number", + "subtype": "float", + "default": 10.0, + "output": false, + "optional": true, + "unit": "m", + "depends_on": { + "variable": "simplify_centerline", + "condition": true, + "mode": "inline" + } + }, + { + "variable": "out_line", + "produces": { + "line": [] + }, + "label": "Output Centerline", + "description": "Output centerline file.", + "type": "file", + "subtype": "vector", + "default": "", + "output": true, + "optional": false + } + ] + }, + { + "name": "Smooth Centerline", + "info": "Smooth sharp vertices of centerlines and keep the rest of each line unchanged.", + "tool_type": "python", + "tool_api": "smooth_centerline", + "cli_name": "smooth_line", + "entry": "beratools.modules.mapping.smooth_centerline:smooth_centerline", + "icon": "tool.gif", + "tech_link": "user/smooth_centerline/", + "parameters": [ + { + "variable": "in_line", + "accepts": "line", + "label": "Input Centerline", + "description": "Input centerlines to smooth.", + "type": "file", + "subtype": "vector|line", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "angle_threshold", + "label": "Angle threshold (degrees)", + "description": "Vertices with an interior angle below this value are smoothed (180 is a straight line). Higher values smooth more vertices.", + "type": "number", + "subtype": "float", + "default": 130, + "output": false, + "optional": true + }, + { + "variable": "buffer_distance", + "label": "Buffer distance (m)", + "description": "Radius around a sharp vertex that is replaced by a straight cut. Larger values smooth more strongly.", + "type": "number", + "subtype": "float", + "default": 2.0, + "output": false, + "optional": true, + "unit": "m" + }, + { + "variable": "out_line", + "produces": { + "line": [] + }, + "label": "Smoothed Centerline", + "description": "Output smoothed centerline file.", + "type": "file", + "subtype": "vector", + "default": "", + "output": true, + "optional": false + } + ] + }, + { + "name": "Canopy Footprint (Absolute Threshold)", + "info": "Creates footprint polygons for each input line based on a least cost corridor method and individual line thresholds.", + "tool_type": "python", + "tool_api": "canopy_footprint_absolute", + "cli_name": "footprint_abs", + "entry": "beratools.modules.mapping.canopy_footprint_absolute:canopy_footprint_abs", + "icon": "canopy_footprint_absolute.gif", + "tech_link": "user/canopy_footprint_abs/", + "parameters": [ + { + "variable": "in_line", + "accepts": "line", + "label": "Centerline", + "description": "Input centerline file.", + "type": "file", + "subtype": "vector|line", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "in_chm", + "accepts": "chm", + "label": "CHM Raster", + "description": "Input CHM image used to calculate the line footprint.", + "type": "file", + "subtype": "raster", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "footprint_mode", + "label": "Footprint Mode", + "description": "Choose absolute threshold or adaptive threshold canopy footprint.", + "type": "list", + "subtype": "text", + "data": [ + "absolute", + "adaptive" + ], + "default": "absolute", + "output": false, + "optional": true, + "depends_on": { + "variable": "in_line", + "condition": "__hidden__", + "mode": "hide" + } + }, + { + "variable": "corridor_thresh", + "label": "Corridor Threshold", + "description": "The least cost corridor thresholds.", + "type": "number", + "subtype": "float", + "default": 3.0, + "output": false, + "optional": true + }, + { + "variable": "max_ln_width", + "label": "Maximum Line Width (m)", + "description": "Maximum processing width for input lines in metres. Internally converted to layer CRS units. A large value may increase processing times whereas a small value may cause undesired clipping.", + "type": "number", + "subtype": "float", + "default": 32.0, + "output": false, + "optional": true + }, + { + "variable": "exp_shk_cell", + "label": "Expand And Shrink Cell Range", + "description": "Range used for cell erosion before final polygons are generated. Useful to remove small artifacts. If the cell size is 1m or larger then set this as zero.", + "type": "number", + "subtype": "int", + "default": 0, + "output": false, + "optional": true + }, + { + "variable": "tree_radius", + "label": "Tree Search Radius", + "description": "Radius of canopy influence in the cost raster for adaptive mode.", + "type": "number", + "subtype": "float", + "default": 1.5, + "output": false, + "optional": true, + "depends_on": { + "variable": "in_line", + "condition": "__hidden__", + "mode": "hide" + } + }, + { + "variable": "max_line_dist", + "label": "Maximum Line Distance", + "description": "Maximum euclidean distance from canopy in adaptive mode.", + "type": "number", + "subtype": "float", + "default": 1.5, + "output": false, + "optional": true, + "depends_on": { + "variable": "in_line", + "condition": "__hidden__", + "mode": "hide" + } + }, + { + "variable": "canopy_avoidance", + "label": "Canopy Avoidance", + "description": "Ratio of importance between canopy search radius and euclidean distance in adaptive mode.", + "type": "number", + "subtype": "float", + "default": 0.0, + "output": false, + "optional": true, + "depends_on": { + "variable": "in_line", + "condition": "__hidden__", + "mode": "hide" + } + }, + { + "variable": "exponent", + "label": "Cost Raster Exponent", + "description": "Exponential weight for cost in adaptive mode.", + "type": "number", + "subtype": "float", + "default": 1.0, + "output": false, + "optional": true, + "depends_on": { + "variable": "in_line", + "condition": "__hidden__", + "mode": "hide" + } + }, + { + "variable": "canopy_thresh_percentage", + "label": "Canopy Threshold Percentage", + "description": "Apply percent on calculated canopy threshold height in adaptive mode.", + "type": "number", + "subtype": "float", + "default": 50, + "output": false, + "optional": true, + "depends_on": { + "variable": "in_line", + "condition": "__hidden__", + "mode": "hide" + } + }, + { + "variable": "simplify_footprint_polygon", + "label": "Simplify Footprint Polygon", + "description": "Simplify the output footprint polygon with topology preservation after raster-to-polygon conversion.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": true, + "output": false, + "optional": true + }, + { + "variable": "footprint_simplify_length", + "label": "Footprint Simplify Length (m)", + "description": "Topology-preserving simplification tolerance for output footprint polygons.", + "type": "number", + "subtype": "float", + "default": 0.5, + "output": false, + "optional": true, + "unit": "m", + "depends_on": { + "variable": "simplify_footprint_polygon", + "condition": true + } + }, + { + "variable": "smooth_footprint_polygon", + "label": "Smooth Footprint Polygon", + "description": "Apply Chaikin smoothing to output footprint polygons after optional simplification.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "footprint_polygon_smooth_iterations", + "label": "Footprint Smooth Iterations", + "description": "Number of Chaikin smoothing iterations for output footprint polygons.", + "type": "number", + "subtype": "int", + "default": 1, + "output": false, + "optional": true, + "depends_on": { + "variable": "smooth_footprint_polygon", + "condition": true + } + }, + { + "variable": "out_footprint", + "produces": { + "footprint": [] + }, + "label": "Output Footprint", + "description": "Output footprint polygon file.", + "type": "file", + "subtype": "vector", + "default": "", + "output": true, + "optional": false + } + ] + }, + { + "name": "Canopy Footprint (Relative Threshold)", + "info": "Creates dynamic footprint polygons for each input line based on a least cost corridor method and individual line canopy thresholds and cost raster.", + "tool_type": "python", + "tool_api": "line_footprint_relative", + "cli_name": "footprint_rel", + "entry": "beratools.modules.mapping.line_footprint_relative:line_footprint_relative", + "icon": "line_footprint_relative.gif", + "tech_link": "user/canopy_footprint_rel/", + "parameters": [ + { + "variable": "in_line", + "accepts": "line", + "label": "Centerline", + "description": "Input line file.", + "type": "file", + "subtype": "vector|line", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "in_chm", + "accepts": "chm", + "label": "CHM Raster", + "description": "Input raster image used calculate the surrounding forest elevation percentile, create canopy and cost raster.", + "type": "file", + "subtype": "raster", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "max_ln_width", + "label": "Maximum Line Width", + "description": "Maximum processing width for input lines. A large value may increase processing times whereas a small value may cause undesired clipping.", + "type": "number", + "subtype": "float", + "default": 32.0, + "output": false, + "optional": true + }, + { + "variable": "exp_shk_cell", + "label": "Expand And Shrink Cell Range", + "description": "Range used for cell erosion before final polygons are generated. Useful to remove small artifacts. If the cell size is 1m or larger then set this as zero.", + "type": "number", + "subtype": "int", + "default": 0, + "output": false, + "optional": true + }, + { + "variable": "out_footprint", + "produces": { + "footprint": [] + }, + "label": "Output Footprint", + "description": "Output footprint polygons.", + "type": "file", + "subtype": "vector", + "default": "", + "output": true, + "optional": false + }, + { + "variable": "out_centerline", + "produces": { + "line": [] + }, + "label": "Output Centerline", + "description": "Output centerline polygons.", + "type": "file", + "subtype": "vector", + "default": "", + "output": true, + "optional": true + }, + { + "variable": "off_ln_dist", + "label": "Offset Line Distance", + "description": "Offset distance from input lines.", + "type": "number", + "subtype": "float", + "default": 10.0, + "output": false, + "optional": true + }, + { + "variable": "canopy_percentile", + "label": "Canopy Percentile", + "description": "The Nth percentile of the surrounding forest.", + "type": "list", + "subtype": "int", + "data": [ + 50, + 55, + 60, + 65, + 70, + 75, + 80, + 85, + 90, + 95 + ], + "default": 90, + "output": false, + "optional": true + }, + { + "variable": "canopy_thresh_percentage", + "label": "Canopy Threshold Percentage", + "description": "Apply percentage on calculating Canopy Threshold height from Canopy percentile elevation.", + "type": "number", + "subtype": "float", + "default": 50, + "output": false, + "optional": true + }, + { + "variable": "tree_radius", + "label": "Tree Search Radius", + "description": "Radius of canopy influence in the cost raster. This factor smooths the canopy in the cost raster which helps to prevent gaps in sparsely vegetated areas (e.g. wetlands) from being incorrectly identified as footprint. A large search radius (>=5m) may cause excessive smoothing of the cost raster which can lead to least cost paths ignoring forest-line nuances in sparsely vegetated forests. A small radius (<=1m) may cause the least cost path to cut corners through small gaps in sparse vegetation as well as avoid small obstacles that should not affect overall line shape.", + "type": "number", + "subtype": "float", + "default": 1.5, + "output": false, + "optional": true + }, + { + "variable": "max_line_dist", + "label": "Maximum Line Distance", + "description": "Maximum euclidean distance from canopy. This is a second smoothing factor which helps to position the forest line shape in the centre of the line footprint. An excessively small (<=1m) or large (>20m) value may cause the centerline to be positioned close to one of the edges of the footprint.", + "type": "number", + "subtype": "float", + "default": 1.5, + "output": false, + "optional": true + }, + { + "variable": "canopy_avoidance", + "label": "Canopy Avoidance", + "description": "Ratio of importance between canopy search radius and euclidean distance. A value close to zero (0) prioritises search radius whereas a value close to one (1) prioritises euclidean distance. A small value (<=0.1) may cause the forest lines to miss nuances in sparsely vegetated terrain whereas a big value (>=0.5) may overemphasize turns in complex trails. This factor influences final footprint size in a minor way.", + "type": "number", + "subtype": "float", + "default": 0.0, + "output": false, + "optional": true + }, + { + "variable": "exponent", + "label": "Cost Raster Exponent", + "description": "Affects the cost of vegetated areas in an exponential fashion. A low (<=1) exponent may lead to lines cutting through corners, whereas a large (>=3) exponent may lead to least cost paths completely avoiding narrow lines.", + "type": "number", + "subtype": "int", + "default": 1, + "output": false, + "optional": true + } + ] + }, + { + "name": "Ground Footprint", + "info": "Generating fixed width ground footprint", + "tool_type": "python", + "tool_api": "ground_footprint", + "cli_name": "footprint_grd", + "entry": "beratools.modules.mapping.ground_footprint:ground_footprint", + "icon": "ground_footprint.gif", + "tech_link": "user/ground_footprint/", + "parameters": [ + { + "variable": "in_line", + "accepts": "line", + "label": "Centerline", + "description": "Input centerline file.", + "type": "file", + "subtype": "vector|line", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "in_footprint", + "accepts": "footprint", + "label": "Input Footprint", + "description": "Input footprint.", + "type": "file", + "subtype": "vector|polygon", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "n_samples", + "label": "Sampling number", + "description": "Sampling number for each line.", + "type": "number", + "subtype": "int", + "default": 15, + "output": false, + "optional": true + }, + { + "variable": "offset", + "label": "Perpendicular line length (m)", + "description": "The length of the perpendicular line in metres. Internally converted to layer CRS units.", + "type": "number", + "subtype": "float", + "default": 30.0, + "output": false, + "optional": true + }, + { + "variable": "max_width", + "label": "Use maximum width", + "description": "Use maximum sampled width for footprint.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": true, + "output": false, + "optional": true + }, + { + "variable": "out_footprint", + "produces": { + "footprint": [] + }, + "label": "Output Ground Footprint", + "description": "Output fixed width ground footprint file.", + "type": "file", + "subtype": "vector", + "default": "", + "output": true, + "optional": false + } + ] + }, + { + "name": "Footprint Plots and Subplots", + "info": "Split line footprints into plots and subplots along their centerlines, with plot, side and subplot IDs.", + "tool_type": "python", + "tool_api": "footprint_plots", + "cli_name": "footprint_plots", + "entry": "beratools.modules.mapping.footprint_plots:footprint_plots", + "icon": "tool.gif", + "tech_link": "user/footprint_plots/", + "parameters": [ + { + "variable": "in_footprint", + "accepts": "footprint", + "label": "Input Footprint", + "description": "Input line footprint polygons.", + "type": "file", + "subtype": "vector|polygon", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "in_line", + "accepts": "line", + "label": "Input Centerline", + "description": "Centerlines of the footprints. Each footprint uses the centerline with the longest overlap.", + "type": "file", + "subtype": "vector|line", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "mode", + "label": "Segmentation mode", + "description": "'fixed_area' cuts plots and subplots to a target area. 'fixed_length' cuts them at a fixed spacing along the centerline.", + "type": "list", + "subtype": "string", + "data": [ + "fixed_area", + "fixed_length" + ], + "default": "fixed_area", + "output": false, + "optional": true + }, + { + "variable": "plot_area", + "label": "Plot area (m2)", + "description": "Fixed area mode: target plot area covering both sides of the line. Each side of a plot is a separate feature.", + "type": "number", + "subtype": "float", + "default": 100.0, + "output": false, + "optional": true, + "depends_on": { + "variable": "mode", + "condition": "fixed_area", + "mode": "hide" + } + }, + { + "variable": "subplot_area", + "label": "Subplot area (m2)", + "description": "Fixed area mode: target subplot area on one side of the line. Subplots nest inside plots, so plot area / (2 x subplot area) is rounded to whole subplots.", + "type": "number", + "subtype": "float", + "default": 10.0, + "output": false, + "optional": true, + "depends_on": { + "variable": "mode", + "condition": "fixed_area", + "mode": "hide" + } + }, + { + "variable": "plot_length", + "label": "Plot length (m)", + "description": "Fixed length mode: distance between plot boundaries along the centerline.", + "type": "number", + "subtype": "float", + "default": 50.0, + "output": false, + "optional": true, + "depends_on": { + "variable": "mode", + "condition": "fixed_length", + "mode": "hide" + } + }, + { + "variable": "subplot_length", + "label": "Subplot length (m)", + "description": "Fixed length mode: distance between subplot boundaries along the centerline. Subplots restart at each plot boundary.", + "type": "number", + "subtype": "float", + "default": 10.0, + "output": false, + "optional": true, + "depends_on": { + "variable": "mode", + "condition": "fixed_length", + "mode": "hide" + } + }, + { + "variable": "remove_overlap", + "label": "Remove overlaps", + "description": "Cut overlaps between footprints, such as at line crossings, so each area is in only one plot and subplot and is not counted twice. A line ending in an overlap always loses it and is trimmed back. At crossings, north-south and east-west lines keep the overlap over lines in other directions, then the longer centerline.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "out_plot", + "produces": { + "footprint": [] + }, + "label": "Output Plots", + "description": "Output plot polygons, one feature per plot side.", + "type": "file", + "subtype": "vector", + "default": "", + "output": true, + "optional": false + }, + { + "variable": "out_subplot", + "produces": { + "footprint": [] + }, + "label": "Output Subplots", + "description": "Output subplot polygons.", + "type": "file", + "subtype": "vector", + "default": "", + "output": true, + "optional": false + } + ] + } + ] +} diff --git a/beratools/modules/mapping/vertex_optimization.py b/beratools/modules/mapping/vertex_optimization.py new file mode 100644 index 0000000..1f6f188 --- /dev/null +++ b/beratools/modules/mapping/vertex_optimization.py @@ -0,0 +1,67 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Richard Zeng + +Description: + This script is part of the BERA Tools. + Webpage: https://github.com/BERATool/beratools + + The purpose of this script is the public interface for vertex optimization. +""" + +import logging + +import beratools.modules.mapping.algo_vertex_optimization as bt_vo +import beratools.utility.spatial_common as sp_common +from beratools.utility.tool_args import CallMode + +LOGGER_NAME="vertex_optimization" +logger = logging.getLogger(LOGGER_NAME) + +def vertex_optimization( + in_line, + in_raster, + search_distance, + line_radius, + out_line, + optimize_internal_vertices=False, + processes=0, + call_mode=CallMode.CLI, + log_level="INFO", +): + if isinstance(optimize_internal_vertices, str): + optimize_internal_vertices = optimize_internal_vertices.lower() in ["true", "1", "yes"] + + in_file, in_layer = sp_common.decode_file_layer(in_line) + if not sp_common.compare_crs(sp_common.vector_crs(in_file,in_layer), sp_common.raster_crs(in_raster)): + return + + vg = bt_vo.VertexGrouping( + in_file, + in_raster, + search_distance, + line_radius, + processes, + call_mode, + layer=in_layer, + optimize_internal_vertices=optimize_internal_vertices, + ) + vg.create_all_vertex_groups() + vg.compute() + vg.update_all_lines() + vg.save_all_layers(out_line) + + +if __name__ == "__main__": + import time + + from beratools.utility.tool_args import compose_tool_kwargs + + start_time = time.time() + kwargs = compose_tool_kwargs("vertex_optimization") + vertex_optimization(**kwargs) + print("Elapsed time: {}".format(time.time() - start_time)) diff --git a/beratools/modules/pc2products/__init__.py b/beratools/modules/pc2products/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/beratools/modules/pc2products/docs/files/api.md b/beratools/modules/pc2products/docs/files/api.md new file mode 100644 index 0000000..2d66039 --- /dev/null +++ b/beratools/modules/pc2products/docs/files/api.md @@ -0,0 +1,19 @@ +# PC2Products API Reference + +## Tools API + +::: beratools.modules.pc2products.rpy_las_info +::: beratools.modules.pc2products.rpy_find_cellsize +::: beratools.modules.pc2products.rpy_gnd_csf +::: beratools.modules.pc2products.rpy_dtm_by +::: beratools.modules.pc2products.rpy_normalized_PC +::: beratools.modules.pc2products.rpy_CHM_DSM_by +::: beratools.modules.pc2products.rpy_PC2hummock_hollow +::: beratools.modules.pc2products.rpy_surface_water +::: beratools.modules.pc2products.rpy_dtw +::: beratools.modules.pc2products.rpy_seismic_line_analysis + +## R Interface + +::: beratools.modules.pc2products.r_interface +::: beratools.modules.pc2products.r_common diff --git a/beratools/modules/pc2products/docs/files/index.md b/beratools/modules/pc2products/docs/files/index.md new file mode 100644 index 0000000..9c3a8f3 --- /dev/null +++ b/beratools/modules/pc2products/docs/files/index.md @@ -0,0 +1,23 @@ +# PC2Products (LiDAR) + +LiDAR point cloud processing. These tools run R and [lidR](https://r-lidar.github.io/lidRbook/) +through [rpy2](https://rpy2.github.io/), so they need R in the environment (see +[Installation](https://beratool.github.io/beratools/user/installation/)). + +| Tool | `bt` subcommand | Details | +|------|-----------------|---------| +| [LiDAR data info](user/las_info.md) | `las_info` | Prints the CRS, extent, density and normalization status of a dataset. | +| [Raster Cell size from LiDAR data](user/cellsize.md) | `cellsize` | Recommends a raster cell size from the point density. | +| [Build LiDAR Spatial Index](user/lidar_index.md) | `lidar_index` | Builds the .lax spatial index of the LAS/LAZ files that have none. | +| [Tile LiDAR Data](user/lidar_tile.md) | `tile` | Splits the LiDAR files of a folder into tiles sized by the point density. | +| [Ground Classify Using CSF](user/gnd_csf.md) | `gnd_csf` | Classifies ground points with the Cloth Simulation Filter. | +| [Generate DTM from LiDAR Data](user/dtm.md) | `dtm` | Builds a bare-earth DTM with TIN, IDW or kriging. | +| [Normalize LiDAR Data](user/normalize.md) | `normalize` | Subtracts the terrain so that Z is height above ground. | +| [Generate CHM or DSM from LiDAR Data](user/chm_dsm.md) | `chm_dsm` | Builds a CHM from normalized data, or a DSM from the original data. | +| [Detect Hummock and Hollow from LiDAR Data](user/hummock_hollow.md) | `hh` | Maps hummocks, hollows and lawns relative to a smoothed terrain. | +| [Surface Water Mapping](user/surface_water.md) | `surface_water` | Classifies surface water from a true-colour orthomosaic. | +| [Depth-to-Water from Surface Water](user/dtw.md) | `dtw` | Kriges a water table from surface water and computes depth to water. | +| [Seismic Line Disturbance Analysis](user/seismic_line_analysis.md) | `line_analysis` | Compares seismic line segments with the surrounding peatland by disturbance class. | + +This site covers the PC2Products (LiDAR) module. Installation, the GUI, the `bt` command and +pipelines are in the [BERA Tools Guide](https://beratool.github.io/beratools/). diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_cellsize.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_cellsize.png new file mode 100644 index 0000000..0569b33 Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_cellsize.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_chm_dsm.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_chm_dsm.png new file mode 100644 index 0000000..02f120a Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_chm_dsm.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_dtm_running.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_dtm_running.png new file mode 100644 index 0000000..d8ad5fc Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_dtm_running.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_dtw.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_dtw.png new file mode 100644 index 0000000..a0ac0a3 Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_dtw.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_gnd_csf.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_gnd_csf.png new file mode 100644 index 0000000..84a1453 Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_gnd_csf.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_hh.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_hh.png new file mode 100644 index 0000000..9930781 Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_hh.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_las_info.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_las_info.png new file mode 100644 index 0000000..3f47467 Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_las_info.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_line_analysis.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_line_analysis.png new file mode 100644 index 0000000..bc9bd49 Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_line_analysis.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_normalize.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_normalize.png new file mode 100644 index 0000000..b5e9b1c Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_normalize.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_surface_water.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_surface_water.png new file mode 100644 index 0000000..508cc08 Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_gui_surface_water.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_chm_dsm.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_chm_dsm.png new file mode 100644 index 0000000..e0d42ad Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_chm_dsm.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_dtm.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_dtm.png new file mode 100644 index 0000000..62a4c6c Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_dtm.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_dtw.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_dtw.png new file mode 100644 index 0000000..73d2502 Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_dtw.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_gnd_csf.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_gnd_csf.png new file mode 100644 index 0000000..7bddbb4 Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_gnd_csf.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_hh.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_hh.png new file mode 100644 index 0000000..9aa5915 Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_hh.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_line_analysis.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_line_analysis.png new file mode 100644 index 0000000..4272180 Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_line_analysis.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_normalize.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_normalize.png new file mode 100644 index 0000000..9733559 Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_normalize.png differ diff --git a/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_surface_water.png b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_surface_water.png new file mode 100644 index 0000000..b56c6f0 Binary files /dev/null and b/beratools/modules/pc2products/docs/files/screenshots/pc2products_output_surface_water.png differ diff --git a/beratools/modules/pc2products/docs/files/technical/images/tiling_blocks.svg b/beratools/modules/pc2products/docs/files/technical/images/tiling_blocks.svg new file mode 100644 index 0000000..714d86f --- /dev/null +++ b/beratools/modules/pc2products/docs/files/technical/images/tiling_blocks.svg @@ -0,0 +1,40 @@ + + + + + +500 m tiles +1 per block +sparsest + + + + +250 m tiles +4 per block + + + + + + + + + +125 m tiles +16 per block + + + + + + + + + + + +100 m tiles +25 per block +densest + \ No newline at end of file diff --git a/beratools/modules/pc2products/docs/files/technical/images/tiling_buffer.svg b/beratools/modules/pc2products/docs/files/technical/images/tiling_buffer.svg new file mode 100644 index 0000000..ecd0a5e --- /dev/null +++ b/beratools/modules/pc2products/docs/files/technical/images/tiling_buffer.svg @@ -0,0 +1,45 @@ + + + + + + + + + + + +tile +100 m tile, 20 m buffer = 140 m read +kept: the tile +written to the output file +read only: the buffer +neighbours' points, for context +Points read per point kept +square of (size + 2 x buffer) / size +500 m + + +1.17x (20 m) + +1.25x (30 m) +250 m + + +1.35x (20 m) + +1.54x (30 m) +125 m + + +1.74x (20 m) + +2.19x (30 m) +100 m + + +1.96x (20 m) + +2.56x (30 m) +dashed box = the tile itself (1x) + \ No newline at end of file diff --git a/beratools/modules/pc2products/docs/files/technical/images/tiling_map.svg b/beratools/modules/pc2products/docs/files/technical/images/tiling_map.svg new file mode 100644 index 0000000..b831165 --- /dev/null +++ b/beratools/modules/pc2products/docs/files/technical/images/tiling_map.svg @@ -0,0 +1,304 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +1 km +EPSG:2956 +Tile size + +500 m: 85 blocks + +250 m: 39 blocks + +125 m: 162 blocks + +100 m: 2 blocks + \ No newline at end of file diff --git a/beratools/modules/pc2products/docs/files/technical/images/tiling_runs.svg b/beratools/modules/pc2products/docs/files/technical/images/tiling_runs.svg new file mode 100644 index 0000000..7e41f76 --- /dev/null +++ b/beratools/modules/pc2products/docs/files/technical/images/tiling_runs.svg @@ -0,0 +1,61 @@ + + + +500 m run +250 m run +125 m run +100 m run +First run + + + + + + + + + + + + + + +x + + + + + + + + + +stops at the failed tile: "Tile 14 of 23 failed, so the run stopped: std::bad_alloc" +Rerun + + + + + + + + + + + + + + + + + + + + + + + +skip_existing: reads tiles_<suffix>.csv, skips the 13 complete tiles (grey), +and continues from tile 14 +Illustration: 23 tiles in four runs. + \ No newline at end of file diff --git a/beratools/modules/pc2products/docs/files/technical/images/tiling_workers.svg b/beratools/modules/pc2products/docs/files/technical/images/tiling_workers.svg new file mode 100644 index 0000000..61f61ab --- /dev/null +++ b/beratools/modules/pc2products/docs/files/technical/images/tiling_workers.svg @@ -0,0 +1,38 @@ + + + +11.5 GB free +1 worker + +19.5 bn (chosen) +2 workers +densest tile doesn't fit +3 workers +densest tile doesn't fit +4 workers +densest tile doesn't fit +20 GB free +1 worker + +16.8 bn +2 workers + +10.1 bn (chosen) +3 workers +densest tile doesn't fit +4 workers +densest tile doesn't fit +32 GB free +1 worker + +14.6 bn +2 workers + +9.1 bn +3 workers + +6.6 bn (chosen) +4 workers +densest tile doesn't fit +Bars: points each worker reads, buffers included, in billions. Fewer is faster. + \ No newline at end of file diff --git a/beratools/modules/pc2products/docs/files/technical/lidar_density_tiling.md b/beratools/modules/pc2products/docs/files/technical/lidar_density_tiling.md new file mode 100644 index 0000000..ec5d754 --- /dev/null +++ b/beratools/modules/pc2products/docs/files/technical/lidar_density_tiling.md @@ -0,0 +1,109 @@ +# How the LiDAR Tools Tile a Point Cloud + +Ground classification, DTM, normalization, CHM/DSM and hummock/hollow split large point clouds into +square tiles. Each tile must fit in one R worker's memory, so tile sizes follow the point density: +500 m where the data is sparse, down to 100 m where it's dense. See +[How the PC2Products Tools Run](tool_behaviour.md#how-all-the-tools-behave) for the `tiling` and +`skip_existing` options. [Tile LiDAR Data](../user/lidar_tile.md) cuts the same tiles ahead of +time and writes them to a folder, for the tools to process by file. + +## From files to tiles + +Before any points are read, the tool plans the tiles from the point counts stored in each file's +`.lax` spatial index. The plan takes about 2 seconds for the 276 Real_Lidar files. + +```mermaid +flowchart LR + A["LAS/LAZ files
+ .lax index
(point counts)"] --> B["50 m
density grid"] + B --> C["500 m blocks
each gets the largest
tile size that fits"] + C --> D["One lidR run per size
500 → 250 → 125 → 100 m
workers in parallel"] + D --> E["Tile outputs
named by corner"] + D --> F["tiles_<suffix>.csv
the plan, for resuming"] +``` + +## Each 500 m block gets one tile size + +The data is divided into 500 m blocks aligned to the coordinate grid at 0, 0. For each block the +planner tries 500 m first, then 250, 125 and 100 m, and keeps the largest size whose densest tile +still fits in a worker's memory. All four sizes divide 500 m evenly, so the tiles of a block fill it +exactly, and blocks of different sizes sit side by side without gaps or overlap. + +![Four 500 m blocks split into 1, 4, 16 and 25 tiles](images/tiling_blocks.svg) + +## Every tile reads a buffer around it + +A tile is processed with a buffer of points around it, so results don't break at the tile edge. +Ground classification uses 20 m and the other tools 30 m. The buffer comes from neighbouring tiles, +and from other files when the tile is near a file edge; the `.lax` index lets the tool read just that +strip. After processing, the buffer is dropped and only the tile itself is written. Small tiles read +proportionally more buffer, which is why the planner uses the largest size that fits. + +![A 100 m tile with a 20 m buffer, and points read per point kept for each tile size](images/tiling_buffer.svg) + +| Tile size | Points read per point kept, 20 m buffer | 30 m buffer | +|-----------|----------------------------------------:|------------:| +| 500 m | 1.17 | 1.25 | +| 250 m | 1.35 | 1.54 | +| 125 m | 1.74 | 2.19 | +| 100 m | 1.96 | 2.56 | + +## Real_Lidar at 11.5 GB free memory + +This is the plan the tool makes for the 276 Real_Lidar files (11.5 billion points, EPSG:2956) with +11.5 GB free and ground classification's 20 m buffer. Sparse edges get 500 m tiles, while the dense +centre needs 125 m and, in two blocks, 100 m tiles. + +![Real_Lidar 500 m blocks coloured by tile size](images/tiling_map.svg) + +| Tile size | Blocks | Densest tile with its buffer | +|-----------|-------:|-----------------------------:| +| 500 m | 85 | 144.6 million points | +| 250 m | 39 | 60.4 million points | +| 125 m | 162 | 22.1 million points | +| 100 m | 2 | 16.3 million points | + +One worker has room for about 21.5 million points. The densest 125 m tile holds 22.1 million points +with its buffer, so the two densest blocks drop to 100 m. With the buffers, the run reads about +19.5 billion points to classify 11.5 billion. + +## More workers means smaller tiles + +The free memory is shared between the workers, so each extra worker leaves less room per worker and +forces smaller tiles, which read more buffer. The planner tries every worker count and picks the +one where each worker reads the fewest points. A tile too dense for that many workers, even at +100 m, doesn't stop it: such tiles are processed after the others in a round with fewer workers, +and the estimate counts that round's time (its points shared out between its workers, and no less +than its largest tile). These figures are for Real_Lidar, where every tile fits: + +![Points read per worker for 1 to 4 workers at 11.5, 20 and 32 GB free](images/tiling_workers.svg) + +| Free memory | 1 worker | 2 workers | 3 workers | 4 workers | +|-------------|---------:|----------:|----------:|----------:| +| 11.5 GB | **19.5** | doesn't fit | doesn't fit | doesn't fit | +| 20 GB | 16.8 | **10.1** | doesn't fit | doesn't fit | +| 32 GB | 14.6 | 9.1 | **6.6** | doesn't fit | + +Billions of points each worker reads, buffers included; the chosen plan is in bold. Each worker has +60% of the free memory divided by the number of workers, minus 1.6 GB for the R session (and +0.21 GB per thread after the first), at the bytes per point measured for each tool: 260 for ground +classification here, up to 850 for the pit-free CHM/DSM (see +[Tiling](tool_behaviour.md#how-all-the-tools-behave)), so the tools that need more per point get +smaller tiles. More memory therefore buys larger tiles first, then more workers. + +## Running and resuming + +lidR needs one tile size per run, so the tool runs once for each size in the plan. Before each run it +prints `R_TILES::`, which the GUI uses to count tiles across all runs. If a tile fails +(for example with `std::bad_alloc` when memory runs out), the tool stops and names the tile. Running +it again with `skip_existing` set to `true` reloads the saved plan, skips every tile whose output is +complete, and starts at the failed one. + +![A first run stops at a failed tile; the rerun skips the finished tiles and continues](images/tiling_runs.svg) + +- A file the stopped run was writing is made again: each output is written as + `.partial.` and renamed when complete, and the next run removes the `.partial` files. +- The plan lists one row per block: `bx, by, size`. Tiles are named by their lower-left corner, for + example `520250_6228125_csfgnd_upto30cm_cloth150cm_hard.las`. +- The raster tools merge the skipped tiles with the new ones into one `Merged_*.tif`. +- Resume only with the same parameters. Output names don't record every parameter, the DTM cell size + for one. diff --git a/beratools/modules/pc2products/docs/files/technical/pc2products_overview.md b/beratools/modules/pc2products/docs/files/technical/pc2products_overview.md new file mode 100644 index 0000000..c517abf --- /dev/null +++ b/beratools/modules/pc2products/docs/files/technical/pc2products_overview.md @@ -0,0 +1,38 @@ +# PC2Products Tool Overview + +Each PC2Products tool is a thin Python wrapper in `beratools/modules/pc2products/`. It validates the inputs and then +calls an R function in `r_scripts_collection.r` through [rpy2](https://rpy2.github.io/). The R +functions use [lidR](https://r-lidar.github.io/lidRbook/) to do the processing. The algorithm each +tool uses is described on its page in the User Guide. + +| Tool | Module | Python function | R function(s) | +|------|--------|-----------------|---------------| +| [LiDAR data info](../user/las_info.md) | `rpy_las_info.py` | `rpy_las_info` | `las_info` | +| [Raster Cell size from LiDAR data](../user/cellsize.md) | `rpy_find_cellsize.py` | `rpy_find_cellsize` | `pd2cellsize` | +| [Build LiDAR Spatial Index](../user/lidar_index.md) | `rpy_lidar_index.py` | `rpy_lidar_index` | `lidar_index` | +| [Tile LiDAR Data](../user/lidar_tile.md) | `rpy_lidar_tile.py` | `rpy_lidar_tile` | `lidar_tile` | +| [Ground Classify Using CSF](../user/gnd_csf.md) | `rpy_gnd_csf.py` | `rpy_gnd_csf` | `classify_gnd_csf` | +| [Generate DTM from LiDAR Data](../user/dtm.md) | `rpy_dtm_by.py` | `rpy_dtm` | `dtm_by_tin`, `dtm_by_knnidw`, `dtm_by_kriging` | +| [Normalize LiDAR Data](../user/normalize.md) | `rpy_normalized_PC.py` | `rpy_normalized_PC` | `normalized_lidar_tin`, `normalized_lidar_knnidw`, `normalized_lidar_kriging` | +| [Generate CHM or DSM from LiDAR Data](../user/chm_dsm.md) | `rpy_CHM_DSM_by.py` | `rpy_chm_dsm` | `chm_by_dsmtin`, `chm_by_pitfree` | +| [Detect Hummock and Hollow from LiDAR Data](../user/hummock_hollow.md) | `rpy_PC2hummock_hollow.py` | `rpy_hh2raster` | `hh_function` | +| [Surface Water Mapping](../user/surface_water.md) | `rpy_surface_water.py` | `rpy_surface_water` | `surface_water_map` | +| [Depth-to-Water from Surface Water](../user/dtw.md) | `rpy_dtw.py` | `rpy_dtw` | `dtw_map` | +| [Seismic Line Disturbance Analysis](../user/seismic_line_analysis.md) | `rpy_seismic_line_analysis.py` | `rpy_seismic_line_analysis` | `seismic_line_analysis` | + +## Shared helpers + +| File | Contents | +|------|----------| +| `r_interface.py` | `configure_r_environment()`: finds R and sets up `R_HOME`, the DLL search path and `PATH` before rpy2 is imported (see [How R is located](tool_behaviour.md#how-r-is-located)). | +| `r_common.py` | Connects rpy2 on first use, and provides `r_max_workers`, `r_processes_by_memory`, `free_memory`, `check_tiling`, `check_las_files_existence`, `check_las_out_folder_existence` and `check_r_packages_installation`. | +| `tests/pc2_test_utils.py` | `has_raster_output` and `has_lidar_output`, used by the tests to check a tool wrote its output. | +| `r_scripts_collection.r` | All the R processing functions, plus `detect_normalized`, `detect_ground_classified` and `mosaic_catalog_outputs`. | + +## Where to go next + +- [How the Tools Run](tool_behaviour.md) +- Architecture: + - [System Overview](https://beratool.github.io/beratools/technical/architecture/system_overview/) + - [Execution Pipeline](https://beratool.github.io/beratools/technical/architecture/execution_pipeline/) + - [Tool Runtime Model](https://beratool.github.io/beratools/technical/architecture/tool_runtime_model/) diff --git a/beratools/modules/pc2products/docs/files/technical/tool_behaviour.md b/beratools/modules/pc2products/docs/files/technical/tool_behaviour.md new file mode 100644 index 0000000..46c5b80 --- /dev/null +++ b/beratools/modules/pc2products/docs/files/technical/tool_behaviour.md @@ -0,0 +1,201 @@ +# How the PC2Products Tools Run + +## How all the tools behave + +These points apply to the eight LiDAR tools. Surface Water Mapping, Depth-to-Water from Surface Water and +Seismic Line Disturbance Analysis work on rasters instead (see their own sections), but they install +their R packages the same way: + +- **Input**: every `.las` / `.laz` file in `in_las_folder` is read as a lidR `LAScatalog`. If the + folder is missing or holds no LAS/LAZ files, the tool stops. This opens every file to read its + header, which for thousands of files on a slow or network drive can take minutes, so the tool + first prints `Reading the headers of 2393 LiDAR file(s)...`, and then the time it took when it + was 10 s or more. +- **Noise removal**: points classified as low noise (class 7) are dropped with + `filter = "-drop_class 7"`. +- **Cell size**: the DTM and CHM/DSM tools don't take a cell size. They calculate it from the point + density, as described in [Raster Cell size from LiDAR data](../user/cellsize.md). + The hummock/hollow tool does the same when `cell_size` is `0`. +- **Output folder**: if `out_folder` doesn't exist, it's created. Existing outputs are overwritten. +- **Resuming a run**: a tool stops at the first tile that fails, with that tile's error (for + example `std::bad_alloc` when it runs out of memory). The tools with a `tiling` option + also take `skip_existing`: set it to `true` and run the tool again with the same parameters to + leave out the tiles whose outputs are complete, and process only the rest. Each output is + written as `.partial.` and renamed when complete, so a tile the run was writing when + it stopped has no output under its name and is made again; the next run removes the `.partial` + files. (A GeoTIFF cut short opens and reads without error, its unwritten rows empty, so it + couldn't be told from a complete one.) Outputs of earlier versions are also checked: a LAS + file must hold all the points its header counts, and a GeoTIFF's last row must be readable. In + the 500 m blocks that have outputs, a + resumed run uses the tile sizes of the earlier run, from the plan it saved next to its outputs + (`tiles_.csv`, for example `tiles_csfgnd_upto30cm_cloth150cm_hard.csv`), so it makes + the same tiles there even when the free memory has changed; the blocks without outputs are tiled + again for the memory free now, so a run that stopped on a tile too large for the memory gets + smaller tiles there. An earlier run without a plan had one tile size, which is read from its + outputs' corner names. If the remaining tiles don't fit, the tool warns, and you need to free + memory or start again in an empty folder. The tool prints how many tiles it skips. The DTM, CHM/DSM and + hummock/hollow tools merge the skipped tiles with the new ones. The output names don't record + every parameter (the DTM's cell size, for example), so don't use `skip_existing` after changing one. + Before skipping, the tool prints `Checking which outputs of an earlier run are complete...`, as + it opens each finished output to check it. +- **Tiles left out**: a tile from which nothing can be interpolated doesn't stop the run. It is + left out, with no output, and the run ends with a warning naming its files, for example + `Warning from 1 tile(s): Left out tile_bad.las: its heights can't be normalized from its 0 ground + point(s) of 5 (they don't span an area).` This covers a tile whose ground points (DTM, + normalization) or points (CHM/DSM) are fewer than 3 or lie on a line, and a tile the algorithm + finds nothing to interpolate in, such as a file of a few points all at Z = 0, where pit-free + finds no first return above its lowest height threshold. The tiles around it cover the area, if + there are any; a rerun with `skip_existing` tries such a tile again, as it has no output. +- **Tiling**: the ground classification, normalization, DTM, CHM/DSM and hummock/hollow tools take + a `tiling` option that sets how the data is split for processing: + - `auto` (the default): process each input file as one tile when every file fits the workers' + share of the free memory and there are at least as many files as workers. Otherwise the tool + plans both ways, by file and as for `tiling`, and tiles the data only when that is estimated + to take less than 1/1.25 of the time by file, as processing by file keeps the file names. A + rerun with `skip_existing` of a run that processed by file stays by file, so the finished + outputs aren't made again under tile names. + - `by_file`: process each input file as one tile, which keeps the tile names. When a file is too + large for the free memory (for example a single large file), the tool warns and splits the + data as for `tiling` instead, so it doesn't stop at its memory limit; the outputs are then + named by tile corner. + - `tiling`: always split the data into square tiles sized for the free memory and the data's + density. Use it for a single large file. The point counts of every file are read from its + `.lax` spatial index, and the data is split into 500 m blocks, aligned at 0, 0. Each block is + tiled with the largest of 500, 250, 125 and 100 m whose densest tile, with its buffer, fits, + so sparse areas get large tiles, which read less buffer, and dense areas small ones. The + number of workers is the one with the least estimated time, buffers included: more workers + have less memory each, so smaller tiles. The tool processes the tiles of each size in turn and + prints, for example, `Processing 162 tile(s) of 125 m...`. Without + the indexes (a read-only input folder), one size is used for all the data, from the files' + average density. [How the LiDAR tools tile a point cloud](lidar_density_tiling.md) shows + this with diagrams. + + **Rounds by size**: one dense file or tile no longer sets the workers for all the data. Whether + by file or tiled, the files or tiles too large for the run's workers are processed after the + others, in rounds with fewer workers, each with a larger share of the memory: for example + `Processing 2390 file(s) with 25 worker(s), 2 thread(s) each...` and then + `Processing 1 file(s) with 1 worker(s), 60 thread(s) each...`. A round's workers are rounded + down to levels each 80% of the one above, so there are only a few rounds. Every round reads the + whole catalog, so tiles' buffers still hold the points of every file and the output is + wall-to-wall, the same as in one round. A resumed run (`skip_existing`) plans its workers again + for the files or tiles left once it knows which are done, and prints, for example, + `Using up to 9 worker(s) for the 228 file(s) left.`; rounds that would start the same number + of workers are one round. + + A file processed by file is counted with its buffer: from the density grid when the tool reads + it, or else taking the buffer to be as dense as the file. + + 60% of the free memory is shared between the workers. Each worker is allowed 1.6 GB fixed + (R with lidR, sf and terra loaded, and the tile beyond its points), 0.21 GB for each thread + after the first, and a number of bytes per point that depends on the tool, measured as the + peak committed memory (which the tool's memory limit counts) on 150 m and 250 m windows of the + same data (13.9 and 35.7 million points, every point a first return, 50% of them ground): + + | Tool | Measured | Allowed | + | --- | --- | --- | + | CHM/DSM, pit-free | 796 | 850 | + | CHM/DSM, TIN | 102 per point plus ~410 per raster cell | 120 per point plus 450 per cell, from the data's average density | + | DTM, TIN; normalization, TIN; hummock/hollow | 231; 352; 309 | from the sampled ground share, at most 670 | + | DTM, IDW | 76 | 160 | + | Ground classification; normalization, IDW | 224; 226 | 260 | + | DTM and normalization, kriging | not measured | 260 | + + The tools that triangulate the ground points need more with more ground: an earlier TIN DTM + of a 560 m window with 20.1 million points, 91% of them ground, peaked at 13.3 GB, about 125 + bytes per point read and 540 per ground point. A tile's ground points aren't known before + reading it, so before planning these tools sample the ground share (classes 2 and 9) of up to + 20 files spread over the data, from five 20 m squares in each read through the `.lax` index + (seconds, even over a network), and size the workers for the largest file share with a 25% + margin: 1.25 × (125 + 540 × share) bytes per point, or 1.25 × 665 × share for the TIN DTM, + which reads only the ground points; never more than 670, the figure for data that is all + ground, which is also used when no ground can be sampled. The tool prints, for example, + `Ground points are up to 38 percent of the points sampled from 7 file(s), so the memory is + sized at 411 bytes per point (670 if every point were ground).` TIN normalization of files of + about 20 million points with their buffers had peaked at about 6 GB per worker, about 250 + bytes per point, but was sized at 670, so half the workers it had room for sat unused. The IDW DTM reads only the + ground points, so its figure is doubled. Before processing, a `.lax` spatial index is + built next to every input file that has none, which reads each such file once (several files + at a time, one per R process, at most 8). With it, reading a tile's buffer from a neighbouring file, or a + tile of a large file, reads only that area instead of the whole file. Memory use is unchanged. + If the input folder is read-only, the tool warns and reads the files without an index, which is + slower. [Build LiDAR Spatial Index](../user/lidar_index.md) builds the indexes ahead of time. + Tiles processed by file are named after their input file. Other tiles are named by their lower-left corner, for example + `526200_6231600_csfgnd_upto30cm_cloth100cm_soft.las`. +- **Progress**: R runs non-interactively, so lidR reports each tile as a line + (`Chunk 3 of 7 (42.9%): state ✓`), which the GUI shows on its progress bar as `Tile 3 of 7`. + With tiles of several sizes, the tool prints `R_TILES::` before each size, so the + GUI counts the tiles of all sizes together. lidR also plots a map of the tiles at the start of + each run; R running non-interactively, the map goes to a null device, as the screen device + opened a window that kept repainting while R was busy. + To see lidR's map of the tiles in an R Graphics window, set the environment variable + `BERATOOLS_R_GRAPHICS=1` before starting the GUI or the tool; R then runs interactively, as lidR + draws the map only then. In that mode lidR shows a text progress bar instead of the tile lines, + which the GUI follows too, unless the R package `progress` is installed: lidR then uses that + package's bar, which the GUI can't read, and only the map shows the progress. +- **Tiled output and mosaic**: the raster tools write one raster per tile. When there is more + than one tile, they also merge this run's tiles into a single `Merged_*.tif`: `gdalbuildvrt` + lists the tiles in a VRT, and `gdal_translate` (through the R package `sf`) writes the merge + from it in one pass as a tiled, DEFLATE-compressed GeoTIFF (BigTIFF when needed). Where tiles + overlap, the first tile's cells are kept. The merged hummock/hollow raster (`Merged_HH_*`) is + Int16, with NA as -32768; the other merged rasters keep the tiles' float type. `terra::mosaic`, + used before, wrote the merge twice on one core: 144 tiles of 2000 x 2000 cells took 155-237 s + that way, against 3-5 s now. +- **Spatial indexes**: a `.lax` file that isn't a LAStools index (cut short when a run stopped + while writing it, say) is built again. If that fails, that file's points are taken to be spread + evenly over it, and the other files still size the tiles from their indexes. +- **Warnings**: a warning is printed once per message after each run, with the number of tiles + that gave it. Messages that differ only in their numbers share one line with each number's + range, for example `Warning from 9 tile(s): Interpolation of 416 to 347838 points failed ...`. +- **Parallel processing**: the tools run their tiles on R workers through `future`: mirai daemons + (`future.mirai`) when that package is installed, which the tools that start workers install + when it's missing, and otherwise R sessions (`future::plan(multisession)`). lidR hands the tiles + out one at a time and, after each, checks every running tile; with `multisession` on Windows + each check waits ~0.2 s, so with many workers most of them sat idle (46 workers on files of + about a minute kept only ~12-16 busy). mirai's check doesn't wait, so all the workers are kept + busy. If `future.mirai` can't be installed (no internet, say) the tool warns and uses + `multisession`. A `processes` value of 0 + or less (the default) means "use every CPU core". + - The tools with a `tiling` option start as many workers as `processes` and the CPU cores + allow (`r_max_workers`), reduced to the most whose tiles still fit in their share of the free + memory (see **Tiling**), never more workers than tiles, and one worker per 20 million points + at most, as starting a worker takes seconds. The workers share the allowed count as lidR + threads, `floor(allowed / workers)` each, for lidR's multi-threaded steps (rasterizing, + interpolating, normalizing): memory often allows fewer workers than cores, which otherwise + sat idle. A worker starts with `OMP_NUM_THREADS` set to its threads, as R's BLAS (Intel MKL) + commits about 0.2 GB per OpenMP thread when sf and terra load, one per core by default. The + tool prints how many workers it uses, the threads of each, and how many points each can hold. + The TIN and kriging DTM tools first halve the allowed count when the cell size is under 1 + map unit. New lidR tools start their workers through `apply_tiling` (or `start_workers`). + - LiDAR data info and Raster Cell size read only the files' headers (and one file) and start no + workers. The surface water and depth-to-water tools size their workers by the memory of a + tile (`r_processes_by_memory`). +- **R packages**: the environment provides only R and rpy2. Each tool checks for the R packages it + needs and installs any missing ones from the CRAN mirror in Canada into the library of the R it + runs on (`/library`, inside the conda or pixi environment). The first run of each tool can + therefore take a while. If a package still can't be installed, the tool stops with + `R packages could not be installed into : `. + +## How R is located + +`r_interface.py` looks for R **before** it imports rpy2, and checks these places in order: + +1. An existing `R_HOME` environment variable +2. `Rscript` or `R` on the `PATH` (`R_HOME` is set from the output of ` RHOME`) +3. R installed in the conda or pixi environment: `Lib/R` (Windows) or `lib/R` (Linux), next to the + Python executable or under `sys.prefix` +4. A standard Windows install under `C:\Program Files\R\R-*` + +It then adds the environment's `Library\bin`, `Library\mingw-w64\bin`, `Library\usr\bin`, `Scripts` +and `R_HOME\bin` folders to the DLL search path and `PATH`. If it can't find R, it prints +`sys.executable`, `sys.prefix`, `R_HOME` and the `which R` / `which Rscript` results to help with +debugging, then raises an error with installation instructions. + +## How the GUI runs a tool + +The GUI starts the tool module in a new process and passes the parameters as JSON with `-i/--input`. +The module checks them against its `tools.json` entry in `BTData.validate_tool_params`: it confirms that +input folders exist, checks list values against the allowed options, and converts numbers and +booleans to the right type. Output parameters aren't checked, because they don't exist yet. + +Each module's `compose_tool_kwargs("")` call must use the tool's `tool_api` from +its module's `tools.json`, or the tool stops with `Tool API '' not found in any module's tools.json`. diff --git a/beratools/modules/pc2products/docs/files/user/cellsize.md b/beratools/modules/pc2products/docs/files/user/cellsize.md new file mode 100644 index 0000000..b2fbe0c --- /dev/null +++ b/beratools/modules/pc2products/docs/files/user/cellsize.md @@ -0,0 +1,30 @@ +# Raster Cell size from LiDAR data + +Calculates the recommended raster cell size from the average point density: + +```text +point_density = total point records / catalog area +cell_size = sqrt(3 / point_density), rounded to the nearest 0.05 map units +``` + +The cell size is printed along with the map units of the CRS. The R function `pd2cellsize` returns +`cell_size`, `map_units` and `point_density`, and the DTM and CHM/DSM tools call it to set their +output resolution. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `in_las_folder` | directory | Yes | Folder containing the input LAS/LAZ tiles. | +| `processes` | int | No | Requested number of parallel workers. | + +```python +from beratools.modules.pc2products.rpy_find_cellsize import rpy_find_cellsize + +rpy_find_cellsize(in_las_folder="tests/data/LiDAR") +``` + +## Command line + +```bash +bt cellsize # show the parameters +bt cellsize --in_las_folder +``` diff --git a/beratools/modules/pc2products/docs/files/user/chm_dsm.md b/beratools/modules/pc2products/docs/files/user/chm_dsm.md new file mode 100644 index 0000000..41e0049 --- /dev/null +++ b/beratools/modules/pc2products/docs/files/user/chm_dsm.md @@ -0,0 +1,45 @@ +# Generate CHM or DSM from LiDAR Data + +Builds a height surface from the point cloud with `lidR::rasterize_canopy`. The tool decides what to +produce by calling `detect_normalized`, which reads the ground points of the **first** LAS/LAZ file +in the folder: those in a 100 m square at its centre, through its `.lax` spatial index, or every +100th ground point of the file when the square has fewer than 100: + +- If the mean |Z| of the ground points (class 2) is **below 1**, the data counts as + height-normalized and the tool produces a **CHM**. +- Otherwise, including when there are no ground points, the tool produces a **DSM**. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `in_las_folder` | directory | Yes | Folder containing the input LAS/LAZ tiles. | +| `out_folder` | directory (output) | Yes | Folder for the output rasters. | +| `style` | `tin` \| `pitfree` | Yes | Surface algorithm. The default is `tin`. An invalid value falls back to `tin`. | +| `tiling` | `auto` \| `by_file` \| `tiling` | No | How the data is split into tiles (see [Tiling](../technical/tool_behaviour.md#how-all-the-tools-behave)). The default is `auto`. | +| `skip_existing` | bool | No | Set to `True` to resume a run that stopped: tiles whose outputs are complete are skipped (see [Resuming a run](../technical/tool_behaviour.md#how-all-the-tools-behave)). The default is `False`. | +| `processes` | int | No | Requested number of parallel workers. | + +| `style` | lidR algorithm | Tile output | Merged output | +|---------|----------------|-------------|---------------| +| `tin` | `dsmtin(max_edge = 3 × cell_size)` | `_TIN_CHM.tif` / `_TIN_DSM.tif` | `Merged_TIN_CHM.tif` / `Merged_TIN_DSM.tif` | +| `pitfree` | `pitfree(thresholds = c(0, 3, 5, 10, 15, 20), max_edge = c(0, 3 × cell_size), subcircle = cell_size)`. Overlap points are also dropped. | `_PitF_CHM.tif` / `_PitF_DSM.tif` | `Merged_PitF_CHM.tif` / `Merged_PitF_DSM.tif` | + +```python +from beratools.modules.pc2products.rpy_CHM_DSM_by import rpy_chm_dsm + +# DSM from the original tiles +rpy_chm_dsm(in_las_folder="tests/data/LiDAR", + out_folder="tests/data/LiDAR/Raster_Output", + style="pitfree") + +# CHM from the output of Normalize LiDAR Data +rpy_chm_dsm(in_las_folder="tests/data/LiDAR/Normalized_PC", + out_folder="tests/data/LiDAR/Raster_Output", + style="tin") +``` + +## Command line + +```bash +bt chm_dsm # show the parameters +bt chm_dsm --in_las_folder --out_folder --style pitfree +``` diff --git a/beratools/modules/pc2products/docs/files/user/dtm.md b/beratools/modules/pc2products/docs/files/user/dtm.md new file mode 100644 index 0000000..8f1d7f3 --- /dev/null +++ b/beratools/modules/pc2products/docs/files/user/dtm.md @@ -0,0 +1,37 @@ +# Generate DTM from LiDAR Data + +Builds a Digital Terrain Model from the ground points with `lidR::rasterize_terrain`. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `in_las_folder` | directory | Yes | Folder containing the input LAS/LAZ tiles. | +| `out_folder` | directory (output) | Yes | Folder for the output rasters. | +| `style` | `tin` \| `idw` \| `kriging` | Yes | Interpolation algorithm. The default is `tin`. An invalid value falls back to `tin`. | +| `tiling` | `auto` \| `by_file` \| `tiling` | No | How the data is split into tiles (see [Tiling](../technical/tool_behaviour.md#how-all-the-tools-behave)). The default is `auto`. | +| `skip_existing` | bool | No | Set to `True` to resume a run that stopped: tiles whose outputs are complete are skipped (see [Resuming a run](../technical/tool_behaviour.md#how-all-the-tools-behave)). The default is `False`. | +| `processes` | int | No | Requested number of parallel workers (see [How all the tools behave](../technical/tool_behaviour.md#how-all-the-tools-behave)). | + +| `style` | lidR algorithm | Tile output | Merged output | +|---------|----------------|-------------|---------------| +| `tin` | `tin()`: Delaunay triangulation | `_TIN_DTM.tif` | `Merged_TIN_DTM.tif` | +| `idw` | `knnidw()`: k-nearest-neighbour inverse distance weighting | `_IDW_DTM.tif` | `Merged_IDW_DTM.tif` | +| `kriging` | `kriging()`: local ordinary kriging with `gstat` | `_K_DTM.tif` | `Merged_K_DTM.tif` | + +```python +from beratools.modules.pc2products.rpy_dtm_by import rpy_dtm + +rpy_dtm(in_las_folder="tests/data/LiDAR", + out_folder="tests/data/LiDAR/Raster_Output", + style="tin") +``` + +While a tool runs, the **Run** button is disabled and the R output streams into the log: + +![Generate DTM from LiDAR Data running in the BERA Tools GUI](../screenshots/pc2products_gui_dtm_running.png) + +## Command line + +```bash +bt dtm # show the parameters +bt dtm --in_las_folder --out_folder --style tin -p 4 +``` diff --git a/beratools/modules/pc2products/docs/files/user/dtw.md b/beratools/modules/pc2products/docs/files/user/dtw.md new file mode 100644 index 0000000..b505c80 --- /dev/null +++ b/beratools/modules/pc2products/docs/files/user/dtw.md @@ -0,0 +1,59 @@ +# Depth-to-Water from Surface Water + +Estimates the water table and depth to water (DTW), following section 2.4 of Chan, Dabros & McDermid +(2026), which adapts Rahman et al. (2017). In peatlands, surface water is closely linked to the +groundwater, so the elevation of the many small pools traces the water table. The tool: + +1. Puts the surface water raster on the DTM grid (by majority if the water raster is finer) and masks + the DTM to the water cells. +2. Splits the area into `grid_size` cells (10 m in the paper). In each cell that contains water, the + minimum water elevation becomes one point at the cell centre. Cells without water give no point. +3. Fits a variogram (`variogram_model`, Matern with M. Stein's parameterization by default, plus a + nugget) and kriges the water table with ordinary kriging from the `nmax` nearest points (gstat). +4. Computes DTW = DTM − water table. Values below 0 and surface water cells are set to `0`. +5. Leaves out the exclusion polygons, if any: they give no water points and are NA in the outputs. + The paper excluded an upland knoll this way, because it had too little surface water. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `in_dtm` | raster | Yes | DTM. The water table and DTW are produced on its grid. | +| `in_water` | raster | Yes | `1` for surface water, for example `surface_water.tif` from [Surface Water Mapping](surface_water.md). | +| `out_folder` | directory (output) | Yes | Folder for the outputs. | +| `in_mask` | vector (polygon) | No | Areas to leave out, as `file.gpkg\|layer` for a GeoPackage. | +| `grid_size` | float | No | Grid cell size (m) for the water points. The default is `10`. | +| `nmax` | int | No | Nearest water points used for each prediction. The default is `10`. | +| `variogram_model` | `Ste` \| `Sph` \| `Exp` \| `Gau` | No | Variogram model. The default is `Ste` (Matern, as in the paper). | +| `kriging_cell_size` | float | No | Krige on a coarser grid (m), then resample bilinearly to the DTM. `0` (the default) kriges on the DTM grid, which is slow for a large 10 cm DTM. | + +| Output | Contents | +|--------|----------| +| `water_table.tif` | Kriged water table elevation. | +| `dtw.tif` | Depth to water (m): positive below ground, `0` on surface water. | +| `water_points.gpkg` | The water elevation points used for kriging. | +| `variogram_model.csv`, `variogram.png` | Fitted variogram parameters and plot. | +| `water_table_cv.csv` | Leave-one-out cross-validation of the water table at the water points (MAE, RMSE). | + +On the paper's data, with the surface water taken from the published `dtw.tif` (cells equal to `0`) +and `kriging_cell_size = 1`, the tool's DTW correlates with the published DTW at r = 0.97, and its +leave-one-out MAE is 3.9 cm. It is about 4 cm deeper on average, probably because cells the paper set +to `0` for lying below the water table were treated as water in that test. + +```python +from beratools.modules.pc2products.rpy_dtw import rpy_dtw + +rpy_dtw(in_dtm="dtm.tif", in_water="surface_water/surface_water.tif", + in_mask="exclude.gpkg|exclude", out_folder="dtw", kriging_cell_size=1.0) +``` + +## Command line + +```bash +bt dtw # show the parameters +bt dtw --in_dtm dtm.tif --in_water surface_water.tif --out_folder --kriging_cell_size 1 +``` + +## Reference + +Chan, Dabros & McDermid (2026), +[*Microtopographic and Hydrological Response to Repeated Seismic Line Disturbance in a Boreal Fen of +Northern Alberta, Canada*](https://doi.org/10.3390/f17040489), *Forests* 17, 489. diff --git a/beratools/modules/pc2products/docs/files/user/gnd_csf.md b/beratools/modules/pc2products/docs/files/user/gnd_csf.md new file mode 100644 index 0000000..65f50ce --- /dev/null +++ b/beratools/modules/pc2products/docs/files/user/gnd_csf.md @@ -0,0 +1,40 @@ +# Ground Classify Using CSF + +Classifies ground points with the Cloth Simulation Filter (Zhang et al., 2016), using +`lidR::classify_ground` with `RCSF`'s `csf()` algorithm. The cloth runs for 500 iterations with a +time step of 0.65. Noise (class 7) and overlap points are dropped when the tiles are read. + +If the input is already ground-classified (the first file has any class 2 points), the existing +classification is replaced and lidR's progress messages are hidden. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `in_las_folder` | directory | Yes | Folder containing the input LAS/LAZ tiles. | +| `out_folder` | directory (output) | Yes | Folder for the classified point clouds. | +| `slope` | bool | No | Set to `True` when steep slopes exist, to reduce errors in post-processing. The default is `False`. | +| `class_threshold` | float | No | Distance to the simulated cloth that separates ground from non-ground points. The default is `0.5`. | +| `cloth_resolution` | float | No | Distance between cloth particles. This is usually the average point spacing. The default is `1.0`. | +| `rigidness` | `1` \| `2` \| `3` | No | Cloth stiffness: `1` is very soft (rugged terrain), `2` is medium, and `3` is hard (flat terrain). The default is `1`. | +| `tiling` | `auto` \| `by_file` \| `tiling` | No | How the data is split for classification (see [Tiling](../technical/tool_behaviour.md#how-all-the-tools-behave)). The default is `auto`. | +| `skip_existing` | bool | No | Set to `True` to resume a run that stopped: tiles whose outputs are complete are skipped (see [Resuming a run](../technical/tool_behaviour.md#how-all-the-tools-behave)). The default is `False`. | +| `processes` | int | No | Requested number of parallel workers. | + +Output: one uncompressed `_csfgnd_uptocm_clothcm_.las` +per tile. The name records the parameters: the ground threshold and the cloth resolution to the +nearest cm, and the rigidness as `soft` (1), `standard` (2) or `hard` (3). For example, a threshold of 0.3, a +cloth resolution of 1.5 and rigidness 3 give `_csfgnd_upto30cm_cloth150cm_hard.las`. + +```python +from beratools.modules.pc2products.rpy_gnd_csf import rpy_gnd_csf + +rpy_gnd_csf(in_las_folder="tests/data/LiDAR", + out_folder="tests/data/LiDAR/Classified_PC", + slope=False, class_threshold=0.3, cloth_resolution=1.0, rigidness=1) +``` + +## Command line + +```bash +bt gnd_csf # show the parameters +bt gnd_csf --in_las_folder --out_folder --slope false --rigidness 2 +``` diff --git a/beratools/modules/pc2products/docs/files/user/hummock_hollow.md b/beratools/modules/pc2products/docs/files/user/hummock_hollow.md new file mode 100644 index 0000000..ee35805 --- /dev/null +++ b/beratools/modules/pc2products/docs/files/user/hummock_hollow.md @@ -0,0 +1,62 @@ +# Detect Hummock and Hollow from LiDAR Data + +> Algorithm details: [Technical Guide → Raster Smoothing and Normalized DTM](https://beratool.github.io/beratools/raster2products/technical/algorithms/raster_smoothing/) + +Maps micro-topography by comparing the terrain with a smoothed copy of itself. For each tile, the +tool: + +1. Builds a DTM with `rasterize_terrain(algorithm = tin())`. +2. Smooths it with a circular moving window of diameter `Min_ws`, using the `mean` or `median` + (`terra::focal`). The window is the cells whose centres lie within its radius, a true circle also + on cells that aren't square; cells with no value are left out, and near the edges of the data the + window holds only the real neighbours. [Normalized DTM from DTM Raster](https://beratool.github.io/beratools/raster2products/user/ndtm_fr_dtmraster/) + smooths a DTM you already have the same way. +3. Subtracts the DTM from the smoothed surface, and classifies each cell using `lawn_range`: + +| Cell | Value in `HH_*.tif` | +|------|---------------------| +| More than `lawn_range` above the smoothed surface | `1` (hummock) | +| More than `lawn_range` below the smoothed surface | `-1` (hollow) | +| Within ±`lawn_range` | `0` (lawn) | + +The data must be ground-classified. If the first file has no class 2 points, the tool prints a +warning and stops without writing anything. Run [Ground Classify Using CSF](gnd_csf.md) +first. The data must not be normalized either: normalized point clouds have their ground at +height 0, so they have no terrain relief and every cell would be lawn. If the ground points of the +first file have a mean height under 1 m, the tool stops with an error; use the ground-classified +point clouds from before normalization. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `in_las_folder` | directory | Yes | Folder containing the ground-classified LAS/LAZ tiles. | +| `out_folder` | directory (output) | Yes | Folder for the output rasters. | +| `Smooth_by` | `mean` \| `median` | Yes | Statistic used to smooth the DTM. The default is `mean`. | +| `Min_ws` | float | Yes | Diameter of the circular moving window, in metres. The default is `3.0`. | +| `lawn_range` | float | Yes | Height band around the smoothed surface that counts as lawn, in metres. The default is `0.3`. | +| `cell_size` | float | No | Output cell size in metres. `0` (the default) calculates it from the point density. | +| `tiling` | `auto` \| `by_file` \| `tiling` | No | How the data is split into tiles (see [Tiling](../technical/tool_behaviour.md#how-all-the-tools-behave)). The default is `auto`. | +| `skip_existing` | bool | No | Set to `True` to resume a run that stopped: tiles whose outputs are complete are skipped (see [Resuming a run](../technical/tool_behaviour.md#how-all-the-tools-behave)). The default is `False`. | +| `processes` | int | No | Requested number of parallel workers. | + +| Output | Contents | +|--------|----------| +| `CHH___m.tif` | Continuous height of the terrain relative to the smoothed surface. | +| `HH___m.tif` | Hummock (`1`), hollow (`-1`) and lawn (`0`) classes. | +| `Merged_CHH__m.tif`, `Merged_HH__m.tif` | Mosaics of all tiles. `Merged_HH_` is a 16-bit integer raster (NA is -32768). | + +```python +from beratools.modules.pc2products.rpy_PC2hummock_hollow import rpy_hh2raster + +rpy_hh2raster(in_las_folder="tests/data/LiDAR/Classified_PC", + out_folder="tests/data/LiDAR/Raster_Output", + Smooth_by="median", Min_ws=3.0, lawn_range=0.1, cell_size=0) +``` + +![Detect Hummock and Hollow from LiDAR Data in the BERA Tools GUI after a run](../screenshots/pc2products_gui_hh.png) + +## Command line + +```bash +bt hh # show the parameters +bt hh --in_las_folder --out_folder --Smooth_by median --Min_ws 3 --lawn_range 0.1 +``` diff --git a/beratools/modules/pc2products/docs/files/user/las_info.md b/beratools/modules/pc2products/docs/files/user/las_info.md new file mode 100644 index 0000000..0e7468e --- /dev/null +++ b/beratools/modules/pc2products/docs/files/user/las_info.md @@ -0,0 +1,35 @@ +# LiDAR data info + +Prints a summary of the LiDAR dataset to the console. It doesn't write any files. + +| Item | How it's calculated | +|------|---------------------| +| Data format | LAS version (`Major.Minor`) of the first file | +| CRS / EPSG / Units | `sf::st_crs` of the catalog. Reports `Unknown` if the CRS is missing. | +| Extent | min X, max X, min Y, max Y across all tiles | +| Area | Catalog area in km² | +| Total Points | Sum of the point records in all tiles | +| Density | Total points / area, in pts/m² | +| Total Files | Number of LAS/LAZ files | +| Normalized | `YES` if the mean \|Z\| of the ground points is below 1 (first file only) | +| Ground Z Range / Z Range | Min and max Z of the ground points and of all points (first file only) | + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `in_las_folder` | directory | Yes | Folder containing the input LAS/LAZ tiles. | +| `processes` | int | No | Requested number of parallel workers. | + +```python +from beratools.modules.pc2products.rpy_las_info import rpy_las_info + +rpy_las_info(in_las_folder="tests/data/LiDAR") +``` + +![LiDAR data info in the BERA Tools GUI, showing the dataset summary in the log](../screenshots/pc2products_gui_las_info.png) + +## Command line + +```bash +bt las_info # show the parameters +bt las_info --in_las_folder +``` diff --git a/beratools/modules/pc2products/docs/files/user/lidar_index.md b/beratools/modules/pc2products/docs/files/user/lidar_index.md new file mode 100644 index 0000000..49ac105 --- /dev/null +++ b/beratools/modules/pc2products/docs/files/user/lidar_index.md @@ -0,0 +1,43 @@ +# Build LiDAR Spatial Index + +Builds a `.lax` spatial index for every LAS/LAZ file in the folder that doesn't have one, and +writes it next to the file. With an index, reading part of a file (a tile of a large file, or the +buffer strip of a neighbouring file) reads only that area instead of the whole file. + +The other LiDAR tools build missing indexes themselves before they process the data (see +[How the PC2Products Tools Run](../technical/tool_behaviour.md#how-all-the-tools-behave)), so +running this tool is optional. It lets you build them ahead of time, because building an index +reads every point of the file once: + +- LAZ files are indexed at about 2.3 million points per second per process (the points are + decompressed), which is about 80 minutes for 11.5 billion points with one process. LAS files + are only read, at about 5.4 million points per second. +- Several files are indexed at once, one per R process: at most 8, one fewer than the CPU cores, + and about one per 200 MB of files. On one hard disk, 118 GB of LAZ (11.5 billion points) took + about 24 minutes with 19 processes and 28 minutes with 6, as the disk serves more reads queued + at once faster. +- Each index is small (34 KB for a 20 GB file), and building indexes uses little memory (1.4 GB + for 8 processes). + +The input folder must be writable. If an index can't be written, the tool prints a warning and +reports how many files have an index. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `in_las_folder` | directory | Yes | Folder containing the LAS/LAZ files. The `.lax` files are written into it. | +| `overwrite` | bool | No | Set to `True` to rebuild the indexes of files that already have one, for example after the files changed. The default is `False`. | +| `processes` | int | No | Most R processes to build indexes with. The default (0) leaves it to the limits above; a value only lowers them, never raises the 8. | + +```python +from beratools.modules.pc2products.rpy_lidar_index import rpy_lidar_index + +rpy_lidar_index(in_las_folder="tests/data/LiDAR") +``` + +## Command line + +```bash +bt lidar_index # show the parameters +bt lidar_index --in_las_folder +bt lidar_index --in_las_folder --overwrite true +``` diff --git a/beratools/modules/pc2products/docs/files/user/lidar_tile.md b/beratools/modules/pc2products/docs/files/user/lidar_tile.md new file mode 100644 index 0000000..02c07e6 --- /dev/null +++ b/beratools/modules/pc2products/docs/files/user/lidar_tile.md @@ -0,0 +1,56 @@ +# Tile LiDAR Data + +Splits the LiDAR files of a folder into square tiles sized by the point density, and writes them to +a new folder. It uses the same plan as the processing tools when they tile the data themselves (see +[How the LiDAR Tools Tile a Point Cloud](../technical/lidar_density_tiling.md)): the data is divided +into 500 m blocks, and each block gets the largest of 500, 250, 125 or 100 m tiles whose densest +tile, with its buffer, fits in the free memory. + +Tiling ahead of time is useful when: + +- the input is a few very large files, or files whose density varies a lot, and you will run + several tools on it: the tiles are cut once, and each tool then processes them by file; +- you want the tiles themselves, for example to share or inspect part of the data; +- you want uniform tiles from a tool's tiled point cloud output, whose tiles vary from 500 m down + to 100 m: run this tool on the output folder with `tile_size` set to `500` (or `1000`) and + `buffer` to `0`, once the chain of tools is done. The tiles combine into exact 500 m blocks. + +The points are copied as they are, noise included, and streamed from file to file, so cutting the +tiles needs about one R session of memory (~1.6 GB) per worker. More workers can therefore cut +tiles than the processing tools would start. + +Output, in `out_folder`: + +- one tile per file, named by its lower-left corner, for example `520250_6228125.laz`; +- `tiles.csv`, the tile size of each 500 m block (`bx, by, size`), which a resumed run reuses; +- a `.lax` spatial index for each tile, so a tool reading a tile's buffer from its neighbours reads + only that strip. + +The tiles are sized for the memory free when this tool runs. A tool that processes them later +with `tiling` set to `auto` processes them by file when they all fit in its free memory, and +otherwise tiles the data again itself, so run it with about as much memory free. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `in_las_folder` | directory | Yes | Folder containing the input LAS/LAZ files. | +| `out_folder` | directory (output) | Yes | Folder for the tiles. It must differ from the input folder. | +| `buffer` | float | No | Buffer (m) a tool reads around each tile when it processes the tiles later: 20 for ground classification, 30 for the other tools. It only sizes the tiles; they are cut without a buffer. The default is `30`. | +| `tile_size` | float | No | `0` sizes the tiles by the point density (500 to 100 m). Any other value is one tile size in metres for all the data. The default is `0`. | +| `laz` | bool | No | `True` writes LAZ tiles, about a third of the size of LAS; `False` writes LAS, which is faster to read. The default is `True`. | +| `skip_existing` | bool | No | Set to `True` to resume a run that stopped: tiles already written completely are not cut again, and the tile sizes are read from `tiles.csv`. The default is `False`. | +| `processes` | int | No | Most R workers to cut tiles with. | + +```python +from beratools.modules.pc2products.rpy_lidar_tile import rpy_lidar_tile + +rpy_lidar_tile(in_las_folder="tests/data/LiDAR", out_folder="tests/data/LiDAR/Tiles") +``` + +## Command line + +```bash +bt tile # show the parameters +bt tile --in_las_folder --out_folder +bt tile --in_las_folder --out_folder --buffer 20 --laz false +bt tile --in_las_folder --out_folder --tile_size 250 +``` diff --git a/beratools/modules/pc2products/docs/files/user/normalize.md b/beratools/modules/pc2products/docs/files/user/normalize.md new file mode 100644 index 0000000..c85a96b --- /dev/null +++ b/beratools/modules/pc2products/docs/files/user/normalize.md @@ -0,0 +1,39 @@ +# Normalize LiDAR Data + +Height-normalizes the point cloud with `lidR::normalize_height`: the terrain is interpolated from the +ground points (class 2) and subtracted from every point, so Z becomes height above ground. Noise +(class 7) is dropped when the tiles are read. The data must be ground-classified, so run +[Ground Classify Using CSF](gnd_csf.md) first if it isn't. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `in_las_folder` | directory | Yes | Folder containing the ground-classified LAS/LAZ tiles. | +| `out_folder` | directory (output) | Yes | Folder in which the `Normalized_PC/` subfolder is created. | +| `style` | `tin` \| `idw` \| `kriging` | Yes | Terrain interpolation algorithm: `tin()`, `knnidw()` or `kriging()`. The default is `tin`. An invalid value falls back to `tin`. | +| `tiling` | `auto` \| `by_file` \| `tiling` | No | How the data is split into tiles (see [Tiling](../technical/tool_behaviour.md#how-all-the-tools-behave)). The default is `auto`. | +| `skip_existing` | bool | No | Set to `True` to resume a run that stopped: tiles whose outputs are complete are skipped (see [Resuming a run](../technical/tool_behaviour.md#how-all-the-tools-behave)). The default is `False`. | +| `processes` | int | No | Requested number of parallel workers. | + +A tile whose ground points are fewer than 3 or lie on a line, such as a file of a few points all +at Z = 0 and none of them ground, can't be normalized: it is left out, with no output file, and +the run ends with a warning naming it (see +[Tiles left out](../technical/tool_behaviour.md#how-all-the-tools-behave)). + +Output: one `/Normalized_PC/n_.las` per input tile. Point +[Generate CHM or DSM from LiDAR Data](chm_dsm.md) at the `Normalized_PC` +folder to get a CHM. + +```python +from beratools.modules.pc2products.rpy_normalized_PC import rpy_normalized_PC + +rpy_normalized_PC(in_las_folder="tests/data/LiDAR", + out_folder="tests/data/LiDAR", + style="tin") +``` + +## Command line + +```bash +bt normalize # show the parameters +bt normalize --in_las_folder --out_folder --style tin +``` diff --git a/beratools/modules/pc2products/docs/files/user/seismic_line_analysis.md b/beratools/modules/pc2products/docs/files/user/seismic_line_analysis.md new file mode 100644 index 0000000..ed5f120 --- /dev/null +++ b/beratools/modules/pc2products/docs/files/user/seismic_line_analysis.md @@ -0,0 +1,85 @@ +# Seismic Line Disturbance Analysis + +Compares seismic line segments with the undisturbed peatland ("matrix") beside them, by disturbance +class. It is adapted from the analysis script of Chan, Dabros & McDermid (2026), +[*Microtopographic and Hydrological Response to Repeated Seismic Line Disturbance in a Boreal Fen of +Northern Alberta, Canada*](https://doi.org/10.3390/f17040489), *Forests* 17, 489. On the paper's +published data it gives the same tables as the original script. It needs only the `terra` and +`ggplot2` R packages; the statistical tests are written in base R. + +For each segment, the tool summarises the rasters under it. Then, for each line segment, it subtracts +the mean of its matrix segments: + +| Attribute | From | Per segment | Deviation | +|-----------|------|-------------|-----------| +| `dtm` | DTM | Mean elevation | Line − matrix (m) | +| `hummock` | Microform raster | Hummock cells / classified cells | Line − matrix | +| `dtw` | Depth-to-water raster | Mean DTW over ground cells (DTW ≠ 0) | Line − matrix (m) | +| `surfacewater` | Depth-to-water raster | Cells with DTW = 0 / all cells | Line − matrix | + +For each attribute it compares the disturbance classes with: + +- a Kruskal–Wallis test, and pairwise Wilcoxon rank-sum tests with Benjamini–Hochberg (BH) correction. + The `mean_group` letters come from these. +- a Brown–Forsythe test, and pairwise Brown–Forsythe tests with BH correction. The `bf_group` letters + come from these. This is the Brown–Forsythe test for equal *means* under unequal variances (the + statistic of `onewaytests::bf.test`, which the original script uses). + +Classes that share a letter don't differ significantly at the chosen `significance`. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `in_segments` | vector (polygon) | Yes | Segment polygons, as `file.gpkg\|layer` for a GeoPackage. Fields: `new_id` links a line segment to its matrix segments, `note` is `original` (line) or `matrix`, and `Class` is the disturbance class. | +| `in_dtm` | raster | Yes | DTM, for example from [Generate DTM from LiDAR Data](dtm.md). | +| `in_microform` | raster | Yes | Hummock (`1`), lawn (`0`) and hollow (`-1`) raster, for example the `HH_` or `Merged_HH_` output of [Detect Hummock and Hollow from LiDAR Data](hummock_hollow.md). | +| `out_folder` | directory (output) | Yes | Folder for the `tables/` and `plots/` outputs. | +| `in_dtw` | raster | No | Depth to water in metres, with `0` for surface water. Without it, `dtw` and `surfacewater` are skipped. | +| `significance` | float | No | Significance level for the letter groupings. The default is `0.05`. | + +The segments are projected to the DTM's coordinate system if they differ. Classes named `New +Disturbance`, `Old Disturbance` and `Re-disturbance` keep the paper's order and colours; any other +class names are sorted alphabetically. + +| Output | Contents | +|--------|----------| +| `tables/segment_values.csv` | Per-segment summaries for every segment. | +| `tables/segment_deviations.csv` | Per-line-segment deviations from the matrix. | +| `tables/_deviation_summary.csv` | By class: n, mean, median, min, max, quartiles, SD, variance, `mean_group` and `bf_group`. | +| `tables/_kruskal_wilcoxon.csv` | Kruskal–Wallis result and BH-adjusted pairwise Wilcoxon p-values. | +| `tables/_brown_forsythe.csv` | Brown–Forsythe result and pairwise p-values (raw and BH-adjusted). | +| `tables/class_microform_proportions.csv`, `tables/class_surfacewater_proportions.csv` | Cell proportions for the matrix and each class. | +| `plots/_violin.png` | Deviation distribution per class, with the class mean (dot) and `mean_group` letters. | +| `plots/microform_barplot.png`, `plots/surfacewater_barplot.png` | Stacked proportions for the matrix and each class. | + +```python +from beratools.modules.pc2products.rpy_seismic_line_analysis import rpy_seismic_line_analysis + +rpy_seismic_line_analysis(in_segments="segments.gpkg|segments", + in_dtm="dtm.tif", in_microform="microform.tif", in_dtw="dtw.tif", + out_folder="analysis") +``` + +## Reproducing Chan et al. (2026) + +The paper's workflow maps onto the PC2Products tools like this: + +| Paper step | PC2Products tool | Settings | +|------------|------------------|----------| +| Ground classification (LAStools in the paper) | Ground Classify Using CSF | Defaults | +| 10 cm DTM with `knnidw` (k = 10, p = 2) | Generate DTM from LiDAR Data | `style = idw` (lidR's `knnidw()` defaults are k = 10, p = 2). The cell size comes from the point density and can't be set. | +| Microforms: DTM minus its 3 m focal mean, ±6 cm | Detect Hummock and Hollow from LiDAR Data | `Smooth_by = mean`, `Min_ws = 3`, `lawn_range = 0.06`, `cell_size = 0.1`. The tool builds its own DTM with TIN. | +| Surface water: rpart classification of the orthomosaic's RGB values, CHM mask (> 0.2 m), patches under 20 × 20 cm removed | Surface Water Mapping | Defaults, with the CHM as `in_chm` | +| Water table: minimum water elevation per 10 m cell, ordinary kriging (Matern, 10 nearest), then DTW = DTM − water table | Depth-to-Water from Surface Water | Defaults, with the upland knoll as `in_mask` | +| Segments along mapped centrelines (Forest Line Mapper) | None | Not available; supply `in_segments` from elsewhere. | +| Comparison and statistics | Seismic Line Disturbance Analysis | `significance = 0.05` | + +The paper's published data (`dtm.tif`, `dtw.tif`, `microform.tif` and `segments.gpkg`, on +[Zenodo](https://doi.org/10.5281/zenodo.18778508)) can be used directly as the inputs to Seismic Line +Disturbance Analysis. + +## Command line + +```bash +bt line_analysis # show the parameters +bt line_analysis --in_segments "segments.gpkg|segments" --in_dtm dtm.tif --in_microform HH.tif --in_dtw dtw.tif --out_folder +``` diff --git a/beratools/modules/pc2products/docs/files/user/surface_water.md b/beratools/modules/pc2products/docs/files/user/surface_water.md new file mode 100644 index 0000000..f349099 --- /dev/null +++ b/beratools/modules/pc2products/docs/files/user/surface_water.md @@ -0,0 +1,55 @@ +# Surface Water Mapping + +Maps surface water from a true-colour orthomosaic, following section 2.4 of Chan, Dabros & McDermid +(2026): + +1. Draws `points_per_polygon` random points inside each training polygon and reads the orthomosaic's + red, green and blue values (bands 1–3) at each point. +2. Trains an `rpart` decision tree on those values, and estimates its accuracy with 5-fold + cross-validation on the training points. +3. Classifies every cell of the orthomosaic. Cells the tree labels `water` become `1`, all others `0`. +4. If a CHM is given, sets cells with canopy taller than `max_canopy_height` to `0`. The CHM is + resampled to the orthomosaic's grid first. +5. Sets water patches (8-connected) smaller than `min_patch_area` to `0`. + +The training polygons need a `class` field. Polygons labelled `water` (in any case) are surface water; +use any other labels for the rest, for example `ground` and `shadow` as in the paper. rpart needs at +least 20 training points before it splits, so the tool warns if the tree ends up with no splits. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `in_ortho` | raster | Yes | True-colour orthomosaic; bands 1–3 are red, green and blue. | +| `in_training` | vector (polygon) | Yes | Training polygons with a `class` field, as `file.gpkg\|layer` for a GeoPackage. | +| `out_folder` | directory (output) | Yes | Folder for the outputs. | +| `in_chm` | raster | No | Canopy height model, for example from [Generate CHM or DSM from LiDAR Data](chm_dsm.md). | +| `max_canopy_height` | float | No | Cells with a CHM above this height (m) can't be water. The default is `0.2`. | +| `min_patch_area` | float | No | Water patches smaller than this area (m²) are removed; `0` keeps them all. The default is `0.04` (20 × 20 cm). | +| `points_per_polygon` | int | No | Random training points per polygon. The default is `2`. | +| `seed` | int | No | Seed for the training points and cross-validation folds. The default is `1`. | + +| Output | Contents | +|--------|----------| +| `surface_water.tif` | `1` for surface water, `0` for everything else. | +| `cv_accuracy.csv`, `cv_confusion_matrix.csv` | 5-fold cross-validation accuracy and confusion matrix. | +| `training_points.gpkg` | The random training points and their classes. | +| `decision_tree.txt` | The fitted tree's splits. | + +```python +from beratools.modules.pc2products.rpy_surface_water import rpy_surface_water + +rpy_surface_water(in_ortho="ortho.tif", in_training="training.gpkg|training", + in_chm="chm.tif", out_folder="surface_water") +``` + +## Command line + +```bash +bt surface_water # show the parameters +bt surface_water --in_ortho ortho.tif --in_training "training.gpkg|training" --in_chm chm.tif --out_folder +``` + +## Reference + +Chan, Dabros & McDermid (2026), +[*Microtopographic and Hydrological Response to Repeated Seismic Line Disturbance in a Boreal Fen of +Northern Alberta, Canada*](https://doi.org/10.3390/f17040489), *Forests* 17, 489. diff --git a/beratools/modules/pc2products/docs/mkdocs.yml b/beratools/modules/pc2products/docs/mkdocs.yml new file mode 100644 index 0000000..0d5224d --- /dev/null +++ b/beratools/modules/pc2products/docs/mkdocs.yml @@ -0,0 +1,29 @@ +# The PC2Products (LiDAR) module's docs site. Shared settings are in docs/base.yml at the repo root. +# Build with `zensical`, not `mkdocs`. +INHERIT: ../../../../docs/base.yml + +site_name: BERA Tools PC2Products (LiDAR) +site_url: https://beratool.github.io/beratools/pc2products/ +edit_uri: edit/main/beratools/modules/pc2products/docs/files/ + +nav: + - Home: index.md + - User Guide: + - user/las_info.md + - user/cellsize.md + - user/lidar_index.md + - user/lidar_tile.md + - user/gnd_csf.md + - user/dtm.md + - user/normalize.md + - user/chm_dsm.md + - user/hummock_hollow.md + - user/surface_water.md + - user/dtw.md + - user/seismic_line_analysis.md + - Technical Guide: + - technical/pc2products_overview.md + - technical/tool_behaviour.md + - technical/lidar_density_tiling.md + - API Reference: api.md + - BERA Tools Guide: https://beratool.github.io/beratools/ diff --git a/beratools/modules/pc2products/r_common.py b/beratools/modules/pc2products/r_common.py new file mode 100644 index 0000000..7a6416b --- /dev/null +++ b/beratools/modules/pc2products/r_common.py @@ -0,0 +1,418 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Maverick Fong + +Description: + This script is helper tools for execute the R scripts. + + Webpage: https://github.com/BERATool/beratools + +""" + +import os +import re +import subprocess +import sys + +import psutil + +r = None +robjects = None + +# ------------------------------------------------------ +# lazy initialization rpy2 +# ------------------------------------------------------ +def _import_robjects(): + """ + Import rpy2.robjects without the "'sh' is not recognized" message on Windows. + + On import, rpy2 runs `R CMD config --ldflags` to find R's DLL folders. On Windows that + command is a shell script that needs sh.exe (from Rtools). Without it, cmd prints + "'sh' is not recognized as an internal or external command" to stderr; rpy2 catches the + failure and falls back to R_HOME/bin/x64, so the message is noise. Silence that one call. + + When sh.exe is found (e.g. from Git) but make is not, the script exits 0 with no output + and rpy2 crashes with IndexError instead of falling back. Report that as a failure too. + """ + if os.name != "nt": + import rpy2.robjects as robjects_module + return robjects_module + + check_output = subprocess.check_output + + def quiet_check_output(cmd, *args, **kwargs): + if "CMD" not in cmd or "config" not in cmd: + return check_output(cmd, *args, **kwargs) + + kwargs.setdefault("stderr", subprocess.DEVNULL) + output = check_output(cmd, *args, **kwargs) + if not output.strip(): + raise subprocess.CalledProcessError(1, cmd, output) + return output + + subprocess.check_output = quiet_check_output + try: + import rpy2.robjects as robjects_module + finally: + subprocess.check_output = check_output + + return robjects_module + + +def r_graphics_enabled(): + """ + Whether R runs interactively, so lidR draws its map of the tiles in an R Graphics window + while it processes them: set environment variable BERATOOLS_R_GRAPHICS to 1, true or yes. + """ + return os.environ.get("BERATOOLS_R_GRAPHICS", "").strip().lower() in ("1", "true", "yes") + +# The Windows Job Object that limits this process's memory; kept open for the life of the process +_memory_job = None + +def limit_memory(fraction=0.8): + """ + Limit the memory of this process, and of the R workers it starts, to `fraction` of the + memory free now, so a tool that needs more fails with R's "cannot allocate" error instead of + running the computer out of memory (on one machine a by_file run left it 0.42 GB free, and the + run then took minutes to release its memory when stopped). + + Windows only: the process joins a Job Object whose processes share a memory commit limit; the + R workers, started by this process, join it too, and any left over end with it. A failure to + set the limit, or another system, leaves memory unlimited. + """ + global _memory_job + if _memory_job is not None or os.name != "nt": + return None + import ctypes + from ctypes import wintypes + + class IO_COUNTERS(ctypes.Structure): + _fields_ = [(n, ctypes.c_ulonglong) for n in ("ReadOperationCount", "WriteOperationCount", + "OtherOperationCount", "ReadTransferCount", "WriteTransferCount", "OtherTransferCount")] + + class BASIC_LIMIT(ctypes.Structure): + _fields_ = [("PerProcessUserTimeLimit", ctypes.c_int64), ("PerJobUserTimeLimit", ctypes.c_int64), + ("LimitFlags", wintypes.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t), + ("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wintypes.DWORD), + ("Affinity", ctypes.c_size_t), ("PriorityClass", wintypes.DWORD), + ("SchedulingClass", wintypes.DWORD)] + + class EXTENDED_LIMIT(ctypes.Structure): + _fields_ = [("BasicLimitInformation", BASIC_LIMIT), ("IoInfo", IO_COUNTERS), + ("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t), + ("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)] + + JOB_OBJECT_LIMIT_JOB_MEMORY, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, EXTENDED_LIMIT_INFORMATION = ( + 0x200, + 0x2000, + 9, + ) + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.CreateJobObjectW.restype = wintypes.HANDLE + kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR] + kernel32.GetCurrentProcess.restype = wintypes.HANDLE + kernel32.SetInformationJobObject.argtypes = [ + wintypes.HANDLE, + ctypes.c_int, + ctypes.c_void_p, + wintypes.DWORD, + ] + kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE] + kernel32.CloseHandle.argtypes = [wintypes.HANDLE] + limit = fraction * psutil.virtual_memory().available + job = None + try: + job = kernel32.CreateJobObjectW(None, None) + info = EXTENDED_LIMIT() + info.BasicLimitInformation.LimitFlags = ( + JOB_OBJECT_LIMIT_JOB_MEMORY | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + ) + info.JobMemoryLimit = int(limit) + ok = bool( + job + and kernel32.SetInformationJobObject( + job, EXTENDED_LIMIT_INFORMATION, ctypes.byref(info), ctypes.sizeof(info) + ) + and kernel32.AssignProcessToJobObject(job, kernel32.GetCurrentProcess()) + ) + reason = f"error {ctypes.get_last_error()}" + except (OSError, ctypes.ArgumentError) as e: + ok, reason = False, str(e) + if not ok: + print(f"[Warning!] Could not limit the tool's memory ({reason}); it runs without a limit.") + if job: + kernel32.CloseHandle(job) + return None + _memory_job = job + # "percent", not "%": the GUI reads a "%" in a tool's output as progress + print(f"Memory limit: {limit / 1e9:.1f} GB ({fraction * 100:.0f} percent of the memory free now) " + f"for this tool and its R workers.") + + # Say what to do when the tool stops at the limit, before Python's traceback + previous_hook = sys.excepthook + def explain_memory_error(kind, value, tb): + if "cannot allocate" in str(value) or "bad_alloc" in str(value): + print( + f"\n[Error] The tool needed more memory than its limit of {limit / 1e9:.1f} GB and stopped. " + "Use tiling 'tiling' or 'auto' instead of 'by_file', close other programs, or use fewer " + "processes.", + flush=True, + ) + previous_hook(kind, value, tb) + sys.excepthook = explain_memory_error + return limit + +# A character R wrote as its code point because the console's code page can't encode it +_R_CODE_POINT = re.compile(r"") + +def decode_r_code_points(text): + """R's output with its "" code points turned back into the characters, such as ⚠.""" + return _R_CODE_POINT.sub(lambda m: chr(int(m.group(1), 16)), text) + +def initialize_r(): + global r + global robjects + + if r is not None: + return + # One OpenBLAS thread before rpy2 starts R, also when r_interface (which sets it) isn't imported + # first; see r_interface + os.environ.setdefault("OPENBLAS_NUM_THREADS", "1") + os.environ.setdefault("OMP_NUM_THREADS", "1") + # Importing rpy2.robjects starts R, whose startup on Windows raises access violations that it + # catches itself; see faulthandler_pause + from beratools.utility.faulthandler_pause import faulthandler_paused + + with faulthandler_paused(): + robjects_module = _import_robjects() + import logging +# suppresses output only during the import/startup phase, +# then restores normal printing for the rest of the test run. + logging.getLogger("rpy2").setLevel(logging.CRITICAL) + logging.getLogger("rpy2.situation").disabled = True + logging.getLogger("rpy2.rinterface_lib").disabled = True + logging.getLogger("rpy2.rinterface_lib.embedded").disabled = True + + from rpy2.rinterface_lib import callbacks + + orig_print = callbacks.consolewrite_print + orig_warn = callbacks.consolewrite_warnerror + + callbacks.consolewrite_print = lambda x: None + callbacks.consolewrite_warnerror = lambda x: None + + # R in python.exe takes Windows' code page (such as 1252), not the UTF-8 that R.exe and Rscript + # declare in their manifests, so it writes the characters it can't encode there as code points: + # lidR's "state ⚠" comes out as "state ". They are turned back into the characters here, + # as the streams are UTF-8 (below). Switching R to a UTF-8 locale instead crashed + # readLAScatalog. + callbacks.consolewrite_print = lambda s: orig_print(decode_r_code_points(s)) + callbacks.consolewrite_warnerror = lambda s: orig_warn(decode_r_code_points(s)) + # Locate R, set up its DLL path and isolate its library before rpy2 starts R, + # whichever module calls first. + import beratools.modules.pc2products.r_interface # noqa: F401 + + robjects = robjects_module + r = robjects.r + + # Run R non-interactively, as Rscript does. lidR then reports each tile as a line on stdout + # ("Chunk 3 of 7 (42.9%): state ✓"), which the GUI reads as progress. Interactive, it draws a + # progress bar with the 'progress' package when that is installed, which came out broken + # ("-2147483648%") or not at all under the GUI. Interactive is also what makes lidR draw its map + # of the tiles in an R Graphics window, so BERATOOLS_R_GRAPHICS=1 keeps R interactive for it; + # the GUI's progress bar then follows lidR's text bar, which works without 'progress' installed. + # The lines hold symbols a Windows pipe's code page can't encode, so the output is UTF-8. + from rpy2.rinterface_lib import openrlib + openrlib.rlib.R_Interactive = r_graphics_enabled() + for stream in (sys.stdout, sys.stderr): + if hasattr(stream, "reconfigure"): + stream.reconfigure(encoding="utf-8", errors="replace") + + # quick startup test + try: + r_version = str(r("R.version.string")[0]) + print(f"Connected to: {r_version}") + except Exception as e: + raise RuntimeError( + f"R was located but rpy2 could not connect to it:\n{e}" + ) + # Every R tool starts R here, so this is where it gets its memory limit + limit_memory() + +def r_processes_by_memory(processes, worker_bytes, tasks): + """ + Workers for an R job whose memory per worker is known: as many as requested (all CPU + cores if processes <= 0), limited by the CPU cores, the number of tasks and the free memory. + 60% of the free memory is shared out, leaving room for the system and other programs. + """ + cpu_count = os.cpu_count() or 1 + requested = processes if processes > 0 else cpu_count + by_memory = int(psutil.virtual_memory().available * 0.6 // worker_bytes) + workers = max(1, min(requested, cpu_count, tasks, by_memory)) + print(f"R workers: {workers} (smallest of: requested {requested}, CPU cores {cpu_count}, " + f"tiles {tasks}, free memory for {by_memory} at {worker_bytes / 1e9:.2f} GB each)") + return workers + +def r_max_workers(processes): + """ + Most R workers for the tiled LiDAR tools: as many as requested (all CPU cores if + processes <= 0), at most the CPU cores. apply_tiling in R then uses as many of them as the + free memory allows for the tiles. + """ + cpu_count = os.cpu_count() or 1 + return min(processes if processes > 0 else cpu_count, cpu_count) + +# How the LiDAR tools split a catalog; see apply_tiling in r_scripts_collection.r +TILING_OPTIONS = ("auto", "by_file", "tiling") + +def check_tiling(tiling): + if tiling not in TILING_OPTIONS: + raise ValueError(f"tiling must be one of {TILING_OPTIONS}, got {tiling!r}") + return str(tiling) + +def free_memory(): + """Free memory in bytes, which R shares out to size the LiDAR tiles.""" + return float(psutil.virtual_memory().available) + +def check_las_files_existence(folder): + if not os.path.exists(folder): + print(f"Error! Cannot locate LiDAR folder({folder}), please check.") + exit() + else: + found = False + for files in os.listdir(folder): + if files.endswith(".las") or files.endswith(".laz"): + found = True + break + if not found: + print(f"Error! Cannot locate input LAS/LAZ file(s) in {folder}, please check!") + exit() + +def check_las_out_folder_existence(folder): + if not os.path.exists(folder): + print("Warning! Cannot locate LiDAR output folder, will be created.") + os.makedirs(folder, exist_ok=True) + + +# R packages the LiDAR tools that start R workers use when installed, and run without: with +# future.mirai the workers are mirai daemons, which lidR keeps busy on Windows where future's +# multisession left many idle (see start_workers in r_scripts_collection.r) +OPTIONAL_WORKER_PACKAGES = ['future.mirai'] + + +def check_r_packages_installation(packages, optional=()): + """ + Install the R packages in packages that are missing, stopping if one can't be installed. + The packages in optional are installed too when missing, but a tool runs without them, so + if they can't be installed (no internet, say) it only warns. + """ + initialize_r() + from rpy2.robjects import StrVector + from rpy2.robjects.packages import importr, isinstalled + + print("Checking R packages....") + cran_names_to_install = [ + pkg for pkg in packages + if not isinstalled(pkg) + ] + optional_missing = [pkg for pkg in optional if not isinstalled(pkg)] + + if not cran_names_to_install: + if optional_missing: + _install_optional_r_packages(optional_missing) + print("Checking R packages....Done") + return + + utils = importr('utils') + + utils.chooseCRANmirror(ind=12) # select the 12th mirror in the list: Canada + + # The environment only provides R itself, so install into that R's own library + # (not a user library) to keep the packages inside the conda/pixi environment. + r_lib = str(r('normalizePath(file.path(R.home(), "library"), winslash = "/")')[0]) + print(f"Installing missing R packages into {r_lib}: {', '.join(cran_names_to_install)}") + + need_fasterRaster = False + if 'fasterRaster' in cran_names_to_install: + cran_names_to_install.remove('fasterRaster') + need_fasterRaster = True + if cran_names_to_install: + utils.install_packages(StrVector(cran_names_to_install), lib=r_lib) + + if need_fasterRaster: + devtools=importr('devtools') + devtools.install_github("adamlilith/fasterRaster", dependencies=True, lib=r_lib) + + still_missing = [pkg for pkg in packages if not isinstalled(pkg)] + if still_missing: + raise RuntimeError( + f"R packages could not be installed into {r_lib}: {', '.join(still_missing)}" + ) + if optional_missing: + _install_optional_r_packages(optional_missing) + + print("Checking R packages....Done") + + +def _install_optional_r_packages(packages): + """Install optional R packages into the environment's R library, only warning on failure.""" + from rpy2.robjects import StrVector + from rpy2.robjects.packages import importr, isinstalled + + r_lib = str(r('normalizePath(file.path(R.home(), "library"), winslash = "/")')[0]) + print(f"Installing optional R packages into {r_lib}: {', '.join(packages)}") + try: + utils = importr('utils') + utils.chooseCRANmirror(ind=12) + utils.install_packages(StrVector(packages), lib=r_lib) + except Exception as e: + print(f"Warning! Could not install {', '.join(packages)} ({e}); the tool runs without it.") + return + missing = [pkg for pkg in packages if not isinstalled(pkg)] + if missing: + print(f"Warning! Could not install {', '.join(missing)}; the tool runs without it.") + + +def bool2Rbool(value): + initialize_r() + from rpy2.robjects import BoolVector + if isinstance(value, bool): + return BoolVector([bool(value)]) + if isinstance(value, str): + v = value.strip().lower() + if v == "true": + return BoolVector([True]) + if v == "false": + return BoolVector([False]) + raise ValueError( + f"Cannot convert {value!r} ({type(value).__name__}) to R logical" + ) + +def float2Rfloat(value): + initialize_r() + from rpy2.robjects import FloatVector + if isinstance(value, (float, int)): + return FloatVector([float(value)]) + + if isinstance(value, str): + return FloatVector([float(value)]) + + raise ValueError( + f"Cannot convert {value!r} ({type(value).__name__}) to R numeric" + ) +def int2Rint(value): + initialize_r() + from rpy2.robjects import IntVector + if isinstance(value, int): + return IntVector([value]) + + if isinstance(value, str): + return IntVector([int(value)]) + + raise ValueError( + f"Cannot convert {value!r} ({type(value).__name__}) to R integer" + ) \ No newline at end of file diff --git a/beratools/modules/pc2products/r_interface.py b/beratools/modules/pc2products/r_interface.py new file mode 100644 index 0000000..e92dc2e --- /dev/null +++ b/beratools/modules/pc2products/r_interface.py @@ -0,0 +1,188 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Author: Maverick Fong + +Description: + This script is helper tools for execute the R scripts. + + Webpage: https://github.com/BERATool/beratools + +""" + +import os +import shutil +import subprocess +import sys +from pathlib import Path + +# One OpenBLAS (and OpenMP) thread, set before R or numpy loads OpenBLAS and passed on to the R +# workers. With one per CPU core, each process reserves a buffer per thread that it never uses +# (~6 GB per process on a 20-core machine), which counts against Windows' memory commit and the +# tools' memory limit (see r_common.limit_memory). The LiDAR tools don't use threaded linear algebra. +os.environ.setdefault("OPENBLAS_NUM_THREADS", "1") +os.environ.setdefault("OMP_NUM_THREADS", "1") + + +def configure_r_environment(): + """Locate and configure R before importing rpy2.""" + # -------------------------------------------------- + # 1. Existing R_HOME + # -------------------------------------------------- + r_home = os.environ.get("R_HOME") + + if r_home: + r_bin = Path(r_home) / "bin" + + if (r_bin / "R.exe").exists() or (r_bin / "R").exists(): + return str(r_home) + + # -------------------------------------------------- + # 2. R on PATH + # -------------------------------------------------- + r_exe = shutil.which("Rscript") or shutil.which("R") + + if r_exe: + try: + # Ask R for its home: on Linux/conda, bin/R is a wrapper script and + # the real R_HOME is /lib/R, not the parent of bin/ + r_home = subprocess.check_output( + [r_exe, "RHOME"], + stderr=subprocess.DEVNULL, + text=True, + ).strip() + + if r_home: + os.environ["R_HOME"] = r_home + return r_home + + except Exception: + pass + + # -------------------------------------------------- + # 3. Conda / Pixi installed R + # -------------------------------------------------- + python_exe = Path(sys.executable) + candidates = [ + # Windows conda/pixi + python_exe.parent / "Lib" / "R", + # Linux/macOS conda/pixi + python_exe.parent.parent / "lib" / "R", + # Alternate pixi layouts + Path(sys.prefix) / "lib" / "R", + Path(sys.prefix) / "Lib" / "R", + ] + for candidate in candidates: + if ( + (candidate / "bin" / "R.exe").exists() + or + (candidate / "bin" / "R").exists() + ): + os.environ["R_HOME"] = str(candidate) + return str(candidate) + + # -------------------------------------------------- + # 4. Standard Windows install + # -------------------------------------------------- + r_root = Path(r"C:\Program Files\R") + + if r_root.exists(): + versions = sorted(r_root.glob("R-*"), reverse=True) + + for version in versions: + if (version / "bin" / "R.exe").exists(): + os.environ["R_HOME"] = str(version) + return str(version) + # -------------------------------------------------- + # 5. Diagnostics + # -------------------------------------------------- + print("sys.executable =", sys.executable) + print("sys.prefix =", sys.prefix) + print("R_HOME =", os.environ.get("R_HOME")) + print("which R =", shutil.which("R")) + print("which Rscript =", shutil.which("Rscript")) + + raise RuntimeError( + "\n" + "R installation not found.\n\n" + "Install R from:\n" + "https://cran.r-project.org/\n\n" + "Or install in conda:\n" + "conda install -c conda-forge r-base rpy2\n" + ) + + +def isolate_env_r_library(r_home): + """ + Keep the environment's R from using the user's personal R library. + + R adds the personal library (R_LIBS_USER, e.g. %LOCALAPPDATA%/R/win-library/4.5 on + Windows) ahead of its own library. For an R installed in the conda/pixi environment, + that would load packages installed for a separate R and stop the tools from installing + into the environment. A non-existent R_LIBS_USER is dropped from .libPaths(), leaving + only the environment's library. A standalone R (outside the environment) is left alone. + """ + try: + in_env = Path(r_home).resolve().is_relative_to(Path(sys.prefix).resolve()) + except OSError: + in_env = False + + if in_env: + os.environ["R_LIBS_USER"] = "NULL" + os.environ.pop("R_LIBS", None) + + return in_env + + +# ------------------------------------------------------ +# Configure R BEFORE importing rpy2 +# ------------------------------------------------------ +R_HOME = configure_r_environment() +R_IN_ENV = isolate_env_r_library(R_HOME) +env_root = Path(sys.executable).parent + +conda_r = env_root / "Scripts" / "R.exe" +print("=" * 60) +print("R CONFIGURATION") +print("=" * 60) +print(f"R_HOME : {os.environ.get('R_HOME')}") +print(f"Conda R.exe : {conda_r}") +print(f"Exists : {conda_r.exists()}") +print(f"R library : {'environment only' if R_IN_ENV else 'R defaults (R is outside the environment)'}") +print("=" * 60) + + +extra_dirs = [ + env_root / "Library" / "bin", + env_root / "Library" / "mingw-w64" / "bin", + env_root / "Library" / "usr" / "bin", + env_root / "Scripts", + Path(R_HOME) / "bin", + Path(R_HOME) / "bin" / "x64", +] + +for d in extra_dirs: + if d.exists(): + try: + os.add_dll_directory(str(d)) + except Exception: + pass + + os.environ["PATH"] = ( + str(d) + + os.pathsep + + os.environ.get("PATH", "") + ) + +# R runs commands through cmd.exe, which runs conda's AutoRun hook (from "conda init") when the +# process was not started from an activated conda shell. The hook calls DOSKEY from System32 and +# prints "'DOSKEY' is not recognized" when System32 is not on PATH, as in some GUI launches. +if os.name == "nt": + system32 = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32") + if not any(p.rstrip("\\").lower() == system32.lower() for p in os.environ["PATH"].split(os.pathsep)): + os.environ["PATH"] += os.pathsep + system32 + +os.environ["RPY2_CFFI_MODE"] = "ABI" \ No newline at end of file diff --git a/beratools/modules/pc2products/r_scripts_collection.r b/beratools/modules/pc2products/r_scripts_collection.r new file mode 100644 index 0000000..2de9e14 --- /dev/null +++ b/beratools/modules/pc2products/r_scripts_collection.r @@ -0,0 +1,2973 @@ +# lidR plots a map of the catalog's tiles at the start of every run with progress on, which the +# tools turn on for the "Chunk 3 of 7" lines the GUI reads, even when R isn't interactive. Under +# the GUI, R starts interactive and only then is set otherwise (see r_common.initialize_r), so its +# device stayed the screen: a window opened, kept repainting ("flashing") while R was busy and +# showed nothing the GUI uses. Non-interactive, plots now go to a null device; R left interactive +# (BERATOOLS_R_GRAPHICS=1) still draws the live map. +if (!interactive()) options(device = function(...) grDevices::pdf(NULL)) + +# lidR's readLAScatalog(in_las_folder, ...), saying so first: it opens every file to read its +# header, which for thousands of files on a slow or network drive takes minutes, and the tools +# printed nothing meanwhile. Every tool reads its catalog with this. +read_catalog <- function(in_las_folder, ...) { + n <- if (length(in_las_folder) == 1 && dir.exists(in_las_folder)) { + length(list.files(in_las_folder, pattern = "\\.la[sz]$", ignore.case = TRUE)) + } else length(in_las_folder) + print(paste0("Reading the headers of ", n, " LiDAR file(s)...")) + flush.console() + t0 <- Sys.time() + ctg <- lidR::readLAScatalog(in_las_folder, ...) + secs <- as.numeric(Sys.time() - t0, units = "secs") + if (secs >= 10) print(paste0("Read the headers in ", round(secs), " s.")) + ctg +} + +############################################################# +# Only the files' headers and the first file are read, so no R workers are started +las_info <- function(in_las_folder) +{ + library(lidR) + library(sf) + library(units) + + print("Loading LiDAR data...") + cat(sprintf("R_PROGRESS:%d\n",round(0.20 * 100))) + flush.console() + ctg <- read_catalog( + in_las_folder, + filter = "-drop_class 7" + ) + + print( + paste0( + "Data format: v", + ctg@data$Version.Major[1], + ".", + ctg@data$Version.Minor[1] + ) + ) + + # CRS information + crs_info <- sf::st_crs(ctg) + + if (is.null(crs_info) || is.na(crs_info$wkt)) + { + print("CRS: Unknown") + } + else + { + if (!is.na(crs_info$epsg)) + { + print(paste0("EPSG: ", crs_info$epsg)) + } + + if (!is.null(crs_info$Name)) + { + print(paste0("CRS: ", crs_info$Name)) + } + + if (!is.null(crs_info$ud_unit)) + { + print( + paste0( + "Units: ", + units::deparse_unit(crs_info$ud_unit) + ) + ) + } + } + + print( + paste0( + "Extent: ", + round(min(ctg@data$Min.X), 2), " ", + round(max(ctg@data$Max.X), 2), " ", + round(min(ctg@data$Min.Y), 2), " ", + round(max(ctg@data$Max.Y), 2) + ) + ) + + area_m2 <- as.numeric(st_area(ctg)) + + print( + paste0( + "Area: ", + round(area_m2 / 1000000, 2), + " km²" + ) + ) + + total_pts <- sum(ctg@data$Number.of.point.records) + + print( + paste0( + "Total Points: ", + format(total_pts, big.mark = ",") + ) + ) + + print( + paste0( + "Density: ", + round(total_pts / area_m2, 2), + " pts/m²" + ) + ) + + print( + paste0( + "Total Files: ", + length(ctg@data$filename) + ) + ) + cat(sprintf("R_PROGRESS:%d\n",round(0.50 * 100))) + flush.console() + # Normalization check + las <- readLAS(list.files(in_las_folder,pattern="\\.la(s|z)$",full.names=TRUE)[1]) + + ground <- filter_poi( + las, + Classification == 2 + ) + + if (!is.empty(ground)) + { + mean_ground_z <- mean(abs(ground$Z), na.rm = TRUE) + + print( + paste0( + "Normalized: ", + ifelse(mean_ground_z < 1, "YES", "NO") + ) + ) + + print( + paste0( + "Ground Z Range: ", + round(min(ground$Z), 2), + " to ", + round(max(ground$Z), 2) + ) + ) + } + else + { + print( + "Normalized: Unknown (no class 2 ground points found)" + ) + } + + print( + paste0( + "Z Range: ", + round(min(las$Z), 2), + " to ", + round(max(las$Z), 2) + ) + ) + cat(sprintf("R_PROGRESS:%d\n",round(1.0 * 100))) + flush.console() +} +######################################################################################### +# tiling: see apply_tiling +dtm_by_tin <- function(in_las_folder, out_folder, cell_size, rprocesses, free_mem, tiling = "auto", skip_existing = FALSE) { + + library(lidR) + library(terra) + library(future) + library(tools) + + if (cell_size < 1.0) { rprocesses =max(1, floor(rprocesses / 2)) } + on.exit(reset_plan(), add = TRUE) + + ctg <- read_catalog(in_las_folder, filter = '-drop_class 7') + print("Generate DTM...") + cat(sprintf("R_PROGRESS:%d\n",round(0.20 * 100))) + flush.console() + ctg <- apply_tiling(ctg, tiling, rprocesses, free_mem, paste0(out_folder, "/{*}_TIN_DTM"), skip_existing = skip_existing, + bytes_per_point = function(ctg) tin_bytes_per_point(ctg, ground_only = TRUE)) + ctg <- select_tiles(ctg, skip_existing, function(save) paste0(save, ".tif"), res = cell_size) + since <- Sys.time() - 1 + ctg@output_options$ + drivers$ + SpatRaster$ + param$ + overwrite <- TRUE + ctg@output_options$drivers$Raster$param$overwrite <- TRUE + opt_progress(ctg) <- TRUE + dtm <- catalog_run(ctg, function(ctg) rasterize_terrain_tiles(ctg, cell_size, tin())) + cat(sprintf("R_PROGRESS:%d\n",round(0.80 * 100))) + flush.console() + mosaic_catalog_outputs(ctg,out_folder,"_TIN_DTM.tif","Merged_TIN_DTM.tif",since) + cat(sprintf("R_PROGRESS:%d\n",round(0.99 * 100))) + flush.console() + # reset R multisession back to default + plan(sequential) +} + +######################################################################################### +# tiling: see apply_tiling +dtm_by_knnidw <- function(in_las_folder, out_folder, cell_size, rprocesses, free_mem, tiling = "auto", skip_existing = FALSE) { + + library(lidR) + library(terra) + library(future) + library(tools) + + on.exit(reset_plan(), add = TRUE) + + ctg <- read_catalog(in_las_folder, filter = '-drop_class 7') + cat(sprintf("R_PROGRESS:%d\n",round(0.20 * 100))) + flush.console() + print("Generate DTM...") + ctg <- apply_tiling(ctg, tiling, rprocesses, free_mem, paste0(out_folder, "/{*}_IDW_DTM"), skip_existing = skip_existing, + bytes_per_point = BYTES_PER_POINT_IDW_DTM) + ctg <- select_tiles(ctg, skip_existing, function(save) paste0(save, ".tif"), res = cell_size) + since <- Sys.time() - 1 + ctg@output_options$ + drivers$ + SpatRaster$ + param$ + overwrite <- TRUE + ctg@output_options$drivers$Raster$param$overwrite <- TRUE + opt_progress(ctg) <- TRUE + dtm <- catalog_run(ctg, function(ctg) rasterize_terrain_tiles(ctg, cell_size, knnidw())) + cat(sprintf("R_PROGRESS:%d\n",round(0.80 * 100))) + flush.console() + mosaic_catalog_outputs(ctg,out_folder,"_IDW_DTM.tif","Merged_IDW_DTM.tif",since) + cat(sprintf("R_PROGRESS:%d\n",round(0.99 * 100))) + flush.console() + # reset R multisession back to default + plan(sequential) +} + +######################################################################################### +# tiling: see apply_tiling +dtm_by_kriging <- function(in_las_folder, out_folder, cell_size, rprocesses, free_mem, tiling = "auto", skip_existing = FALSE) { + + library(lidR) + library(terra) + library(future) + library(tools) + if (cell_size < 1.0) { rprocesses = max(1, floor(rprocesses / 2)) } + on.exit(reset_plan(), add = TRUE) + + ctg <- read_catalog(in_las_folder, filter = '-drop_class 7') + cat(sprintf("R_PROGRESS:%d\n",round(0.20 * 100))) + flush.console() + print("Generate DTM...") + ctg <- apply_tiling(ctg, tiling, rprocesses, free_mem, paste0(out_folder, "/{*}_K_DTM"), skip_existing = skip_existing) + ctg <- select_tiles(ctg, skip_existing, function(save) paste0(save, ".tif"), res = cell_size) + since <- Sys.time() - 1 + ctg@output_options$ + drivers$ + SpatRaster$ + param$ + overwrite <- TRUE + ctg@output_options$drivers$Raster$param$overwrite <- TRUE + opt_progress(ctg) <- TRUE + dtm <- catalog_run(ctg, function(ctg) rasterize_terrain_tiles(ctg, cell_size, kriging())) + cat(sprintf("R_PROGRESS:%d\n",round(0.80 * 100))) + flush.console() + mosaic_catalog_outputs(ctg,out_folder,"_K_DTM.tif","Merged_K_DTM.tif",since) + print("Generate DTM...Done") + cat(sprintf("R_PROGRESS:%d\n",round(0.99 * 100))) + flush.console() + # reset R multisession back to default + plan(sequential) + + +} + +######################################################################################### +# Build the .lax spatial index of every LAS/LAZ file in the folder that has none (all of them with +# overwrite), with up to max_workers R processes; see ensure_lax. The other LiDAR tools build +# missing indexes themselves, so this only does it ahead of time. Returns the number of indexes. +lidar_index <- function(in_las_folder, max_workers, overwrite = FALSE) +{ + files <- list.files(in_las_folder, pattern = "\\.la[sz]$", full.names = TRUE, ignore.case = TRUE) + lax <- paste0(tools::file_path_sans_ext(files), ".lax") + print(paste0("Found ", length(files), " LiDAR file(s), ", sum(file.exists(lax)), " with a spatial index.")) + cat(sprintf("R_PROGRESS:%d\n", 10)) + flush.console() + if (overwrite && any(file.exists(lax))) { + print(paste0("Removing ", sum(file.exists(lax)), " existing spatial index(es) to rebuild them...")) + file.remove(lax[file.exists(lax)]) + } + t0 <- Sys.time() + ok <- ensure_lax(files, max_workers) + n <- sum(file.exists(lax)) + print(paste0(n, " of ", length(files), " file(s) have a spatial index (", + round(as.numeric(Sys.time() - t0, units = "secs"), 1), " s).")) + if (!ok || n < length(files)) { + print("Warning! Some spatial indexes could not be built; check that the folder is writable.") + } + cat(sprintf("R_PROGRESS:%d\n", 99)) + flush.console() + invisible(n) +} + +######################################################################################### +# Split the LiDAR files of a folder into tiles, written to out_folder as _.laz (or .las), named +# by their lower-left corner, with the plan of tile sizes in tiles.csv (see apply_tiling). Tiles are +# sized as the processing tools size them, so that a tool processing them by file later, with a +# buffer of `buffer` m read from the neighbouring tiles, fits in the free memory: by the data's +# density from 500 m down to 100 m, or tile_size m when it is above 0. The points are copied as +# they are, noise included, and streamed from file to file, so a worker needs little memory and up +# to max_workers are used. The tiles' .lax spatial indexes are built at the end. +lidar_tile <- function(in_las_folder, out_folder, buffer, tile_size, laz, max_workers, free_mem, + skip_existing = FALSE) { + library(lidR) + library(future) + + on.exit(reset_plan(), add = TRUE) + if (normalizePath(in_las_folder, mustWork = FALSE) == normalizePath(out_folder, mustWork = FALSE)) { + stop("The output folder must differ from the input folder, or the tiles would be read as input next time.") + } + ctg <- read_catalog(in_las_folder) + cat(sprintf("R_PROGRESS:%d\n", 10)) + flush.console() + ctg <- apply_tiling(ctg, "tiling", max_workers, free_mem, paste0(out_folder, "/{*}"), buffer = buffer, + skip_existing = skip_existing, tile_size = if (tile_size > 0) tile_size else NULL, + fit_warning = FALSE) + # Cutting streams the points, so a tile of any size can be cut; only a tool processing the + # tiles later needs each one to fit + if (isFALSE(ctg@chunk_options$fits)) { + print(paste0("Note: the densest tiles hold more points than a tool can process whole, with a ", + buffer, " m buffer, in the memory free now. Cutting them is not affected, but a tool ", + "processing these tiles later with 'auto' tiling will split them again.")) + } + # The tiles are cut without a buffer; it only sized them + opt_chunk_buffer(ctg) <- 0 + opt_laz_compression(ctg) <- isTRUE(laz) + ext <- if (isTRUE(laz)) ".laz" else ".las" + # Its workers are started below for streaming, so its tiles aren't split into rounds by memory + ctg@chunk_options$workers <- NULL + ctg <- select_tiles(ctg, skip_existing, function(save) paste0(save, ext)) + # Streaming needs about an R session of memory per worker, so more workers than the processing + # tools would have can cut the tiles, up to one per tile. Streaming uses no lidR threads, so + # each worker gets one (sized at 1.6 GB each, workers that got the other cores as threads + # committed more: 3 of 6 threads 8.4 GB, over their share of 11 GB free). + left <- sum(sapply(ctg@chunk_options$runs, `[[`, "n")) + workers <- max(1, min(max_workers, left)) + while (workers > 1 && workers * worker_fixed_bytes(workers, workers) > 0.6 * free_mem) workers <- workers - 1 + start_workers(workers, max_workers, threads = 1) + if (left > 0) print(paste0("Cutting ", left, " tile(s) with ", workers, " worker(s)...")) + opt_progress(ctg) <- TRUE + cat(sprintf("R_PROGRESS:%d\n", 20)) + flush.console() + catalog_run(ctg, function(ctg) catalog_retile(ctg)) + + cat(sprintf("R_PROGRESS:%d\n", 90)) + flush.console() + tiles <- list.files(out_folder, pattern = paste0("^-?[0-9.]+_-?[0-9.]+\\", ext, "$"), full.names = TRUE) + print(paste0(out_folder, " has ", length(tiles), " tile(s); building the spatial indexes they lack...")) + ensure_lax(tiles, max_workers) + cat(sprintf("R_PROGRESS:%d\n", 99)) + flush.console() + invisible(length(tiles)) +} + +######################################################################################### +pd2cellsize <- function(in_las_folder) +{ + library(lidR) + library(sf) + library(units) + + # Only the file headers are read, so no R workers are started + print( + "Calculate output's raster average cell size from point density..." + ) + cat(sprintf("R_PROGRESS:%d\n",round(0.20 * 100))) + flush.console() + if ( + lidR::is(in_las_folder, "LAS") || + lidR::is(in_las_folder, "LAScatalog") + ) + { + ctg <- in_las_folder + } + else + { + ctg <- read_catalog( + in_las_folder, + filter = "-drop_class 7" + ) + } + cat(sprintf("R_PROGRESS:%d\n",round(0.50 * 100))) + flush.console() + crs_info <- sf::st_crs(ctg) + + map_units <- "Unknown" + + if (!is.null(crs_info$ud_unit)) + { + map_units <- units::deparse_unit(crs_info$ud_unit) + } + + area_m2 <- as.numeric(sf::st_area(ctg)) + + point_density <-sum(ctg@data$Number.of.point.records) / area_m2 + + mean_pd <- sqrt(3 / point_density) + + cell_size <- round( + 0.05 * round(mean_pd / 0.05), + 2 + ) + + print( + paste0( + "Calculated cell size: ", + cell_size, + " ", + map_units + ) + ) + cat(sprintf("R_PROGRESS:%d\n",round(0.99 * 100))) + flush.console() + return( + list( + cell_size = cell_size, + map_units = map_units, + point_density = point_density + ) + ) +} + +######################################################################################### +# tiling: see apply_tiling +chm_dsm_by_tin <- function(in_las_folder, out_folder, cell_size, is_normalized, rprocesses, free_mem, tiling = "auto", skip_existing = FALSE) { + library(lidR) + library(terra) + library(future) + library(tools) + + on.exit(reset_plan(), add = TRUE) + + ctg <- read_catalog(in_las_folder, filter = '-drop_class 7') + cat(sprintf("R_PROGRESS:%d\n",round(0.20 * 100))) + flush.console() + if (is_normalized) { + print("Generating CHM using TIN...") + out_template <- paste0(out_folder, "/{*}_TIN_CHM") } + else { + print("Generating DSM using TIN...") + out_template <- paste0(out_folder, "/{*}_TIN_DSM") } + ctg <- apply_tiling(ctg, tiling, rprocesses, free_mem, out_template, skip_existing = skip_existing, + bytes_per_point = bytes_per_point_dsm_tin(ctg, cell_size)) + ctg <- select_tiles(ctg, skip_existing, function(save) paste0(save, ".tif"), res = cell_size) + since <- Sys.time() - 1 + + ctg@output_options$ + drivers$ + SpatRaster$ + param$ + overwrite <- TRUE + ctg@output_options$drivers$Raster$param$overwrite <- TRUE + opt_progress(ctg) <- TRUE + chm <- catalog_run(ctg, function(ctg) rasterize_canopy_tiles(ctg, cell_size, dsmtin(max_edge = (3 * cell_size)), pkg = "terra")) + cat(sprintf("R_PROGRESS:%d\n",round(0.80 * 100))) + flush.console() + if (is_normalized) { + mosaic_catalog_outputs(ctg,out_folder,"_TIN_CHM.tif","Merged_TIN_CHM.tif",since) + print("Generating CHM using TIN...Done")} + else { + mosaic_catalog_outputs(ctg,out_folder,"_TIN_DSM.tif","Merged_TIN_DSM.tif",since) + print("Generating DSM using TIN...Done")} + cat(sprintf("R_PROGRESS:%d\n",round(0.99 * 100))) + flush.console() + # reset R multisession back to default + plan(sequential) +} + +######################################################################################### +# tiling: see apply_tiling +chm_dsm_by_pitfree <- function(in_las_folder, out_folder, cell_size, is_normalized, rprocesses, free_mem, tiling = "auto", skip_existing = FALSE) { + + library(lidR) + library(terra) + library(future) + library(tools) + + on.exit(reset_plan(), add = TRUE) + + ctg <- read_catalog(in_las_folder, filter = '-drop_class 7 -drop_overlap') + cat(sprintf("R_PROGRESS:%d\n",round(0.2 * 100))) + flush.console() + if (is_normalized) { + print("Generate CHM using Pit-free...") + out_template <- paste0(out_folder, "/{*}_PitF_CHM") } + else { + print("Generate DSM using Pit-free...") + out_template <- paste0(out_folder, "/{*}_PitF_DSM") } + ctg <- apply_tiling(ctg, tiling, rprocesses, free_mem, out_template, skip_existing = skip_existing, + bytes_per_point = BYTES_PER_POINT_PITFREE) + ctg <- select_tiles(ctg, skip_existing, function(save) paste0(save, ".tif"), res = cell_size) + since <- Sys.time() - 1 + + ctg@output_options$ + drivers$ + SpatRaster$ + param$ + overwrite <- TRUE + ctg@output_options$drivers$Raster$param$overwrite <- TRUE + opt_progress(ctg) <- TRUE + chm <- catalog_run(ctg, function(ctg) rasterize_canopy_tiles(ctg, cell_size, pitfree(thresholds = c(0, 3, 5, 10, 15, 20), max_edge = c(0, 3 * cell_size), subcircle = (cell_size)))) + cat(sprintf("R_PROGRESS:%d\n",round(0.8 * 100))) + flush.console() + if (is_normalized) { + mosaic_catalog_outputs(ctg,out_folder,"_PitF_CHM.tif","Merged_PitF_CHM.tif",since) + print("Generate CHM using Pit-free...Done")} + else { + mosaic_catalog_outputs(ctg,out_folder,"_PitF_DSM.tif","Merged_PitF_DSM.tif",since) + print("Generate DSM using Pit-free...Done")} + cat(sprintf("R_PROGRESS:%d\n",round(0.99 * 100))) + flush.console() + # reset R multisession back to default + plan(sequential) + +} + +######################################################################################### +# Whether the LiDAR data is normalized: the ground points (class 2) of its first file have a mean +# |Z| under 1 m. It read the whole first file, every point of it (tens of seconds for a file of +# 20 million points); now only the ground points of a 100 m square at the file's centre, read +# through its .lax spatial index, or, with fewer than 100 there, every 100th ground point of the +# file. +detect_normalized <- function(in_las_folder) +{ library(lidR) + + f <- list.files(in_las_folder, pattern = "\\.la(s|z)$", full.names = TRUE)[1] + h <- rlas::read.lasheader(f) + cx <- (h[["Min X"]] + h[["Max X"]]) / 2 + cy <- (h[["Min Y"]] + h[["Max Y"]]) / 2 + read_ground <- function(filter) suppressWarnings(readLAS(f, select = "xyzc", filter = paste("-keep_class 2", filter))) + ground <- read_ground(sprintf("-inside %.3f %.3f %.3f %.3f", cx - 50, cy - 50, cx + 50, cy + 50)) + if (npoints(ground) < 100) ground <- read_ground("-keep_every_nth 100") + if (is.empty(ground)) return(FALSE) + mean(abs(ground$Z), na.rm = TRUE) < 1 +} +############################################################# +# Merge rasters of one grid into out_file: gdalbuildvrt lists them in a VRT, which takes seconds, +# and gdal_translate writes the merged file from it in one pass, compressed. terra::mosaic() wrote +# the whole merge to a temporary file and then copied it to out_file, on one core: 144 tiles of +# 2000 x 2000 cells took 155-237 s that way, 6-9 s with terra::writeRaster() from the VRT, which +# passes every cell through R, and 3-5 s with gdal_translate (12 and 14 min with mosaic() for 2392 +# hummock/hollow tiles of 0.1 m on another machine). Where rasters overlap, the first file's cells +# are kept, as mosaic(fun = "first") did: a VRT draws its later sources over the earlier, so they +# are listed in reverse. NA cells don't cover other rasters'. type is a GDAL data type for the +# merged file (as "Int16"), or NULL for the rasters' own; an integer type marks NA as its lowest +# value, as NaN, the float rasters' NA, has no integer value. +merge_rasters <- function(files, out_file, type = NULL) { + vrt_file <- tempfile(fileext = ".vrt") + on.exit(unlink(vrt_file)) + nodata <- if (!is.null(type) && grepl("Int", type)) { + c(Int8 = "-128", Int16 = "-32768", Int32 = "-2147483648", UInt16 = "65535", UInt32 = "4294967295")[[type]] + } + sf::gdal_utils("buildvrt", rev(normalizePath(files)), vrt_file, + options = if (is.null(nodata)) character(0) else c("-vrtnodata", nodata)) + gtiff <- c("COMPRESS=DEFLATE", "TILED=YES", "BIGTIFF=IF_SAFER", "NUM_THREADS=ALL_CPUS") + if (file.exists(out_file)) unlink(out_file) + sf::gdal_utils("translate", vrt_file, out_file, + options = c(if (!is.null(type)) c("-ot", type), as.vector(rbind("-co", gtiff))), + config_options = c(GDAL_CACHEMAX = "1024")) + invisible(out_file) +} + +# Merge the rasters a catalog run wrote into merged_name. Processed by file, they are named after +# the input files; split into chunks (see apply_tiling), they are named by lower-left corner, so +# the corner-named files written since `since` are merged, leaving out those of earlier runs. +mosaic_catalog_outputs <- function( + ctg, + out_folder, + suffix, + merged_name, + since = NULL +) +{ + if (opt_chunk_size(ctg) == 0) + { + files <- file.path( + out_folder, + paste0( + tools::file_path_sans_ext( + basename(ctg@data$filename) + ), + suffix + ) + ) + } + else + { + files <- list.files( + out_folder, + pattern = paste0("^-?[0-9.]+_-?[0-9.]+", gsub(".", "\\.", suffix, fixed = TRUE), "$"), + full.names = TRUE + ) + if (!is.null(since)) files <- files[file.mtime(files) >= since] + files <- union(files, ctg@chunk_options$kept_outputs) + } + + files <- files[file.exists(files)] + + print(files) + + if (length(files) > 1) + { + merge_rasters(files, file.path(out_folder, merged_name)) + + print( + paste0( + "Created merged raster: ", + merged_name + ) + ) + } +} +################################################################################################ +# A raster (one layer, e.g. a DTM) smoothed by the Smooth_by ("mean" or "median") of a circular +# window of radius map units; the hummock/hollow tool smooths its DTM with it, as +# beratools.modules.raster2products.algo_raster_smoothing.smooth_raster does in Python for the normalized DTM tool. +# Cells with no value are left out of the window, and so are cells beyond the raster's edges: near +# an edge the window holds only the real neighbours. Cells with no value stay without one. +# The window is the cells whose centres lie within radius of the centre cell: a true circle on +# cells that aren't square, which terra's focalMat "circle" isn't (it measures rows in steps of +# the cell width too). radius / cell size is rounded down, which lost a ring when the cell size is +# stored rounded (a 3 m window on 0.25 m cells of a DTM in feet came to 5.9999998 cells), so a +# millionth is added to the radius (RADIUS_SLACK in beratools.utility.spatial_common). +smooth_raster <- function(x, radius, Smooth_by) { + reach <- radius * (1 + 1e-6) + rx <- terra::res(x)[1] + ry <- terra::res(x)[2] + nx <- floor(reach / rx) + ny <- floor(reach / ry) + # rows are y, columns x; an odd number of each, the centre cell in the middle + dx <- matrix((-nx:nx) * rx, nrow = 2 * ny + 1, ncol = 2 * nx + 1, byrow = TRUE) + dy <- matrix((-ny:ny) * ry, nrow = 2 * ny + 1, ncol = 2 * nx + 1) + w <- ifelse(sqrt(dx^2 + dy^2) <= reach, 1, NA) + terra::focal(x, w = w, fun = Smooth_by, na.policy = "omit", na.rm = TRUE, fillvalue = NA, expand = FALSE) +} + +################################################################################################ +# tiling: see apply_tiling +hh_function <- function(in_las_folder,out_folder, cell_size, Smooth_by, Min_ws, lawn_range, rprocesses, free_mem, tiling = "auto", skip_existing = FALSE) { + + library(lidR) + library(terra) + library(sf) + library(future) + + on.exit(reset_plan(), add = TRUE) + + print('Generating Hummock/ Hollow Raster ...') + ctg <- read_catalog(in_las_folder, select = 'xyzc', filter = '-drop_class 7') + cat(sprintf("R_PROGRESS:%d\n",round(0.2 * 100))) + flush.console() + HH_raster <- function(chunk, radius, cell_size, lawn_range, Smooth_by) + { + if (inherits(chunk, "LAS")) { + las <- chunk + } else { + las <- readLAS(chunk)} + if (is.empty(las)) return(NULL) + + las_1 <- filter_poi(las, buffer == 0) + # A tile whose points don't span an area can't give a hull or a DTM (see spans_area) + ground <- las$Classification %in% c(2L, 9L) + if (!spans_area(las_1$X, las_1$Y) || !spans_area(las$X[ground], las$Y[ground])) { + warning("Left out ", chunk_files(chunk), ": its points don't span an ", + "area, so no hummock/hollow raster can be made there.", call. = FALSE) + return(NULL) + } + hull <- st_convex_hull(las_1) + + # convert to SpatialPolygons + bbox <- vect(hull) + + #las to DTM + dtm <- rasterize_terrain(las, res = cell_size, algorithm = tin()) + + sdtm <- smooth_raster(dtm, radius, Smooth_by) + ndtm <- (sdtm - dtm) + positive <- abs(lawn_range) + negative <- positive * -1 + + HH <- ifel(ndtm < negative, 1, ifel(ndtm > positive, -1, 0)) + + cont_hh <- (crop(ndtm, ext(bbox))) * -1 + hh <- crop(HH, ext(bbox)) + + return(list(cont_hh, hh, radius, Smooth_by)) + } + + MultiWrite = function(output_list, file) { + chh = output_list[[1]] + hh = output_list[[2]] + radius = output_list[[3]] + Smooth_by = output_list[[4]] + base_name <- basename(file) + path1 <- file.path(dirname(file),paste0("CHH_", base_name, ".tif")) + path2 <- file.path(dirname(file),paste0("HH_", base_name, ".tif")) + # Each file is written under a .partial name and renamed when complete (see write_whole; + # this runs in the R workers, which don't have the functions of this script) + for (out in list(list(chh, path1), list(hh, path2))) { + part <- sub("\\.tif$", ".partial.tif", out[[2]]) + terra::writeRaster(out[[1]], part, overwrite = TRUE) + if (file.exists(out[[2]])) unlink(out[[2]]) + if (!file.rename(part, out[[2]])) stop("Could not rename ", part, call. = FALSE) + } + } + + MultiWriteDriver = list( + write = MultiWrite, + extension = "", + object = "output_list", + path = "file", + param = list()) + + ctg@output_options$drivers$list <- MultiWriteDriver + + opt_chunk_alignment(ctg) <- c(0, 0) + ctg <- apply_tiling(ctg, tiling, rprocesses, free_mem, paste0(out_folder, "/{*}_", Smooth_by, "_", Min_ws, "m"), + skip_existing = skip_existing, + bytes_per_point = function(ctg) tin_bytes_per_point(ctg)) + ctg <- select_tiles(ctg, skip_existing, function(save) + file.path(dirname(save), paste0(c("CHH_", "HH_"), basename(save), ".tif"))) + ctg@output_options$ + drivers$ + SpatRaster$ + param$ + overwrite <- TRUE + opt_stop_early(ctg) <- TRUE + cat(sprintf("R_PROGRESS:%d\n",round(0.8 * 100))) + flush.console() + # Min_ws is the diameter of the circular moving window; smooth_raster() takes its radius + since <- Sys.time() - 1 + out <- catalog_run(ctg, function(ctg) catalog_apply(ctg, HH_raster, radius = Min_ws / 2, cell_size = cell_size, lawn_range = lawn_range, Smooth_by = Smooth_by)) + # Merge only this run's tiles, as an earlier run with another tiling leaves differently named ones + chh_files <- list.files( + out_folder, + pattern = "^CHH_.*\\.tif$", + full.names = TRUE + ) + chh_files <- chh_files[file.mtime(chh_files) >= since] + # and the tiles a resumed run skipped + kept <- ctg@chunk_options$kept_outputs + chh_files <- union(chh_files, kept[startsWith(basename(kept), "CHH_")]) + + hh_files <- list.files( + out_folder, + pattern = "^HH_.*\\.tif$", + full.names = TRUE + ) + hh_files <- hh_files[file.mtime(hh_files) >= since] + hh_files <- union(hh_files, kept[startsWith(basename(kept), "HH_")]) + + print("Merging the tiles...") + merge_rasters(chh_files, file.path(out_folder, paste0("Merged_CHH_", Smooth_by, "_", Min_ws, "m.tif"))) + # HH is -1, 0 or 1: Int16 is half the size of the tiles' float, and every GIS reads it + merge_rasters(hh_files, file.path(out_folder, paste0("Merged_HH_", Smooth_by, "_", Min_ws, "m.tif")), type = "Int16") + cat(sprintf("R_PROGRESS:%d\n",round(0.99 * 100))) + flush.console() + # reset R multisession back to default + print('Generating Hummock/ Hollow Raster ...Done') + plan(sequential) + +} + +########################################################################### + +# Cells of a LAStools .lax spatial index as a data frame of xmin, ymin, w, h and pts. The index +# is a quadtree whose cells were merged until each holds enough points, and it stores each +# cell's point count, so no points are read. File layout (LAStools lasindex.cpp, lasquadtree.cpp, +# lasinterval.cpp): "LASX" version, "LASS" type, "LASQ" version levels level_index +# implicit_levels min_x max_x min_y max_y (F32), "LASV" version number_cells, then per cell: +# cell_index number_intervals number_points, followed by number_intervals start/end pairs. +read_lax_cells <- function(lax_file) { + con <- rawConnection(readBin(lax_file, "raw", file.size(lax_file))) + on.exit(close(con)) + u32 <- function(n = 1) readBin(con, "integer", n, size = 4, endian = "little") + f32 <- function(n = 1) readBin(con, "numeric", n, size = 4, endian = "little") + sig <- function(s) { + if (rawToChar(readBin(con, "raw", 4)) != s) stop("Not a LAStools spatial index: ", lax_file) + } + sig("LASX"); u32() + sig("LASS"); u32() + sig("LASQ"); u32(4) + bb <- f32(4) + sig("LASV"); u32() + n_cells <- u32() + idx <- pts <- numeric(n_cells) + for (k in seq_len(n_cells)) { + v <- u32(3) + idx[k] <- v[1] + pts[k] <- v[3] + u32(2 * v[2]) # skip the cell's point intervals + } + + # A cell index is the first index of its level plus its index within the level, whose base-4 + # digits pick the child at each level from the root: bit 1 the upper x half, bit 2 the upper y + level_offset <- cumsum(c(0, 4^(0:22))) + lvl <- findInterval(idx, level_offset) - 1 + li <- idx - level_offset[lvl + 1] + x0 <- rep(bb[1], n_cells) + y0 <- rep(bb[3], n_cells) + w <- rep(bb[2] - bb[1], n_cells) + h <- rep(bb[4] - bb[3], n_cells) + for (l in seq_len(max(lvl, 0))) { + on <- lvl >= l + digit <- (li[on] %/% 4^(lvl[on] - l)) %% 4 + w[on] <- w[on] / 2 + h[on] <- h[on] / 2 + x0[on] <- x0[on] + (digit %% 2) * w[on] + y0[on] <- y0[on] + (digit %/% 2) * h[on] + } + data.frame(xmin = x0, ymin = y0, w = w, h = h, pts = pts) +} + +# Cells of the .lax spatial index of the LiDAR file f (see read_lax_cells). An index that can't be +# read is built again: on one machine a single file's .lax was not a LAStools index, and as one +# file's error stopped the density grid of all 2392 files, the run sized its tiles by each file's +# average density, with most files "too large" and rounds of down to 7 workers. If building fails +# too, the file is one cell of its header's extent and point count, as if its points were spread +# evenly over it. +lax_cells <- function(f) { + lax <- paste0(tools::file_path_sans_ext(f), ".lax") + tryCatch(read_lax_cells(lax), error = function(e) { + print(paste0("Warning! Could not read the spatial index of ", basename(f), " (", + conditionMessage(e), "); building it again...")) + unlink(lax) + tryCatch({ + rlas::writelax(f) + read_lax_cells(lax) + }, error = function(e) { + print(paste0("Warning! Could not build the spatial index of ", basename(f), " (", + conditionMessage(e), "); its points are taken to be spread evenly over it.")) + h <- rlas::read.lasheader(f) + data.frame(xmin = h[["Min X"]], ymin = h[["Min Y"]], w = h[["Max X"]] - h[["Min X"]], + h = h[["Max Y"]] - h[["Min Y"]], pts = as.numeric(h[["Number of point records"]])) + }) + }) +} + +# Build a .lax spatial index next to each file that has none, at the cost of reading the file +# once. LASlib then reads only the indexed area for a tile's buffer from a neighbouring file, or a +# chunk of a large file, instead of the whole file: measured ~30% faster reading on a folder of +# tiles and 6-12x on 200 m chunks of a 20 GB file. Memory use is unchanged. Returns FALSE after a +# warning if an index could not be written (e.g. a read-only folder); reading then still works. +# Building decompresses every point of a LAZ file at ~2.3 million points/s on one core (~80 min +# for 11.5 billion points), so several files are indexed at once, one per R process: 8 processes +# built the indexes of 16 cached LAZ files 4.7x faster than one, using 1.4 GB. The count is not +# cut to what a single read of the disk suggests it can feed: on one hard disk 6 processes so +# chosen took 28 min for 118 GB of LAZ and 19 took 24 min, as more reads queued at once read it +# faster. It is at most 8, max_workers, the CPU cores less one, and one per ~200 MB of files, as +# a process takes a second or two to start. +ensure_lax <- function(files, max_workers = 8) { + missing <- files[!file.exists(paste0(tools::file_path_sans_ext(files), ".lax"))] + if (length(missing) == 0) return(invisible(TRUE)) + workers <- min(8, max_workers, max(1, parallel::detectCores() - 1), length(missing), + max(1, floor(sum(file.size(missing)) / 200e6))) + print(paste0("Building the spatial index (.lax) of ", length(missing), " of ", length(files), + " file(s) that have none, with ", workers, " process(es)...")) + cl <- NULL + ok <- tryCatch({ + if (workers == 1) { + for (f in missing) rlas::writelax(f) + } else { + cl <- parallel::makePSOCKcluster(workers) + # largest first, so a big file doesn't start last and keep the others waiting + missing <- missing[order(-file.size(missing))] + parallel::parLapplyLB(cl, missing, function(f) rlas::writelax(f)) + } + TRUE + }, error = function(e) { + print(paste0("Warning! Could not build a spatial index (", conditionMessage(e), + "); reading the LiDAR data without it is slower.")) + FALSE + }, finally = if (!is.null(cl)) parallel::stopCluster(cl)) + invisible(ok) +} + +# Point counts on a grid of `cell` m covering the given files, from their .lax spatial indexes +# (built if missing). A count from an index cell larger than a grid cell is spread evenly over the +# grid cells it covers. Returned as a 2D cumulative sum, padded with a leading row and column of +# zeros, for window_max(). +point_count_grid <- function(files, cell) { + ensure_lax(files) + cells <- do.call(rbind, lapply(files, lax_cells)) + + # Split each index cell into sub-squares no larger than a grid cell + mx <- pmax(1, ceiling(cells$w / cell)) + my <- pmax(1, ceiling(cells$h / cell)) + k <- rep(seq_len(nrow(cells)), mx * my) + sub <- sequence(mx * my) - 1 + x <- cells$xmin[k] + (sub %% mx[k] + 0.5) * cells$w[k] / mx[k] + y <- cells$ymin[k] + (sub %/% mx[k] + 0.5) * cells$h[k] / my[k] + n <- cells$pts[k] / (mx[k] * my[k]) + + xmin <- floor(min(cells$xmin) / cell) * cell + ymin <- floor(min(cells$ymin) / cell) * cell + nc <- ceiling((max(cells$xmin + cells$w) - xmin) / cell) + 1 + nr <- ceiling((max(cells$ymin + cells$h) - ymin) / cell) + 1 + pos <- floor((x - xmin) / cell) * nr + floor((y - ymin) / cell) + 1 + counts <- matrix(0, nr, nc) + agg <- rowsum(n, pos) + counts[as.integer(rownames(agg))] <- agg[, 1] + + s <- matrix(0, nr + 1, nc + 1) + s[-1, -1] <- counts + for (i in seq_len(nr) + 1) s[i, ] <- s[i, ] + s[i - 1, ] + for (j in seq_len(nc) + 1) s[, j] <- s[, j] + s[, j - 1] + # rows are y and columns x, from the corner xmin, ymin + attr(s, "xmin") <- xmin + attr(s, "ymin") <- ymin + attr(s, "cell") <- cell + s +} + +# Tile sizes (m) of a tiled run, largest first. Each divides the 500 m blocks the data is split +# into, so each block can have its own size: the largest whose densest tile fits in memory. +TILE_SIZES <- c(500, 250, 125, 100) +TILE_BLOCK <- 500 + +# The tiles of `size` m (aligned at 0, 0) over point_count_grid()'s grid g, as a data frame of +# their corner x and y, their block's corner bx and by, the points they read with their buffer +# (pts) and the points in the tile itself (own). Points are taken as spread evenly within a grid +# cell, so a cell the area covers in part counts in part: counting whole cells made a 100 m tile +# with a 20 m buffer (140 m) count as up to 200 m, twice its area. +tile_points <- function(g, size, buffer) { + cell <- attr(g, "cell") + x0 <- attr(g, "xmin") + y0 <- attr(g, "ymin") + nr <- nrow(g) - 1 + nc <- ncol(g) - 1 + t <- expand.grid(x = seq(floor(x0 / size) * size, x0 + nc * cell, by = size), + y = seq(floor(y0 / size) * size, y0 + nr * cell, by = size)) + count <- function(margin) grid_rect_points(g, t$x - margin, t$y - margin, t$x + size + margin, t$y + size + margin) + t$pts <- count(buffer) + t$own <- count(0) + t$bx <- floor(t$x / TILE_BLOCK) * TILE_BLOCK + t$by <- floor(t$y / TILE_BLOCK) * TILE_BLOCK + t +} + +# Points in the rectangles x1, y1, x2, y2 from point_count_grid()'s grid g (see tile_points) +grid_rect_points <- function(g, x1, y1, x2, y2) { + cell <- attr(g, "cell") + x0 <- attr(g, "xmin") + y0 <- attr(g, "ymin") + nr <- nrow(g) - 1 + nc <- ncol(g) - 1 + # Points below and left of x, y: the cumulative grid interpolated between cell corners + below <- function(x, y) { + u <- pmin(nc, pmax(0, (x - x0) / cell)) + v <- pmin(nr, pmax(0, (y - y0) / cell)) + j <- pmin(floor(u), nc - 1) + i <- pmin(floor(v), nr - 1) + fu <- u - j + fv <- v - i + (1 - fv) * ((1 - fu) * g[cbind(i + 1, j + 1)] + fu * g[cbind(i + 1, j + 2)]) + + fv * ((1 - fu) * g[cbind(i + 2, j + 1)] + fu * g[cbind(i + 2, j + 2)]) + } + below(x2, y2) - below(x1, y2) - below(x2, y1) + below(x1, y1) +} + +# Largest point count in any k x k window of cells, from point_count_grid()'s cumulative sum. +# Every chunk position is covered, so this bounds the densest chunk whatever its alignment. +window_max <- function(s, k) { + a <- min(k, nrow(s) - 1) + b <- min(k, ncol(s) - 1) + i <- seq_len(nrow(s) - a) + j <- seq_len(ncol(s) - b) + max(s[i + a, j + b] - s[i, j + b] - s[i + a, j] + s[i, j]) +} + +# Memory of one worker, measured with CSF on 240 m and 140 m windows of a 622 points/m2 file: +# ~200 bytes per point read, classified and written, plus ~1.3 GB fixed (an R worker with lidR +# loaded, ~0.7 GB, and ~0.6 GB per tile). A 200 m tile of a denser area (34.9 million points with +# its buffer, CSF with a 1.5 m cloth) then ran out of a 9.2 GB limit and fit in 11 GB, ~230-290 +# bytes per point, so 260 is used. 60% of the free memory is shared between the workers. +# Each tool passes its own figure to apply_tiling. The ones below were measured as the peak +# private (committed) memory, which the tool's memory limit counts, of each tool's function run on +# 150 m and 250 m windows (13.9 and 35.7 million points, 572-620 points/m2, all first returns, 50% +# ground) of the same data, the difference between the two giving the bytes per point. CSF +# (224 bytes per point there), IDW normalization (226) and kriging (not measured) use this default. +BYTES_PER_POINT <- 260 +# The tools that triangulate the ground points (TIN DTM, TIN normalization, hummock/hollow) need +# more, and more with more ground: a TIN DTM of a 560 m window with 20.1 million points, 91% of +# them ground, peaked at 13.3 GB in one R session (1 GB of it before reading the points) at 0.1 m +# and 12.2 GB at 0.5 m cells, so it grows with the points triangulated, not the cells: ~125 bytes +# per point read and ~540 per ground point. A tile's ground points aren't known before reading it, +# so all are taken as ground. With 50% ground the TIN DTM took 231, normalization 352 and +# hummock/hollow 309 bytes per point. +BYTES_PER_POINT_TIN <- 670 +TIN_BYTES_PER_POINT_READ <- 125 +TIN_BYTES_PER_GROUND_POINT <- 540 + +# The bytes per point a TIN tool needs (see BYTES_PER_POINT_TIN) for the catalog's ground share, +# sampled before planning instead of taking every point as ground: TIN normalization of files of +# ~20 million points with their buffers peaked at ~6 GB per worker (~250 bytes per point), but was +# sized at 670, so 7 workers ran where ~16 fit. The ground share (classes 2 and 9) is read from a +# 20 m square at the centre of up to `n` files spread over the catalog, through their .lax indexes +# (so only those points are read, even over a network), and the largest share is used, with a +# 25% margin, as files differ: ~125 bytes per point read and ~540 per ground point. ground_only is +# for a tool that reads only the ground points (the TIN DTM): ~665 per ground point. Never more +# than BYTES_PER_POINT_TIN; that, when no ground can be sampled. Call it after the files' .lax +# indexes exist (apply_tiling calls a function given as bytes_per_point after building them). +tin_bytes_per_point <- function(ctg, ground_only = FALSE, n = 20) { + d <- ctg@data + idx <- unique(round(seq(1, nrow(d), length.out = min(n, nrow(d))))) + # a file's share from five 20 m squares (its centre and the centres of its quarters): a tile + # holds a file, so it is the file's share that sizes a worker, and one small square varies + # far more (one of the sample tiles' squares was 53% ground, the tiles 25-38%) + shares <- vapply(idx, function(i) { + fx <- d$Min.X[i] + (d$Max.X[i] - d$Min.X[i]) * c(0.5, 0.25, 0.75, 0.25, 0.75) + fy <- d$Min.Y[i] + (d$Max.Y[i] - d$Min.Y[i]) * c(0.5, 0.25, 0.25, 0.75, 0.75) + squares <- paste(sprintf("-inside %.3f %.3f %.3f %.3f", fx - 10, fy - 10, fx + 10, fy + 10)) + cls <- unlist(lapply(squares, function(sq) { + las <- tryCatch(suppressWarnings(readLAS(d$filename[i], select = "c", filter = paste("-drop_class 7", sq))), + error = function(e) NULL) + if (is.null(las)) integer(0) else las$Classification + })) + if (length(cls) < 100) return(NA_real_) + mean(cls %in% c(2L, 9L)) + }, numeric(1)) + shares <- shares[!is.na(shares)] + if (length(shares) == 0 || max(shares) == 0) { + print(paste0("Could not sample the ground points' share, so every point is taken as ground (", + BYTES_PER_POINT_TIN, " bytes per point).")) + return(BYTES_PER_POINT_TIN) + } + g <- max(shares) + bytes <- 1.25 * (if (ground_only) (TIN_BYTES_PER_POINT_READ + TIN_BYTES_PER_GROUND_POINT) * g + else TIN_BYTES_PER_POINT_READ + TIN_BYTES_PER_GROUND_POINT * g) + bytes <- round(min(BYTES_PER_POINT_TIN, max(bytes, 100))) + print(paste0("Ground points are up to ", round(100 * g), " percent of the points sampled from ", length(shares), + " file(s), so the memory is sized at ", bytes, " bytes per point (", BYTES_PER_POINT_TIN, + " if every point were ground).")) + bytes +} +# Pit-free DSM/CHM: 796 bytes per point, at 0.25 m and 0.1 m cells alike. It triangulates the first +# returns (all the points there) after lidR's subcircle replaces each by 8. +BYTES_PER_POINT_PITFREE <- 850 +# IDW DTM: 76 bytes per point; it reads only the ground points (50% there), so all are taken as +# ground. +BYTES_PER_POINT_IDW_DTM <- 160 +# TIN DSM/CHM: ~100 bytes per point (102 at 0.25 m cells) plus ~410 per raster cell (168 per point +# at 0.1 m cells): its cells can outnumber the points, so it depends on the cell size; see +# bytes_per_point_dsm_tin. +DSM_TIN_BYTES_PER_POINT <- 120 +DSM_TIN_BYTES_PER_CELL <- 450 +# An R worker with lidR, sf and terra loaded commits ~1.1 GB with one OpenMP thread, and up to +# ~0.55 GB more per tile beyond its points; each further thread adds ~0.21 GB (see start_workers). +WORKER_FIXED_BYTES <- 1.6e9 +WORKER_THREAD_BYTES <- 0.21e9 +# Starting a worker (an R session loading lidR) takes seconds, so each extra worker needs this +# much data to pay off: 7 small test tiles ran in ~100 s with 1 worker and ~180 s with 5 +MIN_POINTS_PER_WORKER <- 20e6 + +# The fixed memory of one of `workers` workers sharing `cores` processes, with the threads it gets +# (see worker_threads) +worker_fixed_bytes <- function(workers, cores = workers) { + WORKER_FIXED_BYTES + WORKER_THREAD_BYTES * (worker_threads(workers, cores) - 1) +} + +# Points one worker can hold when `workers` share the free memory (0 or less if none), at +# bytes_per_point for the tool's algorithm, with the threads of `cores` processes shared out +points_per_worker <- function(free_mem, workers, bytes_per_point = BYTES_PER_POINT, cores = workers) { + (0.6 * free_mem / workers - worker_fixed_bytes(workers, cores)) / bytes_per_point +} + +# points_per_worker() for 1 to max_workers workers +worker_budgets <- function(free_mem, max_workers, bytes_per_point = BYTES_PER_POINT, cores = max_workers) { + vapply(seq_len(max(1, max_workers)), function(w) points_per_worker(free_mem, w, bytes_per_point, cores), numeric(1)) +} + +# The most workers whose share of the free memory holds a chunk (a file or tile) of each of pts +# points, from worker_budgets(); 0 for a chunk too large for even one worker +workers_for <- function(pts, budgets) { + findInterval(-pts, -rev(cummax(rev(budgets)))) +} + +# A run's chunks need not all fit the same number of workers: one dense file or tile would +# otherwise set the workers for all the data (6 of 60 for one file of ~20 million points among +# 2393 smaller ones). The chunks that don't fit the run's workers are processed in later rounds +# with fewer workers, each with a larger share of the memory. The workers of a round are rounded +# down to levels each 1/WORKER_LEVEL_RATIO of the one above, so a run has a few rounds at most, +# each at least 80% of the workers its chunks allow. +WORKER_LEVEL_RATIO <- 1.25 + +# The round (its workers) of chunks that fit `need` workers (see workers_for) in a run of `workers` +# workers; 0 for a chunk too large for one worker +worker_level <- function(need, workers) { + workers <- max(1, workers) + levels <- sort(unique(pmax(1, floor(workers / WORKER_LEVEL_RATIO^(0:ceiling(log(workers, WORKER_LEVEL_RATIO))))))) + i <- findInterval(pmin(need, workers), levels) + ifelse(i == 0, 0, levels[pmax(i, 1)]) +} + +# The workers a round of n chunks at level `level` starts: no more than its chunks, unless fewer +# workers would each have less memory (budgets from worker_budgets) +round_workers <- function(level, n, budgets = NULL) { + w <- max(1, min(level, n)) + if (!is.null(budgets) && level <= length(budgets) && budgets[w] < budgets[level]) w <- level + w +} + +# Estimated time of processing chunks of pts points (buffers included), each fitting need workers, +# in a run of `workers` workers, as points per worker: each round shares its points between its +# workers, and takes no less than its largest chunk +rounds_cost <- function(pts, need, workers) { + level <- pmax(1, worker_level(need, workers)) + rounds <- split(pts, level) + sum(mapply(function(p, l) max(sum(p) / min(l, length(p)), max(p)), rounds, as.numeric(names(rounds)))) +} + +# The run's workers for chunks (files or tiles) of pts points that each fit need workers (see +# workers_for), up to max_workers: those with the least estimated time (see rounds_cost), the most +# of them when several tie, then no more than the chunks fit. Returns list(workers, cost). +best_workers <- function(pts, need, max_workers) { + costs <- vapply(seq_len(max(1, min(max_workers, length(pts)))), function(w) rounds_cost(pts, need, w), numeric(1)) + workers <- max(which(costs <= min(costs) * (1 + 1e-9))) + list(workers = max(worker_level(need, workers)), cost = costs[workers]) +} + +# Processing by file keeps the input file names, so it is used unless tiling is estimated to +# take less than 1/BY_FILE_COST_RATIO of its time (see rounds_cost) +BY_FILE_COST_RATIO <- 1.25 + +# The TIN DSM/CHM's bytes per point at cell_size (m), for the catalog's average density: its +# raster cells per point add to it +bytes_per_point_dsm_tin <- function(ctg, cell_size) { + d <- ctg@data + density <- sum(d$Number.of.point.records) / sum((d$Max.X - d$Min.X) * (d$Max.Y - d$Min.Y)) + DSM_TIN_BYTES_PER_POINT + DSM_TIN_BYTES_PER_CELL / max(density * cell_size^2, 1e-6) +} + +# Workers and tiles for a catalog. tiling is as in apply_tiling: "auto" processes by file when +# every file fits in a worker's share of the free memory and there are at least as many files as +# workers. Otherwise the point counts of the files are read from their spatial indexes (see +# plan_blocks), so each 500 m block gets the largest tile size, from 500 m down to 100 m, whose +# densest tile fits, and the data is tiled unless processing by file, with the files too large for +# the run's workers in later rounds with fewer (see worker_level), is estimated to take about as +# long (see BY_FILE_COST_RATIO). Without the indexes, or with size (m) given, one size is used +# for all the data (see plan_one_size). blocks (a data frame of bx, by and size) are the block +# sizes of an earlier run, as a resumed run needs, and done the "x y" corners of its tiles with +# complete outputs (see plan_blocks). bytes_per_point is the memory the tool's algorithm needs per +# point (see BYTES_PER_POINT). Returns list(workers, chunk_size, fits, budget, blocks, budgets, +# need or tiles): chunk_size is 0 to process by file, or else the largest tile size; blocks is +# NULL for one size; fits is FALSE when a file or tile may not fit even one worker; budgets are +# worker_budgets(); need is the workers each file fits, by file, and tiles each tile's (with +# blocks). +plan_tiling <- function(ctg, tiling, max_workers, free_mem, buffer, cell = 50, size = NULL, blocks = NULL, + bytes_per_point = BYTES_PER_POINT, done = NULL) { + d <- ctg@data + pts <- d$Number.of.point.records + if (!is.null(size) || !is.null(blocks)) tiling <- "tiling" + # the processes allowed, shared out as threads between the workers (see worker_threads) + cores <- max_workers + budget_for <- function(workers) points_per_worker(free_mem, workers, bytes_per_point, cores) + # Only worker counts that leave each worker memory for points, and enough points to be worth + # starting + max_workers <- max(1, min(max_workers, floor(sum(pts) / MIN_POINTS_PER_WORKER))) + while (max_workers > 1 && budget_for(max_workers) <= 0) max_workers <- max_workers - 1 + budgets <- worker_budgets(free_mem, max_workers, bytes_per_point, cores) + done_plan <- function(p) { + p$budgets <- budgets + p + } + # By file, each file in the round of the workers it fits (see worker_level), the run's workers + # those with the least estimated time (see rounds_cost), the most of them when several tie. + # file_pts are the points each file's tile reads, its buffer included when known. + by_file <- function(file_pts) { + need <- workers_for(file_pts, budgets) + fits <- all(need > 0) + workers <- 1 + cost <- Inf + if (fits) { + best <- best_workers(file_pts, need, max_workers) + workers <- best$workers + cost <- best$cost + } + done_plan(list(workers = workers, chunk_size = 0, fits = fits, budget = budgets[workers], blocks = NULL, + need = need, pts = file_pts, cost = cost)) + } + + # Without the density grid, a file's buffer is taken to be as dense as the file + w <- pmax(d$Max.X - d$Min.X, 1) + h <- pmax(d$Max.Y - d$Min.Y, 1) + buffered <- pts * (w + 2 * buffer) * (h + 2 * buffer) / (w * h) + if (tiling == "by_file") return(by_file(buffered)) + if (tiling == "auto" && max(buffered) <= budgets[max_workers] && nrow(d) >= max_workers) return(by_file(buffered)) + + print(paste0("Reading the point density of ", nrow(d), " file(s) from their spatial index...")) + g <- tryCatch(point_count_grid(d$filename, cell), error = function(e) { + print(paste0("Warning! Could not read or build a spatial index (", conditionMessage(e), + "); sizing the tiles by each file's average density instead.")) + NULL + }) + if (is.null(g) || !is.null(size)) { + p <- plan_one_size(d, g, max_workers, free_mem, buffer, size, cell, bytes_per_point, cores) + # Files that fit the workers the tiles would have are processed whole, keeping their names + if (tiling == "auto" && max(buffered) <= budget_for(p$workers) && nrow(d) >= p$workers) return(by_file(buffered)) + return(done_plan(p)) + } + p <- plan_blocks(g, max_workers, free_mem, buffer, blocks, bytes_per_point, done, cores) + if (tiling == "auto") { + # The files with their buffers, from the density grid; a file's points can be outside the + # grid's cells only by rounding + file_pts <- pmax(pts, grid_rect_points(g, d$Min.X - buffer, d$Min.Y - buffer, d$Max.X + buffer, d$Max.Y + buffer)) + f <- by_file(file_pts) + if (f$fits && f$cost <= BY_FILE_COST_RATIO * p$cost) return(f) + } + done_plan(p) +} + +# Tile sizes for each 500 m block, and the workers (see plan_tiling), from point_count_grid()'s +# grid g. A block gets the largest of TILE_SIZES whose densest tile, with its buffer, fits in a +# worker's share of the free memory. More workers have less memory each, so smaller tiles that +# read more buffer; a tile too dense for even the smallest size goes to a later round with fewer +# workers (see worker_level). The workers are chosen for the least estimated time (see +# rounds_cost), buffers included. Tiles are no larger than the data's area shared out, so every +# worker has one. Returns tiles too: each tile's x, y, size and the workers it fits (need). With +# blocks of an earlier run, their sizes are kept. Tiles whose corner ("x y") is in done have +# complete outputs and are skipped, so they count neither in the fit nor in the workers' share. +plan_blocks <- function(g, max_workers, free_mem, buffer, blocks = NULL, bytes_per_point = BYTES_PER_POINT, + done = NULL, cores = max_workers) { + key <- function(t) paste(t$bx, t$by) + tiles <- lapply(TILE_SIZES, function(size) { + t <- tile_points(g, size, buffer) + t <- t[t$own > 0, ] + # only the tiles of the size their block was cut at in the earlier run can be done + if (!is.null(blocks) && length(done)) { + cut <- blocks$size[match(key(t), paste(blocks$bx, blocks$by))] + t <- t[!(paste(t$x, t$y) %in% done & !is.na(cut) & cut == size), ] + } + t + }) + all_tiles <- do.call(rbind, tiles) + data_blocks <- all_tiles[!duplicated(key(all_tiles)), c("bx", "by")] + k <- key(data_blocks) + # one row per block, one column per tile size; 0 for a block with no tile left of that size + per_block <- function(f) { + matrix(sapply(tiles, function(t) { + v <- if (nrow(t)) tapply(t$pts, key(t), f)[k] else rep(NA, length(k)) + ifelse(is.na(v), 0, v) + }), nrow = length(k)) + } + densest <- per_block(max) + area <- nrow(tiles[[length(TILE_SIZES)]]) * min(TILE_SIZES)^2 + fixed <- NULL + if (!is.null(blocks)) fixed <- match(blocks$size[match(k, paste(blocks$bx, blocks$by))], TILE_SIZES) + budgets <- worker_budgets(free_mem, max_workers, bytes_per_point, cores) + block_of <- lapply(tiles, function(t) match(key(t), k)) + + plan_for <- function(workers) { + budget <- budgets[workers] + allowed <- TILE_SIZES <= max(sqrt(area / workers), min(TILE_SIZES)) + ok <- densest <= budget & matrix(allowed, nrow(densest), length(TILE_SIZES), byrow = TRUE) + chosen <- apply(ok, 1, function(r) if (any(r)) which(r)[1] else length(TILE_SIZES)) + if (!is.null(fixed)) chosen <- ifelse(is.na(fixed), chosen, fixed) + # the tiles of each block at its size; those too large for this many workers are processed + # in later rounds with fewer (see worker_level) + t <- do.call(rbind, lapply(seq_along(TILE_SIZES), function(s) { + x <- tiles[[s]][chosen[block_of[[s]]] == s, c("x", "y", "pts")] + if (nrow(x)) x$size <- TILE_SIZES[s] else x$size <- numeric(0) + x + })) + need <- workers_for(t$pts, budgets) + fits <- all(need > 0) + list(workers = workers, fits = fits, budget = budget, chosen = chosen, n = nrow(t), + cost = if (fits && nrow(t)) rounds_cost(t$pts, need, workers) else Inf, + tiles = data.frame(x = t$x, y = t$y, size = t$size, need = need, pts = t$pts)) + } + plans <- lapply(seq_len(max_workers), plan_for) + valid <- Filter(function(p) p$fits && p$n >= p$workers, plans) + p <- if (length(valid)) valid[[which.min(sapply(valid, `[[`, "cost"))]] else plans[[1]] + if (p$fits && p$n) { + # no more workers than the tiles fit + p$workers <- max(worker_level(p$tiles$need, p$workers)) + p$budget <- budgets[p$workers] + } + sizes <- TILE_SIZES[p$chosen] + list(workers = p$workers, chunk_size = max(sizes), fits = p$fits, budget = p$budget, cost = p$cost, + tiles = p$tiles, blocks = data.frame(bx = data_blocks$bx, by = data_blocks$by, size = sizes)) +} + +# One tile size for all the data (see plan_tiling), when the files' spatial indexes can't be read +# (g NULL) or the size is given: the most workers, up to max_workers and the number of tiles, +# whose tiles fit in their share of the free memory. Tiles are sized for the densest data and give +# every worker one, and are at least 10 buffers wide so the buffer adds under ~45% to each read, +# down to 3 buffers wide on data too dense for that. Density is read from the grid g of point +# counts, or else is each file's average. +plan_one_size <- function(d, g, max_workers, free_mem, buffer, size = NULL, cell = 50, + bytes_per_point = BYTES_PER_POINT, cores = max_workers) { + pts <- d$Number.of.point.records + area <- (d$Max.X - d$Min.X) * (d$Max.Y - d$Min.Y) + density <- max(pts / area) + min_size <- 10 * buffer + smallest <- 3 * buffer + # Points in the densest chunk of `size` m, with its buffer + densest <- function(size) { + if (is.null(g)) density * (size + 2 * buffer)^2 + else window_max(g, ceiling((size + 2 * buffer) / cell)) + } + # Tiles a run makes: the chunks (aligned at 0, 0) that the files' extents touch + n_tiles <- function(size) { + cells <- unlist(lapply(seq_len(nrow(d)), function(i) { + xs <- seq(floor(d$Min.X[i] / size), floor(d$Max.X[i] / size)) + ys <- seq(floor(d$Min.Y[i] / size), floor(d$Max.Y[i] / size)) + outer(xs, ys, paste) + })) + length(unique(cells)) + } + # The plan for `workers`, or NULL if their tiles don't fit (always a plan for 1 worker) + plan_for <- function(workers) { + budget <- points_per_worker(free_mem, workers, bytes_per_point, cores) + s <- size + if (is.null(s)) { + chunk_area <- min(max(budget, 0) / density, sum(area) / workers) + s <- max(floor(sqrt(chunk_area) / cell) * cell, min_size) + # Below min_size only when the densest chunk doesn't fit otherwise + while (densest(s) > budget && (s > min_size || s - cell >= smallest)) s <- s - cell + } + fits <- densest(s) <= budget + if (!fits && workers > 1) return(NULL) + list(workers = workers, chunk_size = s, fits = fits, budget = budget, blocks = NULL) + } + + # Fewer workers when their tiles don't fit, and no more workers than tiles, as each worker + # costs a start-up and memory; fewer workers may then allow larger tiles, so plan again + workers <- max_workers + repeat { + p <- plan_for(workers) + if (is.null(p)) { + workers <- workers - 1 + next + } + n <- n_tiles(p$chunk_size) + if (n < p$workers) { + workers <- max(1, n) + next + } + return(p) + } +} + +# Where a tiled run keeps its tile size for each 500 m block, next to its outputs: out_template +# with "tiles" for {*}, e.g. "tiles_csfgnd_upto30cm_cloth150cm_hard.csv" +tile_plan_file <- function(out_template) paste0(sub("{*}", "tiles", out_template, fixed = TRUE), ".csv") + +# The lidR (OpenMP) threads each of `workers` workers gets: an equal share of the max_workers +# processes allowed, at most the CPU cores. Memory often allows fewer workers than cores (dense +# files, or the TIN tools' memory per point), and with one thread each the other cores sat idle; +# lidR's multi-threaded steps (rasterizing, interpolating, normalizing, filtering) can use them. +# workers x threads stays within the cores, so lidR keeps them: it sets the workers to one thread +# when they would oversubscribe the cores. +worker_threads <- function(workers, max_workers) { + cores <- min(max(1, max_workers), max(1, parallelly::availableCores())) + max(1L, as.integer(floor(cores / max(1, workers)))) +} + +# Start `workers` R workers with future::plan(multisession), each with worker_threads() lidR +# threads, and return the threads per worker; the caller resets the plan. The workers start with +# OMP_NUM_THREADS set to their threads: R's BLAS (Intel MKL in the conda environment) commits +# ~0.2 GB per OpenMP thread when sf and terra load, so a worker left at the default of one thread +# per core committed ~4.6 GB on 20 cores before reading a point, and several times that on a large +# server, all counted by the tool's memory limit. OMP_NUM_THREADS also caps lidR's threads, so it is +# set to the threads the worker uses. New tools should start their workers with this. +# +# The workers are mirai daemons (future.mirai) when that package is installed, else R sessions +# (future's multisession). lidR hands the tiles to the workers one at a time and, after each, +# asks future whether each running tile is done. With multisession that check waits on the +# worker's socket, and on Windows R's socketSelect takes ~0.2 s however short its timeout, so +# handing out a tile took ~0.2 s per tile running: 46 workers on files of about a minute kept only +# ~12-16 of them busy, the others never getting a file. mirai's check doesn't wait, so tiles are +# handed out every ~0.3 s whatever the workers, and all of them are kept busy (16 of 16 against +# 11 of 16 in a test, in 75 s against 137 s). +start_workers <- function(workers, max_workers, threads = worker_threads(workers, max_workers)) { + old <- Sys.getenv("OMP_NUM_THREADS", unset = NA) + Sys.setenv(OMP_NUM_THREADS = threads) + on.exit(if (is.na(old)) Sys.unsetenv("OMP_NUM_THREADS") else Sys.setenv(OMP_NUM_THREADS = old), add = TRUE) + if (requireNamespace("future.mirai", quietly = TRUE)) { + future::plan(future.mirai::mirai_multisession, workers = workers) + } else { + future::plan(future::multisession, workers = workers) + } + set_lidr_threads(threads) + threads +} + +# Set how a catalog is split for processing, start its R workers and set where its outputs go. +# tiling is one of: +# "auto" tile only when a file is too large for the free memory or there are fewer files +# than workers, otherwise process by file +# "by_file" process each file as one tile, keeping the file names; when a file is too large for +# the free memory, warns and tiles the data as "tiling" does instead +# "tiling" always split into tiles sized for the free memory and the data's density +# The most workers, up to max_workers, whose tiles fit in the free memory are started with +# future::plan(multisession), sharing the cores as lidR threads (see set_worker_threads); the +# caller resets the plan. out_template +# is the output path with {*} for the input file name; when the data is tiled, {*} becomes the +# tile's lower-left corner. buffer (m) defaults to the catalog's. Tile sizes that vary with the +# density are kept in ctg@chunk_options$blocks and saved in tile_plan_file(); select_tiles then +# splits the run into one lidR run per size. With skip_existing, the 500 m blocks of an earlier +# run that have outputs keep their tile size, so a resumed run makes the same tiles there, and the +# blocks without outputs are planned again for the free memory now. tile_size (m) fixes one size +# for all the data. bytes_per_point is the memory the tool's algorithm needs per point, measured +# for each tool (see BYTES_PER_POINT and the figures after it); a new tool should measure its own. +# Whether the densest tile fits a +# worker is kept in ctg@chunk_options$fits; fit_warning = FALSE leaves warning about it to the +# caller. +apply_tiling <- function(ctg, tiling, max_workers, free_mem, out_template, buffer = opt_chunk_buffer(ctg), + skip_existing = FALSE, tile_size = NULL, fit_warning = TRUE, + bytes_per_point = BYTES_PER_POINT) { + if (!tiling %in% c("auto", "by_file", "tiling")) stop("Unknown tiling option: ", tiling) + ensure_lax(ctg@data$filename) + # a tool's memory per point that depends on its data (see tin_bytes_per_point), read now that + # the files have their .lax indexes + if (is.function(bytes_per_point)) bytes_per_point <- bytes_per_point(ctg) + opt_chunk_buffer(ctg) <- buffer + ctg <- write_outputs_whole(ctg, dirname(out_template)) + plan_file <- tile_plan_file(out_template) + size <- tile_size + blocks <- NULL + done <- NULL + resume_by_file <- isTRUE(skip_existing) && is.null(tile_size) && tiling == "auto" && !file.exists(plan_file) && + by_file_outputs_exist(ctg, out_template) + if (resume_by_file) { + # Tiling now would name the outputs by tile corner and make them all again beside the + # earlier run's. A tiled run leaves its plan_file, and its outputs are named by corner, + # which only input files named by corner (as lidar_tile's) can match. + print("Resuming an earlier run that processed the LiDAR data by file, as its outputs are named after the input files...") + tiling <- "by_file" + } + if (isTRUE(skip_existing) && is.null(tile_size) && !resume_by_file) { + if (file.exists(plan_file)) { + blocks <- utils::read.csv(plan_file) + # Output corners can be off the tile grid by under a cell where the raster's cells + # don't divide the tile, so they are snapped to the 25 m that every tile size is a + # multiple of + corners <- round(output_corners(out_template, complete = TRUE) / 25) * 25 + done <- unique(paste(corners$x, corners$y)) + started <- paste(floor(corners$x / TILE_BLOCK) * TILE_BLOCK, floor(corners$y / TILE_BLOCK) * TILE_BLOCK) + kept <- paste(blocks$bx, blocks$by) %in% started + print(paste0("Resuming an earlier run with its tile sizes, from ", basename(plan_file), ", for the ", + sum(kept), " block(s) with outputs; the other ", sum(!kept), + " block(s) are tiled again for the free memory now...")) + blocks <- blocks[kept, , drop = FALSE] + } else { + size <- existing_tile_size(out_template) + if (!is.null(size)) { + print(paste0("Resuming an earlier run with ", size, " m tiles, the size of its outputs...")) + } + } + } + p <- plan_tiling(ctg, tiling, max(1, max_workers), free_mem, buffer, size = size, blocks = blocks, + bytes_per_point = bytes_per_point, done = done) + if (tiling == "by_file" && !p$fits && is.null(size) && is.null(blocks)) { + # A file too large for a worker would stop the tool at its memory limit, so tile the data + pts <- ctg@data$Number.of.point.records + print(paste0("Warning! ", sum(pts > p$budget), " file(s) are too large to process whole in the free memory ", + "(the largest, ", basename(ctg@data$filename[which.max(pts)]), ", needs about ", + round((max(pts) * bytes_per_point + WORKER_FIXED_BYTES) / 1e9, 1), + " GB), so the data is tiled instead of processed by file.")) + p <- plan_tiling(ctg, "tiling", max(1, max_workers), free_mem, buffer, bytes_per_point = bytes_per_point) + } + threads <- start_workers(p$workers, max_workers) + print(paste0("Using ", p$workers, " of up to ", max_workers, " worker(s), with ", threads, + " thread(s) each: ", round(free_mem / 1e9, 1), " GB free memory allows about ", + round(max(p$budget, 0) / 1e6, 1), " million points per worker.")) + # The run's workers, for select_tiles to split it into rounds and catalog_run to start them + ctg@chunk_options$workers <- p$workers + ctg@chunk_options$max_workers <- max_workers + ctg@chunk_options$budgets <- p$budgets + # A plan left by an earlier run would mislead a later resume + if (is.null(p$blocks) && is.null(blocks) && file.exists(plan_file)) file.remove(plan_file) + if (p$chunk_size == 0) { + print(paste0("Processing the LiDAR data by file with ", p$workers, " worker(s)...")) + # lidR makes no tile for a file whose points are all on a line or at one place (an extent + # of no area) but still names the tiles after the files in order, so every later file's + # output took the name of the file before it. Such a file can't give a raster anyway. + d <- ctg@data + flat <- d$Max.X <= d$Min.X | d$Max.Y <= d$Min.Y + if (p$fits) ctg@chunk_options$need <- data.frame(need = p$need, pts = p$pts) + if (any(flat)) { + print(paste0("Note: ", sum(flat), " file(s) are left out as their points cover no area (on a line or ", + "at one place): ", paste(basename(d$filename[flat]), collapse = ", "), ".")) + ctg <- ctg[!flat, ] + if (p$fits) ctg@chunk_options$need <- data.frame(need = p$need[!flat], pts = p$pts[!flat]) + } + opt_output_files(ctg) <- out_template + return(ctg) + } + if (p$fits) ctg@chunk_options$tile_need <- p$tiles + if (is.null(p$blocks)) { + print(paste0("Tiling the LiDAR data into ", p$chunk_size, " m chunks for ", p$workers, " worker(s)...")) + } else { + utils::write.csv(p$blocks, plan_file, row.names = FALSE) + n <- table(factor(p$blocks$size, levels = TILE_SIZES)) + n <- n[n > 0] + print(paste0("Tiling the LiDAR data by its density for ", p$workers, " worker(s), in 500 m blocks of ", + paste0(names(n), " m tiles (", n, " block(s))", collapse = ", "), "...")) + ctg@chunk_options$blocks <- p$blocks + } + ctg@chunk_options$fits <- p$fits + if (!p$fits && fit_warning) { + print(paste0("Warning! The densest tiles may not fit in the free memory; ", + "close other programs if R runs out of memory.")) + } + # lidR warns about chunks under 250 m; the size here is chosen for the free memory, so it's quiet + suppressMessages(opt_chunk_size(ctg) <- p$chunk_size) + opt_chunk_alignment(ctg) <- c(0, 0) + # A chunk can span several files, so outputs are named by their lower-left corner + opt_output_files(ctg) <- sub("{*}", "{XLEFT}_{YBOTTOM}", out_template, fixed = TRUE) + ctg +} + +# The corners (x, y) of the outputs of an earlier run named by tile corner (see apply_tiling), as +# a data frame with one row per output file. Also finds outputs with a prefix before the corner, +# such as the hummock/hollow tool's CHH_ and HH_. With complete, only the files that were written +# completely (see output_complete). +output_corners <- function(out_template, complete = FALSE) { + parts <- strsplit(basename(out_template), "{*}", fixed = TRUE)[[1]] + prefix <- parts[1] + suffix <- if (length(parts) > 1) parts[2] else "" + files <- list.files(dirname(out_template), full.names = TRUE) + names <- sub("^(CHH|HH)_", "", tools::file_path_sans_ext(basename(files))) + keep <- startsWith(names, prefix) & endsWith(names, suffix) + files <- files[keep] + names <- names[keep] + corner <- substr(names, nchar(prefix) + 1, nchar(names) - nchar(suffix)) + corners <- regmatches(corner, regexec("^(-?[0-9.]+)_(-?[0-9.]+)$", corner)) + ok <- lengths(corners) == 3 + if (complete && any(ok)) ok[ok] <- vapply(files[ok], output_complete, logical(1)) + data.frame(x = as.numeric(vapply(corners[ok], `[`, "", 2)), + y = as.numeric(vapply(corners[ok], `[`, "", 3))) +} + +# Whether an earlier run processed the catalog by file: an output named after an input file (see +# apply_tiling), with or without the hummock/hollow tool's CHH_ and HH_ prefixes +by_file_outputs_exist <- function(ctg, out_template) { + expected <- vapply(tools::file_path_sans_ext(basename(ctg@data$filename)), function(name) + sub("{*}", name, basename(out_template), fixed = TRUE), character(1)) + files <- list.files(dirname(out_template)) + names <- sub("^(CHH|HH)_", "", tools::file_path_sans_ext(files)) + any(expected %in% names) +} + +# The size (m) of the tiles of an earlier run whose outputs are named by tile corner (see +# apply_tiling), from the corners of its outputs, or NULL when no two outputs show it. +existing_tile_size <- function(out_template) { + corners <- output_corners(out_template) + if (nrow(corners) < 2) return(NULL) + steps <- unlist(lapply(corners, function(v) diff(sort(unique(v))))) + steps <- steps[steps > 0] + if (length(steps) == 0) NULL else min(steps) +} + +# A write function for a lidR output driver that calls `write` with the output path, its argument +# named `path`, changed to .partial., and renames the file to its name once written. A +# tool stopped while writing a GeoTIFF left a file that opens and reads without error, its +# unwritten rows NA, so a resumed run (skip_existing) took it for complete (see output_complete) +# and the merged raster had a hole there; now a file has its name only when complete. The +# function travels to the R workers in the catalog, so it uses only base R and its arguments. +write_whole <- function(write, path) { + force(write) + force(path) + function(...) { + args <- list(...) + final <- as.character(args[[path]]) + part <- sub("(\\.[A-Za-z0-9]+)$", ".partial\\1", final) + if (identical(part, final)) part <- paste0(final, ".partial") + args[[path]] <- part + do.call(write, args) + if (file.exists(final)) unlink(final) + if (!file.rename(part, final)) stop("Could not rename ", part, " to ", basename(final), call. = FALSE) + invisible(final) + } +} + +# The catalog with its LAS and raster output drivers writing each file whole (see write_whole), +# and the partial files a stopped run left in out_dir removed. Drivers of other outputs, such as +# the hummock/hollow tool's two rasters per tile, write their files whole themselves. +write_outputs_whole <- function(ctg, out_dir) { + drivers <- ctg@output_options$drivers + for (name in intersect(names(drivers), c("LAS", "SpatRaster", "Raster", "stars"))) { + drivers[[name]]$write <- write_whole(drivers[[name]]$write, drivers[[name]]$path) + } + ctg@output_options$drivers <- drivers + left <- list.files(out_dir, pattern = "\\.partial\\.(tif|las|laz)$", full.names = TRUE, ignore.case = TRUE) + if (length(left)) { + print(paste0("Removing ", length(left), " partly written file(s) of a run that stopped...")) + file.remove(left) + } + ctg +} + +# Whether an output file was written completely, as a run that stopped can leave the files it was +# writing cut short: a LAS file must hold all the points its header counts and a GeoTIFF's last row +# must be readable. Other files only need to exist. +output_complete <- function(f) { + if (!file.exists(f)) return(FALSE) + ext <- tolower(tools::file_ext(f)) + tryCatch({ + if (ext == "las") { + h <- rlas::read.lasheader(f) + n <- max(h[["Number of point records"]], h[["Extended number of point records"]]) + file.size(f) >= h[["Offset to point data"]] + h[["Point Data Record Length"]] * n + } else if (ext == "tif") { + r <- terra::rast(f) + length(terra::values(r, row = terra::nrow(r), nrows = 1)) > 0 + } else if (ext == "laz") { + rlas::read.lasheader(f) + TRUE + } else TRUE + }, error = function(e) FALSE) +} + +# Split a run into one lidR run (a round) per tile size, as apply_tiling's tiles can vary in size +# with the density, and per worker count, as files or tiles too large for the run's workers are +# processed after the others with fewer (see worker_level and chunk_need; a resumed run plans the workers for the tiles left), each round leaving +# out the tiles of the others; the round's workers are in its `workers`. Call it after apply_tiling and run +# the catalog with catalog_run. With skip_existing, also leave out the tiles whose outputs are all +# complete, so a rerun of a run that stopped resumes where it stopped. outputs(save) gives the +# files a tile writes from its output path without extension. The raster tools pass their cell +# size as res, since lidR then aligns the chunks to the raster. The skipped outputs are kept in +# ctg@chunk_options$kept_outputs, so they are merged with the new ones. +select_tiles <- function(ctg, skip_existing, outputs, res = NULL) { + blocks <- ctg@chunk_options$blocks + sizes <- if (is.null(blocks)) opt_chunk_size(ctg) else sort(unique(blocks$size), decreasing = TRUE) + realignment <- if (is.null(res)) FALSE else list(res = res, start = c(0, 0)) + runs <- list() + kept <- character(0) + n_done <- n_all <- 0 + sized_info <- list() + if (isTRUE(skip_existing)) { + print("Checking which outputs of an earlier run are complete...") + flush.console() + } + for (size in sizes) { + sized <- ctg + if (size > 0) suppressMessages(opt_chunk_size(sized) <- size) + chunks <- suppressMessages(engine_chunks(sized, realignment, plot = FALSE)) + # By file, lidR names the tiles after the files in order, so a file it made no tile for + # would give every later file's output the wrong name (see apply_tiling) + if (size == 0 && length(chunks) != nrow(sized@data)) { + stop("lidR made ", length(chunks), " tile(s) for ", nrow(sized@data), " file(s), so the outputs would ", + "be named after the wrong files; use tiling 'tiling' for this data.", call. = FALSE) + } + # the tiles of this size: those whose centre is in a block of this size + mine <- rep(TRUE, length(chunks)) + if (!is.null(blocks)) { + own <- paste(blocks$bx, blocks$by)[blocks$size == size] + mine <- vapply(chunks, function(chunk) { + paste(floor(chunk@center$x / TILE_BLOCK) * TILE_BLOCK, + floor(chunk@center$y / TILE_BLOCK) * TILE_BLOCK) %in% own + }, logical(1)) + } + done <- rep(FALSE, length(chunks)) + if (isTRUE(skip_existing)) { + done[mine] <- vapply(chunks[mine], function(chunk) { + all(vapply(outputs(chunk@save), output_complete, logical(1))) + }, logical(1)) + } + kept <- c(kept, unlist(lapply(chunks[done], function(chunk) outputs(chunk@save)))) + n_done <- n_done + sum(done) + n_all <- n_all + sum(mine) + sized_info[[length(sized_info) + 1]] <- list(size = size, n = length(chunks), left = mine & !done, + fit = chunk_need(ctg, chunks, size)) + } + if (isTRUE(skip_existing)) { + if (n_done == 0) print("No tile has complete outputs yet, so all tiles are processed.") + else print(paste0("Skipping ", n_done, " of ", n_all, " tile(s) whose outputs are complete; ", + n_all - n_done, " tile(s) left to process...")) + } + # The run's workers, and the round of each tile: the run's workers, or fewer for a tile too + # large for them. A resumed run plans them for the tiles left: planned for all of them, a + # run whose earlier run had done the small files first sized its workers for files it + # skipped, and made rounds of one file. + workers <- ctg@chunk_options$workers + by_file <- length(sizes) == 1 && sizes == 0 + left_fit <- do.call(rbind, lapply(sized_info, function(s) if (!is.null(s$fit)) s$fit[s$left, , drop = FALSE])) + if (!is.null(workers) && !is.null(left_fit) && nrow(left_fit) > 0) { + if (n_done > 0) { + workers <- best_workers(left_fit$pts, left_fit$need, length(ctg@chunk_options$budgets))$workers + print(paste0("Using up to ", workers, " worker(s) for the ", nrow(left_fit), if (by_file) " file(s)" else " tile(s)", + " left.")) + } + later <- sum(worker_level(left_fit$need, workers) < workers) + if (later > 0) { + print(paste0(later, " of the ", nrow(left_fit), if (by_file) " file(s)" else " tile(s)", + " are too large for ", workers, " worker(s), so they are processed after the others with fewer.")) + } + } + for (s in sized_info) { + if (!any(s$left)) { + runs[[length(runs) + 1]] <- list(size = s$size, drop = seq_len(s$n), n = 0) + next + } + level <- if (is.null(workers)) rep(0, s$n) + else if (is.null(s$fit)) rep(workers, s$n) + else worker_level(s$fit$need, workers) + # each level's workers; levels that start the same workers (a level with fewer tiles than + # workers starts one per tile) are one round, as a tile fits fewer workers than its level + levels <- sort(unique(level[s$left]), decreasing = TRUE) + starts <- vapply(levels, function(l) { + if (l > 0) round_workers(l, sum(s$left & level == l), ctg@chunk_options$budgets) else 0 + }, numeric(1)) + for (w in unique(starts)) { + round <- s$left & level %in% levels[starts == w] + runs[[length(runs) + 1]] <- list(size = s$size, drop = which(!round), n = sum(round), + workers = if (w > 0) w) + } + } + ctg@chunk_options$runs <- runs + ctg@chunk_options$kept_outputs <- kept + ctg +} + +# The workers each of a run's chunks of `size` m (0 by file) fits and the points it reads, from +# apply_tiling's plan, as a data frame of need (see workers_for) and pts, one row per chunk; NULL +# when the plan has none (one tile size for all the data, or no workers set) +chunk_need <- function(ctg, chunks, size) { + if (is.null(ctg@chunk_options$workers)) return(NULL) + if (size == 0) { + # by file, lidR makes the tiles in the order of the files (see select_tiles) + f <- ctg@chunk_options$need + if (is.null(f) || nrow(f) != length(chunks)) return(NULL) + return(data.frame(need = pmax(f$need, 1), pts = f$pts)) + } + t <- ctg@chunk_options$tile_need + if (is.null(t)) return(NULL) + corner <- function(v) floor(v / size) * size + key <- vapply(chunks, function(chunk) paste(size, corner(chunk@center$x), corner(chunk@center$y)), "") + i <- match(key, paste(t$size, t$x, t$y)) + # a tile the plan didn't count (rounding at the data's edge) fits the most workers, and is small + data.frame(need = ifelse(is.na(i), length(ctg@chunk_options$budgets), pmax(t$need[i], 1)), + pts = ifelse(is.na(i), 0, t$pts[i])) +} + +# Run FUN(ctg), a lidR catalog function such as function(ctg) classify_ground(ctg, csf()), once for +# each round select_tiles made (a tile size, and the files or tiles too large for the run's workers +# with fewer), starting each round's workers, and stop with the error of a tile that fails. Each +# round reads the whole catalog, so its tiles' buffers hold the points of every file. Before each +# run, prints "R_TILES::", so the GUI counts the tiles of +# all runs. Returns the last run's results, unmerged (a list), or NULL when no tile is left to process. +catalog_run <- function(ctg, FUN) { + runs <- ctg@chunk_options$runs + opt_merge(ctg) <- FALSE + if (is.null(runs)) return(stop_on_tile_error(FUN(ctg))) + total <- sum(sapply(runs, `[[`, "n")) + if (total == 0) { + print("All tiles have complete outputs; none is left to process.") + return(NULL) + } + done <- 0 + result <- NULL + started <- ctg@chunk_options$workers + rounds <- sum(vapply(runs, function(run) run$n > 0, logical(1))) + for (run in runs) { + if (run$n == 0) next + sized <- ctg + if (run$size > 0) suppressMessages(opt_chunk_size(sized) <- run$size) + sized@chunk_options$drop <- run$drop + # lidR merges a run's results into one object (a catalog of the written files, say), + # and fails with "subscript out of bounds" when every tile of the run was left out + # (returned NULL), as a round holding only a file with nothing to normalize was. The + # tools read their outputs from the files instead, so the results aren't merged. + opt_merge(sized) <- FALSE + workers <- "" + if (!is.null(run$workers)) { + if (!identical(as.numeric(run$workers), as.numeric(started))) { + start_workers(run$workers, ctg@chunk_options$max_workers) + started <- run$workers + } + workers <- paste0(" with ", run$workers, " worker(s), ", + worker_threads(run$workers, ctg@chunk_options$max_workers), " thread(s) each") + } + if (rounds > 1) { + print(paste0("Processing ", run$n, if (run$size > 0) paste0(" tile(s) of ", run$size, " m") else " file(s)", + workers, "...")) + } + cat(sprintf("R_TILES:%d:%d\n", done, total)) + flush.console() + result <- stop_on_tile_error(FUN(sized), done, total) + done <- done + run$n + } + result +} + +# Whether points x, y span an area, as a DTM needs: lidR masks the DTM with the convex hull of the +# ground points and triangulates them, and with all of them at one or two places, or on a line, the +# hull isn't a polygon (GEOS's "IllegalArgumentException: Invalid number of points in LinearRing", +# which sf can report as "scan() expected 'a real'") or there are fewer than 3 points to +# triangulate, which stopped the whole run. +spans_area <- function(x, y) { + i <- grDevices::chull(x, y) + if (length(i) < 3) return(FALSE) + xs <- x[i] + ys <- y[i] + abs(sum(xs * c(ys[-1], ys[1]) - c(xs[-1], xs[1]) * ys)) > 0 +} + +# The input files a tile was read from, for messages ("a tile" for a LAS that isn't one) +chunk_files <- function(chunk) { + if (methods::.hasSlot(chunk, "files")) paste(basename(chunk@files), collapse = ", ") else "a tile" +} + +# The DTM of each tile of a catalog, as lidR's rasterize_terrain(ctg, res, algorithm) makes it, but +# a tile whose ground points don't span an area (see spans_area), such as a sliver at the edge of +# the data, is left out with a warning naming its files instead of stopping the run; the tiles +# around it cover its area. +rasterize_terrain_tiles <- function(ctg, res, algorithm) { + opt_select(ctg) <- "xyzc" + opt_filter(ctg) <- paste("-keep_class 2 9", opt_filter(ctg)) + dtm_tile <- function(chunk, res, algorithm) { + las <- readLAS(chunk) + if (is.empty(las)) return(NULL) + if (!spans_area(las$X, las$Y)) { + warning("Left out ", chunk_files(chunk), ": its ", npoints(las), + " ground point(s) don't span an area, so no DTM can be made there.", call. = FALSE) + return(NULL) + } + dtm <- rasterize_terrain(las, res = res, algorithm = algorithm) + terra::crop(dtm, terra::ext(as.numeric(sf::st_bbox(chunk))[c(1, 3, 2, 4)])) + } + options <- list(need_buffer = TRUE, drop_null = TRUE, automerge = TRUE, + raster_alignment = list(res = res, start = c(0, 0))) + catalog_apply(ctg, dtm_tile, res = res, algorithm = algorithm, .options = options) +} + +# Each tile of a catalog normalized, as lidR's normalize_height(ctg, algorithm) makes it (the tile +# read with its buffer, normalized, the buffer cropped off and the tile written), but a tile whose +# ground points (class 2 and 9) don't span an area (see spans_area) is left out with a warning +# naming its files: a file of a few points, all at Z = 0 and none of them ground, stopped the whole +# run with "Internal error in C_interpolate_delaunay: cannot triangulate less than 3 points". So +# is a tile the algorithm can't interpolate for another such reason. +normalize_tiles <- function(ctg, algorithm) { + opt_select(ctg) <- "*" + normalize_tile <- function(chunk, algorithm) { + las <- readLAS(chunk) + if (is.empty(las)) return(NULL) + ground <- las$Classification %in% c(2L, 9L) + left_out <- function(why) { + warning("Left out ", chunk_files(chunk), ": its heights can't be normalized from its ", sum(ground), + " ground point(s) of ", npoints(las), " (", why, ").", call. = FALSE) + NULL + } + if (sum(ground) < 3 || !spans_area(las$X[ground], las$Y[ground])) return(left_out("they don't span an area")) + las <- tryCatch(normalize_height(las, algorithm), error = function(e) { + msg <- conditionMessage(e) + if (!grepl("triangulate|No ground points|Interpolation failed|NAs everywhere", msg)) stop(e) + left_out(trimws(msg)) + }) + if (is.null(las)) return(NULL) + # the buffer cropped off, as lidR does for a tile it reads itself (engine_crop) + buffer <- NULL + las <- filter_poi(las, buffer == lidR:::LIDRNOBUFFER) + if (is.empty(las)) NULL else las + } + options <- list(need_buffer = TRUE, drop_null = TRUE, need_output_file = TRUE, automerge = TRUE) + catalog_apply(ctg, normalize_tile, algorithm = algorithm, .options = options) +} + +# An empty raster of resolution res, on the grid that starts at 0, 0, covering the points of las with +# one cell to spare on each side. Given a resolution, lidR rounds the bounding box of the points to +# the grid in floating point, and when the lowest or leftmost point lies on a cell edge, the +# rounded edge can come out a hair (1e-9 m) inside it: pitfree then stops the whole run with "C++ +# unexpected internal error in 'filter_with_grid': point out of raster". The spare cell keeps every +# point inside; the tile's raster is cropped to the tile afterwards. +canopy_template <- function(las, res) { + bb <- as.numeric(sf::st_bbox(las)) + ext <- terra::ext(floor(bb[1] / res) * res - res, ceiling(bb[3] / res) * res + res, + floor(bb[2] / res) * res - res, ceiling(bb[4] / res) * res + res) + crs <- sf::st_crs(las) + terra::rast(ext, resolution = res, crs = if (is.na(crs)) "" else crs$wkt) +} + +# The DSM or CHM of each tile of a catalog, as lidR's rasterize_canopy(ctg, res, algorithm, ...) +# makes it, but a tile whose points don't span an area (see spans_area) is left out with a warning +# naming its files: with dsmtin, it stopped the whole run ("Interpolation failed in the first +# layer (NAs everywhere)"). So is a tile the algorithm finds nothing to interpolate in: pit-free +# triangulates only the first returns above each of its height thresholds, the lowest 0, so a +# tile whose first returns are at or below Z = 0 (a file with broken or zero elevations, say) +# stopped the run with "Interpolation failed (NAs everywhere)". +rasterize_canopy_tiles <- function(ctg, res, algorithm, ...) { + opt_select(ctg) <- "xyzr" + if (opt_wall_to_wall(ctg)) opt_chunk_buffer(ctg) <- 2 + canopy_tile <- function(chunk, res, algorithm, ...) { + las <- readLAS(chunk) + if (is.empty(las)) return(NULL) + if (!spans_area(las$X, las$Y)) { + warning("Left out ", chunk_files(chunk), ": its ", npoints(las), + " point(s) don't span an area, so no DSM or CHM can be made there.", call. = FALSE) + return(NULL) + } + chm <- tryCatch(rasterize_canopy(las, canopy_template(las, res), algorithm, ...), error = function(e) { + msg <- conditionMessage(e) + if (!grepl("Interpolation failed|not enought points to triangulate|No first returns found", msg)) stop(e) + first <- las$Z[las$ReturnNumber == 1L] + warning("Left out ", chunk_files(chunk), ": no DSM or CHM could be interpolated from its ", + length(first), " first return(s)", + if (length(first)) paste0(" (Z from ", round(min(first), 2), " to ", round(max(first), 2), ")"), + ": ", msg, call. = FALSE) + NULL + }) + if (is.null(chm)) return(NULL) + terra::crop(chm, terra::ext(as.numeric(sf::st_bbox(chunk))[c(1, 3, 2, 4)])) + } + options <- list(need_buffer = TRUE, drop_null = TRUE, automerge = TRUE, + raster_alignment = list(res = res, start = c(0, 0))) + catalog_apply(ctg, canopy_tile, res = res, algorithm = algorithm, ..., .options = options) +} + +# Stop the R workers, as the tools do on exit. When the tool is stopping on an error, a worker that +# died (out of memory, say) makes future's clean-up fail on its connection; future catches that, +# but the caught "invalid connection" still replaces the message geterrmessage() gives, which is +# what rpy2 reports to Python, so the tile's error was lost. The message is kept as it was, the way +# base R's try() sets it. +reset_plan <- function() { + msg <- geterrmessage() + tryCatch(future::plan(future::sequential), error = function(e) NULL) + if (!identical(geterrmessage(), msg)) .Internal(seterrmessage(msg)) + invisible(NULL) +} + +# The lines that report the tiles' warnings, one warning per tile in warned: each message once, with +# the number of tiles that gave it. Messages that differ only in their numbers are one line, with +# the range of each number that differs: "Interpolation of 1198 points failed ..." came once per +# tile with its own count, so a run of 2392 tiles printed a line for each, and now prints +# "Warning from 9 tile(s): Interpolation of 416 to 347838 points failed ...". Only +# whole numbers standing as words count, not those in file names such as n_526600_6235400.las. +warning_lines <- function(warned) { + num <- "(? 1) { + nums <- do.call(rbind, lapply(regmatches(w, gregexpr(num, w, perl = TRUE)), as.numeric)) + lo <- apply(nums, 2, min) + hi <- apply(nums, 2, max) + regmatches(line, gregexpr(num, line, perl = TRUE)) <- + list(ifelse(lo == hi, sprintf("%.0f", lo), sprintf("%.0f to %.0f", lo, hi))) + } + paste0("Warning from ", sum(template == t), " tile(s): ", line) + }, character(1), USE.NAMES = FALSE) +} + +# Evaluate a lidR catalog call such as classify_ground(ctg, ...) and stop with the error of a tile +# that failed. lidR stops at the first tile that fails (opt_stop_early), but unless it is the first +# tile it only reports the error as a message and returns the tiles done so far, so a run that +# stopped would look finished, or fail later on an empty result with an unrelated error. done and +# total count the tiles of all runs (see catalog_run), to name the tile among them. A tile that +# finishes with a warning shows as state ⚠, and lidR keeps its warning to itself, so the warnings +# are printed once each after the run, with the number of tiles that gave them. A worker that +# dies, as when the memory limit stops it in the middle of an allocation, reports no error of its +# own: the main R session only finds its connection gone ("invalid connection" or a FutureError), +# so that is explained instead. +stop_on_tile_error <- function(expr, done = 0, total = NULL) { + tile <- NULL + error <- character(0) + warned <- character(0) + on.exit(for (line in warning_lines(warned)) print(line)) + worker_lost <- function(e) { + inherits(e, "FutureError") || + grepl("invalid connection|error (reading from|writing to) connection|ignoring SIGPIPE", + conditionMessage(e)) + } + result <- withCallingHandlers( + tryCatch(expr, error = function(e) { + if (worker_lost(e)) { + stop("An R worker stopped while processing a tile (", trimws(conditionMessage(e)), + "), most likely because it ran out of memory, so the run stopped.", + "\nRun the tool again with skip_existing set to true to resume; close other programs ", + "or use fewer processes if it stops again.", call. = FALSE) + } + if (is.null(tile)) stop(e) else NULL + }), + warning = function(w) { + warned <<- c(warned, trimws(conditionMessage(w))) + invokeRestart("muffleWarning") + }, + message = function(m) { + text <- trimws(conditionMessage(m)) + failed <- regmatches(text, regexec("An error occurred when processing the chunk (\\d+)", text))[[1]] + if (length(failed)) tile <<- done + as.numeric(failed[2]) + else if (!is.null(tile)) error <<- c(error, text) + }) + if (!is.null(tile)) { + stop("Tile ", tile, if (!is.null(total)) paste0(" of ", total), " failed, so the run stopped: ", + paste(error, collapse = " "), + "\nRun the tool again with skip_existing set to true to resume from this tile.", call. = FALSE) + } + result +} + +# File name suffix of the ground classification outputs, from its parameters: the ground threshold +# and the cloth resolution to the nearest cm (no decimal point, which would read like an extension), +# and the cloth's rigidness, e.g. "_csfgnd_upto30cm_cloth150cm_hard" +csf_output_suffix <- function(class_threshold, cloth_resolution, rigidness) { + cm <- function(m) format(round(m * 100), scientific = FALSE, trim = TRUE) + stiffness <- c("soft", "standard", "hard")[as.integer(rigidness)] + if (is.na(stiffness)) stiffness <- paste0("rig", rigidness) + paste0("_csfgnd_upto", cm(class_threshold), "cm_cloth", cm(cloth_resolution), "cm_", stiffness) +} + +# tiling: see apply_tiling +classify_gnd_csf <- function(in_las_folder, out_folder, slope, class_threshold, cloth_resolution, rigidness,rprocesses,rest,free_mem,tiling = "auto", skip_existing = FALSE) { + library(lidR) + library(future) + library(RCSF) + + print("loading LiDAR Data") + on.exit(reset_plan(), add = TRUE) + + ctg <- read_catalog(in_las_folder, filter = '-drop_class 7 -drop_overlap') + cat(sprintf("R_PROGRESS:%d\n",round(0.2 * 100))) + flush.console() + + ctg <- apply_tiling(ctg, tiling, rprocesses, free_mem, + paste0(out_folder, "/{*}", csf_output_suffix(class_threshold, cloth_resolution, rigidness)), + buffer = 20, skip_existing = skip_existing) + opt_laz_compression(ctg) <- FALSE + ctg <- select_tiles(ctg, skip_existing, function(save) paste0(save, ".las")) + gnd_csf <- csf(slope, class_threshold = class_threshold, cloth_resolution = cloth_resolution, rigidness = rigidness, iterations = 500, time_step = 0.65) + print("Classify ground start....") + cat(sprintf("R_PROGRESS:%d\n",round(0.5 * 100))) + flush.console() + if (rest == TRUE) {suppressMessages({ + c_ctg <- catalog_run(ctg, function(ctg) classify_ground(ctg, gnd_csf))}) + } + else{c_ctg <- catalog_run(ctg, function(ctg) classify_ground(ctg, gnd_csf))} + cat(sprintf("R_PROGRESS:%d\n",round(0.99 * 100))) + flush.console() +} +############################################################################################ +# Whether any point of `class` lies in the densest cells of a file's .lax spatial index (built if +# missing). LASlib reads only the points of those cells, so the file is not scanned. +probe_class_in_index <- function(f, keep, n_cells = 3) { + ensure_lax(f) + cells <- lax_cells(f) + for (k in head(order(-cells$pts), n_cells)) { + inside <- sprintf("-inside %.2f %.2f %.2f %.2f", cells$xmin[k], cells$ymin[k], + cells$xmin[k] + cells$w[k], cells$ymin[k] + cells$h[k]) + las <- suppressWarnings(readLAS(f, select = "c", filter = paste(keep, inside))) + if (!is.empty(las)) return(TRUE) + } + FALSE +} + +# Whether the points of the folder are classified with `class`, as a one-element list (TRUE or +# FALSE). Tiles cut by density can hold a few points at the edge of the data or over water with +# none of the class although the data is classified (a 1051-point CSF output tile had no ground), +# and the tools read such a tile's class points from its neighbours' buffer, so the data counts +# as classified when the files without the class hold at most 1% of its points. Only points of +# `class` are read, as loading every point of a large file takes more memory than classifying it. +# Each file is first probed in a few cells of its spatial index and is read in full only if the +# probes find none, as reading the class points of every file scans all the data (~9 min for +# 122 CSF output tiles of 500 MB). The files are checked smallest first and the check stops once +# the files without the class pass 1% of the points: on unclassified data it reads a few small +# files in full, not every file (118 GB of LAZ, ~80 min on one core). +detect_class <- function(in_las_folder,class) +{ + library(lidR) + ctg <- read_catalog(in_las_folder) + keep <- paste("-keep_class", class) + # Index every file at once, as the tools that call this go on to index them all anyway, so + # the files are reported in one message instead of one large file at a time + ensure_lax(ctg@data$filename) + print(paste0("Checking that the LiDAR data has points of class ", class, "...")) + + has_class <- function(f) { + found <- tryCatch(probe_class_in_index(f, keep), error = function(e) { + print(paste0("Warning! Could not probe ", basename(f), " through a spatial index (", + conditionMessage(e), "); reading the whole file instead.")) + FALSE + }) + if (found) return(TRUE) + las <- suppressWarnings(readLAS(f, select = "c", filter = keep)) + !is.empty(las) + } + files <- ctg@data$filename + n_points <- as.numeric(ctg@data$Number.of.point.records) + allowed <- 0.01 * sum(n_points) + missing <- 0 + for (i in order(file.size(files))) { + if (has_class(files[i])) next + missing <- missing + 1 + allowed <- allowed - n_points[i] + if (allowed < 0) return(list(FALSE)) + } + if (missing > 0) + print(paste0("Note: ", missing, " small file(s) have no points of class ", class, + ", e.g. at the edge of the data or over water; their neighbours' are used.")) + list(TRUE) +} + +############################################################################################ +# Seismic line disturbance analysis +# Adapted from the analysis script of Chan, Dabros & McDermid (2026), "Microtopographic and +# Hydrological Response to Repeated Seismic Line Disturbance in a Boreal Fen of Northern +# Alberta, Canada", Forests 17, 489. Compares elevation, hummock cover, depth-to-water and +# surface water on seismic line segments against the adjacent matrix segments, by +# disturbance class. Uses only terra and ggplot2; the statistical tests are base R. +############################################################################################ + +# Brown-Forsythe test for equality of group means under unequal variances. +# Same statistic as onewaytests::bf.test, which the published analysis script uses. +bf_means_test <- function(y, g) { + ok <- !is.na(y) & !is.na(g) + y <- y[ok] + g <- droplevels(as.factor(g[ok])) + n <- tapply(y, g, length) + m <- tapply(y, g, mean) + v <- tapply(y, g, var) + N <- sum(n) + w <- (1 - n / N) * v + stat <- sum(n * (m - sum(n * m) / N)^2) / sum(w) + df1 <- nlevels(g) - 1 + df2 <- 1 / sum((w / sum(w))^2 / (n - 1)) + list(statistic = unname(stat), df1 = df1, df2 = unname(df2), + p.value = unname(pf(stat, df1, df2, lower.tail = FALSE))) +} + +# Pairwise tests between all class pairs, BH-adjusted. test_fun(y, g) returns a p-value. +pairwise_p <- function(y, g, test_fun) { + pairs <- t(combn(levels(g), 2)) + p <- apply(pairs, 1, function(pr) { + idx <- g %in% pr + test_fun(y[idx], droplevels(g[idx])) + }) + data.frame(group1 = pairs[, 1], group2 = pairs[, 2], p_value = p, + p_adjusted = p.adjust(p, method = "BH"), stringsAsFactors = FALSE) +} + +# Compact letter display: groups sharing a letter do not differ significantly. +# Insert-absorb algorithm; letters are assigned in class order. +group_letters <- function(levs, pairs, alpha, uppercase = TRUE) { + cols <- list(levs) + sig <- pairs[!is.na(pairs$p_adjusted) & pairs$p_adjusted < alpha, , drop = FALSE] + for (k in seq_len(nrow(sig))) { + a <- sig$group1[k] + b <- sig$group2[k] + split_cols <- list() + for (col in cols) { + if (a %in% col && b %in% col) { + split_cols <- c(split_cols, list(setdiff(col, a)), list(setdiff(col, b))) + } else { + split_cols <- c(split_cols, list(col)) + } + } + # Absorb columns contained in another column (or repeating an earlier one) + keep <- vapply(seq_along(split_cols), function(i) { + !any(vapply(seq_along(split_cols), function(j) { + j != i && all(split_cols[[i]] %in% split_cols[[j]]) && + (length(split_cols[[j]]) > length(split_cols[[i]]) || j < i) + }, logical(1))) + }, logical(1)) + cols <- split_cols[keep] + } + cols <- cols[order(vapply(cols, function(col) min(match(col, levs)), numeric(1)))] + abc <- (if (uppercase) LETTERS else letters)[seq_along(cols)] + vapply(levs, function(lv) { + paste(abc[vapply(cols, function(col) lv %in% col, logical(1))], collapse = "") + }, character(1)) +} + +seismic_line_analysis <- function(segments_path, segments_layer, dtm_path, microform_path, + dtw_path, out_folder, alpha) { + library(terra) + library(ggplot2) + + tables_dir <- file.path(out_folder, "tables") + plots_dir <- file.path(out_folder, "plots") + dir.create(tables_dir, showWarnings = FALSE, recursive = TRUE) + dir.create(plots_dir, showWarnings = FALSE, recursive = TRUE) + + print("Reading input data...") + segs <- if (nzchar(segments_layer)) vect(segments_path, layer = segments_layer) else vect(segments_path) + missing_fields <- setdiff(c("new_id", "note", "Class"), names(segs)) + if (length(missing_fields) > 0) { + stop("Segment layer is missing field(s): ", paste(missing_fields, collapse = ", "), + ". Expected new_id, note ('original' or 'matrix') and Class.") + } + bad_notes <- setdiff(unique(segs$note), c("original", "matrix")) + if (length(bad_notes) > 0) { + stop("Field 'note' must be 'original' (seismic line) or 'matrix'; found: ", + paste(bad_notes, collapse = ", ")) + } + + dtm <- rast(dtm_path) + microform <- rast(microform_path) + has_dtw <- nzchar(dtw_path) + dtw <- if (has_dtw) rast(dtw_path) else NULL + if (!same.crs(segs, dtm)) { + print("Projecting segments to the DTM's coordinate system...") + segs <- project(segs, dtm) + } + + # Class order and colours: the paper's three classes keep its order and palette + known_colours <- c("New Disturbance" = "#A3FF73", "Old Disturbance" = "#F64A7D", + "Re-disturbance" = "#E79800") + line_classes <- unique(segs$Class[segs$note == "original"]) + line_classes <- line_classes[!is.na(line_classes)] + class_levels <- if (all(line_classes %in% names(known_colours))) { + names(known_colours)[names(known_colours) %in% line_classes] + } else { + sort(line_classes) + } + if (length(class_levels) < 2) stop("At least two disturbance classes are needed in field 'Class'.") + class_colours <- setNames(grDevices::hcl.colors(length(class_levels), "Dark 3"), class_levels) + known <- intersect(class_levels, names(known_colours)) + class_colours[known] <- known_colours[known] + + # ---- Per-segment values (one terra::extract per raster) -------------------------------- + print(paste("Extracting raster values over", nrow(segs), "segments...")) + seg_values <- function(r) { + v <- terra::extract(r, segs) + split(v[[2]], factor(v$ID, levels = seq_len(nrow(segs)))) + } + seg_df <- data.frame(new_id = segs$new_id, note = segs$note, Class = segs$Class, + stringsAsFactors = FALSE) + + vals <- seg_values(dtm) + seg_df$dtm_mean <- vapply(vals, mean, numeric(1), na.rm = TRUE) + seg_df$dtm_median <- vapply(vals, median, numeric(1), na.rm = TRUE) + seg_df$dtm_sd <- vapply(vals, sd, numeric(1), na.rm = TRUE) + + mf_vals <- seg_values(microform) + count <- function(v, code) sum(v == code, na.rm = TRUE) + n_hum <- vapply(mf_vals, count, numeric(1), code = 1) + n_lawn <- vapply(mf_vals, count, numeric(1), code = 0) + n_hol <- vapply(mf_vals, count, numeric(1), code = -1) + n_cls <- n_hum + n_lawn + n_hol + seg_df$hummock_prop <- n_hum / n_cls + seg_df$lawn_prop <- n_lawn / n_cls + seg_df$hollow_prop <- n_hol / n_cls + + if (has_dtw) { + dtw_vals <- seg_values(dtw) + # DTW is summarised over ground cells only; DTW == 0 marks surface water + seg_df$dtw_mean <- vapply(dtw_vals, function(v) mean(v[v != 0], na.rm = TRUE), numeric(1)) + seg_df$dtw_median <- vapply(dtw_vals, function(v) median(v[v != 0], na.rm = TRUE), numeric(1)) + seg_df$water_prop <- vapply(dtw_vals, function(v) sum(v == 0, na.rm = TRUE) / length(v), numeric(1)) + } + write.csv(seg_df, file.path(tables_dir, "segment_values.csv"), row.names = FALSE) + + # ---- Line-vs-matrix deviations --------------------------------------------------------- + print("Computing line-vs-matrix deviations...") + line_df <- seg_df[seg_df$note == "original" & !is.na(seg_df$Class), ] + matrix_df <- seg_df[seg_df$note == "matrix", ] + deviation <- function(col) { + matrix_mean <- tapply(matrix_df[[col]], matrix_df$new_id, mean, na.rm = TRUE) + line_df[[col]] - unname(matrix_mean[as.character(line_df$new_id)]) + } + + metrics <- list( + dtm = list(col = "dtm_mean", ylab = bquote(Elev[Line] - Elev[Matrix] ~ "(m)")), + hummock = list(col = "hummock_prop", ylab = bquote(Hum_Prop[Line] - Hum_Prop[Matrix])) + ) + if (has_dtw) { + metrics$dtw <- list(col = "dtw_mean", ylab = bquote(DTW[Line] - DTW[Matrix] ~ "(m)")) + metrics$surfacewater <- list(col = "water_prop", ylab = bquote(SW_Prop[Line] - SW_Prop[Matrix])) + } + + dev_df <- line_df[, c("new_id", "Class")] + for (m in names(metrics)) dev_df[[paste0(m, "_deviation")]] <- deviation(metrics[[m]]$col) + write.csv(dev_df, file.path(tables_dir, "segment_deviations.csv"), row.names = FALSE) + + violin_theme <- theme( + axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1, colour = "black"), + axis.text.y = element_text(colour = "black"), + legend.position = "none", + panel.background = element_rect(fill = "gray99", colour = "black"), + panel.grid.major = element_line(linewidth = 0.1, colour = "gray70"), + panel.grid.minor = element_blank()) + + # ---- Summaries, tests and violin plots per metric -------------------------------------- + print("Running statistical tests...") + for (m in names(metrics)) { + y <- dev_df[[paste0(m, "_deviation")]] + ok <- is.finite(y) + y <- y[ok] + g <- factor(dev_df$Class[ok], levels = class_levels) + + kw <- kruskal.test(y, g) + wilcox_pairs <- pairwise_p(y, g, function(yy, gg) { + suppressWarnings(wilcox.test(yy ~ gg)$p.value) + }) + bf <- bf_means_test(y, g) + bf_pairs <- pairwise_p(y, g, function(yy, gg) bf_means_test(yy, gg)$p.value) + + mean_groups <- group_letters(class_levels, wilcox_pairs, alpha, uppercase = TRUE) + bf_groups <- group_letters(class_levels, bf_pairs, alpha, uppercase = FALSE) + + summary_df <- do.call(rbind, lapply(class_levels, function(cl) { + v <- y[g == cl] + data.frame(Class = cl, n = length(v), mean = mean(v), median = median(v), + min = min(v), max = max(v), + q25 = unname(quantile(v, 0.25)), q75 = unname(quantile(v, 0.75)), + sd = sd(v), var = var(v), + mean_group = mean_groups[[cl]], bf_group = bf_groups[[cl]], + stringsAsFactors = FALSE) + })) + summary_df <- cbind(attribute = m, summary_df) + write.csv(summary_df, file.path(tables_dir, paste0(m, "_deviation_summary.csv")), row.names = FALSE) + + write.csv(cbind(attribute = m, KW_stat = unname(kw$statistic), KW_df = unname(kw$parameter), + KW_pval = kw$p.value, + setNames(wilcox_pairs, c("Wilcoxon_group1", "Wilcoxon_group2", + "Wilcoxon_pval", "Wilcoxon_pval_adj"))), + file.path(tables_dir, paste0(m, "_kruskal_wilcoxon.csv")), row.names = FALSE) + write.csv(cbind(attribute = m, BF_stat = bf$statistic, BF_df1 = bf$df1, BF_df2 = bf$df2, + BF_pval = bf$p.value, + setNames(bf_pairs, c("BF_group1", "BF_group2", "BF_pval", "BF_pval_adj"))), + file.path(tables_dir, paste0(m, "_brown_forsythe.csv")), row.names = FALSE) + + print(paste0(m, " deviation by class:")) + print(summary_df[, c("Class", "n", "mean", "sd", "mean_group", "bf_group")], row.names = FALSE) + + plot_df <- data.frame(Class = g, value = y) + label_df <- data.frame(Class = factor(class_levels, levels = class_levels), + value = max(y) + 0.08 * diff(range(y)), + label = unname(mean_groups)) + violin <- ggplot(plot_df, aes(x = Class, y = value, fill = Class)) + + geom_violin() + + stat_summary(fun = mean, geom = "point", size = 2) + + geom_text(data = label_df, aes(label = label), fontface = "bold", size = 4) + + ylab(metrics[[m]]$ylab) + + xlab("Disturbance Class") + + scale_fill_manual(values = class_colours) + + violin_theme + ggsave(file.path(plots_dir, paste0(m, "_violin.png")), violin, + width = 3.2, height = 4, scale = 0.8, bg = "white") + } + + # ---- Class-level proportions and stacked bar plots ------------------------------------- + print("Creating class proportion plots...") + bar_theme <- theme( + axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1, colour = "black"), + axis.text.y = element_text(colour = "black"), + panel.background = element_rect(fill = "gray99", colour = "black"), + panel.grid.major = element_blank(), + panel.grid.minor = element_blank()) + + group_label <- ifelse(seg_df$note == "matrix", "Matrix", seg_df$Class) + bar_levels <- c("Matrix", class_levels) + + # Cell-level proportions per class, pooled over its segments + class_cells <- function(vals_list, cl) unlist(vals_list[which(group_label == cl)]) + mf_props <- do.call(rbind, lapply(bar_levels, function(cl) { + v <- class_cells(mf_vals, cl) + n <- length(v) + data.frame(Class = cl, Hummock = sum(v == 1, na.rm = TRUE) / n, + Lawn = sum(v == 0, na.rm = TRUE) / n, Hollow = sum(v == -1, na.rm = TRUE) / n) + })) + write.csv(mf_props, file.path(tables_dir, "class_microform_proportions.csv"), row.names = FALSE) + + mf_long <- data.frame( + Class = factor(rep(mf_props$Class, 3), levels = bar_levels), + Microform = factor(rep(c("Hummock", "Lawn", "Hollow"), each = nrow(mf_props)), + levels = c("Hummock", "Lawn", "Hollow")), + proportion = c(mf_props$Hummock, mf_props$Lawn, mf_props$Hollow)) + mf_bar <- ggplot(mf_long, aes(x = Class, y = proportion, fill = Microform)) + + geom_col(width = 0.7) + + geom_text(aes(label = round(proportion, 2), colour = Microform), + position = position_stack(vjust = 0.5), size = 3, fontface = "bold", + show.legend = FALSE) + + scale_fill_manual(values = c(Hummock = "#FFE924", Lawn = "#21918D", Hollow = "#440054")) + + scale_colour_manual(values = c(Hummock = "black", Lawn = "white", Hollow = "white")) + + ylab("Proportion") + xlab("Disturbance Class") + bar_theme + ggsave(file.path(plots_dir, "microform_barplot.png"), mf_bar, + width = 4.5, height = 4, scale = 0.8, bg = "white") + + if (has_dtw) { + sw_props <- do.call(rbind, lapply(bar_levels, function(cl) { + v <- class_cells(dtw_vals, cl) + water <- sum(v == 0, na.rm = TRUE) / length(v) + data.frame(Class = cl, Water = water, NonWater = 1 - water) + })) + write.csv(sw_props, file.path(tables_dir, "class_surfacewater_proportions.csv"), row.names = FALSE) + + sw_long <- data.frame( + Class = factor(rep(sw_props$Class, 2), levels = bar_levels), + Cover = factor(rep(c("Non-Water", "Water"), each = nrow(sw_props)), + levels = c("Non-Water", "Water")), + proportion = c(sw_props$NonWater, sw_props$Water)) + sw_bar <- ggplot(sw_long, aes(x = Class, y = proportion, fill = Cover)) + + geom_col(width = 0.7) + + geom_text(aes(label = round(proportion, 2)), position = position_stack(vjust = 0.5), + size = 3, fontface = "bold") + + scale_fill_manual(values = c("Non-Water" = "grey77", Water = "cornflowerblue"), + name = "Cover Type") + + ylab("Proportion") + xlab("Disturbance Class") + bar_theme + ggsave(file.path(plots_dir, "surfacewater_barplot.png"), sw_bar, + width = 4.5, height = 4, scale = 0.8, bg = "white") + } + + print(paste("Tables saved to:", tables_dir)) + print(paste("Plots saved to:", plots_dir)) +} + +############################################################################################ +# Surface water mapping +# Follows the surface water classification of Chan, Dabros & McDermid (2026), Forests 17, 489 +# (section 2.4): random training points in labelled polygons, an rpart decision tree on the +# orthomosaic's RGB values, a canopy height mask, and removal of small water patches. +############################################################################################ +# Make a temporary folder inside out_folder and send every temporary write there instead of the +# system temp drive (heavy temp traffic there gets R killed by antivirus software): terra's temp +# files in this session, and TMPDIR/TMP/TEMP and GDAL's CPL_TMPDIR, which R worker processes +# started afterwards inherit. Returns the folder; call restore_temp_dir(it) when done, which +# restores the options and deletes the folder. +use_temp_dir <- function(out_folder, prefix) { + dir <- normalizePath(tempfile(prefix, tmpdir = out_folder), winslash = "/", mustWork = FALSE) + dir.create(dir, recursive = TRUE) + vars <- c("TMPDIR", "TMP", "TEMP", "CPL_TMPDIR") + attr(dir, "env") <- Sys.getenv(vars, unset = NA) + attr(dir, "terra_tempdir") <- terra::terraOptions(print = FALSE)$tempdir + do.call(Sys.setenv, as.list(setNames(rep(dir, length(vars)), vars))) + terra::terraOptions(tempdir = dir) + dir +} + +restore_temp_dir <- function(dir) { + terra::terraOptions(tempdir = attr(dir, "terra_tempdir")) + env <- attr(dir, "env") + for (v in names(env)) { + if (is.na(env[[v]])) Sys.unsetenv(v) else do.call(Sys.setenv, setNames(list(env[[v]]), v)) + } + gc() # release raster file handles so Windows lets the files be deleted + unlink(dir, recursive = TRUE) + if (dir.exists(dir)) print(paste("Warning! Could not delete the temporary folder:", dir)) +} + +# Run fun(i, ...) with the arguments in args for tiles 1..n_tiles on `workers` R processes (in +# this session if 1) and return the results in tile order. The tiles run in batches (a multiple +# of the worker count, about 20 batches), with progress printed after each one in the GUI's +# format: a quoted PROGRESS_LABEL line and a %value line. +run_tiles <- function(fun, args, n_tiles, workers, label) { + if (workers > 1) { + # The workers start with one OpenMP thread, as their terra and gstat work uses none, and + # R's BLAS (Intel MKL) commits ~0.2 GB per OpenMP thread, one per core by default, when + # terra loads (see start_workers) + old <- Sys.getenv("OMP_NUM_THREADS", unset = NA) + Sys.setenv(OMP_NUM_THREADS = 1) + cl <- parallel::makeCluster(workers) + if (is.na(old)) Sys.unsetenv("OMP_NUM_THREADS") else Sys.setenv(OMP_NUM_THREADS = old) + on.exit(parallel::stopCluster(cl)) + parallel::clusterCall(cl, function(lib) .libPaths(lib), .libPaths()) + } + batch <- workers * ceiling(n_tiles / workers / 20) + results <- vector("list", n_tiles) + for (start in seq(1, n_tiles, by = batch)) { + ids <- start:min(start + batch - 1, n_tiles) + results[ids] <- if (workers > 1) { + do.call(parallel::parLapplyLB, c(list(cl = cl, X = ids, fun = fun), args)) + } else { + do.call(lapply, c(list(X = ids, FUN = fun), args)) + } + cat(sprintf(' "PROGRESS_LABEL %s %d of %d" \n', label, max(ids), n_tiles)) + cat(sprintf(" %%%s \n", round(100 * max(ids) / n_tiles, 1))) + flush.console() + } + results +} + +# Classify cells (rows of an n x 3 red, green, blue matrix) with the decision tree's lookup table: +# 1 water, 0 other, NA where a band is NA. See "Lookup table" in surface_water_map. +water_lut_lookup <- function(rgb, lut, breaks) { + idx <- integer(nrow(rgb)) + stride <- 1L + for (b in 1:3) { + idx <- idx + stride * findInterval(rgb[, b], breaks[[b]]) + stride <- stride * (length(breaks[[b]]) + 1L) + } + lut[idx + 1L] +} + +# Classify one tile of the orthomosaic (water 1, other 0), mask it with the CHM and remove small +# water patches, then write the tile without its buffer. Runs in a worker process, so it opens +# its rasters from file paths and gets every function it needs as an argument. The tile is held +# as plain vectors, so its memory use is set by tile_size. +surface_water_tile <- function(i, tiles, ortho_path, lut, breaks, lookup, tall_path, + min_patch_area, tile_size, buffer, tile_dir, memfrac) { + library(terra) + # Share the memory between workers and keep terra's temporary files in tile_dir, which + # surface_water_map removes; restore the options for the calling session afterwards + opts <- terraOptions(print = FALSE) + on.exit(terraOptions(memfrac = opts$memfrac, tempdir = opts$tempdir, progress = opts$progress)) + terraOptions(memfrac = memfrac, tempdir = tile_dir, progress = 0) + + ortho <- rast(ortho_path, lyrs = 1:3) + rx <- res(ortho)[1] + ry <- res(ortho)[2] + grid_of <- function(r0, r1, c0, c1) { + rast(nrows = r1 - r0 + 1, ncols = c1 - c0 + 1, crs = crs(ortho), + extent = ext(xFromCol(ortho, c0) - rx / 2, xFromCol(ortho, c1) + rx / 2, + yFromRow(ortho, r1) - ry / 2, yFromRow(ortho, r0) + ry / 2)) + } + r0 <- tiles$row[i] + c0 <- tiles$col[i] + r1 <- min(r0 + tile_size - 1, nrow(ortho)) + c1 <- min(c0 + tile_size - 1, ncol(ortho)) + br0 <- max(1, r0 - buffer) + br1 <- min(nrow(ortho), r1 + buffer) + bc0 <- max(1, c0 - buffer) + bc1 <- min(ncol(ortho), c1 + buffer) + grid <- grid_of(br0, br1, bc0, bc1) + + # Read only the buffered window of the orthomosaic; values come row by row + readStart(ortho) + rgb <- readValues(ortho, row = br0, nrows = br1 - br0 + 1, col = bc0, ncols = bc1 - bc0 + 1, + mat = TRUE) + readStop(ortho) + water <- lookup(rgb, lut, breaks) + rm(rgb) + + # Cells under canopy taller than max_canopy_height cannot be water; tall_path is the canopy + # mask prepared once by surface_water_map (this also sets cells without orthomosaic values + # to 0, so the step is skipped only for all-dry tiles) + if (nzchar(tall_path) && any(is.na(water) | water == 1L)) { + tall <- values(resample(rast(tall_path), grid, method = "near"), mat = FALSE) + water[!is.na(tall) & tall == 1] <- 0L + rm(tall) + } + + # Remove water patches smaller than min_patch_area (m2) + if (min_patch_area > 0 && any(water == 1L, na.rm = TRUE)) { + patch_ids <- values(patches(setValues(grid, water), directions = 8, zeroAsNA = TRUE), + mat = FALSE) + in_patch <- which(!is.na(patch_ids)) + sizes <- tabulate(patch_ids[in_patch]) + small <- in_patch[sizes[patch_ids[in_patch]] * rx * ry < min_patch_area] + water[small] <- 0L + rm(patch_ids, in_patch, small) + } + + # Drop the buffer: keep the tile's own rows and columns + keep_rows <- (r0 - br0) + seq_len(r1 - r0 + 1) + keep_cols <- (c0 - bc0) + seq_len(c1 - c0 + 1) + keep <- as.vector(outer(keep_cols, (keep_rows - 1) * (bc1 - bc0 + 1), "+")) + water <- water[keep] + + out <- file.path(tile_dir, sprintf("tile_%05d.tif", i)) + writeRaster(setValues(grid_of(r0, r1, c0, c1), water), out, datatype = "INT1U", overwrite = TRUE) + list(file = out, water = sum(water == 1L, na.rm = TRUE), valid = sum(!is.na(water))) +} + +surface_water_map <- function(ortho_path, training_path, training_layer, chm_path, + max_canopy_height, min_patch_area, points_per_polygon, seed, + out_folder, tile_size = 2000, rprocesses = 1) { + library(terra) + library(rpart) + + dir.create(out_folder, showWarnings = FALSE, recursive = TRUE) + tile_dir <- use_temp_dir(out_folder, "surface_water_temp_") + on.exit(restore_temp_dir(tile_dir), add = TRUE) + + print("Reading input data...") + ortho <- rast(ortho_path) + if (nlyr(ortho) < 3) stop("The orthomosaic needs at least three bands (red, green, blue).") + ortho <- ortho[[1:3]] + names(ortho) <- c("red", "green", "blue") + + train <- if (nzchar(training_layer)) vect(training_path, layer = training_layer) else vect(training_path) + if (!"class" %in% names(train)) { + stop("Training polygons need a 'class' field, with 'water' for surface water polygons.") + } + train$class <- tolower(trimws(train$class)) + if (!"water" %in% train$class) stop("No training polygons have class 'water'.") + if (length(unique(train$class)) < 2) stop("Training polygons need at least one class besides 'water'.") + if (!same.crs(train, ortho)) train <- project(train, ortho) + + # ---- Training points: random points inside each polygon -------------------------------- + set.seed(seed) + pts <- do.call(rbind, lapply(seq_len(nrow(train)), function(i) { + p <- spatSample(train[i], points_per_polygon, method = "random") + values(p) <- data.frame(class = rep(train$class[i], nrow(p))) + p + })) + rgb_vals <- terra::extract(ortho, pts, ID = FALSE) + samples <- data.frame(class = factor(pts$class), rgb_vals) + samples <- samples[complete.cases(samples), ] + print(paste("Training points per class:", + paste(names(table(samples$class)), table(samples$class), sep = " = ", collapse = ", "))) + + # ---- Decision tree and 5-fold cross-validation ------------------------------------------ + model <- rpart(class ~ red + green + blue, data = samples, method = "class") + if (nrow(model$frame) == 1) { + print(paste0("Warning! The decision tree has no splits, so every cell gets the same class. ", + "Add training polygons or raise points_per_polygon (rpart needs at least ", + "20 points to split).")) + } + + folds <- sample(rep(1:5, length.out = nrow(samples))) + cv_pred <- factor(rep(NA, nrow(samples)), levels = levels(samples$class)) + for (k in 1:5) { + fold_model <- rpart(class ~ red + green + blue, data = samples[folds != k, ], method = "class") + cv_pred[folds == k] <- predict(fold_model, samples[folds == k, ], type = "class") + } + accuracy <- mean(cv_pred == samples$class) + print(paste("5-fold cross-validation overall accuracy:", round(100 * accuracy, 1), "percent")) + + confusion <- as.data.frame.matrix(table(observed = samples$class, predicted = cv_pred)) + write.csv(cbind(observed = rownames(confusion), confusion), + file.path(out_folder, "cv_confusion_matrix.csv"), row.names = FALSE) + write.csv(data.frame(n_points = nrow(samples), cv_overall_accuracy = accuracy), + file.path(out_folder, "cv_accuracy.csv"), row.names = FALSE) + writeVector(pts, file.path(out_folder, "training_points.gpkg"), overwrite = TRUE) + capture.output(print(model), file = file.path(out_folder, "decision_tree.txt")) + + # ---- Lookup table for the decision tree -------------------------------------------------- + # The tree only compares each band with its split values, so cells whose bands fall between + # the same split values always get the same class. Classifying one value per interval gives a + # small lookup table, and findInterval then classifies millions of cells far faster than + # predict() on each cell, with the same result. + bands <- c("red", "green", "blue") + split_vals <- if (is.null(model$splits)) numeric(0) else model$splits[, "index"] + split_vars <- if (is.null(model$splits)) character(0) else rownames(model$splits) + breaks <- lapply(bands, function(b) sort(unique(split_vals[split_vars == b]))) + reps <- lapply(breaks, function(b) if (length(b)) c(b[1] - 1, b) else 0) + names(reps) <- bands + lut <- as.integer(predict(model, do.call(expand.grid, reps), type = "class") == "water") + + check <- rbind(samples[, bands], spatSample(ortho, 10000, method = "regular", na.rm = TRUE)) + if (!identical(water_lut_lookup(as.matrix(check), lut, breaks), + as.integer(predict(model, check, type = "class") == "water"))) { + stop("The decision tree lookup table disagrees with predict(); please report this.") + } + + # ---- Classify the orthomosaic in tiles --------------------------------------------------- + # A water patch smaller than min_patch_area has fewer than min_patch_area / cell_area cells, + # so it spans fewer rows and columns than that. With a buffer this wide, every small patch + # touching a tile lies whole inside the buffered tile, and every patch cut by the buffer edge + # keeps more cells than the limit, so per-tile patch removal matches a whole-raster run. + cell_area <- prod(res(ortho)) + buffer <- if (min_patch_area > 0) ceiling(sqrt(min_patch_area / cell_area)) else 0 + tile_size <- max(1, as.integer(tile_size)) + tiles <- expand.grid(row = seq(1, nrow(ortho), by = tile_size), + col = seq(1, ncol(ortho), by = tile_size)) + workers <- max(1, min(as.integer(rprocesses), nrow(tiles))) + if (buffer > tile_size) { + print(paste0("Warning! Each tile reads a ", buffer, "-cell buffer for patch removal, more than ", + "the tile size of ", tile_size, " cells; a larger tile size reads less overlap.")) + } + print(paste0("Classifying the orthomosaic in ", nrow(tiles), " tile(s) of ", tile_size, " x ", + tile_size, " cells with ", workers, " worker(s)...")) + if (nzchar(chm_path)) print(paste("Masking cells with canopy height above", max_canopy_height, "m...")) + if (min_patch_area > 0) print(paste("Removing water patches smaller than", min_patch_area, "m2...")) + + # Prepare the canopy mask once for all tiles: project the CHM to the orthomosaic's CRS if + # needed, crop it, and threshold it at its own resolution into a small 0/1 raster (1 = canopy + # taller than max_canopy_height). Each tile then only resamples this mask to its grid. + tall_path <- "" + if (nzchar(chm_path)) { + chm <- rast(chm_path, lyrs = 1) + if (!same.crs(chm, ortho)) chm <- project(chm, crs(ortho), method = "near") + if (is.null(intersect(ext(chm), ext(ortho)))) { + print("Warning! The CHM does not overlap the orthomosaic; no canopy mask is applied.") + } else { + chm <- crop(chm, ortho, snap = "out") + tall_path <- file.path(tile_dir, "tall_canopy.tif") + writeRaster(!is.na(chm) & chm > max_canopy_height, tall_path, datatype = "INT1U", + gdal = c("COMPRESS=DEFLATE", "TILED=YES")) + } + rm(chm) + } + + tile_args <- list(tiles = tiles, ortho_path = ortho_path, lut = lut, breaks = breaks, + lookup = water_lut_lookup, tall_path = tall_path, min_patch_area = min_patch_area, + tile_size = tile_size, buffer = buffer, tile_dir = tile_dir, + memfrac = 0.6 / workers) + results <- run_tiles(surface_water_tile, tile_args, nrow(tiles), workers, "Surface water tiles") + + out_file <- file.path(out_folder, "surface_water.tif") + writeRaster(vrt(vapply(results, `[[`, "", "file")), out_file, datatype = "INT1U", + overwrite = TRUE, names = "surface_water", + gdal = c("COMPRESS=DEFLATE", "TILED=YES", "BIGTIFF=IF_SAFER")) + water_cover <- sum(vapply(results, `[[`, 0, "water")) / max(1, sum(vapply(results, `[[`, 0, "valid"))) + # No "%" sign in messages: the GUI reads any "%" as a progress value + print(paste("Surface water covers", round(100 * water_cover, 1), "percent of the classified area")) + print(paste("Surface water raster saved to:", out_file)) +} + +############################################################################################ +# Water table and depth-to-water (DTW) +# Follows Chan, Dabros & McDermid (2026), Forests 17, 489 (section 2.4), after Rahman et al. +# (2017): the DTM is masked to surface water, the minimum water elevation in each grid cell is +# kriged into a water table surface, and DTW = DTM - water table (0 on surface water). +############################################################################################ +# Krige the water table at the cell centres of one tile of the kriging grid and write the tile. +# Each prediction uses only the nmax nearest water points, so tiles give the same values as +# kriging the whole grid at once. Cells marked 1 in skip_path (if given) are left NA. Runs in a +# worker process, so it opens its rasters from file paths and loads its own packages. +dtw_tile <- function(i, tiles, target_path, skip_path, obs, fitted_vgm, nmax, tile_size, tile_dir, + memfrac) { + library(terra) + library(gstat) + opts <- terraOptions(print = FALSE) + on.exit(terraOptions(memfrac = opts$memfrac, tempdir = opts$tempdir, progress = opts$progress)) + terraOptions(memfrac = memfrac, tempdir = tile_dir, progress = 0) + + target <- rast(target_path, lyrs = 1) + r0 <- tiles$row[i] + c0 <- tiles$col[i] + r1 <- min(r0 + tile_size - 1, nrow(target)) + c1 <- min(c0 + tile_size - 1, ncol(target)) + nr <- r1 - r0 + 1 + nc <- c1 - c0 + 1 + rx <- res(target)[1] + ry <- res(target)[2] + grid <- rast(nrows = nr, ncols = nc, crs = crs(target), + extent = ext(xFromCol(target, c0) - rx / 2, xFromCol(target, c1) + rx / 2, + yFromRow(target, r1) - ry / 2, yFromRow(target, r0) + ry / 2)) + + # Cell centres, row by row + cells <- data.frame(x = rep(xFromCol(target, c0:c1), times = nr), + y = rep(yFromRow(target, r0:r1), each = nc)) + krige <- rep(TRUE, nrow(cells)) + if (nzchar(skip_path)) { + skip <- rast(skip_path) + readStart(skip) + krige <- readValues(skip, row = r0, nrows = nr, col = c0, ncols = nc) == 0 + readStop(skip) + } + water_table <- rep(NA_real_, nrow(cells)) + if (any(krige)) { + model <- gstat(formula = elev ~ 1, locations = ~x + y, data = obs, model = fitted_vgm, nmax = nmax) + water_table[krige] <- predict(model, cells[krige, ], debug.level = 0)$var1.pred + } + + out <- file.path(tile_dir, sprintf("water_table_%05d.tif", i)) + writeRaster(setValues(grid, water_table), out, datatype = "FLT8S", overwrite = TRUE) + out +} + +dtw_map <- function(dtm_path, water_path, mask_path, mask_layer, grid_size, nmax, vgm_model, + kriging_res, out_folder, tile_size = 1000, rprocesses = 1) { + library(terra) + library(gstat) + + dir.create(out_folder, showWarnings = FALSE, recursive = TRUE) + tile_dir <- use_temp_dir(out_folder, "dtw_temp_") + on.exit(restore_temp_dir(tile_dir), add = TRUE) + + print("Reading input data...") + dtm <- rast(dtm_path)[[1]] + names(dtm) <- "dtm" + if (isTRUE(is.lonlat(dtm))) { + stop("The DTM has a geographic (longitude/latitude) CRS, but the grid size and kriging cell ", + "size are in metres. Project the DTM to a projected CRS first.") + } + water <- rast(water_path)[[1]] + # Put the surface water raster on the DTM grid; "mode" keeps the majority class when the + # water raster is finer than the DTM (e.g. a 2 cm orthomosaic classification) + if (!compareGeom(water, dtm, stopOnError = FALSE)) { + method <- if (res(water)[1] < res(dtm)[1]) "mode" else "near" + print(paste0("Resampling the surface water raster to the DTM grid (", method, ")...")) + water <- if (same.crs(water, dtm)) resample(water, dtm, method = method) else project(water, dtm, method = method) + } + is_water <- !is.na(water) & water == 1 + + # Exclusion polygons, rasterized once on the DTM grid (1 = excluded); touches = TRUE matches + # how mask() treats polygons + excluded <- NULL + if (nzchar(mask_path)) { + exclude <- if (nzchar(mask_layer)) vect(mask_path, layer = mask_layer) else vect(mask_path) + if (!same.crs(exclude, dtm)) exclude <- project(exclude, dtm) + print(paste("Excluding", nrow(exclude), "mask polygon(s) from the analysis...")) + excluded <- rasterize(exclude, dtm, field = 1, background = 0, touches = TRUE) + } + + # ---- Water elevations: minimum per grid cell, at the grid cell centre --------------------- + water_elev <- mask(dtm, is_water, maskvalues = FALSE) + if (!is.null(excluded)) water_elev <- mask(water_elev, excluded, maskvalues = 1) + fact <- max(1, round(grid_size / res(dtm)[1])) + grid_min <- aggregate(water_elev, fact = fact, fun = "min", na.rm = TRUE) + pts <- as.points(grid_min, na.rm = TRUE) + names(pts) <- "elev" + obs <- data.frame(crds(pts), elev = pts$elev) + print(paste("Water elevation points:", nrow(obs), "grid cells of", fact * res(dtm)[1], "m contain surface water")) + if (nrow(obs) < 10) stop("Too few grid cells contain surface water to krige a water table (need at least 10).") + writeVector(pts, file.path(out_folder, "water_points.gpkg"), overwrite = TRUE) + + # ---- Variogram and ordinary kriging ------------------------------------------------------- + print(paste("Fitting the", vgm_model, "variogram...")) + sample_vgm <- variogram(elev ~ 1, locations = ~x + y, data = obs) + fitted_vgm <- tryCatch( + fit.variogram(sample_vgm, vgm(vgm_model)), + error = function(e) stop("Variogram fit failed for model '", vgm_model, "': ", conditionMessage(e), + ". Try another variogram model.")) + if (isTRUE(attr(fitted_vgm, "singular"))) { + print("Warning! The variogram fit is singular; check the fitted parameters or try another model.") + } + print(fitted_vgm) + write.csv(as.data.frame(fitted_vgm)[, c("model", "psill", "range", "kappa")], + file.path(out_folder, "variogram_model.csv"), row.names = FALSE) + + png(file.path(out_folder, "variogram.png"), width = 1200, height = 900, res = 200) + plot(sample_vgm$dist, sample_vgm$gamma, pch = 19, xlab = "Distance (m)", ylab = "Semivariance", + main = paste("Water elevation variogram:", vgm_model), ylim = c(0, max(sample_vgm$gamma) * 1.1)) + lines(variogramLine(fitted_vgm, maxdist = max(sample_vgm$dist)), col = "blue", lwd = 2) + dev.off() + + model <- gstat(formula = elev ~ 1, locations = ~x + y, data = obs, model = fitted_vgm, nmax = nmax) + + # Leave-one-out cross-validation of the water table at the water points + cv <- gstat.cv(model, nfold = nrow(obs), verbose = FALSE, debug.level = 0) + cv_stats <- data.frame(n_points = nrow(obs), mae = mean(abs(cv$residual)), + rmse = sqrt(mean(cv$residual^2))) + write.csv(cv_stats, file.path(out_folder, "water_table_cv.csv"), row.names = FALSE) + print(paste0("Water table leave-one-out cross-validation: MAE = ", round(cv_stats$mae, 3), + " m, RMSE = ", round(cv_stats$rmse, 3), " m")) + + # ---- Krige the water table in parallel tiles --------------------------------------------- + # On the DTM grid, cells without a DTM value or inside the exclusion polygons end up NA, so + # they are not kriged. A coarser kriging grid is kriged in full, because the bilinear + # resampling to the DTM also reads the cells next to them. + on_dtm_grid <- !(kriging_res > res(dtm)[1]) + if (on_dtm_grid) { + target <- dtm + target_path <- dtm_path + skip <- is.na(dtm) + if (!is.null(excluded)) skip <- skip | excluded == 1 + skip_path <- file.path(tile_dir, "skip.tif") + writeRaster(skip, skip_path, datatype = "INT1U") + print(paste("Kriging on the DTM grid (", ncell(dtm), "cells)...")) + } else { + target <- aggregate(dtm, fact = round(kriging_res / res(dtm)[1]), fun = "mean", na.rm = TRUE) + target_path <- file.path(tile_dir, "kriging_grid.tif") + target <- writeRaster(target, target_path) + skip_path <- "" + print(paste("Kriging on a", res(target)[1], "m grid, then resampling bilinearly to the DTM...")) + } + + tile_size <- max(1, as.integer(tile_size)) + tiles <- expand.grid(row = seq(1, nrow(target), by = tile_size), + col = seq(1, ncol(target), by = tile_size)) + workers <- max(1, min(as.integer(rprocesses), nrow(tiles))) + print(paste0("Kriging in ", nrow(tiles), " tile(s) of ", tile_size, " x ", tile_size, + " cells with ", workers, " worker(s)...")) + tile_files <- run_tiles(dtw_tile, list(tiles = tiles, target_path = target_path, + skip_path = skip_path, obs = obs, fitted_vgm = fitted_vgm, + nmax = nmax, tile_size = tile_size, tile_dir = tile_dir, + memfrac = 0.6 / workers), + nrow(tiles), workers, "Kriging tiles") + water_table <- vrt(unlist(tile_files)) + ext(water_table) <- ext(target) # drop rounding differences between the tile extents + if (!on_dtm_grid) water_table <- resample(water_table, dtm, method = "bilinear") + + # ---- Outputs, one pass each ---------------------------------------------------------------- + # Water table: NA where the DTM is NA or excluded. DTW = DTM - water table, 0 on surface water + # and where the water table is above ground, NA where excluded. + layers <- c(dtm, water_table, is_water) + if (!is.null(excluded)) layers <- c(layers, excluded) + water_table_values <- function(v) { + wt <- v[, 2] + wt[is.na(v[, 1])] <- NA + if (ncol(v) > 3) wt[v[, 4] == 1] <- NA + wt + } + dtw_values <- function(v) { + wt <- v[, 2] + wt[is.na(v[, 1])] <- NA + dtw <- v[, 1] - wt + dtw[!is.na(dtw) & dtw < 0] <- 0 + dtw[v[, 3] == 1] <- 0 + if (ncol(v) > 3) dtw[v[, 4] == 1] <- NA + dtw + } + gdal <- c("COMPRESS=DEFLATE", "PREDICTOR=3", "TILED=YES", "BIGTIFF=IF_SAFER") + app(layers, water_table_values, filename = file.path(out_folder, "water_table.tif"), + overwrite = TRUE, wopt = list(names = "water_table", datatype = "FLT4S", gdal = gdal)) + dtw <- app(layers, dtw_values, filename = file.path(out_folder, "dtw.tif"), + overwrite = TRUE, wopt = list(names = "dtw", datatype = "FLT4S", gdal = gdal)) + stats <- global(dtw, c("mean", "max"), na.rm = TRUE) + print(paste0("DTW: mean = ", round(stats[1, "mean"], 3), " m, max = ", round(stats[1, "max"], 3), " m")) + print(paste("Water table and DTW rasters saved to:", out_folder)) +} +############################################################################################################### +# tiling: see apply_tiling +normalized_lidar_knnidw <- function(in_las_folder, out_folder, rprocesses, free_mem, tiling = "auto", skip_existing = FALSE) { + + library(lidR) + library(future) + + on.exit(reset_plan(), add = TRUE) + + #read Las file and drop any noise from the point cloud + ctg <- read_catalog(in_las_folder, filter = '-drop_class 7') + cat(sprintf("R_PROGRESS:%d\n",20)) + flush.console() + ctg <- apply_tiling(ctg, tiling, rprocesses, free_mem, paste0(out_folder, "/n_{*}"), skip_existing = skip_existing) + ctg <- select_tiles(ctg, skip_existing, function(save) paste0(save, ".las")) + print("Normalize lidar data...") + opt_progress(ctg) <- TRUE + cat(sprintf("R_PROGRESS:%d\n",50)) + flush.console() + n_las <- catalog_run(ctg, function(ctg) normalize_tiles(ctg, knnidw())) + cat(sprintf("R_PROGRESS:%d\n",round(0.99 * 100))) + flush.console() + print("Normalize lidar data...Done") + # reset R multisession back to default + plan(sequential) +} + +########################################################################## +# tiling: see apply_tiling +normalized_lidar_tin <- function(in_las_folder, out_folder, rprocesses, free_mem, tiling = "auto", skip_existing = FALSE) { + + library(lidR) + library(future) + + on.exit(reset_plan(), add = TRUE) + + #read Las file and drop any noise from the point cloud + ctg <- read_catalog(in_las_folder, filter = '-drop_class 7') + cat(sprintf("R_PROGRESS:%d\n",round(0.2 * 100))) + flush.console() + ctg <- apply_tiling(ctg, tiling, rprocesses, free_mem, paste0(out_folder, "/n_{*}"), skip_existing = skip_existing, + bytes_per_point = function(ctg) tin_bytes_per_point(ctg)) + ctg <- select_tiles(ctg, skip_existing, function(save) paste0(save, ".las")) + print("Normalize lidar data...") + opt_progress(ctg) <- TRUE + cat(sprintf("R_PROGRESS:%d\n",round(0.5 * 100))) + flush.console() + n_las <- catalog_run(ctg, function(ctg) normalize_tiles(ctg, tin())) + # reset R multisession back to default + cat(sprintf("R_PROGRESS:%d\n",round(0.99 * 100))) + flush.console() + print("Normalize lidar data...Done") + plan(sequential) +} + +########################################################################## +# tiling: see apply_tiling +normalized_lidar_kriging <- function(in_las_folder, out_folder, rprocesses, free_mem, tiling = "auto", skip_existing = FALSE) { + + library(lidR) + library(future) + + on.exit(reset_plan(), add = TRUE) + cat(sprintf("R_PROGRESS:%d\n",round(0.2 * 100))) + flush.console() + #read Las file and drop any noise from the point cloud + ctg <- read_catalog(in_las_folder, filter = '-drop_class 7') + cat(sprintf("R_PROGRESS:%d\n",round(0.5 * 100))) + flush.console() + ctg <- apply_tiling(ctg, tiling, rprocesses, free_mem, paste0(out_folder, "/n_{*}"), skip_existing = skip_existing) + ctg <- select_tiles(ctg, skip_existing, function(save) paste0(save, ".las")) + print("Normalize lidar data...") + opt_progress(ctg) <- TRUE + n_las <- catalog_run(ctg, function(ctg) normalize_tiles(ctg, kriging())) + cat(sprintf("R_PROGRESS:%d\n",round(0.99 * 100))) + flush.console() + print("Normalize lidar data...Done") + # reset R multisession back to default + plan(sequential) +} diff --git a/beratools/modules/pc2products/rpy_CHM_DSM_by.py b/beratools/modules/pc2products/rpy_CHM_DSM_by.py new file mode 100644 index 0000000..671434c --- /dev/null +++ b/beratools/modules/pc2products/rpy_CHM_DSM_by.py @@ -0,0 +1,90 @@ +import os +import time + +from beratools.modules.pc2products.r_interface import configure_r_environment +from beratools.utility.tool_args import compose_tool_kwargs + +configure_r_environment() +import beratools.modules.pc2products.r_common as r_common # noqa: E402 + + +def rpy_chm_dsm_by(in_las_folder, + out_folder, + style, + cell_size=0.0, + processes=0, + tiling="auto", + skip_existing:bool=False, + **kwargs,): + + tiling = r_common.check_tiling(tiling) + r_common.check_las_files_existence(in_las_folder) + r_common.check_las_out_folder_existence(out_folder) + packages = ['lidR','gstat', 'rlas', 'future', 'terra', 'sp','raster','stars','sf'] + try: + r_common.check_r_packages_installation(packages, r_common.OPTIONAL_WORKER_PACKAGES) + except Exception as e: + print(f"Failed to verify R packages: {e}") + raise + if style not in ["tin", "pitfree"]: + print("[Warning!] invalid algorithm, default algorithm will be used.") + style = "tin" + + if not os.path.exists(out_folder): + print("[Warning!] Cannot locate output folder, It will be created.") + os.makedirs(out_folder) + + print("Checking input parameters....Done") + + # assign R script file to local variable + Beratools_R_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'r_scripts_collection.r') + # Defining the R script and loading the instance in Python + r_common.r['source'](Beratools_R_script) + + if cell_size == 0.0: + print("[INFO] No cell size given, the cell size will be estimated from the LiDAR data.") + from rpy2.rinterface_lib import callbacks + old_print = callbacks.consolewrite_print + old_warn = callbacks.consolewrite_warnerror + try: + callbacks.consolewrite_print = lambda x: None + callbacks.consolewrite_warnerror = lambda x: None + find_cellsize_algorithm = r_common.robjects.globalenv['pd2cellsize'] + results = find_cellsize_algorithm(in_las_folder) + finally: + callbacks.consolewrite_print = old_print + callbacks.consolewrite_warnerror = old_warn + cell_size=float(results.rx2("cell_size")[0]) + + is_normalized = bool(r_common.robjects.globalenv['detect_normalized'](in_las_folder)[0]) + if is_normalized: + print("[INFO]: LiDAR data is normalized, the output will be CHM.") + else: + print("[INFO]: LiDAR data is not normalized, the output will be DSM.") + + # Loading the function defined in R script. + if style == "tin": + r_chm_dsm_by_algorithm = r_common.robjects.globalenv['chm_dsm_by_tin'] + else: + r_chm_dsm_by_algorithm = r_common.robjects.globalenv['chm_dsm_by_pitfree'] + + # Invoking the R function + r_chm_dsm_by_algorithm(in_las_folder, out_folder, cell_size, is_normalized, + r_common.r_max_workers(processes), + r_common.free_memory(), tiling, bool(skip_existing)) + + +if __name__ == '__main__': + + start_time = time.time() + + print("Checking input parameters....") + kwargs = compose_tool_kwargs("rpy_CHM_DSM_by") + + rpy_chm_dsm_by(**kwargs) + + print('CHM/DSM process is done in {} seconds' + .format(round(time.time() - start_time, 5))) + + + diff --git a/beratools/modules/pc2products/rpy_PC2hummock_hollow.py b/beratools/modules/pc2products/rpy_PC2hummock_hollow.py new file mode 100644 index 0000000..24dbcd4 --- /dev/null +++ b/beratools/modules/pc2products/rpy_PC2hummock_hollow.py @@ -0,0 +1,106 @@ +import os +import time + +from beratools.modules.pc2products.r_interface import configure_r_environment +from beratools.utility.tool_args import compose_tool_kwargs + +configure_r_environment() +import beratools.modules.pc2products.r_common as r_common # noqa: E402 + + +def rpy_hh2raster(in_las_folder, + out_folder, + Smooth_by, + Min_ws=3.0, + lawn_range=0.3, + cell_size=0.0, + processes=0, + tiling="auto", + skip_existing:bool=False, + **kwargs,): + """ + Generate a raster of hummock hollows from LiDAR data. + + INPUT: LiDAR folder, output folder, smoothing method, minimum watershed size, lawn range, cell size + returnValue: raster of hummock hollows + """ + # cell_size = float(cell_size) + # Min_ws = float(Min_ws) + # lawn_range = float(lawn_range) + tiling = r_common.check_tiling(tiling) + r_common.check_las_files_existence(in_las_folder) + r_common.check_las_out_folder_existence(out_folder) + packages = ['lidR', 'rlas', 'future', 'terra', 'sp','raster','stars','sf'] + try: + r_common.check_r_packages_installation(packages, r_common.OPTIONAL_WORKER_PACKAGES) + except Exception as e: + print(f"Failed to verify R packages: {e}") + raise + + print("Checking input parameters....Done") + + # assign R script file to local variable + Beratools_R_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'r_scripts_collection.r') + # Defining the R script and loading the instance in Python + r_common.r['source'](Beratools_R_script) + + if cell_size == 0.0: + print("[INFO] No cell size given, the cell size will be estimated from the LiDAR data.") + from rpy2.rinterface_lib import callbacks + old_print = callbacks.consolewrite_print + old_warn = callbacks.consolewrite_warnerror + try: + callbacks.consolewrite_print = lambda x: None + callbacks.consolewrite_warnerror = lambda x: None + find_cellsize_algorithm = r_common.robjects.globalenv['pd2cellsize'] + results = find_cellsize_algorithm(in_las_folder) + finally: + callbacks.consolewrite_print = old_print + callbacks.consolewrite_warnerror = old_warn + cell_size=float(results.rx2("cell_size")[0]) + + is_gnd_classified = [ + list(r_item)[0] for r_item in r_common.robjects.globalenv["detect_class"](in_las_folder, 2) + ] + + # Normalized data has its ground at height 0, so the DTM is flat and every cell is lawn: a run + # of 2392 normalized files took 1.5 days for CHH values between -0.05 and 0.01 m + if False not in is_gnd_classified and bool( + r_common.robjects.globalenv["detect_normalized"](in_las_folder)[0] + ): + print("Error! The LiDAR data is normalized (its ground is at height 0), so it has no terrain " + "relief and every cell would be lawn. Use the ground-classified point clouds from " + "before normalization.") + exit() + + if False not in is_gnd_classified: + hh_function_algorithm=r_common.robjects.globalenv['hh_function'] + hh_function_algorithm( + in_las_folder, + out_folder, + float(cell_size), + Smooth_by, + float(Min_ws), + float(lawn_range), + r_common.r_max_workers(processes), + r_common.free_memory(), + tiling, + bool(skip_existing), + ) + else: + print("[Warning!] The LiDAR data is not classified, please run ground classification first.") + exit() + + +if __name__ == '__main__': + + start_time = time.time() + + print("Checking input parameters....") + kwargs = compose_tool_kwargs("rpy_PC2hummock_hollow") + + rpy_hh2raster(**kwargs) + + print('Hummock and hollow process is done in {} seconds' + .format(round(time.time() - start_time, 5))) + diff --git a/beratools/modules/pc2products/rpy_dtm_by.py b/beratools/modules/pc2products/rpy_dtm_by.py new file mode 100644 index 0000000..5567f6a --- /dev/null +++ b/beratools/modules/pc2products/rpy_dtm_by.py @@ -0,0 +1,94 @@ +import os +import time + +from beratools.modules.pc2products.r_interface import configure_r_environment +from beratools.utility.tool_args import compose_tool_kwargs + +configure_r_environment() +import beratools.modules.pc2products.r_common as r_common # noqa: E402 + + +def rpy_dtm(in_las_folder, + out_folder, + style, + cell_size=0.0, + processes=0, + tiling="auto", + skip_existing:bool=False, + **kwargs,): + + tiling = r_common.check_tiling(tiling) + r_common.check_las_files_existence(in_las_folder) + r_common.check_las_out_folder_existence(out_folder) + packages = ['lidR', 'gstat', 'rlas', 'future', 'terra', 'sp','raster','stars','sf'] + try: + r_common.check_r_packages_installation(packages, r_common.OPTIONAL_WORKER_PACKAGES) + except Exception as e: + print(f"Failed to verify R packages: {e}") + raise + if style not in ["tin", "idw", "kriging"]: + print("[Warning!] invalid algorithm, default algorithm will be used.") + style = "tin" + + if not os.path.exists(out_folder): + print("[Warning!] Cannot locate output folder, It will be created.") + os.makedirs(out_folder) + + print("Checking input parameters....Done") + + # assign R script file to local variable + Beratools_R_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'r_scripts_collection.r') + # Defining the R script and loading the instance in Python + r_common.r['source'](Beratools_R_script) + + if cell_size == 0.0: + print("[INFO] No cell size given, the cell size will be estimated from the LiDAR data.") + from rpy2.rinterface_lib import callbacks + old_print = callbacks.consolewrite_print + old_warn = callbacks.consolewrite_warnerror + try: + callbacks.consolewrite_print = lambda x: None + callbacks.consolewrite_warnerror = lambda x: None + find_cellsize_algorithm = r_common.robjects.globalenv['pd2cellsize'] + results = find_cellsize_algorithm(in_las_folder) + finally: + callbacks.consolewrite_print = old_print + callbacks.consolewrite_warnerror = old_warn + cell_size=float(results.rx2("cell_size")[0]) + is_gnd_classified = [ + list(r_item)[0] for r_item in r_common.robjects.globalenv["detect_class"](in_las_folder, 2) + ] + if False in is_gnd_classified: + print("[Warning!] The LiDAR data is not classified, please run ground classification first.") + exit() + is_normalized = bool(r_common.robjects.globalenv['detect_normalized'](in_las_folder)[0]) + if is_normalized: + print("[INFO]: LiDAR data is normalized, the output will be normalized DTM.") + else: + print("[INFO]: LiDAR data is not normalized, the output will be regular DTM.") + + # Loading the function defined in R script. + if style == "tin": + r_chm_by_algorithm = r_common.robjects.globalenv['dtm_by_tin'] + elif style == "idw": + r_chm_by_algorithm = r_common.robjects.globalenv['dtm_by_knnidw'] + else: + r_chm_by_algorithm = r_common.robjects.globalenv['dtm_by_kriging'] + # Invoking the R function + r_chm_by_algorithm(in_las_folder, out_folder, cell_size, r_common.r_max_workers(processes), + r_common.free_memory(), tiling, bool(skip_existing)) + +if __name__ == '__main__': + + start_time = time.time() + + print("Checking input parameters....") + kwargs = compose_tool_kwargs("rpy_dtm_by") + + rpy_dtm(**kwargs) + + print('DTM process is done in {} seconds' + .format(round(time.time() - start_time, 5))) + + + diff --git a/beratools/modules/pc2products/rpy_dtw.py b/beratools/modules/pc2products/rpy_dtw.py new file mode 100644 index 0000000..96d0483 --- /dev/null +++ b/beratools/modules/pc2products/rpy_dtw.py @@ -0,0 +1,96 @@ +import math +import os +import time + +import rasterio + +from beratools.modules.pc2products.r_interface import configure_r_environment +from beratools.utility.tool_args import compose_tool_kwargs + +configure_r_environment() +import beratools.modules.pc2products.r_common as r_common # noqa: E402 +from beratools.utility.spatial_common import decode_file_layer # noqa: E402 + +# Peak memory of one R worker in dtw_tile: the R session itself, plus about 100 bytes per cell of +# the tile (cell coordinates, gstat's prediction table and the kriged values) +R_WORKER_BYTES = 200e6 +TILE_BYTES_PER_CELL = 100 + + +def dtw_processes(processes, in_dtm, kriging_cell_size, tile_size): + """ + R workers for kriging the water table on this machine: one per CPU core and tile of the + kriging grid, as far as the free memory holds one tile per worker. processes > 0 caps the count. + """ + with rasterio.open(in_dtm) as src: + width, height, cell_size = src.width, src.height, abs(src.res[0]) + if kriging_cell_size > cell_size: + fact = max(1, round(kriging_cell_size / cell_size)) + width, height = math.ceil(width / fact), math.ceil(height / fact) + tile_size = max(1, tile_size) + tile_cells = min(tile_size, height) * min(tile_size, width) + tiles = math.ceil(height / tile_size) * math.ceil(width / tile_size) + return r_common.r_processes_by_memory( + processes, R_WORKER_BYTES + TILE_BYTES_PER_CELL * tile_cells, tiles) + + +def rpy_dtw(in_dtm, + in_water, + out_folder, + in_mask="", + grid_size=10.0, + nmax=10, + variogram_model="Ste", + kriging_cell_size=0.01, + tile_size=1000, + processes=0, + **kwargs,): + """ + Krige a water table from surface water elevations and compute depth-to-water. + + Follows Chan, Dabros & McDermid (2026), Forests 17, 489, section 2.4. + INPUT: DTM, surface water raster (1 water, e.g. from Surface Water Mapping), output folder, + optional exclusion polygons, grid size, nearest observations, variogram model, + kriging cell size (0 = DTM cell size), tile size (kriging grid cells per side; tiles + are kriged in parallel by `processes` R workers) + returnValue: water_table.tif and dtw.tif (0 on surface water) in out_folder + """ + mask_path, mask_layer = decode_file_layer(in_mask or "") + mask_layer = mask_layer or "" # R gets "" for no layer; rpy2 cannot pass None + for label, path in (("DTM", in_dtm), ("surface water", in_water), ("mask", mask_path)): + if path and not os.path.isfile(path): + raise FileNotFoundError(f"Cannot locate the {label} file: {path}") + os.makedirs(out_folder, exist_ok=True) + + packages = ['terra', 'gstat'] + try: + r_common.check_r_packages_installation(packages) + except Exception as e: + print(f"Failed to verify R packages: {e}") + raise + + rprocesses = dtw_processes(processes, in_dtm, float(kriging_cell_size), int(tile_size)) + + print("Checking input parameters....Done") + + # assign R script file to local variable + Beratools_R_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'r_scripts_collection.r') + # Defining the R script and loading the instance in Python + r_common.r['source'](Beratools_R_script) + + dtw_map = r_common.robjects.globalenv['dtw_map'] + dtw_map(in_dtm, in_water, mask_path, mask_layer, float(grid_size), int(nmax), + str(variogram_model), float(kriging_cell_size), out_folder, + int(tile_size), rprocesses) + +if __name__ == '__main__': + + start_time = time.time() + + print("Checking input parameters....") + kwargs = compose_tool_kwargs("rpy_dtw") + + rpy_dtw(**kwargs) + + print('Depth-to-water is done in {} seconds' + .format(round(time.time() - start_time, 5))) diff --git a/beratools/modules/pc2products/rpy_find_cellsize.py b/beratools/modules/pc2products/rpy_find_cellsize.py new file mode 100644 index 0000000..f43041d --- /dev/null +++ b/beratools/modules/pc2products/rpy_find_cellsize.py @@ -0,0 +1,51 @@ +import os +import time + +from beratools.modules.pc2products.r_interface import configure_r_environment +from beratools.utility.tool_args import compose_tool_kwargs + +configure_r_environment() +import beratools.modules.pc2products.r_common as r_common # noqa: E402 + + +def rpy_find_cellsize(in_las_folder, + processes=0, + **kwargs,): + """ + Print the raster cell size suited to the LiDAR data's point density. It reads only the + files' headers, so it starts no R workers and processes is unused; it is kept as every tool + takes it. + """ + r_common.check_las_files_existence(in_las_folder) + packages = ['lidR', 'rlas', 'future', 'terra', 'sp','raster','stars','sf'] + try: + r_common.check_r_packages_installation(packages) + except Exception as e: + print(f"Failed to verify R packages: {e}") + raise + + print("Checking input parameters....Done") + + # assign R script file to local variable + Beratools_R_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'r_scripts_collection.r') + # Defining the R script and loading the instance in Python + r_common.r['source'](Beratools_R_script) + + find_cellsize_algorith=r_common.robjects.globalenv['pd2cellsize'] + _=find_cellsize_algorith(in_las_folder) + + +if __name__ == '__main__': + + start_time = time.time() + + print("Checking input parameters....") + kwargs = compose_tool_kwargs("rpy_find_cellsize") + + rpy_find_cellsize(**kwargs) + + print('Finding cell size is done in {} seconds' + .format(round(time.time() - start_time, 5))) + + + diff --git a/beratools/modules/pc2products/rpy_gnd_csf.py b/beratools/modules/pc2products/rpy_gnd_csf.py new file mode 100644 index 0000000..9a229d0 --- /dev/null +++ b/beratools/modules/pc2products/rpy_gnd_csf.py @@ -0,0 +1,73 @@ +import os +import time + +from beratools.modules.pc2products.r_interface import configure_r_environment +from beratools.utility.tool_args import compose_tool_kwargs + +configure_r_environment() +import beratools.modules.pc2products.r_common as r_common # noqa: E402 + + +def rpy_gnd_csf(in_las_folder, + out_folder, + slope:bool=False, + class_threshold=0.3, + cloth_resolution=1.0, + rigidness=1, + processes=1, + tiling="auto", + skip_existing:bool=False, + **kwargs,): + """ + Classify the ground points of LiDAR data with the Cloth Simulation Filter (CSF). + + INPUT: LiDAR folder, output folder, slope (steep terrain), class threshold, cloth resolution, + rigidness, tiling, skip existing outputs + returnValue: none; the ground-classified LiDAR files are written to out_folder + """ + tiling = r_common.check_tiling(tiling) + r_common.check_las_files_existence(in_las_folder) + r_common.check_las_out_folder_existence(out_folder) + packages = ['lidR', 'RCSF', 'rlas', 'future', 'terra', 'sp','raster','stars','sf'] + try: + r_common.check_r_packages_installation(packages, r_common.OPTIONAL_WORKER_PACKAGES) + except Exception as e: + print(f"Failed to verify R packages: {e}") + raise + + print("Checking input parameters....Done") + + max_workers = r_common.r_max_workers(processes) + + # assign R script file to local variable + Beratools_R_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'r_scripts_collection.r') + # Defining the R script and loading the instance in Python + r_common.r['source'](Beratools_R_script) + + is_gnd_classified = [ + list(r_item)[0] for r_item in r_common.robjects.globalenv["detect_class"](in_las_folder, 2) + ] + rest = False + if False not in is_gnd_classified: + rest=True + print("Classified LiDAR data detected, process will rest and overwrite existing PC...") + else: + print("The LiDAR data will being classified......") + classify_gnd_csf_algorith = r_common.robjects.globalenv['classify_gnd_csf'] + classify_gnd_csf_algorith(in_las_folder, out_folder, bool(slope), float(class_threshold), + float(cloth_resolution),int(rigidness), + max_workers,bool(rest), + r_common.free_memory(), tiling, bool(skip_existing)) + +if __name__ == '__main__': + + start_time = time.time() + + print("Checking input parameters....") + kwargs = compose_tool_kwargs("rpy_gnd_csf") + + rpy_gnd_csf(**kwargs) + + print('LiDAR classification is done in {} seconds' + .format(round(time.time() - start_time, 5))) + diff --git a/beratools/modules/pc2products/rpy_las_info.py b/beratools/modules/pc2products/rpy_las_info.py new file mode 100644 index 0000000..5b0393a --- /dev/null +++ b/beratools/modules/pc2products/rpy_las_info.py @@ -0,0 +1,66 @@ +import os +import time + +from beratools.modules.pc2products.r_interface import configure_r_environment +from beratools.utility.tool_args import compose_tool_kwargs + +configure_r_environment() +import beratools.modules.pc2products.r_common as r_common # noqa: E402 + + +def rpy_las_info(in_las_folder, + processes=0, + **kwargs,): + """ + Report information about the LAS files of a folder. + + It reports: + LAS version + CRS + EPSG + Units + Extent + Area + Point count + Point density + Number of files + Normalized / not normalized + Ground elevation statistics + + It reads only the files' headers and one file, so it starts no R workers and processes is + unused; it is kept as every tool takes it. + """ + r_common.check_las_files_existence(in_las_folder) + packages = ['lidR', 'rlas', 'future', 'terra', 'sp','raster','stars','sf'] + try: + r_common.check_r_packages_installation(packages) + except Exception as e: + print(f"Failed to verify R packages: {e}") + raise + + print("Checking input parameters....Done") + + # assign R script file to local variable + Beratools_R_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'r_scripts_collection.r') + # Defining the R script and loading the instance in Python + r_common.r['source'](Beratools_R_script) + + + las_info_algorith=r_common.robjects.globalenv['las_info'] + las_info_algorith(in_las_folder) + + +if __name__ == '__main__': + + start_time = time.time() + + print("Checking input parameters....") + kwargs = compose_tool_kwargs("rpy_las_info") + + rpy_las_info(**kwargs) + + print('LiDAR information is done in {} seconds' + .format(round(time.time() - start_time, 5))) + + + diff --git a/beratools/modules/pc2products/rpy_lidar_index.py b/beratools/modules/pc2products/rpy_lidar_index.py new file mode 100644 index 0000000..144e172 --- /dev/null +++ b/beratools/modules/pc2products/rpy_lidar_index.py @@ -0,0 +1,50 @@ +import os +import time + +from beratools.modules.pc2products.r_interface import configure_r_environment +from beratools.utility.tool_args import compose_tool_kwargs + +configure_r_environment() +import beratools.modules.pc2products.r_common as r_common # noqa: E402 + + +def rpy_lidar_index(in_las_folder, + overwrite:bool=False, + processes=0, + **kwargs,): + """ + Build the .lax spatial index of every LAS/LAZ file in the folder that has none. + + INPUT: LiDAR folder, overwrite (rebuild existing indexes) + returnValue: none; the .lax files are written next to the LiDAR files + """ + r_common.check_las_files_existence(in_las_folder) + packages = ['lidR', 'rlas'] + try: + r_common.check_r_packages_installation(packages) + except Exception as e: + print(f"Failed to verify R packages: {e}") + raise + + print("Checking input parameters....Done") + + # assign R script file to local variable + Beratools_R_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'r_scripts_collection.r') + # Defining the R script and loading the instance in Python + r_common.r['source'](Beratools_R_script) + + lidar_index_algorithm = r_common.robjects.globalenv['lidar_index'] + lidar_index_algorithm(in_las_folder, r_common.r_max_workers(processes), bool(overwrite)) + + +if __name__ == '__main__': + + start_time = time.time() + + print("Checking input parameters....") + kwargs = compose_tool_kwargs("rpy_lidar_index") + + rpy_lidar_index(**kwargs) + + print('LiDAR spatial index is done in {} seconds' + .format(round(time.time() - start_time, 5))) diff --git a/beratools/modules/pc2products/rpy_lidar_tile.py b/beratools/modules/pc2products/rpy_lidar_tile.py new file mode 100644 index 0000000..d33bc19 --- /dev/null +++ b/beratools/modules/pc2products/rpy_lidar_tile.py @@ -0,0 +1,61 @@ +import os +import time + +from beratools.modules.pc2products.r_interface import configure_r_environment +from beratools.utility.tool_args import compose_tool_kwargs + +configure_r_environment() +import beratools.modules.pc2products.r_common as r_common # noqa: E402 + + +def rpy_lidar_tile(in_las_folder, + out_folder, + buffer=30.0, + tile_size=0.0, + laz:bool=True, + skip_existing:bool=False, + processes=0, + **kwargs,): + """ + Split the LiDAR files of a folder into tiles sized by the point density. + + INPUT: LiDAR folder, output folder, buffer the tiles are sized for (m), fixed tile size (m, 0 to + size by density), LAZ output, skip tiles already written + returnValue: none; the tiles, tiles.csv and the tiles' .lax files are written to out_folder + """ + r_common.check_las_files_existence(in_las_folder) + r_common.check_las_out_folder_existence(out_folder) + if float(buffer) < 0: + raise ValueError(f"buffer must be 0 or more, got {buffer}") + if float(tile_size) < 0: + raise ValueError(f"tile_size must be 0 (size by density) or more, got {tile_size}") + packages = ['lidR', 'rlas', 'future'] + try: + r_common.check_r_packages_installation(packages, r_common.OPTIONAL_WORKER_PACKAGES) + except Exception as e: + print(f"Failed to verify R packages: {e}") + raise + + print("Checking input parameters....Done") + + # assign R script file to local variable + Beratools_R_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'r_scripts_collection.r') + # Defining the R script and loading the instance in Python + r_common.r['source'](Beratools_R_script) + + lidar_tile_algorithm = r_common.robjects.globalenv['lidar_tile'] + lidar_tile_algorithm(in_las_folder, out_folder, float(buffer), float(tile_size), bool(laz), + r_common.r_max_workers(processes), r_common.free_memory(), bool(skip_existing)) + + +if __name__ == '__main__': + + start_time = time.time() + + print("Checking input parameters....") + kwargs = compose_tool_kwargs("rpy_lidar_tile") + + rpy_lidar_tile(**kwargs) + + print('LiDAR tiling is done in {} seconds' + .format(round(time.time() - start_time, 5))) diff --git a/beratools/modules/pc2products/rpy_normalized_PC.py b/beratools/modules/pc2products/rpy_normalized_PC.py new file mode 100644 index 0000000..16cf6b8 --- /dev/null +++ b/beratools/modules/pc2products/rpy_normalized_PC.py @@ -0,0 +1,69 @@ +import os +import time + +from beratools.modules.pc2products.r_interface import configure_r_environment +from beratools.utility.tool_args import compose_tool_kwargs + +configure_r_environment() +import beratools.modules.pc2products.r_common as r_common # noqa: E402 + + +def rpy_normalized_PC(in_las_folder, + out_folder, + style, + processes=0, + tiling="auto", + skip_existing:bool=False, + **kwargs, ): + + tiling = r_common.check_tiling(tiling) + r_common.check_las_files_existence(in_las_folder) + r_common.check_las_out_folder_existence(out_folder) + packages = ['lidR', 'gstat', 'rlas', 'future', 'terra', 'sp','raster','stars','sf'] + try: + r_common.check_r_packages_installation(packages, r_common.OPTIONAL_WORKER_PACKAGES) + except Exception as e: + print(f"Failed to verify R packages: {e}") + raise + if style not in ["tin", "idw", "kriging"]: + print("Warning! invalid algorithm, default algorithm will be used.") + style = "tin" + + if not os.path.exists(out_folder): + print("Warning! Cannot locate output folder, It will be created.") + os.makedirs(out_folder) + + print("Checking input parameters....Done") + + max_workers = r_common.r_max_workers(processes) + + # assign R script file to local variable + Beratools_R_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'r_scripts_collection.r') + # Defining the R script and loading the instance in Python + r_common.r['source'](Beratools_R_script) + + # Loading the function defined in R script. + if style == "tin": + r_normalized_PC = r_common.robjects.globalenv['normalized_lidar_tin'] + elif style == "idw": + r_normalized_PC = r_common.robjects.globalenv['normalized_lidar_knnidw'] + else: + r_normalized_PC = r_common.robjects.globalenv['normalized_lidar_kriging'] + # Invoking the R function + r_normalized_PC(in_las_folder, out_folder, max_workers, r_common.free_memory(), tiling, + bool(skip_existing)) + +if __name__ == '__main__': + + start_time = time.time() + + print("Checking input parameters....") + kwargs = compose_tool_kwargs("rpy_normalized_PC") + + rpy_normalized_PC(**kwargs) + + print('Normalization process is done in {} seconds' + .format(round(time.time() - start_time, 5))) + + + diff --git a/beratools/modules/pc2products/rpy_seismic_line_analysis.py b/beratools/modules/pc2products/rpy_seismic_line_analysis.py new file mode 100644 index 0000000..749ab98 --- /dev/null +++ b/beratools/modules/pc2products/rpy_seismic_line_analysis.py @@ -0,0 +1,76 @@ +import os +import time + +from beratools.modules.pc2products.r_interface import configure_r_environment +from beratools.utility.tool_args import compose_tool_kwargs + +configure_r_environment() +import beratools.modules.pc2products.r_common as r_common # noqa: E402 + + +def _split_file_layer(value): + """Split a 'path|layer' (or 'path::layer') vector input into its path and layer.""" + for sep in ("|", "::"): + if sep in value: + path, layer = value.split(sep, 1) + return path.strip(), layer.strip() + return value.strip(), "" + + +def rpy_seismic_line_analysis(in_segments, + in_dtm, + in_microform, + out_folder, + in_dtw="", + significance=0.05, + processes=0, + **kwargs,): + """ + Compare seismic line segments with the adjacent matrix, by disturbance class. + + Adapted from Chan, Dabros & McDermid (2026), Forests 17, 489. + INPUT: segment polygons (fields new_id, note, Class), DTM raster, microform raster + (1 hummock, 0 lawn, -1 hollow), optional depth-to-water raster (0 = surface water), + output folder, significance level + returnValue: CSV tables and PNG plots in out_folder/tables and out_folder/plots + """ + segments_path, segments_layer = _split_file_layer(in_segments) + in_dtw = in_dtw or "" + for label, path in (("segments", segments_path), ("DTM", in_dtm), + ("microform", in_microform), ("depth-to-water", in_dtw)): + if path and not os.path.isfile(path): + print(f"Error! Cannot locate the {label} file: {path}") + exit() + os.makedirs(out_folder, exist_ok=True) + + packages = ['terra', 'ggplot2'] + try: + r_common.check_r_packages_installation(packages) + except Exception as e: + print(f"Failed to verify R packages: {e}") + raise + + print("Checking input parameters....Done") + if not in_dtw: + print("No depth-to-water raster given: depth-to-water and surface water are skipped.") + + # assign R script file to local variable + Beratools_R_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'r_scripts_collection.r') + # Defining the R script and loading the instance in Python + r_common.r['source'](Beratools_R_script) + + seismic_line_analysis = r_common.robjects.globalenv['seismic_line_analysis'] + seismic_line_analysis(segments_path, segments_layer, in_dtm, in_microform, in_dtw, + out_folder, float(significance)) + +if __name__ == '__main__': + + start_time = time.time() + + print("Checking input parameters....") + kwargs = compose_tool_kwargs("rpy_seismic_line_analysis") + + rpy_seismic_line_analysis(**kwargs) + + print('Seismic line analysis is done in {} seconds' + .format(round(time.time() - start_time, 5))) diff --git a/beratools/modules/pc2products/rpy_surface_water.py b/beratools/modules/pc2products/rpy_surface_water.py new file mode 100644 index 0000000..613324a --- /dev/null +++ b/beratools/modules/pc2products/rpy_surface_water.py @@ -0,0 +1,102 @@ +import math +import os +import time + +import rasterio + +from beratools.modules.pc2products.r_interface import configure_r_environment +from beratools.utility.tool_args import compose_tool_kwargs + +configure_r_environment() +import beratools.modules.pc2products.r_common as r_common # noqa: E402 +from beratools.utility.spatial_common import decode_file_layer # noqa: E402 + +# Peak memory of one R worker in surface_water_tile: the R session itself, plus about 100 bytes +# per cell of the buffered tile (RGB values, class codes, resampled CHM, patch ids and copies). +# Measured: 535 MB for a 2000 x 2000 tile with CHM and patch removal (estimate 600 MB). +R_WORKER_BYTES = 200e6 +TILE_BYTES_PER_CELL = 100 + + +def surface_water_processes(processes, in_ortho, tile_size, min_patch_area): + """ + R workers for surface_water_map on this machine: one per CPU core and tile, as far as the + free memory holds one buffered tile per worker. processes > 0 caps the count. + """ + with rasterio.open(in_ortho) as src: + width, height = src.width, src.height + cell_area = abs(src.res[0] * src.res[1]) + tile_size = max(1, tile_size) + buffer = math.ceil(min_patch_area / cell_area) if min_patch_area > 0 else 0 + tile_cells = (min(tile_size, height) + 2 * buffer) * (min(tile_size, width) + 2 * buffer) + tiles = math.ceil(height / tile_size) * math.ceil(width / tile_size) + return r_common.r_processes_by_memory( + processes, R_WORKER_BYTES + TILE_BYTES_PER_CELL * tile_cells, tiles) + + +def rpy_surface_water(in_ortho, + in_training, + out_folder, + in_chm="", + max_canopy_height=0.2, + min_patch_area=0.04, + points_per_polygon=2, + seed=1, + tile_size=2000, + processes=0, + **kwargs,): + """ + Map surface water from a true-colour orthomosaic with a decision tree. + + Follows Chan, Dabros & McDermid (2026), Forests 17, 489, section 2.4. + INPUT: orthomosaic (bands 1-3 red, green, blue), training polygons with a 'class' field + ('water' plus other classes such as 'ground' and 'shadow'), output folder, + optional CHM, canopy height mask threshold, minimum water patch area, + training points per polygon, random seed, tile size (cells per side; tiles are + classified in parallel by `processes` R workers) + returnValue: surface_water.tif (1 water, 0 not water) and cross-validation tables in out_folder + """ + training_path, training_layer = decode_file_layer(in_training) + training_layer = training_layer or "" # R gets "" for no layer; rpy2 cannot pass None + in_chm = in_chm or "" + for label, path in (("orthomosaic", in_ortho), ("training polygons", training_path), + ("CHM", in_chm)): + if path and not os.path.isfile(path): + raise FileNotFoundError(f"Cannot locate the {label} file: {path}") + os.makedirs(out_folder, exist_ok=True) + + packages = ['terra', 'rpart'] + try: + r_common.check_r_packages_installation(packages) + except Exception as e: + print(f"Failed to verify R packages: {e}") + raise + + rprocesses = surface_water_processes(processes, in_ortho, int(tile_size), float(min_patch_area)) + + print("Checking input parameters....Done") + if not in_chm: + print("No CHM given: cells under canopy are not masked out.") + + # assign R script file to local variable + Beratools_R_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'r_scripts_collection.r') + # Defining the R script and loading the instance in Python + r_common.r['source'](Beratools_R_script) + + surface_water_map = r_common.robjects.globalenv['surface_water_map'] + surface_water_map(in_ortho, training_path, training_layer, in_chm, + float(max_canopy_height), float(min_patch_area), + int(points_per_polygon), int(seed), out_folder, + int(tile_size), rprocesses) + +if __name__ == '__main__': + + start_time = time.time() + + print("Checking input parameters....") + kwargs = compose_tool_kwargs("rpy_surface_water") + + rpy_surface_water(**kwargs) + + print('Surface water mapping is done in {} seconds' + .format(round(time.time() - start_time, 5))) \ No newline at end of file diff --git a/beratools/modules/pc2products/tests/conftest.py b/beratools/modules/pc2products/tests/conftest.py new file mode 100644 index 0000000..9010cb4 --- /dev/null +++ b/beratools/modules/pc2products/tests/conftest.py @@ -0,0 +1,188 @@ +"""Test configuration for the PC2Products tests.""" + +import logging +import os +import time +import warnings +from pathlib import Path + +import pytest +from synthetic_data import make_dtw_data, make_seismic_line_data, make_surface_water_data + +# Test the work-in-progress modules and tools too (see core/registry.py) +os.environ["BERATOOLS_WIP"] = "1" + +# This module's sample data, in tests/data next to this file +DATA_DIR = Path(__file__).resolve().parent / "data" + + +def pytest_configure(config): + warnings.simplefilter("ignore", category=FutureWarning) + warnings.simplefilter("ignore", category=DeprecationWarning) + # Set the global logging level to ERROR to suppress DEBUG and INFO logs + logging.basicConfig(level=logging.ERROR) + + # Set logger to ERROR to suppress debug logs + logging.getLogger("pyogrio").setLevel(logging.ERROR) + logging.getLogger("rasterio").setLevel(logging.ERROR) + logging.getLogger("rasterio.env").setLevel(logging.ERROR) + logging.getLogger("beratools.external.polygon_centerline._src").setLevel(logging.ERROR) + logging.getLogger("pyproj").setLevel(logging.WARNING) + + +@pytest.fixture +def testdata_dir(): + return DATA_DIR + + +@pytest.fixture(scope="session") +def available_cpu_cores(): + return os.cpu_count() + +# --------------------------------------------------------------------------- +# PC2Products (R) tools +# --------------------------------------------------------------------------- + +# Integration arguments: each tool uses original inputs +@pytest.fixture +def tool_r_arguments_integration(testdata_dir, available_cpu_cores): + return { + "args_rpy_dtm": { + "in_las_folder": f"{testdata_dir.joinpath('LiDAR').as_posix()}", + "out_folder": f"{testdata_dir.joinpath('LiDAR','Raster_Output').as_posix()}", + "style": "tin", + }, + "args_dsm_by": { + "in_las_folder": f"{testdata_dir.joinpath('LiDAR').as_posix()}", + "out_folder": f"{testdata_dir.joinpath('LiDAR', 'Raster_Output').as_posix()}", + "style": "tin", + }, + "args_las_info": { + "in_las_folder": f"{testdata_dir.joinpath('LiDAR').as_posix()}", + }, + "args_find_cellsize": { + "in_las_folder": f"{testdata_dir.joinpath('LiDAR').as_posix()}", + }, + + "args_hh": { + "in_las_folder": f"{testdata_dir.joinpath('LiDAR').as_posix()}", + "out_folder": f"{testdata_dir.joinpath('LiDAR', 'Raster_Output').as_posix()}", + "Smooth_by": "median", + "Min_ws": 3.0, + "lawn_range": 0.1, + "cell_size":0, + }, + "args_classify_gnd_csf":{ + "in_las_folder": f"{testdata_dir.joinpath('LiDAR').as_posix()}", + "out_folder": f"{testdata_dir.joinpath('LiDAR', 'Classified_PC').as_posix()}", + "slope":False, + "class_threshold":0.3, + "cloth_resolution":1.0, + "rigidness":1, + }, + "args_normalized_PC": { + "in_las_folder": f"{testdata_dir.joinpath('LiDAR').as_posix()}", + "out_folder": f"{testdata_dir.joinpath('LiDAR', 'Normalized_PC').as_posix()}", + "style": "tin" + }, + "args_chm_by": { + "in_las_folder": f"{testdata_dir.joinpath('LiDAR', 'Normalized_PC').as_posix()}", + "out_folder": f"{testdata_dir.joinpath('LiDAR', 'Raster_Output').as_posix()}", + "style": "tin", + } + } + + +# Workflow arguments: chained outputs +@pytest.fixture +def tool_arguments_r_workflow(testdata_dir, available_cpu_cores): + return { + "args_classify_gnd_csf":{ + "in_las_folder": f"{testdata_dir.joinpath('LiDAR').as_posix()}", + "out_folder": f"{testdata_dir.joinpath('LiDAR', 'Classified_PC').as_posix()}", + "slope":False, + "class_threshold":0.3, + "cloth_resolution":1.0, + "rigidness":1, + }, + "args_rpy_dtm": { + "in_las_folder": f"{testdata_dir.joinpath('LiDAR').as_posix()}", + "out_folder": f"{testdata_dir.joinpath('LiDAR', 'Raster_Output').as_posix()}", + "style": "tin", + }, + "args_dsm_by": { + "in_las_folder": f"{testdata_dir.joinpath('LiDAR').as_posix()}", + "out_folder": f"{testdata_dir.joinpath('LiDAR', 'Raster_Output').as_posix()}", + "style": "tin", + }, + "args_las_info": { + "in_las_folder": f"{testdata_dir.joinpath('LiDAR').as_posix()}", + }, + "args_find_cellsize": { + "in_las_folder": f"{testdata_dir.joinpath('LiDAR').as_posix()}", + }, + "args_hh": { + "in_las_folder": f"{testdata_dir.joinpath('LiDAR').as_posix()}", + "out_folder": f"{testdata_dir.joinpath('LiDAR', 'Raster_Output').as_posix()}", + "Smooth_by": "median", + "Min_ws": 3.0, + "lawn_range": 0.1, + "cell_size": 0, + }, + "args_normalized_PC":{ + "in_las_folder": f"{testdata_dir.joinpath('LiDAR').as_posix()}", + "out_folder": f"{testdata_dir.joinpath('LiDAR', 'Normalized_PC').as_posix()}", + "style":"tin" + }, + "args_chm_by": { + "in_las_folder": f"{testdata_dir.joinpath('LiDAR', 'Normalized_PC').as_posix()}", + "out_folder": f"{testdata_dir.joinpath('LiDAR', 'Raster_Output').as_posix()}", + "style": "tin", + } + } + + +@pytest.fixture +def raster_output_dir(testdata_dir): + return testdata_dir.joinpath("LiDAR", "Raster_Output") + +@pytest.fixture +def classified_output_dir(testdata_dir): + return testdata_dir.joinpath("LiDAR", "Classified_PC") + +@pytest.fixture +def normalized_output_dir(testdata_dir): + return testdata_dir.joinpath("LiDAR", "Normalized_PC") + + +@pytest.fixture +def cleanup_r_output_files(raster_output_dir, classified_output_dir, normalized_output_dir): + """Fixture to clean up generated output files after the test.""" + yield # Yield here allows the test to run first + time.sleep(1) # Wait a little to allow file system operations to complete + # R tool outputs (tiles, merged rasters, VRTs); temp.txt keeps the folder tracked in git + raster_outputs = [ f for f in raster_output_dir.glob("*") if f.is_file() ] + pc_outputs = [f for f in classified_output_dir.glob("*") if f.is_file() + and f.name and (f.suffix == ".las" or f.suffix == ".laz")] + pc_outputs =pc_outputs+ [f for f in normalized_output_dir.glob("*") if f.is_file() + and f.name and (f.suffix == ".las" or f.suffix == ".laz")] + for file_path in [*raster_outputs, *pc_outputs]: + if file_path.exists(): + file_path.unlink() + assert not file_path.exists(), f"Failed to remove {file_path}" + + +# Synthetic inputs for the surface water, depth-to-water and seismic line tests (see synthetic_data.py) +@pytest.fixture +def seismic_line_data(tmp_path): + return make_seismic_line_data(tmp_path / "seismic_line_inputs") + + +@pytest.fixture +def surface_water_data(tmp_path): + return make_surface_water_data(tmp_path / "surface_water_inputs") + + +@pytest.fixture +def dtw_data(tmp_path): + return make_dtw_data(tmp_path / "dtw_inputs") \ No newline at end of file diff --git a/beratools/modules/pc2products/tests/data/LiDAR/tile_554400_6138400.las b/beratools/modules/pc2products/tests/data/LiDAR/tile_554400_6138400.las new file mode 100644 index 0000000..4fdff01 Binary files /dev/null and b/beratools/modules/pc2products/tests/data/LiDAR/tile_554400_6138400.las differ diff --git a/beratools/modules/pc2products/tests/data/LiDAR/tile_554500_6138400.las b/beratools/modules/pc2products/tests/data/LiDAR/tile_554500_6138400.las new file mode 100644 index 0000000..713ca31 Binary files /dev/null and b/beratools/modules/pc2products/tests/data/LiDAR/tile_554500_6138400.las differ diff --git a/beratools/modules/pc2products/tests/data/LiDAR/tile_554500_6138500.las b/beratools/modules/pc2products/tests/data/LiDAR/tile_554500_6138500.las new file mode 100644 index 0000000..3d20f60 Binary files /dev/null and b/beratools/modules/pc2products/tests/data/LiDAR/tile_554500_6138500.las differ diff --git a/beratools/modules/pc2products/tests/data/LiDAR/tile_554600_6138300.las b/beratools/modules/pc2products/tests/data/LiDAR/tile_554600_6138300.las new file mode 100644 index 0000000..f5a1bd2 Binary files /dev/null and b/beratools/modules/pc2products/tests/data/LiDAR/tile_554600_6138300.las differ diff --git a/beratools/modules/pc2products/tests/data/LiDAR/tile_554600_6138400.las b/beratools/modules/pc2products/tests/data/LiDAR/tile_554600_6138400.las new file mode 100644 index 0000000..a119079 Binary files /dev/null and b/beratools/modules/pc2products/tests/data/LiDAR/tile_554600_6138400.las differ diff --git a/beratools/modules/pc2products/tests/data/LiDAR/tile_554600_6138500.las b/beratools/modules/pc2products/tests/data/LiDAR/tile_554600_6138500.las new file mode 100644 index 0000000..2e31e66 Binary files /dev/null and b/beratools/modules/pc2products/tests/data/LiDAR/tile_554600_6138500.las differ diff --git a/beratools/modules/pc2products/tests/data/LiDAR/tile_554700_6138400.las b/beratools/modules/pc2products/tests/data/LiDAR/tile_554700_6138400.las new file mode 100644 index 0000000..12ef6e2 Binary files /dev/null and b/beratools/modules/pc2products/tests/data/LiDAR/tile_554700_6138400.las differ diff --git a/beratools/modules/pc2products/tests/pc2_test_utils.py b/beratools/modules/pc2products/tests/pc2_test_utils.py new file mode 100644 index 0000000..0f1ef40 --- /dev/null +++ b/beratools/modules/pc2products/tests/pc2_test_utils.py @@ -0,0 +1,41 @@ +"""Helper functions for testing.""" + +from pathlib import Path + + +def has_raster_output(results: str | list, pattern=None) -> bool: + """Return True if the folder contains at least one raster file.""" + raster_exts = {".tif", ".tiff", ".img", ".vrt", ".asc", ".bil", ".jp2"} + if isinstance(results, list): + if pattern: + return any(f.is_file() and f.suffix.lower() in raster_exts and f.match(pattern) for f in results) + else: + return any(f.is_file() and f.suffix.lower() in raster_exts for f in results) + + else: + folder = Path(results) + if not folder.is_dir(): + return False + return any(f.is_file() and f.suffix.lower() in raster_exts for f in folder.iterdir()) + + +def has_lidar_output(folder: str|Path) -> bool: + """Return True if the folder contains at least one lidar file.""" + lidar_exts = {".laz", ".las"} + folder = Path(folder) + if not folder.is_dir(): + return False + + return any(f.is_file() and f.suffix.lower() in lidar_exts for f in folder.iterdir()) + + +def list_files_in_folder(folder: str|Path, pattern= None) -> list[Path]: + """List all files in a folder with a specific extension.""" + files_list=[] + folder = Path(folder) + if folder.is_dir(): + if pattern: + files_list=[f for f in folder.glob(pattern) if f.is_file()] + else: + files_list=[f for f in folder.iterdir() if f.is_file()] + return files_list diff --git a/beratools/modules/pc2products/tests/synthetic_data.py b/beratools/modules/pc2products/tests/synthetic_data.py new file mode 100644 index 0000000..1113bd0 --- /dev/null +++ b/beratools/modules/pc2products/tests/synthetic_data.py @@ -0,0 +1,244 @@ +"""Synthetic rasters and polygons for the surface water, depth-to-water and seismic line tests.""" + +from pathlib import Path + +# --------------------------------------------------------------------------- +# Synthetic inputs for Seismic Line Disturbance Analysis +# --------------------------------------------------------------------------- + +# Per-segment line depression below the matrix (m), four segments per class. +SEISMIC_LINE_DEPTHS = { + "New Disturbance": [0.08, 0.10, 0.10, 0.12], + "Old Disturbance": [0.06, 0.11, 0.11, 0.16], + "Re-disturbance": [0.12, 0.14, 0.14, 0.16], +} +# Rows (of 20) of each line segment marked hummock; matrix segments have 4 of 20 (0.2). +SEISMIC_LINE_HUMMOCK_ROWS = {"New Disturbance": 1, "Old Disturbance": 3, "Re-disturbance": 0} +# Rows (of 20) of each line segment holding surface water (DTW == 0); matrix has none. +SEISMIC_LINE_WATER_ROWS = {"New Disturbance": 0, "Old Disturbance": 6, "Re-disturbance": 6} + +# Expected class means of the line-minus-matrix deviations +SEISMIC_LINE_EXPECTED = { + "dtm": {"New Disturbance": -0.10, "Old Disturbance": -0.11, "Re-disturbance": -0.14}, + "hummock": {"New Disturbance": -0.15, "Old Disturbance": -0.05, "Re-disturbance": -0.20}, + "dtw": {"New Disturbance": -0.10, "Old Disturbance": -0.10, "Re-disturbance": -0.10}, + "surfacewater": {"New Disturbance": 0.0, "Old Disturbance": 0.3, "Re-disturbance": 0.3}, +} + + +def _rectangle_wkb(xmin, ymin, xmax, ymax): + import struct + + ring = [(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax), (xmin, ymin)] + wkb = struct.pack(" xmin) & (x < xmax) & (y > ymin) & (y < ymax) + assert np.all(np.isnan(dtw[excluded])) + assert np.all(np.isnan(water_table[excluded])) + + kept = ~excluded + assert np.all(dtw[kept & water] == 0) + assert np.nanmin(dtw[kept]) >= 0 + # The kriged water table follows the true one closely, so DTW off the pools is ~0.2 m + assert np.nanmean(np.abs(water_table[kept] - dtw_water_table(x[kept], y[kept]))) < 0.02 + assert np.nanmean(dtw[kept & ~water]) == pytest.approx(DTW_GROUND_HEIGHT, abs=0.02) + + with open(out / "water_table_cv.csv", newline="", encoding="utf-8") as f: + cv = next(csv.DictReader(f)) + assert int(cv["n_points"]) == 96 # 100 grid cells, 4 inside the excluded corner + assert float(cv["rmse"]) < 0.05 + for name in ("water_points.gpkg", "variogram_model.csv", "variogram.png"): + assert (out / name).is_file() + + +def test_dtw_coarser_kriging_grid(dtw_data, tmp_path): + out = tmp_path / "dtw" + rpy_dtw( + in_dtm=dtw_data["dtm"], + in_water=dtw_data["water"], + out_folder=out.as_posix(), + kriging_cell_size=2.0, + ) + + dtw, x, y = _read(out / "dtw.tif") + assert not np.isnan(dtw).all() + # 1% of cells are pools (DTW 0); the rest sit DTW_GROUND_HEIGHT above the water table + assert np.nanmean(dtw) == pytest.approx(DTW_GROUND_HEIGHT * 0.99, abs=0.03) diff --git a/beratools/modules/pc2products/tests/test_pc2products_tools_json.py b/beratools/modules/pc2products/tests/test_pc2products_tools_json.py new file mode 100644 index 0000000..11387ea --- /dev/null +++ b/beratools/modules/pc2products/tests/test_pc2products_tools_json.py @@ -0,0 +1,36 @@ +"""The PC2Products module's tools.json, as the frame loads it.""" + +from beratools.core import registry + +MODULE = "pc2products" + +# The bt subcommands of this module's released tools; they must not change +CLI_NAMES = { + "dtm": "rpy_dtm_by", + "normalize": "rpy_normalized_PC", + "chm_dsm": "rpy_CHM_DSM_by", + "las_info": "rpy_las_info", + "cellsize": "rpy_find_cellsize", + "lidar_index": "rpy_lidar_index", + "tile": "rpy_lidar_tile", + "hh": "rpy_PC2hummock_hollow", + "gnd_csf": "rpy_gnd_csf", + "surface_water": "rpy_surface_water", + "dtw": "rpy_dtw", + "line_analysis": "rpy_seismic_line_analysis", +} + + +def _box(): + return next(box for box in registry.get_registry().toolbox if box["module"] == MODULE) + + +def test_module_loads_without_errors(): + assert [e for e in registry.get_registry().errors if e.startswith(f"{MODULE}:")] == [] + assert _box()["category"] == "PC2Products" + + +def test_cli_names_are_unchanged(): + # work-in-progress tools aren't published, and are checked in tests of their own + released = [tool for tool in _box()["tools"] if tool["status"] == "released"] + assert {tool["cli_name"]: tool["tool_api"] for tool in released} == CLI_NAMES diff --git a/beratools/modules/pc2products/tests/test_r_environment.py b/beratools/modules/pc2products/tests/test_r_environment.py new file mode 100644 index 0000000..d015a81 --- /dev/null +++ b/beratools/modules/pc2products/tests/test_r_environment.py @@ -0,0 +1,33 @@ +"""Verify R environment is available.""" + +import pytest + +# Union of the packages the rpy_* tools check for. +REQUIRED = ["lidR", "RCSF", "rlas", "future", "terra", "sp", "raster", "stars", "sf", "gstat", + "rpart", "ggplot2"] + + +def test_r_packages(): + # Start R through r_common so R is located and configured before rpy2 loads it. + # The environment only provides R; install anything missing the same way the tools do. + from beratools.modules.pc2products import r_common + + try: + r_common.initialize_r() + from rpy2.robjects.packages import importr + except Exception as exc: + pytest.fail(f"rpy2 not available: {exc}") + + r_common.check_r_packages_installation(REQUIRED) + + missing = [] + + for pkg in REQUIRED: + try: + importr(pkg) + except Exception: + missing.append(pkg) + + assert not missing, ( + f"Missing R packages: {', '.join(missing)}" + ) diff --git a/beratools/modules/pc2products/tests/test_r_tools.py b/beratools/modules/pc2products/tests/test_r_tools.py new file mode 100644 index 0000000..b9134c2 --- /dev/null +++ b/beratools/modules/pc2products/tests/test_r_tools.py @@ -0,0 +1,206 @@ +"""Integration tests: run each PC2Products LiDAR tool on the sample tiles and check its output.""" + +import shutil +from pprint import pprint + +import pytest +from pc2_test_utils import has_lidar_output, has_raster_output, list_files_in_folder + +from beratools.modules.pc2products.rpy_CHM_DSM_by import rpy_chm_dsm_by +from beratools.modules.pc2products.rpy_dtm_by import rpy_dtm +from beratools.modules.pc2products.rpy_find_cellsize import rpy_find_cellsize +from beratools.modules.pc2products.rpy_gnd_csf import rpy_gnd_csf +from beratools.modules.pc2products.rpy_las_info import rpy_las_info +from beratools.modules.pc2products.rpy_lidar_index import rpy_lidar_index +from beratools.modules.pc2products.rpy_normalized_PC import rpy_normalized_PC +from beratools.modules.pc2products.rpy_PC2hummock_hollow import rpy_hh2raster +from beratools.utility.spatial_common import decode_file_layer + + +# Integration TESTS +def test_rpy_dtm(tool_r_arguments_integration): + """Test for DTM from the LiDAR data tool.""" + args_rpy_dtm = tool_r_arguments_integration["args_rpy_dtm"] + pprint(args_rpy_dtm) + + rpy_dtm(**args_rpy_dtm) + + out_file_list = list_files_in_folder(args_rpy_dtm["out_folder"])#,"*_TIN_DTM.tif") + assert has_raster_output(out_file_list,"Merged_*_DTM.tif"), "out_folder no output!" + + + +def test_rpy_dsm(tool_r_arguments_integration): + """Test for CHM/DSM from the LiDAR tool.""" + args_rpy_dsm = tool_r_arguments_integration["args_dsm_by"] + pprint(args_rpy_dsm) + + rpy_chm_dsm_by(**args_rpy_dsm) + + out_file_list = list_files_in_folder(args_rpy_dsm["out_folder"]) + assert has_raster_output(out_file_list,"Merged_*_DSM.tif"), "out_folder no output!" + + +def test_rpy_las_info(tool_r_arguments_integration): + """Test for LiDAR metadata from the LiDAR tool.""" + args_rpy_las_info = tool_r_arguments_integration["args_las_info"] + pprint(args_rpy_las_info) + + rpy_las_info(**args_rpy_las_info) + +def test_rpy_find_cellsize(tool_r_arguments_integration): + """"Test for finding cell size from LiDAR data in the LiDAR tool.""" + args_rpy_find_cellsize = tool_r_arguments_integration["args_find_cellsize"] + pprint(args_rpy_find_cellsize) + + rpy_find_cellsize(**args_rpy_find_cellsize) + + +def test_rpy_lidar_index(testdata_dir, tmp_path): + """Test for building the .lax spatial indexes, on a copy of the sample tiles.""" + for f in testdata_dir.joinpath("LiDAR").glob("*.las"): + shutil.copy(f, tmp_path) + las_files = sorted(tmp_path.glob("*.las")) + assert las_files and not list(tmp_path.glob("*.lax")) + + rpy_lidar_index(in_las_folder=tmp_path.as_posix()) + + lax_files = [f.with_suffix(".lax") for f in las_files] + assert all(f.exists() and f.stat().st_size > 0 for f in lax_files) + built = {f: f.stat().st_mtime_ns for f in lax_files} + + # existing indexes are kept, unless overwrite rebuilds them + rpy_lidar_index(in_las_folder=tmp_path.as_posix()) + assert {f: f.stat().st_mtime_ns for f in lax_files} == built + rpy_lidar_index(in_las_folder=tmp_path.as_posix(), overwrite=True) + assert all(f.exists() and f.stat().st_mtime_ns > built[f] for f in lax_files) + + +def _las_point_count(path): + """Points in a LAS file, from its header: the 64-bit count of LAS 1.4, else the legacy one.""" + import struct + with open(path, "rb") as f: + header = f.read(255) + legacy = struct.unpack_from("= 4 and len(header) >= 255: + return struct.unpack_from("= 0.95 + for name in ("cv_confusion_matrix.csv", "training_points.gpkg", "decision_tree.txt"): + assert (out / name).is_file() + + +def test_surface_water_without_chm_keeps_water_under_canopy(surface_water_data, tmp_path): + out = tmp_path / "water" + rpy_surface_water( + in_ortho=surface_water_data["ortho"], + in_training=f"{surface_water_data['training']}|training", + out_folder=out.as_posix(), + points_per_polygon=20, + min_patch_area=0, + ) + + with rasterio.open(Path(out, "surface_water.tif")) as src: + assert np.all(_area_values(src, SURFACE_WATER_UNDER_TREE) == 1) + # With min_patch_area = 0 the one-cell speck is kept + assert np.all(_area_values(src, SURFACE_WATER_SPECK) == 1) diff --git a/beratools/modules/pc2products/tools.json b/beratools/modules/pc2products/tools.json new file mode 100644 index 0000000..b519cf9 --- /dev/null +++ b/beratools/modules/pc2products/tools.json @@ -0,0 +1,978 @@ +{ + "$schema": "../../gui/assets/module.schema.json", + "module": "pc2products", + "version": "0.7.0", + "requires_frame": ">=0.7", + "category": "PC2Products", + "description": "Tools used to work with LiDAR point cloud data to produce different results. e.g. DTM, DSM and CHM.", + "docs_url": "https://beratool.github.io/beratools/pc2products/", + "tools": [ + { + "name": "LiDAR data info", + "info": "Display the LiDAR data format version, data extent, area, number of points, point density, and number of files of the input LiDAR data (las/laz).", + "batch_processing": false, + "tool_type": "python", + "tool_api": "rpy_las_info", + "cli_name": "las_info", + "entry": "beratools.modules.pc2products.rpy_las_info:rpy_las_info", + "tech_link": "user/las_info/", + "parameters": [ + { + "variable": "in_las_folder", + "accepts": "las", + "label": "Input folder", + "description": "Input LiDAR point cloud folder.", + "type": "directory", + "subtype": "file", + "default": "", + "output": false, + "optional": false + } + ] + }, + { + "name": "Raster Cell size from LiDAR data", + "info": "Calculate the recommended output raster cell size (round up to the nearest 5cm) base on the square root of (3 / point density) of LiDAR data (las/laz).", + "batch_processing": false, + "tool_type": "python", + "tool_api": "rpy_find_cellsize", + "cli_name": "cellsize", + "entry": "beratools.modules.pc2products.rpy_find_cellsize:rpy_find_cellsize", + "tech_link": "user/cellsize/", + "parameters": [ + { + "variable": "in_las_folder", + "accepts": "las", + "label": "Input folder", + "description": "Input LiDAR point cloud folder.", + "type": "directory", + "subtype": "file", + "default": "", + "output": false, + "optional": false + } + ] + }, + { + "name": "Build LiDAR Spatial Index", + "info": "Build the spatial index (.lax) of every LiDAR file (las/laz) in the folder that has none, next to the file. The other LiDAR tools build missing indexes themselves; run this first to do it ahead of time, as it reads every point once. Several files are indexed at once, one per process (at most 8).", + "batch_processing": false, + "tool_type": "python", + "tool_api": "rpy_lidar_index", + "cli_name": "lidar_index", + "entry": "beratools.modules.pc2products.rpy_lidar_index:rpy_lidar_index", + "tech_link": "user/lidar_index/", + "parameters": [ + { + "variable": "in_las_folder", + "accepts": "las", + "label": "Input folder", + "description": "Input LiDAR point cloud folder. The .lax files are written into it.", + "type": "directory", + "subtype": "file", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "overwrite", + "label": "Rebuild existing indexes", + "description": "Set to true to rebuild the indexes of files that already have one, e.g. after the files changed.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + } + ] + }, + { + "name": "Tile LiDAR Data", + "info": "Split the LiDAR files (las/laz) of a folder into square tiles sized by the point density: each 500 m block gets the largest of 500, 250, 125 or 100 m tiles whose densest tile, with its buffer, fits in the free memory, so the processing tools can later process the tiles by file. Tiles are named by their lower-left corner, the plan of tile sizes is saved as tiles.csv, and each tile gets a spatial index (.lax).", + "batch_processing": false, + "tool_type": "python", + "tool_api": "rpy_lidar_tile", + "cli_name": "tile", + "entry": "beratools.modules.pc2products.rpy_lidar_tile:rpy_lidar_tile", + "tech_link": "user/lidar_tile/", + "parameters": [ + { + "variable": "in_las_folder", + "accepts": "las", + "label": "Input LiDAR folder", + "description": "Input LiDAR point cloud folder.", + "type": "directory", + "subtype": "file", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "out_folder", + "produces": { + "las": [] + }, + "label": "Output folder for the tiles", + "description": "Folder for the tiles. It must differ from the input folder.", + "type": "directory", + "subtype": "file", + "default": "", + "output": true, + "optional": false + }, + { + "variable": "buffer", + "label": "Buffer the tiles are sized for (m)", + "description": "Buffer a tool reads around each tile when it processes the tiles later: 20 for ground classification, 30 for the other tools. The tiles themselves are cut without a buffer.", + "type": "number", + "subtype": "float", + "default": 30.0, + "output": false, + "optional": true + }, + { + "variable": "tile_size", + "label": "Tile size (m)", + "description": "Set to 0 to size the tiles by the point density (500 to 100 m), or give one size in metres for all tiles.", + "type": "number", + "subtype": "float", + "default": 0.0, + "output": false, + "optional": true + }, + { + "variable": "laz", + "label": "Compress the tiles (LAZ)", + "description": "Set to true to write LAZ tiles, about a third of the size of LAS, or false for LAS, which is faster to read.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": true, + "output": false, + "optional": true + }, + { + "variable": "skip_existing", + "label": "Skip tiles with outputs", + "description": "Set to true to resume a run that stopped: tiles already written completely are not cut again.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + } + ] + }, + { + "name": "Ground Classify Using CSF", + "info": "It implements an algorithm for segmentation of ground points base on a Cloth Simulation Filter. This method is a strict implementation of the CSF algorithm made by Zhang et al. (2016) that relies on the authors’ original source code written and exposed to R via the the RCSF package from the R package LidR.", + "batch_processing": false, + "tool_type": "python", + "tool_api": "rpy_gnd_csf", + "cli_name": "gnd_csf", + "entry": "beratools.modules.pc2products.rpy_gnd_csf:rpy_gnd_csf", + "tech_link": "user/gnd_csf/", + "parameters": [ + { + "variable": "in_las_folder", + "accepts": "las", + "label": "Input LiDAR point cloud folder", + "description": "Input LiDAR point cloud folder.", + "type": "directory", + "subtype": "file", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "out_folder", + "produces": { + "las": [] + }, + "label": "Output folder for the classified results data", + "description": "Output folder for the ground classified results data.", + "type": "directory", + "subtype": "file", + "default": "", + "output": true, + "optional": false + }, + { + "variable": "slope", + "label": "Steep slopes exists", + "description": "If steep slopes exist, set this parameter to TRUE to reduce errors during post-processing.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "class_threshold", + "label": "Ground threshold", + "description": "The distance to the simulated cloth to classify a point cloud into ground and non-ground.", + "type": "number", + "subtype": "float", + "default": 0.5, + "output": false, + "optional": true + }, + { + "variable": "cloth_resolution", + "label": "The distance between particles in the cloth", + "description": "This is usually set to the average distance of the points in the point cloud.", + "type": "number", + "subtype": "float", + "default": 1.0, + "output": false, + "optional": true + }, + { + "variable": "rigidness", + "label": "The rigidness of the cloth", + "description": "Set '1' stands for very soft (to fit rugged terrain),'2' stands for medium, and '3' stands for hard cloth (for flat terrain).", + "type": "list", + "subtype": "int", + "data": [ + 1, + 2, + 3 + ], + "default": 1, + "output": false, + "optional": true + }, + { + "variable": "tiling", + "label": "How to split the data", + "description": "'auto' tiles the data only when a file is too large for the free memory, 'by_file' processes each input file as one tile (and tiles the data instead when a file is too large for the free memory), and 'tiling' always splits the data into tiles sized for the free memory.", + "type": "list", + "subtype": "text", + "data": [ + "auto", + "by_file", + "tiling" + ], + "default": "auto", + "output": false, + "optional": true + }, + { + "variable": "skip_existing", + "label": "Skip tiles with outputs", + "description": "Set to true to resume a run that stopped: tiles whose outputs in the output folder are complete are not processed again. Use it only with the same parameters and tiling, as the output names don't record all of them.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + } + ] + }, + { + "name": "Normalize LiDAR Data", + "info": "Normalize LiDAR data using TIN, IDW or Kriging algorithm.", + "batch_processing": false, + "tool_type": "python", + "tool_api": "rpy_normalized_PC", + "cli_name": "normalize", + "entry": "beratools.modules.pc2products.rpy_normalized_PC:rpy_normalized_PC", + "icon": "", + "tech_link": "user/normalize/", + "parameters": [ + { + "variable": "in_las_folder", + "accepts": "las", + "label": "Input LiDAR folder", + "description": "Input LiDAR point cloud folder.", + "type": "directory", + "subtype": "file", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "out_folder", + "produces": { + "las": [] + }, + "label": "Products Output folder", + "description": "Output folder for the normalized LiDAR data.", + "type": "directory", + "subtype": "file", + "default": "", + "output": true, + "optional": false + }, + { + "variable": "style", + "label": "Algorithms", + "description": "Select the algorithm to normalize the LiDAR data.", + "type": "list", + "subtype": "text", + "data": [ + "tin", + "idw", + "kriging" + ], + "default": "tin", + "output": false, + "optional": false + }, + { + "variable": "tiling", + "label": "How to split the data", + "description": "'auto' tiles the data only when a file is too large for the free memory, 'by_file' processes each input file as one tile (and tiles the data instead when a file is too large for the free memory), and 'tiling' always splits the data into tiles sized for the free memory.", + "type": "list", + "subtype": "text", + "data": [ + "auto", + "by_file", + "tiling" + ], + "default": "auto", + "output": false, + "optional": true + }, + { + "variable": "skip_existing", + "label": "Skip tiles with outputs", + "description": "Set to true to resume a run that stopped: tiles whose outputs in the output folder are complete are not processed again. Use it only with the same parameters and tiling, as the output names don't record all of them.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + } + ] + }, + { + "name": "Generate DTM from LiDAR Data", + "info": "Generate DTM from LiDAR data using TIN, IDW or Kriging algorithm.", + "batch_processing": false, + "tool_type": "python", + "tool_api": "rpy_dtm_by", + "cli_name": "dtm", + "entry": "beratools.modules.pc2products.rpy_dtm_by:rpy_dtm", + "icon": "", + "tech_link": "user/dtm/", + "parameters": [ + { + "variable": "in_las_folder", + "accepts": "las", + "label": "Input LiDAR folder", + "description": "Input LiDAR point cloud folder.", + "type": "directory", + "subtype": "file", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "out_folder", + "produces": { + "dtm": [ + "Merged_*_DTM.tif", + "*_DTM.tif" + ] + }, + "label": "Products Output folder", + "description": "Output folder for the DSM raster results.", + "type": "directory", + "subtype": "file", + "default": "", + "output": true, + "optional": false + }, + { + "variable": "style", + "label": "By what algorithms", + "description": "Select the algorithm to generate the DSM raster.", + "type": "list", + "subtype": "text", + "data": [ + "tin", + "idw", + "kriging" + ], + "default": "tin", + "output": false, + "optional": false + }, + { + "variable": "cell_size", + "label": "Output raster cell size", + "description": "Define the output cell size.(in metres).\n Input 0 for cell size calculated from LiDAR data.", + "type": "number", + "subtype": "float", + "default": 0.0, + "output": false, + "optional": true + }, + { + "variable": "tiling", + "label": "How to split the data", + "description": "'auto' tiles the data only when a file is too large for the free memory, 'by_file' processes each input file as one tile (and tiles the data instead when a file is too large for the free memory), and 'tiling' always splits the data into tiles sized for the free memory.", + "type": "list", + "subtype": "text", + "data": [ + "auto", + "by_file", + "tiling" + ], + "default": "auto", + "output": false, + "optional": true + }, + { + "variable": "skip_existing", + "label": "Skip tiles with outputs", + "description": "Set to true to resume a run that stopped: tiles whose outputs in the output folder are complete are not processed again. Use it only with the same parameters and tiling, as the output names don't record all of them.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + } + ] + }, + { + "name": "Generate CHM or DSM from LiDAR Data", + "info": "Generate CHM from LiDAR data if it is normalized else generate DSM using TIN or Pitfree algorithm.", + "batch_processing": false, + "tool_type": "python", + "tool_api": "rpy_CHM_DSM_by", + "cli_name": "chm_dsm", + "entry": "beratools.modules.pc2products.rpy_CHM_DSM_by:rpy_chm_dsm_by", + "icon": "", + "tech_link": "user/chm_dsm/", + "parameters": [ + { + "variable": "in_las_folder", + "accepts": "las", + "label": "Input LiDAR folder", + "description": "Input LiDAR point cloud folder.", + "type": "directory", + "subtype": "file", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "out_folder", + "produces": { + "chm": [ + "Merged_*_CHM.tif", + "*_CHM.tif" + ], + "dsm": [ + "Merged_*_DSM.tif", + "*_DSM.tif" + ] + }, + "label": "Products Output folder", + "description": "Output folder for the DSM raster results.", + "type": "directory", + "subtype": "file", + "default": "", + "output": true, + "optional": false + }, + { + "variable": "style", + "label": "By what algorithms", + "description": "Select the algorithm to generate the DSM raster.", + "type": "list", + "subtype": "text", + "data": [ + "tin", + "pitfree" + ], + "default": "tin", + "output": false, + "optional": false + }, + { + "variable": "cell_size", + "label": "Output raster cell size", + "description": "Define the output cell size.(in metres).\n Input 0 for cell size calculated from LiDAR data.", + "type": "number", + "subtype": "float", + "default": 0.0, + "output": false, + "optional": true + }, + { + "variable": "tiling", + "label": "How to split the data", + "description": "'auto' tiles the data only when a file is too large for the free memory, 'by_file' processes each input file as one tile (and tiles the data instead when a file is too large for the free memory), and 'tiling' always splits the data into tiles sized for the free memory.", + "type": "list", + "subtype": "text", + "data": [ + "auto", + "by_file", + "tiling" + ], + "default": "auto", + "output": false, + "optional": true + }, + { + "variable": "skip_existing", + "label": "Skip tiles with outputs", + "description": "Set to true to resume a run that stopped: tiles whose outputs in the output folder are complete are not processed again. Use it only with the same parameters and tiling, as the output names don't record all of them.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + } + ] + }, + { + "name": "Detect Hummock and Hollow from LiDAR Data", + "info": "Hummock and Hollow (Micro-topography) detection from LiDAR data using dynamic moving windows and lawns threshold.", + "batch_processing": false, + "tool_type": "python", + "tool_api": "rpy_PC2hummock_hollow", + "cli_name": "hh", + "entry": "beratools.modules.pc2products.rpy_PC2hummock_hollow:rpy_hh2raster", + "icon": "", + "tech_link": "user/hummock_hollow/", + "parameters": [ + { + "variable": "in_las_folder", + "accepts": "las", + "label": "Input LiDAR folder", + "description": "Input LiDAR point cloud folder.", + "type": "directory", + "subtype": "file", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "out_folder", + "produces": { + "microform": [ + "Merged_HH_*.tif", + "HH_*.tif" + ] + }, + "label": "Products Output folder", + "description": "Output folder for the DSM raster results.", + "type": "directory", + "subtype": "file", + "default": "", + "output": true, + "optional": false + }, + { + "variable": "Smooth_by", + "label": "Smoothing DEM by mean or median", + "description": "Select parameter : 'mean' or 'median' to smooth the DEM surface.", + "type": "list", + "subtype": "text", + "data": [ + "mean", + "median" + ], + "default": "mean", + "output": false, + "optional": false + }, + { + "variable": "Min_ws", + "label": "Minimum circular moving window", + "description": "Minimum circular diameter of the dynamic moving window (in metres).", + "type": "number", + "subtype": "float", + "default": 3.0, + "output": false, + "optional": false + }, + { + "variable": "lawn_range", + "label": "Height consider as lawns", + "description": "Set the height from bare ground as lawns (in metres).", + "type": "number", + "subtype": "float", + "default": 0.3, + "output": false, + "optional": false + }, + { + "variable": "cell_size", + "label": "Output raster cell size", + "description": "Define the output Hummock/Hollow raster' cell size.(in metres).\n Input 0 for cell size calculated from LiDAR data.", + "type": "number", + "subtype": "float", + "default": 0.0, + "output": false, + "optional": true + }, + { + "variable": "tiling", + "label": "How to split the data", + "description": "'auto' tiles the data only when a file is too large for the free memory, 'by_file' processes each input file as one tile (and tiles the data instead when a file is too large for the free memory), and 'tiling' always splits the data into tiles sized for the free memory.", + "type": "list", + "subtype": "text", + "data": [ + "auto", + "by_file", + "tiling" + ], + "default": "auto", + "output": false, + "optional": true + }, + { + "variable": "skip_existing", + "label": "Skip tiles with outputs", + "description": "Set to true to resume a run that stopped: tiles whose outputs in the output folder are complete are not processed again. Use it only with the same parameters and tiling, as the output names don't record all of them.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + } + ] + }, + { + "name": "Surface Water Mapping", + "info": "Map surface water from a true-colour orthomosaic: an rpart decision tree trained on random points in labelled polygons, an optional canopy height mask and removal of small water patches (Chan, Dabros & McDermid 2026, Forests 17, 489).", + "batch_processing": false, + "tool_type": "python", + "tool_api": "rpy_surface_water", + "cli_name": "surface_water", + "entry": "beratools.modules.pc2products.rpy_surface_water:rpy_surface_water", + "icon": "", + "tech_link": "user/surface_water/", + "parameters": [ + { + "variable": "in_ortho", + "label": "Orthomosaic raster", + "description": "True-colour orthomosaic; bands 1-3 are read as red, green and blue.", + "type": "file", + "subtype": "raster", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "in_training", + "label": "Training polygons", + "description": "Polygons with a 'class' field: 'water' for surface water and other labels (e.g. 'ground', 'shadow') for everything else.", + "type": "file", + "subtype": "vector|polygon", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "out_folder", + "produces": { + "water": [ + "surface_water.tif" + ] + }, + "label": "Output folder", + "description": "Folder for surface_water.tif (1 water, 0 not water) and the cross-validation tables.", + "type": "directory", + "subtype": "file", + "default": "", + "output": true, + "optional": false + }, + { + "variable": "in_chm", + "accepts": "chm", + "label": "Canopy height model", + "description": "Optional CHM; cells with canopy taller than the maximum canopy height cannot be water.", + "type": "file", + "subtype": "raster", + "default": "", + "output": false, + "optional": true + }, + { + "variable": "max_canopy_height", + "label": "Maximum canopy height", + "description": "Cells with CHM above this height (m) are not water. Used only with a CHM.", + "type": "number", + "subtype": "float", + "default": 0.2, + "output": false, + "optional": true + }, + { + "variable": "min_patch_area", + "label": "Minimum water patch area", + "description": "Water patches smaller than this area (m2) are removed. 0 keeps every patch.", + "type": "number", + "subtype": "float", + "default": 0.04, + "output": false, + "optional": true + }, + { + "variable": "points_per_polygon", + "label": "Training points per polygon", + "description": "Number of random training points drawn inside each training polygon.", + "type": "number", + "subtype": "int", + "default": 2, + "output": false, + "optional": true + }, + { + "variable": "seed", + "label": "Random seed", + "description": "Seed for the random training points and cross-validation folds.", + "type": "number", + "subtype": "int", + "default": 1, + "output": false, + "optional": true + }, + { + "variable": "tile_size", + "label": "Tile size (cells)", + "description": "The orthomosaic is classified in square tiles of this many cells per side, in parallel; smaller tiles use less memory per worker.", + "type": "number", + "subtype": "int", + "default": 2000, + "output": false, + "optional": true + } + ] + }, + { + "name": "Depth-to-Water from Surface Water", + "info": "Krige a water table from the minimum surface water elevation in each grid cell, then compute depth-to-water as DTM minus water table, 0 on surface water (Chan, Dabros & McDermid 2026, Forests 17, 489; Rahman et al. 2017).", + "batch_processing": false, + "tool_type": "python", + "tool_api": "rpy_dtw", + "cli_name": "dtw", + "entry": "beratools.modules.pc2products.rpy_dtw:rpy_dtw", + "icon": "", + "tech_link": "user/dtw/", + "parameters": [ + { + "variable": "in_dtm", + "accepts": "dtm", + "label": "DTM raster", + "description": "Digital terrain model, e.g. from Generate DTM from LiDAR Data. The water table and DTW are produced on its grid.", + "type": "file", + "subtype": "raster", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "in_water", + "accepts": "water", + "label": "Surface water raster", + "description": "Raster with 1 for surface water, e.g. surface_water.tif from Surface Water Mapping. Resampled to the DTM grid if needed.", + "type": "file", + "subtype": "raster", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "out_folder", + "produces": { + "dtw": [ + "dtw.tif" + ] + }, + "label": "Output folder", + "description": "Folder for water_table.tif, dtw.tif and the variogram and cross-validation outputs.", + "type": "directory", + "subtype": "file", + "default": "", + "output": true, + "optional": false + }, + { + "variable": "in_mask", + "label": "Exclusion polygons", + "description": "Optional polygons to leave out (e.g. uplands with too little surface water); they get no water points and NA in the outputs.", + "type": "file", + "subtype": "vector|polygon", + "default": "", + "output": false, + "optional": true + }, + { + "variable": "grid_size", + "label": "Water point grid size", + "description": "Size (m) of the grid cells; the minimum water elevation in each cell becomes one kriging point.", + "type": "number", + "subtype": "float", + "default": 10.0, + "output": false, + "optional": true + }, + { + "variable": "nmax", + "label": "Nearest observations", + "description": "Number of nearest water points used for each kriging prediction.", + "type": "number", + "subtype": "int", + "default": 10, + "output": false, + "optional": true + }, + { + "variable": "variogram_model", + "label": "Variogram model", + "description": "gstat variogram model: Ste (Matern, M. Stein's parameterization), Sph (spherical), Exp (exponential) or Gau (Gaussian).", + "type": "list", + "subtype": "text", + "data": [ + "Ste", + "Sph", + "Exp", + "Gau" + ], + "default": "Ste", + "output": false, + "optional": true + }, + { + "variable": "kriging_cell_size", + "label": "Kriging cell size", + "description": "Cell size (m) for kriging; the result is resampled bilinearly to the DTM. 0 kriges on the DTM grid itself, which is slow for large fine DTMs.", + "type": "number", + "subtype": "float", + "default": 0.01, + "output": false, + "optional": true + }, + { + "variable": "tile_size", + "label": "Tile size (cells)", + "description": "The kriging grid is kriged in square tiles of this many cells per side, in parallel; smaller tiles use less memory per worker.", + "type": "number", + "subtype": "int", + "default": 1000, + "output": false, + "optional": true + } + ] + }, + { + "name": "Seismic Line Disturbance Analysis", + "info": "Compare seismic line segments with the adjacent undisturbed matrix by disturbance class: elevation, hummock cover, depth-to-water and surface water deviations, with Kruskal-Wallis, pairwise Wilcoxon and Brown-Forsythe tests (Chan, Dabros & McDermid 2026, Forests 17, 489).", + "batch_processing": false, + "tool_type": "python", + "tool_api": "rpy_seismic_line_analysis", + "cli_name": "line_analysis", + "entry": "beratools.modules.pc2products.rpy_seismic_line_analysis:rpy_seismic_line_analysis", + "icon": "", + "tech_link": "user/seismic_line_analysis/", + "parameters": [ + { + "variable": "in_segments", + "label": "Segment polygons", + "description": "Seismic line and matrix segment polygons with fields new_id (links a line segment to its matrix segments), note ('original' for line, 'matrix' for matrix) and Class (disturbance class).", + "type": "file", + "subtype": "vector|polygon", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "in_dtm", + "accepts": "dtm", + "label": "DTM raster", + "description": "Digital terrain model, e.g. from Generate DTM from LiDAR Data.", + "type": "file", + "subtype": "raster", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "in_microform", + "accepts": "microform", + "label": "Microform raster", + "description": "Hummock (1), lawn (0) and hollow (-1) raster, e.g. the HH_ output of Detect Hummock and Hollow from LiDAR Data.", + "type": "file", + "subtype": "raster", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "out_folder", + "label": "Output folder", + "description": "Folder for the output tables (CSV) and plots (PNG).", + "type": "directory", + "subtype": "file", + "default": "", + "output": true, + "optional": false + }, + { + "variable": "in_dtw", + "accepts": "dtw", + "label": "Depth-to-water raster", + "description": "Depth-to-water raster in metres, with 0 marking surface water. Leave empty to skip the depth-to-water and surface water analyses.", + "type": "file", + "subtype": "raster", + "default": "", + "output": false, + "optional": true + }, + { + "variable": "significance", + "label": "Significance level", + "description": "Significance level for the letter groupings of the pairwise tests.", + "type": "number", + "subtype": "float", + "default": 0.05, + "output": false, + "optional": true + } + ] + } + ] +} diff --git a/beratools/modules/raster2products/__init__.py b/beratools/modules/raster2products/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/beratools/modules/raster2products/algo_raster_smoothing.py b/beratools/modules/raster2products/algo_raster_smoothing.py new file mode 100644 index 0000000..74d2bc4 --- /dev/null +++ b/beratools/modules/raster2products/algo_raster_smoothing.py @@ -0,0 +1,275 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Description: + Smoothing a raster by the mean or median of a circular moving window, and the normalized raster + (the raster minus the smoothed raster). smooth_raster smooths any one-band raster the same way as + smooth_raster in r_scripts_collection.r (used by the hummock/hollow tool). + + Cells with no value (NaN) are left out of the window, and so are cells beyond the array's + edges: near an edge the window holds only the real neighbours. Cells with no value stay NaN. + The loops run in parallel on numba's threads (see numba.set_num_threads). smooth_rasters smooths + several rasters (tiles) in one parallel loop over all their rows, so a batch of tiles keeps many + threads busy; it runs one parallel loop at a time, so it works with any numba threading layer. +""" + +import numba +import numpy as np + +# Moved to the frame's shared helpers; imported here so old imports keep working +from beratools.utility.spatial_common import RADIUS_SLACK, circle_kernel, window_reach # noqa: F401 + +SMOOTH_BY = ("mean", "median") + + +@numba.njit(inline="always") +def _full_row(tile, out, r, dy, dx, median, buf): + """Row r of a tile: the mean or median of the window's values, gathered for every cell.""" + rows, cols = tile.shape + for c in range(cols): + if np.isnan(tile[r, c]): + continue + m = 0 + total = 0.0 + for k in range(dy.size): + rr = r + dy[k] + cc = c + dx[k] + if 0 <= rr < rows and 0 <= cc < cols: + v = tile[rr, cc] + if not np.isnan(v): + buf[m] = v + total += v + m += 1 + # the median of an even count is the mean of the two middle values, as R's median + out[r, c] = np.median(buf[:m]) if median else total / m + + +@numba.njit(inline="always") +def _insertion_sort(a, n): + for i in range(1, n): + v = a[i] + j = i - 1 + while j >= 0 and a[j] > v: + a[j + 1] = a[j] + j -= 1 + a[j + 1] = v + + +@numba.njit(inline="always") +def _sliding_median_row(tile, out, r, dys, lo, hi, win, tmp, add, rem): + """ + Row r of a tile: the median of the window, sliding it along the row. The window's values are + kept sorted, and moving one cell east only the cells leaving its west edge (column lo of each + window row) and entering its east edge (column hi) change. These few are sorted and merged into + the window in one pass, instead of finding the median of all the window's values for every cell. + The window's rows must be contiguous spans of columns (as a circle's are). Same values as + _full_row. + """ + rows, cols = tile.shape + nk = dys.size + # the window of the row's first cell + m = 0 + for k in range(nk): + rr = r + dys[k] + if rr < 0 or rr >= rows: + continue + for cc in range(max(0, lo[k]), min(cols - 1, hi[k]) + 1): + v = tile[rr, cc] + if not np.isnan(v): + win[m] = v + m += 1 + win[:m].sort() + for c in range(cols): + if c > 0: + na = 0 + nr = 0 + for k in range(nk): + rr = r + dys[k] + if rr < 0 or rr >= rows: + continue + cr = c - 1 + lo[k] # leaves the window + if 0 <= cr < cols: + v = tile[rr, cr] + if not np.isnan(v): + rem[nr] = v + nr += 1 + ca = c + hi[k] # enters it + if 0 <= ca < cols: + v = tile[rr, ca] + if not np.isnan(v): + add[na] = v + na += 1 + if na > 0 or nr > 0: + _insertion_sort(add, na) + _insertion_sort(rem, nr) + # merge: the window without rem, with add, sorted + i = 0 + j = 0 + p = 0 + t = 0 + while i < m: + v = win[i] + if j < nr and v == rem[j]: + j += 1 + i += 1 + continue + while p < na and add[p] <= v: + tmp[t] = add[p] + t += 1 + p += 1 + tmp[t] = v + t += 1 + i += 1 + while p < na: + tmp[t] = add[p] + t += 1 + p += 1 + win, tmp = tmp, win + m = t + if m > 0 and not np.isnan(tile[r, c]): + # the median of an even count is the mean of the two middle values, as R's median + h = m // 2 + out[r, c] = win[h] if m % 2 == 1 else (win[h - 1] + win[h]) / 2 + + +@numba.njit(parallel=True, nogil=True, cache=True) +def _smooth_tiles_full(data, offsets, heights, widths, row_start, dy, dx, median): + """ + The tiles (packed one after another in data) smoothed cell by cell, in one parallel loop + over all the tiles' rows. + """ + out = np.full(data.size, np.nan) + for task in numba.prange(row_start[-1]): + k = np.searchsorted(row_start, task, side="right") - 1 + h, w, o = heights[k], widths[k], offsets[k] + buf = np.empty(dy.size) + tile = data[o : o + h * w].reshape((h, w)) + _full_row(tile, out[o : o + h * w].reshape((h, w)), task - row_start[k], dy, dx, median, buf) + return out + + +@numba.njit(parallel=True, nogil=True, cache=True) +def _median_tiles_sliding(data, offsets, heights, widths, row_start, dys, lo, hi): + """ + The tiles' sliding median (see _sliding_median_row), in one parallel loop over all their + rows. + """ + out = np.full(data.size, np.nan) + n = 0 + for k in range(dys.size): + n += hi[k] - lo[k] + 1 + for task in numba.prange(row_start[-1]): + k = np.searchsorted(row_start, task, side="right") - 1 + h, w, o = heights[k], widths[k], offsets[k] + win = np.empty(n) + tmp = np.empty(n) + add = np.empty(dys.size) + rem = np.empty(dys.size) + tile = data[o : o + h * w].reshape((h, w)) + _sliding_median_row(tile, out[o : o + h * w].reshape((h, w)), task - row_start[k], dys, lo, hi, + win, tmp, add, rem) + return out + + +def _row_spans(kernel): + """ + The kernel's rows as spans of columns (row offset, first and last column offset from the + centre), or None if a row's cells aren't contiguous. + """ + cy, cx = kernel.shape[0] // 2, kernel.shape[1] // 2 + dys, lo, hi = [], [], [] + for row in range(kernel.shape[0]): + cols = np.nonzero(kernel[row])[0] + if cols.size == 0: + continue + if cols[-1] - cols[0] + 1 != cols.size: + return None + dys.append(row - cy) + lo.append(cols[0] - cx) + hi.append(cols[-1] - cx) + return np.array(dys, np.int64), np.array(lo, np.int64), np.array(hi, np.int64) + + +def _offsets(kernel): + dy, dx = np.nonzero(kernel) + return (dy - kernel.shape[0] // 2).astype(np.int64), (dx - kernel.shape[1] // 2).astype(np.int64) + + +def _check(kernel, smooth_by): + if smooth_by not in SMOOTH_BY: + raise ValueError(f"Smooth_by must be 'mean' or 'median', got {smooth_by!r}") + kernel = np.asarray(kernel, dtype=bool) + if kernel.ndim != 2 or kernel.shape[0] % 2 == 0 or kernel.shape[1] % 2 == 0: + raise ValueError("The kernel must be a 2-D array of odd size each way") + return kernel + + +def _pack(rasters): + """ + The rasters one after another in one flat float64 array, with each one's offset, height and + width, and the index of each one's first row among all the rows. + """ + tiles = [np.ascontiguousarray(r, dtype=np.float64) for r in rasters] + heights = np.array([t.shape[0] for t in tiles], dtype=np.int64) + widths = np.array([t.shape[1] for t in tiles], dtype=np.int64) + sizes = heights * widths + offsets = np.concatenate(([0], np.cumsum(sizes)[:-1])).astype(np.int64) + row_start = np.concatenate(([0], np.cumsum(heights))).astype(np.int64) + data = tiles[0].ravel() if len(tiles) == 1 else np.concatenate([t.ravel() for t in tiles]) + return data, offsets, heights, widths, row_start + + +def smooth_rasters(rasters, kernel, smooth_by): + """ + Several rasters' values (2-D arrays, NaN for no value; e.g. the buffered tiles of a DTM), each + smoothed by the mean or median of the cells of kernel (a boolean array of odd size each way, see + circle_kernel) around each cell. + + All the rasters' rows are shared out in one parallel loop, so a batch of tiles keeps more + threads busy than one tile. Returns a list of float64 arrays, one per raster. + """ + kernel = _check(kernel, smooth_by) + if not len(rasters): + return [] + data, offsets, heights, widths, row_start = _pack(rasters) + spans = _row_spans(kernel) if smooth_by == "median" else None + if spans is not None: # a circle's rows always are spans + out = _median_tiles_sliding(data, offsets, heights, widths, row_start, *spans) + else: + out = _smooth_tiles_full(data, offsets, heights, widths, row_start, *_offsets(kernel), + smooth_by == "median") + return [out[o : o + h * w].reshape(h, w) for o, h, w in zip(offsets, heights, widths)] + + +def smooth_raster(values, kernel, smooth_by): + """ + A raster's values (a 2-D array, NaN for no value; e.g. a DTM) smoothed by the mean or median + of the cells of kernel (a boolean array of odd size each way, see circle_kernel) around each + cell. + """ + return smooth_rasters([values], kernel, smooth_by)[0] + + +def _smooth(values, dy, dx, median): + """ + The mean or median of the cells at offsets (dy, dx) around each cell, gathered for every cell + (no sliding): the reference the sliding median is tested against. + """ + data, offsets, heights, widths, row_start = _pack([values]) + out = _smooth_tiles_full(data, offsets, heights, widths, row_start, np.asarray(dy, np.int64), + np.asarray(dx, np.int64), bool(median)) + return out.reshape(heights[0], widths[0]) + + +def normalized_rasters(rasters, kernel, smooth_by): + """Each raster minus its smoothed raster (see smooth_rasters).""" + rasters = [np.asarray(r, dtype=np.float64) for r in rasters] + return [r - s for r, s in zip(rasters, smooth_rasters(rasters, kernel, smooth_by))] + + +def normalized_raster(x, kernel, smooth_by): + """The raster minus the smoothed raster: hummocks positive, hollows negative, a plane 0.""" + return normalized_rasters([x], kernel, smooth_by)[0] diff --git a/beratools/modules/raster2products/docs/files/api.md b/beratools/modules/raster2products/docs/files/api.md new file mode 100644 index 0000000..de05222 --- /dev/null +++ b/beratools/modules/raster2products/docs/files/api.md @@ -0,0 +1,14 @@ +# Raster2Products API Reference + +## Tools API + +::: beratools.modules.raster2products.ndtm_fr_dtmraster + +## Algorithms + +::: beratools.modules.raster2products.algo_raster_smoothing + options: + members: + - circle_kernel + - smooth_raster + - normalized_raster diff --git a/beratools/modules/raster2products/docs/files/index.md b/beratools/modules/raster2products/docs/files/index.md new file mode 100644 index 0000000..68ff56d --- /dev/null +++ b/beratools/modules/raster2products/docs/files/index.md @@ -0,0 +1,11 @@ +# Raster2Products + +Tools that make rasters from other rasters, such as a DTM. They run in Python and need no R; they +read large rasters in tiles and process each tile in parallel. + +| Tool | `bt` subcommand | Details | +|------|-----------------|---------| +| [Normalized DTM from DTM Raster](user/ndtm_fr_dtmraster.md) | `ndtm_fr_dtmraster` | Subtracts a smoothed DTM from a DTM, so hummocks are positive and hollows negative. | + +This site covers the Raster2Products module. Installation, the GUI, the `bt` command and +pipelines are in the [BERA Tools Guide](https://beratool.github.io/beratools/). diff --git a/beratools/modules/raster2products/docs/files/technical/algorithms/raster_smoothing.md b/beratools/modules/raster2products/docs/files/technical/algorithms/raster_smoothing.md new file mode 100644 index 0000000..0466587 --- /dev/null +++ b/beratools/modules/raster2products/docs/files/technical/algorithms/raster_smoothing.md @@ -0,0 +1,129 @@ +# Raster Smoothing and Normalized DTM — Algorithm Notes + +Related user pages: [Normalized DTM from DTM Raster](../../user/ndtm_fr_dtmraster.md), +[Detect Hummock and Hollow from LiDAR Data](https://beratool.github.io/beratools/pc2products/user/hummock_hollow/) + +## Purpose + +Smooth a one-band raster, such as a DTM, by the `mean` or `median` of a circular moving window. +The normalized DTM is the DTM minus its smoothed DTM: hummocks are positive, hollows negative, and a +plane, flat or sloping, is `0`. + +The smoothing is written twice, with the same results: + +- Python: `smooth_raster` in `beratools/modules/raster2products/algo_raster_smoothing.py`, used by Normalized DTM from + DTM Raster (`beratools/modules/raster2products/ndtm_fr_dtmraster.py`). It needs no R. +- R: `smooth_raster` in `beratools/modules/pc2products/r_scripts_collection.r`, used by Detect Hummock and Hollow + from LiDAR Data on the DTM it builds from the point cloud. + +A test (`test_r_smooth_raster_matches_python` in the frame's `tests/test_cross_module.py`, as it +uses a tool of each module) checks that the +two give the same values. + +## Inputs and outputs + +- Inputs: a raster (NaN or the raster's nodata for no value), the window's radius in map units, + `mean` or `median` +- Output: the smoothed raster on the same grid; the normalized DTM tool writes + `ndtm___m.tif` + +## Method summary + +1. **Window** (`circle_kernel`): the cells whose centres lie within the radius of the centre cell, + measured with the cell width across and the cell height up and down. It is a true circle also on + cells that aren't square. `terra::focalMat(x, d, "circle")` isn't: it measures rows in steps of + the cell width too, so on 0.3 × 0.2 m cells a 1.5 m radius reached only 1.0 m up and down. +2. **Radius slack**: the window is `2 * floor(r / cell) + 1` cells each way. A cell size stored + rounded can put `r / cell` just under a whole number (a 3 m window on 0.25 m cells of a DTM in + feet came to 5.9999998 cells), which would lose the outer ring, so the radius is multiplied by + `1 + 1e-6` (`RADIUS_SLACK`). +3. **Smoothing** (`smooth_raster`): for each cell with a value, the mean or median of the cells of + the window that have a value. Cells with no value, and cells beyond the raster's edges, are left + out, so near an edge the window holds only the real neighbours. Cells with no value stay without + one. The median of an even count is the mean of the two middle values, as R's `median`. +4. **Normalized DTM** (`normalized_raster`): the DTM minus the smoothed DTM. + +The Python loops are compiled with numba and run in parallel on `processes` threads, one row of +cells per task. The R version passes the window to `terra::focal(..., na.rm = TRUE, expand = FALSE)`. + +The median slides the window along each row (`_median_sliding`). The window's values are kept +sorted; moving one cell east, only the cells leaving its west edge and entering its east edge change +(about 60 of the 709 cells of a 3 m window on 0.1 m cells). These few are sorted and merged into the +window in one pass, and the median is read from the middle. That gives exactly the values of finding +the median of the whole window at every cell, about 3 times faster for a 709-cell window and 2 times +for a 113-cell one. A window whose rows aren't single spans of columns (not a circle) uses the full +median at every cell. The mean adds up the window at every cell. + +## A folder of DTM files (Normalized DTM from DTM Raster) + +A folder's GeoTIFFs are read as one mosaic (`Mosaic` in `beratools/modules/raster2products/ndtm_fr_dtmraster.py`), +leaving out files named `ndtm_*`, `Merged_*` (the LiDAR tools' mosaic next to their tiles) and +`*.partial.tif`: + +- The files must share the CRS and the cell size (to a relative `1e-6`), be north up, and have their + corners on one grid, whole cells apart (to `1e-3` of a cell), so each file is a rectangle of rows + and columns counted from the first file's corner. The files are never resampled. +- A window of the mosaic is read from every file it overlaps, in name order. **Where files overlap, + the first file wins**: a later file fills only the cells the earlier ones have no value in. The + tool warns with the number of overlapping pairs. +- Outside every file, the mosaic has no value, as beyond a single DTM's edges. + +Each output is a rectangle of the mosaic: a file's own rectangle (one output per file) and, with +`merge_output`, also the mosaic's whole extent. With `merge_output` the tiles are laid over the +mosaic's extent, and each smoothed tile is written into the merged output and into each file's +output it overlaps, so every cell is smoothed once for all the outputs. As the windows read the mosaic, not the file, the outputs of +neighbouring files join without seams and have the values of one run on the merged DTM. + +## Tiling (Normalized DTM from DTM Raster) + +Each output is computed in square tiles of `tile_size` cells, one after another, each read with a +buffer as wide as the window's reach. Every cell's window then lies whole inside the buffered tile, +or reaches the DTM's own edge as it would in a run on the whole DTM (cells outside the DTM are read +as no value), so the tiles join with exactly the same values as smoothing the whole DTM at once. +Each tile is cropped back to its own cells and written into the output, which is written under a +`.partial.tif` name and renamed once complete. + +Reading, smoothing and writing overlap, on three threads of the tool: + +- A **reader** thread reads the next buffered tiles from the DTM files, up to one batch's cells + ahead, so the smoothing doesn't wait on the drive. +- The main thread smooths the tiles in **batches**, in one parallel loop over all the batch's rows + (`smooth_rasters`). A batch takes tiles until it has 32 rows per thread + (`BATCH_ROWS_PER_THREAD`): a 2000-cell tile already has that for up to ~60 threads, so a laptop or + a small machine smooths one tile at a time and pays nothing for batching, while a machine with + ~100 cores smooths 2 or 3 tiles at once, which keeps its threads busy. A batch uses at most a + quarter of the free memory (`BATCH_MEMORY_FRACTION`, about 40 bytes a cell). +- A **writer** thread writes (and compresses) the smoothed tiles while the next batch is smoothed, + holding at most 16 tiles (`WRITE_QUEUE`). + +The values are the same whatever the batches; an error on any thread stops the run and leaves no +`.partial.tif` file. Batching and the overlap matter most where reading or writing is slow (a +network or iSCSI drive) or where a tile has fewer rows than the machine has threads to fill; on a +laptop with the DTM on a local disk they gain little. + +## Assumptions + +- The raster is in a projected CRS. The normalized DTM tool converts `Min_ws` (metres) to the map + units from the CRS, and refuses a CRS in degrees. +- The window is at least 3 cells across: `Min_ws` at least twice the cell size. + +## Edge cases + +- A tile with no values is written as no data; a DTM with no values at all is refused. In a folder, + a file with no values gets no output (with a warning). +- Files of a folder on another grid, CRS or cell size are refused: resample them onto one grid + first. +- A larger window takes longer, about in proportion to the cells in the circle. Per 2000 × 2000 + tile on 20 threads: a 3 m window on 0.25 m cells (113 cells) about 0.2 s for the median and 0.1 s + for the mean; on 0.1 m cells (709 cells) about 0.7 s for the median and 0.3 s for the mean. +- A folder's files are opened at the start to read their grids, with progress. The first 8 are + opened one at a time and timed: if an open takes 10 ms or more (a network or iSCSI drive, where + each open waits on the network), the rest are opened 16 at a time; otherwise they stay one at a + time, as on a local disk threads only wait on each other (`HEADER_PROBE`, `HEADER_SLOW_OPEN`, + `HEADER_THREADS`). For thousands of files on a network drive this can still take a while. +- GDAL lists a file's folder on every open, looking for sidecar files (`.aux.xml`, `.ovr`, `.tfw`, + ...). In a folder of 2,380 DTM tiles on an iSCSI drive, that made each open take about 0.1 s, so the + tool opens the DTM files without it (`GDAL_DISABLE_READDIR_ON_OPEN=EMPTY_DIR`), unless the first + file reads differently without it (its CRS, grid, no-data value or mask is in a sidecar file). +- The mosaic keeps up to 256 DTM files open (`OPEN_FILES`), so a file is opened about once in a run, + not once for each tile whose buffered window reaches it. diff --git a/beratools/modules/raster2products/docs/files/user/ndtm_fr_dtmraster.md b/beratools/modules/raster2products/docs/files/user/ndtm_fr_dtmraster.md new file mode 100644 index 0000000..aebfd4d --- /dev/null +++ b/beratools/modules/raster2products/docs/files/user/ndtm_fr_dtmraster.md @@ -0,0 +1,80 @@ +# Normalized DTM from DTM Raster + +> Algorithm details: [Technical Guide → Raster Smoothing and Normalized DTM](../technical/algorithms/raster_smoothing.md) + +Maps the micro-topography of a DTM: the DTM minus the DTM smoothed by the mean or median of a +circular moving window. Ground higher than its surroundings (hummocks) is positive, ground lower +(hollows) is negative, and a plane, flat or sloping, is `0`. It is the continuous surface that +[Detect Hummock and Hollow from LiDAR Data](https://beratool.github.io/beratools/pc2products/user/hummock_hollow/) writes as `CHH_*.tif`, made from a DTM +you already have instead of from the point cloud. + +The DTM can be one raster, or a folder of DTM GeoTIFFs, such as the per-tile DTMs of +[Generate DTM from LiDAR Data](https://beratool.github.io/beratools/pc2products/user/dtm/). The files of a folder are read as one mosaic, so each cell's +window reaches across the files' edges into the neighbouring files: the outputs join without seams, +with the same values as one run on the merged DTM. + +The tool: + +1. Converts `Min_ws`, the window's diameter in metres, to the DTM's map units from its CRS, so a DTM + in feet gets the same window. The DTM must be in a projected CRS. `Min_ws` must be at least twice + the cell size (a window of 3 cells across): 0.5 m on 0.25 m cells. The window is the cells whose + centres lie within its radius, a true circle also on cells that aren't square. +2. For a folder, checks that the files share the CRS, the cell size and the grid (their corners + whole cells apart), and warns about files that overlap. **Where files overlap, the first file in + name order wins**: a later file's value is used only where the earlier ones have none. +3. Reads the DTM in square tiles of `tile_size` cells, one after another, each with a buffer as wide + as the window's radius, so every cell's window lies whole inside it: the tiles join with the same + values as smoothing the whole DTM at once. +4. Smooths each tile by `Smooth_by` over the window (cells with no value are left out, and near the + DTM's edges the window holds only the cells inside the DTM), in parallel on `processes` threads + (all CPU cores but one by default), subtracts the smoothed DTM from the DTM, and writes the tile + into the outputs on the DTM's grid: one output per DTM file, and with `merge_output` also one + merged output. A tile is smoothed once and written into every output it overlaps, so the merged + output costs no more smoothing. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `in_dtm` | raster or folder | Yes | DTM in a projected CRS, for example `Merged_TIN_DTM.tif` from [Generate DTM from LiDAR Data](https://beratool.github.io/beratools/pc2products/user/dtm/) or a GDAL `.vrt`, or a folder of DTM GeoTIFFs (`*.tif`) on one grid. In the GUI, `...` picks a file and `Folder...` a folder. The outputs have the DTM's cells. | +| `out_folder` | directory (output) | Yes | Folder for the outputs. | +| `Smooth_by` | `mean` \| `median` | Yes | How the window smooths the DTM. The default is `mean`. | +| `Min_ws` | float | Yes | Diameter of the circular window in metres. The default is `3`. | +| `merge_output` | bool | No | For a folder: `true` writes one normalized DTM over all the files, named after the folder, as well as the one per file; `false` (the default) writes only the one per file, on its grid. The values are the same either way. | +| `tile_size` | int | No | Cells per side of the tiles the DTM is read in. The default is `2000`; smaller tiles use less memory. | + +| Output | Contents | +|--------|----------| +| `ndtm___m.tif` | Normalized DTM (m): positive on hummocks, negative in hollows. One per DTM file (`` is the file's name), and with `merge_output` also one for the folder (`` is the folder's name; no DTM file may have that name). | + +Files in the DTM folder named `ndtm_*` (this tool's outputs), `Merged_*` (the mosaic the LiDAR tools +write next to their tiles, such as `Merged_TIN_DTM.tif`, which would overlap every tile) or +`*.partial.tif` (partly written files) are not read as DTMs. So the output folder of Generate DTM +from LiDAR Data can be given as it is, and the outputs can go into the DTM folder itself. + +The tool runs in Python (numpy and numba) and needs no R. It reads the next tiles and writes the +finished ones while it smooths, and on a machine with many cores it smooths a few tiles at once. It +holds about 40 bytes per cell of the tiles in hand, about 0.2 GB for each 2000-cell tile, and at +most a quarter of the free memory for a batch. A 2000 × 2000-cell tile with a 3 m +window takes about 0.2 s on 0.25 m cells and 0.7 s on 0.1 m cells for the median (20 threads); the +mean is faster, and a larger window takes longer, about in proportion to the cells in the circle. +Smaller cells cost twice: more cells, and more cells in each window. For a large area at 0.1 m, the +time is mostly the number of tiles times this, plus reading the DTM files, which is slower from a +network drive. For a folder, the tool first reads every file's grid, with progress. + +```python +from beratools.modules.raster2products.ndtm_fr_dtmraster import ndtm_fr_dtmraster + +ndtm_fr_dtmraster(in_dtm="dtm/Merged_TIN_DTM.tif", out_folder="ndtm", Smooth_by="median", Min_ws=3.0) +# the DTM tiles of Generate DTM from LiDAR Data: one output per tile, and also one merged output +ndtm_fr_dtmraster(in_dtm="dtm", out_folder="ndtm", Smooth_by="median", Min_ws=3.0) +ndtm_fr_dtmraster(in_dtm="dtm", out_folder="ndtm", Smooth_by="median", Min_ws=3.0, merge_output=True) +``` + +The function returns the list of the outputs written, the merged one first. + +## Command line + +```bash +bt ndtm_fr_dtmraster # show the parameters +bt ndtm_fr_dtmraster --in_dtm dtm/Merged_TIN_DTM.tif --out_folder --Smooth_by median --Min_ws 3 +bt ndtm_fr_dtmraster --in_dtm dtm --out_folder --Smooth_by median --Min_ws 3 --merge_output true +``` diff --git a/beratools/modules/raster2products/docs/mkdocs.yml b/beratools/modules/raster2products/docs/mkdocs.yml new file mode 100644 index 0000000..ce57c53 --- /dev/null +++ b/beratools/modules/raster2products/docs/mkdocs.yml @@ -0,0 +1,16 @@ +# The Raster2Products module's docs site. Shared settings are in docs/base.yml at the repo root. +# Build with `zensical`, not `mkdocs`. +INHERIT: ../../../../docs/base.yml + +site_name: BERA Tools Raster2Products +site_url: https://beratool.github.io/beratools/raster2products/ +edit_uri: edit/main/beratools/modules/raster2products/docs/files/ + +nav: + - Home: index.md + - User Guide: + - user/ndtm_fr_dtmraster.md + - Technical Guide: + - technical/algorithms/raster_smoothing.md + - API Reference: api.md + - BERA Tools Guide: https://beratool.github.io/beratools/ diff --git a/beratools/modules/raster2products/ndtm_fr_dtmraster.py b/beratools/modules/raster2products/ndtm_fr_dtmraster.py new file mode 100644 index 0000000..57165b9 --- /dev/null +++ b/beratools/modules/raster2products/ndtm_fr_dtmraster.py @@ -0,0 +1,612 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Description: + Normalized DTM from a DTM raster, or from a folder of DTM rasters: the DTM minus the DTM smoothed + by the mean or median of a circular moving window, so hummocks are positive and hollows negative + (see beratools.modules.raster2products.algo_raster_smoothing). Pure Python: no R needed. + + The files of a folder are read as one mosaic, so the windows reach across the files' edges and + the outputs join without seams: one output per file, on its grid, and optionally one merged output. +""" + +import os +import queue +import threading +import time +from collections import OrderedDict, deque +from concurrent.futures import ThreadPoolExecutor +from contextlib import closing +from pathlib import Path + +import numba +import numpy as np +import psutil +import rasterio +from rasterio.transform import Affine +from rasterio.windows import Window + +import beratools.modules.raster2products.algo_raster_smoothing as smoothing +import beratools.utility.spatial_common as sp_common +from beratools.core.tool_base import print_msg +from beratools.utility.tool_args import CallMode, determine_cpu_core_limit + +DTM_SUFFIXES = (".tif", ".tiff") +GRID_TOLERANCE = 1e-3 # of a cell: how far a file's corner may be off the mosaic's grid +# Reading the DTM files' headers: after the first, HEADER_PROBE files are opened one at a time and timed. +# If an open takes HEADER_SLOW_OPEN seconds or more on average, it waits mostly on the disk or the +# network (a network drive), so the rest are opened HEADER_THREADS at a time; a quick open (a local +# disk, ~3 ms) is slower on threads, which then mostly wait on each other's locks. +HEADER_PROBE = 8 +HEADER_SLOW_OPEN = 0.010 +HEADER_THREADS = 16 +# GDAL lists a file's folder on every open, looking for sidecar files (.aux.xml, .ovr, .tfw, ...). +# In a folder of thousands of DTM tiles on an iSCSI drive that made each open take ~0.1 s, so the +# DTM files are opened without it, unless the first file reads differently without it (a sidecar +# matters, see sidecars_matter) +NO_READDIR = {"GDAL_DISABLE_READDIR_ON_OPEN": "EMPTY_DIR"} +OPEN_FILES = 256 # DTM files the mosaic keeps open, so each is opened about once in a run + + +def output_name(in_dtm, smooth_by, min_ws): + """ + ndtm___m.tif, with Min_ws written as R prints it (3, not 3.0). + For a folder, the DTM name is the folder's name. + """ + path = Path(in_dtm) + name = path.name if path.is_dir() else path.stem + return f"ndtm_{name}_{smooth_by}_{float(min_ws):.15g}m.tif" + + +# Files of a DTM folder that aren't read as DTM tiles: this tool's outputs, partly written files, +# and the Merged_* mosaics the LiDAR tools write next to their tiles (Merged_TIN_DTM.tif), which +# would overlap every tile +LEFT_OUT_PREFIXES = ("ndtm_", "merged_") + + +def dtm_files(in_dtm): + """ + The DTM file, or the GeoTIFFs of a folder in name order, leaving out this tool's outputs + (ndtm_*), Merged_* mosaics and partly written files (*.partial.tif). + """ + path = Path(in_dtm) + if path.is_file(): + return [path] + if not path.is_dir(): + raise FileNotFoundError(f"Cannot locate the DTM file or folder: {in_dtm}") + tifs = sorted(f for f in path.iterdir() if f.is_file() and f.suffix.lower() in DTM_SUFFIXES) + left_out = [f for f in tifs + if f.name.lower().startswith(LEFT_OUT_PREFIXES) or ".partial." in f.name.lower()] + files = [f for f in tifs if f not in left_out] + if left_out: + shown = ", ".join(f.name for f in left_out[:3]) + (", ..." if len(left_out) > 3 else "") + print(f"Not read as DTM tiles: {len(left_out)} file(s) named ndtm_*, Merged_* or *.partial.tif " + f"({shown}).", flush=True) + if not files: + raise FileNotFoundError(f"No DTM GeoTIFFs (*.tif) in the folder: {in_dtm}") + return files + + +def _describe(path): + with rasterio.open(path) as src: + return src.crs, src.transform, src.nodata, src.mask_flag_enums, src.count, src.dtypes + + +def sidecars_matter(path): + """ + Whether the DTM file reads differently (CRS, grid, no-data value or mask) when GDAL doesn't + look for sidecar files next to it. + """ + with_listing = _describe(path) + with rasterio.Env(**NO_READDIR): + return _describe(path) != with_listing + + +class Mosaic: + """ + DTM files on one grid (same CRS and cell size, corners on the same grid), read as one raster. + + Each file's cells are a rectangle of rows and columns of the grid, counted from the first file's + top-left corner. Where files overlap, the first file in name order wins: the value of a later + file is used only where the earlier ones have none. + """ + + def __init__(self, files, gdal_env=None): + self.files = [Path(f) for f in files] + self.gdal_env = dict(gdal_env or {}) # GDAL options for opening the files (NO_READDIR) + self._datasets = OrderedDict() # the files kept open, by index, least recently read first + headers = self._read_headers() + self.crs, t0 = headers[0][0], headers[0][1] + if t0.b != 0 or t0.d != 0 or t0.a <= 0 or t0.e >= 0: + raise ValueError(f"The DTM must be north up, without rotation: {self.files[0].name}") + self.res_x, self.res_y = t0.a, -t0.e + self.left, self.top = t0.c, t0.f + rects = [] + for f, (crs, t, height, width) in zip(self.files, headers): + if crs != self.crs: + raise ValueError( + f"{f.name} has another CRS than {self.files[0].name}; all DTM files must share one." + ) + if t.b != 0 or t.d != 0 or not np.isclose(t.a, self.res_x, rtol=1e-6) \ + or not np.isclose(-t.e, self.res_y, rtol=1e-6): + raise ValueError( + f"{f.name} has other cells ({abs(t.a):g} x {abs(t.e):g}) than {self.files[0].name} " + f"({self.res_x:g} x {self.res_y:g}); all DTM files must share the cell size." + ) + col = (t.c - self.left) / self.res_x + row = (self.top - t.f) / self.res_y + if abs(col - round(col)) > GRID_TOLERANCE or abs(row - round(row)) > GRID_TOLERANCE: + raise ValueError( + f"{f.name} is not on the grid of {self.files[0].name}: its corner is off by a part " + "of a cell. Resample the DTM files onto one grid first." + ) + rects.append((round(row), round(col), height, width)) + self.rects = np.array(rects, dtype=np.int64) # row, col, height, width + r0, c0 = self.rects[:, 0].min(), self.rects[:, 1].min() + r1 = (self.rects[:, 0] + self.rects[:, 2]).max() + c1 = (self.rects[:, 1] + self.rects[:, 3]).max() + self.extent = (int(r0), int(c0), int(r1 - r0), int(c1 - c0)) + + def _read_headers(self, threads=None): + """ + Each file's CRS, transform, height and width, in the files' order. The first files are + opened one at a time; if they are slow to open (a network drive), the rest are opened + HEADER_THREADS at a time. threads (True or False) forces either way. + """ + + def header(f): + with rasterio.Env(**self.gdal_env), rasterio.open(f) as src: + return src.crs, src.transform, src.height, src.width + + n = len(self.files) + if n == 1: + return [header(self.files[0])] + print(f"Reading the grids of {n} DTM files...", flush=True) + step = max(1, n // 50) + headers = [] + + def add(h): + headers.append(h) + if len(headers) % step == 0 or len(headers) == n: + print_msg("Reading DTM file grids", len(headers), n) + + # the first open also starts GDAL and PROJ up, so it isn't timed + add(header(self.files[0])) + start = time.perf_counter() + for f in self.files[1 : HEADER_PROBE + 1]: + add(header(f)) + probed = len(headers) - 1 + rest = self.files[HEADER_PROBE + 1 :] + if threads is None: + threads = probed > 0 and (time.perf_counter() - start) / probed >= HEADER_SLOW_OPEN + if threads and len(rest) > 1: + print(f"The DTM files are slow to open (a network drive?); reading {HEADER_THREADS} at a time.", + flush=True) + with ThreadPoolExecutor(max_workers=HEADER_THREADS) as pool: + for h in pool.map(header, rest): + add(h) + else: + for f in rest: + add(header(f)) + return headers + + def _dataset(self, i): + """File i, opened once and kept open (up to OPEN_FILES, closing the least recently read).""" + src = self._datasets.pop(i, None) + if src is None: + with rasterio.Env(**self.gdal_env): + src = rasterio.open(self.files[i]) + while len(self._datasets) >= OPEN_FILES: + self._datasets.popitem(last=False)[1].close() + self._datasets[i] = src + return src + + def close(self): + while self._datasets: + self._datasets.popitem()[1].close() + + def transform_at(self, row, col): + x, y = self.left + col * self.res_x, self.top - row * self.res_y + return Affine(self.res_x, 0, x, 0, -self.res_y, y) + + def overlaps(self): + """Pairs (i, j), i < j, of files whose cells overlap.""" + r0, c0 = self.rects[:, 0], self.rects[:, 1] + r1, c1 = r0 + self.rects[:, 2], c0 + self.rects[:, 3] + pairs = [] + for i in range(len(self.rects) - 1): + j = np.arange(i + 1, len(self.rects)) + hit = (np.minimum(r1[i], r1[j]) > np.maximum(r0[i], r0[j])) & \ + (np.minimum(c1[i], c1[j]) > np.maximum(c0[i], c0[j])) + pairs += [(i, int(k)) for k in j[hit]] + return pairs + + def read(self, row, col, height, width): + """The cells of a window of the grid (float64, NaN for no value, also outside the files).""" + out = np.full((height, width), np.nan) + r0, c0 = self.rects[:, 0], self.rects[:, 1] + top, left = np.maximum(r0, row), np.maximum(c0, col) + bottom = np.minimum(r0 + self.rects[:, 2], row + height) + right = np.minimum(c0 + self.rects[:, 3], col + width) + for i in np.nonzero((bottom > top) & (right > left))[0]: # in name order: the first wins + h, w = int(bottom[i] - top[i]), int(right[i] - left[i]) + window = Window(int(left[i] - c0[i]), int(top[i] - r0[i]), w, h) + part = self._dataset(i).read(1, window=window, masked=True) + part = part.astype(np.float64).filled(np.nan) + dest = out[top[i] - row : top[i] - row + h, left[i] - col : left[i] - col + w] + empty = np.isnan(dest) + dest[empty] = part[empty] + return out + + +def _threads(processes): + threads = determine_cpu_core_limit() if processes <= 0 else processes + return max(1, min(threads, numba.config.NUMBA_NUM_THREADS)) + + +# Tiles are smoothed in batches, in one parallel loop over all the batch's rows (smooth_rasters). +# A batch takes tiles until it has BATCH_ROWS_PER_THREAD rows for each thread: a 2000-cell tile +# already gives that to up to ~60 threads, so a laptop or a small machine smooths one tile at a +# time, and a machine with ~100 cores several tiles at once, keeping its threads busy. A batch +# holds at most BATCH_MEMORY_FRACTION of the free memory, at BYTES_PER_BATCH_CELL a cell (the tile, +# its packed copy, the smoothed and the normalized tile). Meanwhile the next tiles are read on one +# thread (up to one more batch's cells) and the smoothed ones written on another, so reading, +# smoothing and writing (compressing) overlap. +BATCH_ROWS_PER_THREAD = 32 +BATCH_MEMORY_FRACTION = 0.25 +BYTES_PER_BATCH_CELL = 40 +WRITE_QUEUE = 16 # smoothed tiles waiting to be written (at most ~16 MB each) + + +def batch_limits(threads): + """Rows and cells a batch of tiles is filled up to on this machine.""" + free = psutil.virtual_memory().available + return threads * BATCH_ROWS_PER_THREAD, max(1, int(free * BATCH_MEMORY_FRACTION / BYTES_PER_BATCH_CELL)) + + +def _read_ahead(read, jobs, max_cells): + """(job, read(job)) for each job in order, read on a thread up to max_cells cells ahead.""" + cond = threading.Condition() + items = deque() + state = {"queued": 0, "done": False, "error": None, "stop": False} + + def run(): + try: + for job in jobs: + part = read(job) + with cond: + while state["queued"] and state["queued"] + part.size > max_cells and not state["stop"]: + cond.wait() + if state["stop"]: + return + items.append((job, part)) + state["queued"] += part.size + cond.notify_all() + except BaseException as e: # raised again in the main thread + with cond: + state["error"] = e + finally: + with cond: + state["done"] = True + cond.notify_all() + + reader = threading.Thread(target=run, name="ndtm-reader", daemon=True) + reader.start() + try: + while True: + with cond: + while not items and not state["done"]: + cond.wait() + if state["error"] is not None: + raise state["error"] + if not items: + return + job, part = items.popleft() + state["queued"] -= part.size + cond.notify_all() + yield job, part + finally: + with cond: + state["stop"] = True + cond.notify_all() + reader.join() + + +def _overlap(a, b): + """The rectangle (row, col, height, width) two rectangles share, or None.""" + top, left = max(a[0], b[0]), max(a[1], b[1]) + bottom, right = min(a[0] + a[2], b[0] + b[2]), min(a[1] + a[3], b[1] + b[3]) + return (top, left, bottom - top, right - left) if bottom > top and right > left else None + + +def _write_outputs(mosaic, targets, kernel, smooth_by, tile_size, threads, progress, grids=None): + """ + Write the normalized DTM of each target (a rectangle row, col, height, width of the mosaic, + and its output file), in tiles read with a buffer of the window's reach and smoothed in batches + (see batch_limits). grids are the rectangles tiled, each with the targets its tiles are written + into (by default each target's own rectangle, into it alone): a tile is smoothed once and + written into each of its targets it overlaps, so one tiling of the mosaic's extent writes the + merged output and the per-file outputs together. Each output is written under a .partial name + and renamed once complete, so a stopped run leaves no cut-short file under the name; an output + with no values isn't written. Returns, for each target, whether it was written. + """ + buf_y, buf_x = kernel.shape[0] // 2, kernel.shape[1] // 2 + if grids is None: + grids = [(rect, [t]) for t, (rect, _) in enumerate(targets)] + jobs = [] # (row, col, height, width of the tile in the mosaic, [(target, shared rectangle)]) + for (row, col, height, width), into in grids: + for r in range(row, row + height, tile_size): + for c in range(col, col + width, tile_size): + tile = (r, c, min(tile_size, row + height - r), min(tile_size, col + width - c)) + outs = [(t, part) for t in into if (part := _overlap(tile, targets[t][0]))] + jobs.append((*tile, outs)) + remaining = [0] * len(targets) + for job in jobs: + for t, _ in job[4]: + remaining[t] += 1 + has_values = [False] * len(targets) + written = [False] * len(targets) + open_outputs = {} # target -> (dataset, .partial path) + max_rows, max_cells = batch_limits(threads) + + def read(job): + r, c, h, w, _ = job + return mosaic.read(r - buf_y, c - buf_x, h + 2 * buf_y, w + 2 * buf_x) + + def open_output(t): + (row, col, height, width), out_file = targets[t] + profile = dict( + driver="GTiff", width=width, height=height, count=1, dtype="float32", crs=mosaic.crs, + transform=mosaic.transform_at(row, col), nodata=np.nan, compress="deflate", predictor=3, + tiled=True, blockxsize=256, blockysize=256, BIGTIFF="IF_SAFER", + ) + partial = out_file.with_name(out_file.stem + ".partial.tif") + dst = rasterio.open(partial, "w", **profile) + dst.set_band_description(1, "ndtm") + open_outputs[t] = (dst, partial) + + def write(job, values): + r, c, _, _, outs = job + for t, (pr, pc, ph, pw) in outs: + if t not in open_outputs: + open_output(t) + row, col = targets[t][0][:2] + part = values[pr - r : pr - r + ph, pc - c : pc - c + pw] + open_outputs[t][0].write(part, 1, window=Window(pc - col, pr - row, pw, ph)) + remaining[t] -= 1 + if remaining[t] == 0: + dst, partial = open_outputs.pop(t) + dst.close() + if has_values[t]: + os.replace(partial, targets[t][1]) + written[t] = True + print(f"Normalized DTM saved to: {targets[t][1].as_posix()}", flush=True) + else: + partial.unlink() + progress() + + # the smoothed tiles are written on a thread, in order, while the next batch is smoothed + to_write = queue.Queue(maxsize=WRITE_QUEUE) + writer_error = [] + + def writer(): + try: + while True: + item = to_write.get() + if item is None: + return + write(*item) + except BaseException as e: # raised again in the main thread + writer_error.append(e) + while to_write.get() is not None: # let the main thread finish putting + pass + + def put(item): + while True: + if writer_error: + raise writer_error[0] + try: + to_write.put(item, timeout=0.5) + return + except queue.Full: + pass + + writing = threading.Thread(target=writer, name="ndtm-writer", daemon=True) + writing.start() + batch = [] + + def flush(): + ndtms = smoothing.normalized_rasters([part for _, part in batch], kernel, smooth_by) + for (job, _), ndtm in zip(batch, ndtms): + h, w = job[2], job[3] + put((job, ndtm[buf_y : buf_y + h, buf_x : buf_x + w].astype(np.float32))) + batch.clear() + + try: + try: + with closing(_read_ahead(read, jobs, max_cells)) as tiles: + rows = cells = 0 + for job, part in tiles: + r, c, h, w, outs = job + core = part[buf_y : buf_y + h, buf_x : buf_x + w] + if np.isnan(core).all(): + put((job, np.full((h, w), np.nan, dtype=np.float32))) + continue + for t, (pr, pc, ph, pw) in outs: + if not has_values[t]: + has_values[t] = not np.isnan( + core[pr - r : pr - r + ph, pc - c : pc - c + pw] + ).all() + if batch and cells + part.size > max_cells: + flush() + rows = cells = 0 + batch.append((job, part)) + rows += part.shape[0] + cells += part.size + if rows >= max_rows: + flush() + rows = cells = 0 + if batch: + flush() + finally: + to_write.put(None) + writing.join() + if writer_error: + raise writer_error[0] + finally: + for dst, partial in open_outputs.values(): # a run that stopped + dst.close() + partial.unlink(missing_ok=True) + return written + + +def ndtm_fr_dtmraster( + in_dtm, + out_folder, + Smooth_by="mean", + Min_ws=3.0, + merge_output=False, + tile_size=2000, + processes=0, + call_mode=CallMode.CLI, + log_level="INFO", + **kwargs, +): + """ + Normalized DTM from a DTM raster, or from a folder of DTM rasters. + + Args: + in_dtm: DTM raster (GeoTIFF, or a GDAL .vrt of DTM tiles) in a projected CRS, or a folder of + DTM GeoTIFFs on one grid (same CRS and cell size), read as one mosaic; where files + overlap, the first in name order wins + out_folder: folder for the output(s) + Smooth_by: 'mean' or 'median' of the cells in the window + Min_ws: the window's diameter in metres, converted to the DTM's map units + merge_output: for a folder, also write one merged output, besides the one per file + tile_size: cells per side of the square tiles the DTM is processed in; each tile is read + with a buffer of the window's radius, so the tiles give the same values as the whole + DTM at once + processes: threads that smooth each tile (0: all CPU cores but one) + + Returns: + The list of the paths of the outputs written, ndtm___m.tif in + out_folder: one per DTM file, on its grid, and with merge_output first one for the folder + (named after it). Each tile is smoothed once and written into every output it overlaps. + """ + if Smooth_by not in smoothing.SMOOTH_BY: + raise ValueError(f"Smooth_by must be 'mean' or 'median', got {Smooth_by!r}") + Min_ws = float(Min_ws) + if not Min_ws > 0: + raise ValueError(f"Min_ws must be a window size in metres above 0, got {Min_ws}") + if isinstance(merge_output, str): + merge_output = merge_output.strip().lower() == "true" + tile_size = max(1, int(tile_size)) + files = dtm_files(in_dtm) + is_folder = Path(in_dtm).is_dir() + + gdal_env = NO_READDIR + if sidecars_matter(files[0]): + print(f"{files[0].name} reads differently without its sidecar files (.aux.xml, .tfw, ...), so GDAL " + "looks for them on every open, which is slower in a large folder.", flush=True) + gdal_env = {} + mosaic = Mosaic(files, gdal_env) + if mosaic.crs is None or not mosaic.crs.is_projected: + raise ValueError( + "The DTM's CRS is not projected (or unknown), so a window in metres can't be converted " + "to its units. Project the DTM first." + ) + unit_m = mosaic.crs.linear_units_factor[1] # metres per map unit + radius = Min_ws / 2 / unit_m + # a radius of at least one cell each way, so the circle is at least 3 cells across + cell = max(mosaic.res_x, mosaic.res_y) + if sp_common.window_reach(radius) / cell < 1: + raise ValueError( + f"A {Min_ws:g} m window is under 3 cells across at the DTM's {round(cell * unit_m, 3)} m cells; " + f"use a window of at least {round(2 * cell * unit_m, 3)} m." + ) + kernel = sp_common.circle_kernel(radius, mosaic.res_x, mosaic.res_y) + threads = _threads(int(processes)) + numba.set_num_threads(threads) + + out_dir = Path(out_folder) + grids = None # each target tiled on its own + if not is_folder: + targets = [(mosaic.extent, out_dir / output_name(files[0], Smooth_by, Min_ws))] + else: + targets = [(tuple(int(v) for v in rect), out_dir / output_name(f, Smooth_by, Min_ws)) + for f, rect in zip(files, mosaic.rects)] + names = [t[1].name.lower() for t in targets] + if len(set(names)) < len(names): + raise ValueError("Two DTM files have the same name apart from the extension; rename one.") + if merge_output: + # the merged output and the per-file ones, from one tiling of the mosaic's extent + merged = out_dir / output_name(in_dtm, Smooth_by, Min_ws) + if merged.name.lower() in names: + raise ValueError(f"A DTM file gives the merged output's name, {merged.name}; rename it.") + targets.insert(0, (mosaic.extent, merged)) + grids = [(mosaic.extent, list(range(len(targets))))] + + print("Generating the normalized DTM...", flush=True) + if is_folder: + print(f"{len(files)} DTM file(s) in {Path(in_dtm).as_posix()}, read as one mosaic of " + f"{mosaic.extent[2]} x {mosaic.extent[3]} cells; writing " + f"{'one merged output and one per file' if merge_output else 'one output per file'}.", + flush=True) + pairs = mosaic.overlaps() + if pairs: + shown = ", ".join(f"{files[i].name} and {files[j].name}" for i, j in pairs[:3]) + shown += ", ..." if len(pairs) > 3 else "" + print( + f"Warning! {len(pairs)} pair(s) of DTM files overlap ({shown}). " + "Where they overlap, the first file in name order wins: a later file's value is used only " + "where the earlier ones have none.", + flush=True, + ) + print( + f"Smoothing by the {Smooth_by} of a {Min_ws:g} m circular window " + f"({kernel.shape[1]} x {kernel.shape[0]} cells, {int(kernel.sum())} in the circle) on cells of " + f"{round(mosaic.res_x * unit_m, 3)} x {round(mosaic.res_y * unit_m, 3)} m, in tiles of " + f"{tile_size} x {tile_size} cells with {threads} thread(s), smoothed in batches of up to " + f"{batch_limits(threads)[0]} rows of tiles while the next tiles are read...", + flush=True, + ) + + out_dir.mkdir(parents=True, exist_ok=True) + # the partly written outputs of a run that stopped + for left in out_dir.glob("ndtm_*.partial.tif"): + print(f"Removing a partly written file of a run that stopped: {left.name}", flush=True) + left.unlink() + + total = sum(-(-rect[2] // tile_size) * -(-rect[3] // tile_size) + for rect, _ in (grids or targets)) + done = [0] + + def progress(): + done[0] += 1 + print_msg("Normalized DTM tiles", done[0], total) + + try: + ok_targets = _write_outputs(mosaic, targets, kernel, Smooth_by, tile_size, threads, progress, grids) + finally: + mosaic.close() + written = [out_file.as_posix() for (_, out_file), ok in zip(targets, ok_targets) if ok] + if len(targets) > 1: + for (_, out_file), ok in zip(targets, ok_targets): + if not ok: + print(f"Warning! {out_file.name} isn't written: its DTM file has no values.", flush=True) + if not written: + raise ValueError("The DTM has no values, so no normalized DTM can be made.") + return written + + +if __name__ == "__main__": + from beratools.utility.tool_args import compose_tool_kwargs + + start_time = time.time() + print("Checking input parameters....") + kwargs = compose_tool_kwargs("ndtm_fr_dtmraster") + ndtm_fr_dtmraster(**kwargs) + print("Normalized DTM is done in {} seconds".format(round(time.time() - start_time, 5))) diff --git a/beratools/modules/raster2products/tests/conftest.py b/beratools/modules/raster2products/tests/conftest.py new file mode 100644 index 0000000..1bc9166 --- /dev/null +++ b/beratools/modules/raster2products/tests/conftest.py @@ -0,0 +1,28 @@ +"""Test configuration for the Raster2Products tests.""" + +import logging +import os +import warnings + +import pytest + +# Test the work-in-progress modules and tools too (see core/registry.py) +os.environ["BERATOOLS_WIP"] = "1" + +def pytest_configure(config): + warnings.simplefilter("ignore", category=FutureWarning) + warnings.simplefilter("ignore", category=DeprecationWarning) + # Set the global logging level to ERROR to suppress DEBUG and INFO logs + logging.basicConfig(level=logging.ERROR) + + # Set logger to ERROR to suppress debug logs + logging.getLogger("pyogrio").setLevel(logging.ERROR) + logging.getLogger("rasterio").setLevel(logging.ERROR) + logging.getLogger("rasterio.env").setLevel(logging.ERROR) + logging.getLogger("beratools.external.polygon_centerline._src").setLevel(logging.ERROR) + logging.getLogger("pyproj").setLevel(logging.WARNING) + + +@pytest.fixture(scope="session") +def available_cpu_cores(): + return os.cpu_count() \ No newline at end of file diff --git a/beratools/modules/raster2products/tests/test_cli_raster2products.py b/beratools/modules/raster2products/tests/test_cli_raster2products.py new file mode 100644 index 0000000..e94a3ba --- /dev/null +++ b/beratools/modules/raster2products/tests/test_cli_raster2products.py @@ -0,0 +1,57 @@ +"""The bt subcommands of the Raster2Products tools: how their values are parsed and checked.""" + +import pytest + +from beratools.cli import entry + + +@pytest.fixture +def fake_tool(monkeypatch): + """Replace tool dispatch with a recorder; return the kwargs it received.""" + received = {} + + def _fake_tool(**kwargs): + received.update(kwargs) + + monkeypatch.setattr("beratools.utility.env_checks.configure_gdal_proj_environment", lambda: None) + monkeypatch.setattr("beratools.utility.env_checks.warn_gdal_proj_env", lambda: None) + monkeypatch.setattr(entry, "_resolve_tool_function", lambda _api: _fake_tool) + return received + + +def test_ndtm_fr_dtmraster_converts_numbers_and_checks_smoothing(fake_tool): + code = entry.run( + argv=["ndtm_fr_dtmraster", "--in_dtm", "dtm.tif", "--out_folder", "out", "--Smooth_by", "median", + "--Min_ws", "4.5", "--tile_size", "1000"], + prog_name="bt", + ) + + assert code == 0 + assert fake_tool["Smooth_by"] == "median" + assert fake_tool["Min_ws"] == pytest.approx(4.5) + assert fake_tool["tile_size"] == 1000 and type(fake_tool["tile_size"]) is int + assert fake_tool["merge_output"] is False # optional, false by default + + entry.run( + argv=[ + "ndtm_fr_dtmraster", + "--in_dtm", + "dtm_tiles", + "--out_folder", + "out", + "--Smooth_by", + "mean", + "--Min_ws", + "3", + "--merge_output", + "true", + ], + prog_name="bt", + ) + assert fake_tool["merge_output"] is True + + with pytest.raises(SystemExit): + entry.run( + argv=["ndtm_fr_dtmraster", "--in_dtm", "dtm.tif", "--out_folder", "out", "--Smooth_by", "max"], + prog_name="bt", + ) diff --git a/beratools/modules/raster2products/tests/test_ndtm_fr_dtmraster.py b/beratools/modules/raster2products/tests/test_ndtm_fr_dtmraster.py new file mode 100644 index 0000000..a256806 --- /dev/null +++ b/beratools/modules/raster2products/tests/test_ndtm_fr_dtmraster.py @@ -0,0 +1,526 @@ +""" +Tests for Normalized DTM from DTM Raster (pure Python) and the DTM smoothing it shares with the +hummock/hollow tool (R): the last test, which needs R, checks that the two smooth alike. +""" + +from pathlib import Path + +import numpy as np +import pytest +import rasterio +from rasterio.transform import from_origin + +import beratools.modules.raster2products.algo_raster_smoothing as smoothing +from beratools.modules.raster2products.ndtm_fr_dtmraster import ndtm_fr_dtmraster, output_name +from beratools.utility.spatial_common import circle_kernel + +CELL = 0.25 +SIZE = 240 # cells per side, 60 m +HUMMOCK = (20.0, 40.0) # centre (m from the top-left corner) +HOLLOW = (40.0, 20.0) + + +def _write_dtm(path, crs="EPSG:3400"): + """ + A plane tilted 2% to the east, with a hummock 0.5 m high and a hollow 0.5 m deep, each 1 m + in radius. Smoothing a plane with a symmetric window gives the plane back, so away from the + edges and the two features the normalized DTM is 0. + """ + x = (np.arange(SIZE) + 0.5) * CELL + xx, yy = np.meshgrid(x, x) + dtm = 500 + 0.02 * xx + for (cx, cy), height in ((HUMMOCK, 0.5), (HOLLOW, -0.5)): + dtm += np.where(np.hypot(xx - cx, yy - cy) <= 1.0, height, 0.0) + profile = dict(driver="GTiff", width=SIZE, height=SIZE, count=1, dtype="float32", crs=crs, + transform=from_origin(500000, 6000000 + SIZE * CELL, CELL, CELL), nodata=-9999) + with rasterio.open(path, "w", **profile) as dst: + dst.write(dtm.astype("float32"), 1) + return path + + +def _read(path): + with rasterio.open(path) as src: + return src.read(1, masked=True).filled(np.nan), src.transform, src.crs + + +def _at(values, point): + col, row = int(point[0] / CELL), int(point[1] / CELL) + return values[row, col] + + +def test_ndtm_finds_hummock_and_hollow_and_tiles_match(tmp_path): + dtm = _write_dtm(tmp_path / "dtm.tif") + tiled = tmp_path / "tiled" + whole = tmp_path / "whole" + # 50-cell tiles: windows cross tile edges everywhere + ndtm_fr_dtmraster( + in_dtm=str(dtm), out_folder=str(tiled), Smooth_by="median", Min_ws=4.0, tile_size=50, processes=2 + ) + ndtm_fr_dtmraster( + in_dtm=str(dtm), out_folder=str(whole), Smooth_by="median", Min_ws=4.0, tile_size=10000, processes=1 + ) + + name = "ndtm_dtm_median_4m.tif" + a, transform, crs = _read(tiled / name) + b, _, _ = _read(whole / name) + np.testing.assert_array_equal(a, b) + with rasterio.open(dtm) as src: + assert transform == src.transform and crs == src.crs and a.shape == (src.height, src.width) + + # The feature fills a quarter of the window, which shifts the median of the tilted plane by + # ~1.5 cm, so the heights come out a little under 0.5 m + assert _at(a, HUMMOCK) == pytest.approx(0.5, abs=0.03) + assert _at(a, HOLLOW) == pytest.approx(-0.5, abs=0.03) + inner = a[20:-20, 20:-20] # away from the DTM's edges + features = np.abs(inner) > 1e-3 + assert features.sum() < 0.05 * inner.size # only around the hummock and hollow + + +def test_ndtm_mean_of_plane_is_zero(tmp_path): + dtm = _write_dtm(tmp_path / "dtm.tif") + ndtm_fr_dtmraster( + in_dtm=str(dtm), out_folder=str(tmp_path), Smooth_by="mean", Min_ws=3.0, tile_size=64, processes=2 + ) + values, _, _ = _read(tmp_path / "ndtm_dtm_mean_3m.tif") + # a cell far from both features + assert _at(values, (50.0, 50.0)) == pytest.approx(0.0, abs=1e-4) + + +def test_ndtm_refuses_dtm_in_degrees(tmp_path): + dtm = _write_dtm(tmp_path / "dtm_ll.tif", crs="EPSG:4326") + with pytest.raises(Exception, match="not projected"): + ndtm_fr_dtmraster(in_dtm=str(dtm), out_folder=str(tmp_path / "out"), Min_ws=3.0) + + +def test_ndtm_checks_inputs(tmp_path): + with pytest.raises(FileNotFoundError): + ndtm_fr_dtmraster(in_dtm=str(tmp_path / "missing.tif"), out_folder=str(tmp_path)) + dtm = _write_dtm(tmp_path / "dtm.tif") + with pytest.raises(ValueError, match="Smooth_by"): + ndtm_fr_dtmraster(in_dtm=str(dtm), out_folder=str(tmp_path), Smooth_by="max") + + +def test_ndtm_window_holds_only_real_neighbours_at_the_edge(tmp_path): + """ + A flat DTM at 0 with its west column at 1. A 0.5 m window on 0.25 m cells is a cross of 5 + cells; on the west column it holds the cell, the two above and below it (1) and the one east + (0), so the mean is 3/4 and the normalized DTM 1 - 3/4 = 0.25. Copying the edge cells outwards + would put a fifth 1 in the window and give 0.2. + """ + dtm = np.zeros((20, 20), dtype="float32") + dtm[:, 0] = 1 + profile = dict(driver="GTiff", width=20, height=20, count=1, dtype="float32", crs="EPSG:3400", + transform=from_origin(500000, 6000005, CELL, CELL), nodata=-9999) + with rasterio.open(tmp_path / "edge.tif", "w", **profile) as dst: + dst.write(dtm, 1) + ndtm_fr_dtmraster( + in_dtm=str(tmp_path / "edge.tif"), out_folder=str(tmp_path), Min_ws=2 * CELL, processes=1 + ) + values, _, _ = _read(tmp_path / "ndtm_edge_mean_0.5m.tif") + assert values[10, 0] == pytest.approx(0.25, abs=1e-6) + assert values[10, 1] == pytest.approx(-1 / 5, abs=1e-6) # inside: a full cross with one 1 + + +def test_ndtm_smallest_window_is_twice_the_cell_size(tmp_path): + dtm = _write_dtm(tmp_path / "dtm.tif") + # 0.5 m on 0.25 m cells: a radius of 1 cell, a window 3 cells across + ndtm_fr_dtmraster(in_dtm=str(dtm), out_folder=str(tmp_path), Min_ws=2 * CELL, processes=1) + assert (tmp_path / "ndtm_dtm_mean_0.5m.tif").exists() + with pytest.raises(Exception, match="at least 0.5 m"): + ndtm_fr_dtmraster(in_dtm=str(dtm), out_folder=str(tmp_path), Min_ws=0.4, processes=1) + + +def test_ndtm_removes_partial_file_and_writes_float32(tmp_path): + dtm = _write_dtm(tmp_path / "dtm.tif") + out = tmp_path / "out" + out.mkdir() + partial = out / "ndtm_dtm_mean_3m.partial.tif" + partial.write_bytes(b"cut short") + ndtm_fr_dtmraster(in_dtm=str(dtm), out_folder=str(out), Min_ws=3.0, processes=1) + assert not partial.exists() + assert sorted(f.name for f in out.glob("ndtm_*m.tif")) == ["ndtm_dtm_mean_3m.tif"] + with rasterio.open(out / "ndtm_dtm_mean_3m.tif") as src: + assert src.dtypes[0] == "float32" + assert src.tags(ns="IMAGE_STRUCTURE").get("PREDICTOR") == "3" + + +def test_output_name_writes_min_ws_as_r_prints_it(): + assert output_name("a/Merged_TIN_DTM.tif", "mean", 3.0) == "ndtm_Merged_TIN_DTM_mean_3m.tif" + assert output_name("dtm.vrt", "median", "4.5") == "ndtm_dtm_median_4.5m.tif" + + +def test_circle_kernel_is_a_true_circle_on_cells_that_are_not_square(): + kernel = circle_kernel(1.5, 0.3, 0.2) + assert kernel.shape == (15, 11) # 7 rows and 5 columns each way + rows, cols = np.nonzero(kernel) + assert np.hypot((cols - 5) * 0.3, (rows - 7) * 0.2).max() <= 1.5 + assert ( + kernel[0, 5] and kernel[14, 5] and kernel[7, 0] and kernel[7, 10] + ) # 1.4 m up and down, 1.5 m across + # the millionth added to the radius keeps the ring at radius / cell size stored rounded + assert circle_kernel(1.5, 0.25 * (1 + 1e-8), 0.25 * (1 + 1e-8)).shape == (13, 13) + + +def _smooth_brute_force(dtm, kernel, smooth_by): + """The mean or median of the real cells of the window, cell by cell.""" + ky, kx = kernel.shape[0] // 2, kernel.shape[1] // 2 + rows, cols = dtm.shape + out = np.full(dtm.shape, np.nan) + for r in range(rows): + for c in range(cols): + if np.isnan(dtm[r, c]): + continue + window = np.full(kernel.shape, np.nan) + r0, r1, c0, c1 = max(0, r - ky), min(rows, r + ky + 1), max(0, c - kx), min(cols, c + kx + 1) + window[r0 - r + ky : r1 - r + ky, c0 - c + kx : c1 - c + kx] = dtm[r0:r1, c0:c1] + values = window[kernel] + out[r, c] = (np.nanmean if smooth_by == "mean" else np.nanmedian)(values) + return out + + +@pytest.mark.parametrize("smooth_by", ["mean", "median"]) +def test_smooth_raster_matches_brute_force_with_gaps_and_edges(smooth_by): + rng = np.random.default_rng(1) + dtm = rng.normal(500, 1, (40, 30)) + dtm[rng.random(dtm.shape) < 0.1] = np.nan + dtm[:5, :8] = np.nan + kernel = circle_kernel(1.0, 0.25, 0.2) + np.testing.assert_allclose(smoothing.smooth_raster(dtm, kernel, smooth_by), + _smooth_brute_force(dtm, kernel, smooth_by), rtol=0, atol=1e-9) + + +def test_ndtm_threads_give_the_same_values(tmp_path): + dtm = _write_dtm(tmp_path / "dtm.tif") + ndtm_fr_dtmraster(in_dtm=str(dtm), out_folder=str(tmp_path / "one"), Smooth_by="median", processes=1) + ndtm_fr_dtmraster(in_dtm=str(dtm), out_folder=str(tmp_path / "four"), Smooth_by="median", processes=4) + a, b = ( + _read(tmp_path / "one" / "ndtm_dtm_median_3m.tif")[0], + _read(tmp_path / "four" / "ndtm_dtm_median_3m.tif")[0], + ) + np.testing.assert_array_equal(a, b) + + +def test_ndtm_refuses_dtm_with_no_values(tmp_path): + empty = np.full((20, 20), -9999, dtype="float32") + profile = dict(driver="GTiff", width=20, height=20, count=1, dtype="float32", crs="EPSG:3400", + transform=from_origin(500000, 6000005, CELL, CELL), nodata=-9999) + with rasterio.open(tmp_path / "empty.tif", "w", **profile) as dst: + dst.write(empty, 1) + with pytest.raises(ValueError, match="no values"): + ndtm_fr_dtmraster(in_dtm=str(tmp_path / "empty.tif"), out_folder=str(tmp_path / "out")) + assert not list((tmp_path / "out").glob("ndtm_*")) + +# --------------------------------------------------------------------------- +# A folder of DTM files +# --------------------------------------------------------------------------- + + +def _split_dtm(dtm_path, folder, pieces, overlap=0, edit=None): + """ + Cut the DTM into pieces x pieces files (named in row-major order), each overlapping its + neighbours by `overlap` cells; edit(name, values) may change a file's values. + """ + folder.mkdir(exist_ok=True) + with rasterio.open(dtm_path) as src: + values, profile = src.read(1), src.profile + step = SIZE // pieces + paths = [] + for i in range(pieces): + for j in range(pieces): + r0, c0 = max(0, i * step - overlap), max(0, j * step - overlap) + r1, c1 = min(SIZE, (i + 1) * step + overlap), min(SIZE, (j + 1) * step + overlap) + part = values[r0:r1, c0:c1].copy() + name = f"dtm_{i}{j}.tif" + if edit: + part = edit(name, part) + t = profile["transform"] + p = dict(profile, width=c1 - c0, height=r1 - r0, + transform=from_origin(t.c + c0 * CELL, t.f - r0 * CELL, CELL, CELL)) + with rasterio.open(folder / name, "w", **p) as dst: + dst.write(part, 1) + paths.append((folder / name, (r0, c0, r1, c1))) + return paths + + +def test_folder_outputs_per_file_join_without_seams(tmp_path): + dtm = _write_dtm(tmp_path / "dtm.tif") + whole = ndtm_fr_dtmraster(in_dtm=str(dtm), out_folder=str(tmp_path / "whole"), Smooth_by="median") + assert [Path(p).name for p in whole] == ["ndtm_dtm_median_3m.tif"] + expected = _read(tmp_path / "whole" / "ndtm_dtm_median_3m.tif")[0] + + parts = _split_dtm(dtm, tmp_path / "tiles", 3) + out = tmp_path / "out" + written = ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(out), Smooth_by="median", + tile_size=50) + assert len(written) == 9 + for path, (r0, c0, r1, c1) in parts: + values, transform, _ = _read(out / f"ndtm_{path.stem}_median_3m.tif") + with rasterio.open(path) as src: + assert transform == src.transform and values.shape == (src.height, src.width) + np.testing.assert_array_equal(values, expected[r0:r1, c0:c1]) + + +def test_folder_merged_output_equals_the_whole_dtm(tmp_path): + dtm = _write_dtm(tmp_path / "dtm.tif") + ndtm_fr_dtmraster(in_dtm=str(dtm), out_folder=str(tmp_path / "whole")) + _split_dtm(dtm, tmp_path / "tiles", 2) + written = ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(tmp_path / "out"), + merge_output="true") + # the merged output first, then the one per file + assert [Path(p).name for p in written] == ["ndtm_tiles_mean_3m.tif"] + [ + f"ndtm_dtm_{i}{j}_mean_3m.tif" for i in range(2) for j in range(2)] + a, ta, _ = _read(tmp_path / "whole" / "ndtm_dtm_mean_3m.tif") + b, tb, _ = _read(tmp_path / "out" / "ndtm_tiles_mean_3m.tif") + assert ta == tb + np.testing.assert_array_equal(a, b) + + +def test_folder_merged_also_writes_the_per_file_outputs(tmp_path, capsys): + dtm = _write_dtm(tmp_path / "dtm.tif") + # overlapping files, and 37-cell tiles that straddle the files' edges + parts = _split_dtm(dtm, tmp_path / "tiles", 3, overlap=4, + edit=lambda name, v: v + 1 if name == "dtm_11.tif" else v) + per_file = ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(tmp_path / "per_file"), + Smooth_by="median", tile_size=37) + capsys.readouterr() + both = ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(tmp_path / "both"), + Smooth_by="median", tile_size=37, merge_output=True) + assert [Path(p).name for p in both] == ["ndtm_tiles_median_3m.tif"] + [Path(p).name for p in per_file] + # one tiling of the mosaic: each tile smoothed once, for all the outputs + n = (-(-SIZE // 37)) ** 2 + assert f"Normalized DTM tiles {n} of {n}\"" in capsys.readouterr().out + merged = _read(tmp_path / "both" / "ndtm_tiles_median_3m.tif")[0] + for path, (r0, c0, r1, c1) in parts: + name = f"ndtm_{path.stem}_median_3m.tif" + a, ta, _ = _read(tmp_path / "per_file" / name) + b, tb, _ = _read(tmp_path / "both" / name) + assert ta == tb + np.testing.assert_array_equal(a, b) + np.testing.assert_array_equal(b, merged[r0:r1, c0:c1]) + + +def test_folder_merged_output_name_taken_by_a_dtm_file(tmp_path): + dtm = _write_dtm(tmp_path / "dtm.tif") + _split_dtm(dtm, tmp_path / "tiles", 2) + (tmp_path / "tiles" / "tiles.tif").write_bytes((tmp_path / "tiles" / "dtm_00.tif").read_bytes()) + with pytest.raises(ValueError, match="merged output's name"): + ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(tmp_path / "out"), merge_output=True) + + +def test_folder_overlap_first_file_wins_and_warns(tmp_path, capsys): + dtm = _write_dtm(tmp_path / "dtm.tif") + # the second file (dtm_01) is raised 1 m: where it overlaps dtm_00, dtm_00's values are used + _split_dtm(dtm, tmp_path / "tiles", 2, overlap=10, + edit=lambda name, v: v + 1 if name == "dtm_01.tif" else v) + ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(tmp_path / "out"), merge_output=True) + out = capsys.readouterr().out + assert "Warning! 6 pair(s) of DTM files overlap" in out and "first file in name order wins" in out + + # inside dtm_00, away from the band where dtm_01's raised values start, the ndtm is the plane's 0 + merged = _read(tmp_path / "out" / "ndtm_tiles_mean_3m.tif")[0] + assert merged[60, 100] == pytest.approx(0.0, abs=1e-4) + # in the overlap (cols 110-129) dtm_00 wins: a window 6 cells wide each way still sees only it + assert merged[60, 120] == pytest.approx(0.0, abs=1e-4) + # just past the overlap, dtm_01's raised values meet dtm_00's: a step the smoothing sees + assert merged[60, 131] > 0.1 + + +def test_folder_skips_ndtm_merged_and_partial_files(tmp_path): + dtm = _write_dtm(tmp_path / "dtm.tif") + _split_dtm(dtm, tmp_path / "tiles", 2) + # the outputs written into the DTM folder itself aren't read as DTMs on the next run + first = ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(tmp_path / "tiles")) + (tmp_path / "tiles" / "x.partial.tif").write_bytes(b"cut short") + # nor is a Merged_* mosaic next to the tiles, as Generate DTM from LiDAR Data writes + (tmp_path / "tiles" / "Merged_TIN_DTM.tif").write_bytes(dtm.read_bytes()) + again = ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(tmp_path / "tiles")) + assert len(first) == len(again) == 4 + + +def test_folder_refuses_files_off_the_grid(tmp_path): + dtm = _write_dtm(tmp_path / "dtm.tif") + parts = _split_dtm(dtm, tmp_path / "tiles", 2) + path = parts[1][0] + with rasterio.open(path) as src: + values, profile = src.read(1), src.profile + t = profile["transform"] + profile["transform"] = from_origin(t.c + CELL / 3, t.f, CELL, CELL) # a third of a cell off + with rasterio.open(path, "w", **profile) as dst: + dst.write(values, 1) + with pytest.raises(ValueError, match="not on the grid"): + ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(tmp_path / "out")) + + +def test_folder_refuses_other_cell_size_or_crs(tmp_path): + dtm = _write_dtm(tmp_path / "dtm.tif") + folder = tmp_path / "tiles" + _split_dtm(dtm, folder, 2) + with rasterio.open(folder / "dtm_00.tif") as src: + values, profile = src.read(1), src.profile + t = profile["transform"] + coarse = dict(profile, transform=from_origin(t.c, t.f, 0.5, 0.5)) + with rasterio.open(folder / "dtm_99.tif", "w", **coarse) as dst: + dst.write(values, 1) + with pytest.raises(ValueError, match="cell size"): + ndtm_fr_dtmraster(in_dtm=str(folder), out_folder=str(tmp_path / "out")) + with rasterio.open(folder / "dtm_99.tif", "w", **dict(profile, crs="EPSG:3401")) as dst: + dst.write(values, 1) + with pytest.raises(ValueError, match="CRS"): + ndtm_fr_dtmraster(in_dtm=str(folder), out_folder=str(tmp_path / "out")) + + +def test_folder_without_dtm_files_is_refused(tmp_path): + (tmp_path / "empty").mkdir() + with pytest.raises(FileNotFoundError, match="No DTM GeoTIFFs"): + ndtm_fr_dtmraster(in_dtm=str(tmp_path / "empty"), out_folder=str(tmp_path / "out")) + + +@pytest.mark.parametrize("radius, res_x, res_y", [(1.5, 0.1, 0.1), (1.0, 0.25, 0.2), (0.25, 0.25, 0.25)]) +def test_sliding_median_is_identical_to_the_full_median(radius, res_x, res_y): + """ + The median slides along each row (keeping the window sorted); it gives exactly the values of + finding the median of the whole window at every cell, with ties, gaps and edges. + """ + rng = np.random.default_rng(3) + values = np.round(500 + rng.normal(0, 1, (120, 97)).cumsum(0) * 0.01, 2) # many ties + values[rng.random(values.shape) < 0.1] = np.nan + values[:20, :30] = np.nan + kernel = circle_kernel(radius, res_x, res_y) + dy, dx = np.nonzero(kernel) + full = smoothing._smooth(values, (dy - kernel.shape[0] // 2).astype(np.int64), + (dx - kernel.shape[1] // 2).astype(np.int64), True) + np.testing.assert_array_equal(smoothing.smooth_raster(values, kernel, "median"), full) + + +def test_median_of_a_kernel_with_gaps_in_its_rows(): + """A ring (its middle row isn't one span of columns) can't slide; it uses the full median.""" + ring = np.ones((5, 5), dtype=bool) + ring[1:4, 1:4] = False + assert smoothing._row_spans(ring) is None + values = np.random.default_rng(4).normal(0, 1, (30, 30)) + np.testing.assert_allclose(smoothing.smooth_raster(values, ring, "median"), + _smooth_brute_force(values, ring, "median"), rtol=0, atol=1e-12) + + +def test_folder_headers_read_one_at_a_time_or_on_threads_alike(tmp_path, monkeypatch, capsys): + from beratools.modules.raster2products import ndtm_fr_dtmraster as tool + + dtm = _write_dtm(tmp_path / "dtm.tif") + files = [p for p, _ in _split_dtm(dtm, tmp_path / "tiles", 4)] # 16 files: 1 + 8 probed, 7 more + mosaic = tool.Mosaic(files) + serial = mosaic._read_headers(threads=False) + threaded = mosaic._read_headers(threads=True) + assert serial == threaded and len(serial) == 16 + + # quick opens (a local disk) stay one at a time; slow ones switch to threads + capsys.readouterr() + tool.Mosaic(files) + assert "slow to open" not in capsys.readouterr().out + monkeypatch.setattr(tool, "HEADER_SLOW_OPEN", 0.0) + slow = tool.Mosaic(files) + assert "slow to open" in capsys.readouterr().out + np.testing.assert_array_equal(slow.rects, mosaic.rects) + + +def test_sidecar_files_are_looked_for_only_when_they_matter(tmp_path, capsys): + from beratools.modules.raster2products import ndtm_fr_dtmraster as tool + + dtm = _write_dtm(tmp_path / "dtm.tif") + assert not tool.sidecars_matter(dtm) + + # a DTM whose no-data value is only in its .aux.xml: GDAL must look for it + values = _read(dtm)[0].astype("float32") + values[:10, :] = -1 + profile = dict(driver="GTiff", width=SIZE, height=SIZE, count=1, dtype="float32", crs="EPSG:3400", + transform=from_origin(500000, 6000000 + SIZE * CELL, CELL, CELL)) + with rasterio.open(tmp_path / "aux.tif", "w", **profile) as dst: + dst.write(values, 1) + (tmp_path / "aux.tif.aux.xml").write_text( + '-1') + assert tool.sidecars_matter(tmp_path / "aux.tif") + ndtm_fr_dtmraster(in_dtm=str(tmp_path / "aux.tif"), out_folder=str(tmp_path / "out")) + assert "reads differently without its sidecar files" in capsys.readouterr().out + out = _read(tmp_path / "out" / "ndtm_aux_mean_3m.tif")[0] + assert np.isnan(out[:10]).all() and not np.isnan(out[10:]).any() # -1 read as no data + + +def test_folder_gives_the_same_values_with_few_files_kept_open(tmp_path, monkeypatch): + from beratools.modules.raster2products import ndtm_fr_dtmraster as tool + + dtm = _write_dtm(tmp_path / "dtm.tif") + _split_dtm(dtm, tmp_path / "tiles", 3) + ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(tmp_path / "many"), merge_output=True, + tile_size=50) + monkeypatch.setattr(tool, "OPEN_FILES", 2) + ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(tmp_path / "few"), merge_output=True, + tile_size=50) + np.testing.assert_array_equal(_read(tmp_path / "many" / "ndtm_tiles_mean_3m.tif")[0], + _read(tmp_path / "few" / "ndtm_tiles_mean_3m.tif")[0]) + + +def test_smoothing_tiles_together_equals_one_by_one(): + rng = np.random.default_rng(5) + tiles = [rng.normal(500, 1, shape) for shape in ((40, 33), (7, 90), (61, 12), (1, 5))] + tiles[0][rng.random(tiles[0].shape) < 0.2] = np.nan + kernel = circle_kernel(1.0, 0.25, 0.2) + for smooth_by in ("mean", "median"): + together = smoothing.smooth_rasters(tiles, kernel, smooth_by) + for tile, out in zip(tiles, together): + np.testing.assert_array_equal(out, smoothing.smooth_raster(tile, kernel, smooth_by)) + + +@pytest.mark.parametrize("rows_per_thread, memory_fraction", [(10**6, 0.25), (0, 0.25), (10**6, 1e-12)]) +def test_batches_give_the_same_values(tmp_path, monkeypatch, rows_per_thread, memory_fraction): + """All tiles in one batch, one tile per batch, or a memory cap of one tile: the same outputs.""" + from beratools.modules.raster2products import ndtm_fr_dtmraster as tool + + dtm = _write_dtm(tmp_path / "dtm.tif") + _split_dtm(dtm, tmp_path / "tiles", 3) + ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(tmp_path / "ref"), Smooth_by="median", + tile_size=50) + monkeypatch.setattr(tool, "BATCH_ROWS_PER_THREAD", rows_per_thread) + monkeypatch.setattr(tool, "BATCH_MEMORY_FRACTION", memory_fraction) + ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(tmp_path / "out"), Smooth_by="median", + tile_size=50) + for ref in sorted((tmp_path / "ref").glob("ndtm_*.tif")): + np.testing.assert_array_equal(_read(ref)[0], _read(tmp_path / "out" / ref.name)[0]) + + +def test_a_read_error_stops_the_run_and_leaves_no_partial_files(tmp_path, monkeypatch): + from beratools.modules.raster2products import ndtm_fr_dtmraster as tool + + dtm = _write_dtm(tmp_path / "dtm.tif") + _split_dtm(dtm, tmp_path / "tiles", 3) + reads = [0] + read = tool.Mosaic.read + + def failing_read(self, *args): + reads[0] += 1 + if reads[0] == 5: + raise OSError("the drive went away") + return read(self, *args) + + monkeypatch.setattr(tool.Mosaic, "read", failing_read) + with pytest.raises(OSError, match="the drive went away"): + ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(tmp_path / "out"), tile_size=50) + assert not list((tmp_path / "out").glob("*.partial.tif")) + + +def test_a_write_error_stops_the_run_and_leaves_no_partial_files(tmp_path, monkeypatch): + import rasterio.io + + dtm = _write_dtm(tmp_path / "dtm.tif") + _split_dtm(dtm, tmp_path / "tiles", 3) + writes = [0] + write = rasterio.io.DatasetWriter.write + + def failing_write(self, *args, **kwargs): + writes[0] += 1 + if writes[0] == 4: + raise OSError("the disk is full") + return write(self, *args, **kwargs) + + monkeypatch.setattr(rasterio.io.DatasetWriter, "write", failing_write) + with pytest.raises(OSError, match="the disk is full"): + ndtm_fr_dtmraster(in_dtm=str(tmp_path / "tiles"), out_folder=str(tmp_path / "out"), tile_size=50) + assert not list((tmp_path / "out").glob("*.partial.tif")) diff --git a/beratools/modules/raster2products/tests/test_raster2products_tools_json.py b/beratools/modules/raster2products/tests/test_raster2products_tools_json.py new file mode 100644 index 0000000..a3a59de --- /dev/null +++ b/beratools/modules/raster2products/tests/test_raster2products_tools_json.py @@ -0,0 +1,27 @@ +"""The Raster2Products module's tools.json, as the frame loads it.""" + +from beratools.core import registry + +MODULE = "raster2products" + +# The bt subcommands of this module's tools; they must not change +CLI_NAMES = { + "ndtm_fr_dtmraster": "ndtm_fr_dtmraster", +} + + +def _box(): + return next(box for box in registry.get_registry().toolbox if box["module"] == MODULE) + + +def test_module_loads_without_errors(): + assert [e for e in registry.get_registry().errors if e.startswith(f"{MODULE}:")] == [] + assert _box()["category"] == "Raster2Products" + + +def test_cli_names_are_unchanged(): + assert {tool["cli_name"]: tool["tool_api"] for tool in _box()["tools"]} == CLI_NAMES + + +def test_no_tool_is_wip(): + assert all(tool["status"] == "released" for tool in _box()["tools"]) diff --git a/beratools/modules/raster2products/tools.json b/beratools/modules/raster2products/tools.json new file mode 100644 index 0000000..c593255 --- /dev/null +++ b/beratools/modules/raster2products/tools.json @@ -0,0 +1,99 @@ +{ + "$schema": "../../gui/assets/module.schema.json", + "module": "raster2products", + "version": "0.7.0", + "requires_frame": ">=0.7", + "category": "Raster2Products", + "description": "Tools used to work with raster data, such as a DTM, to produce other rasters, e.g. a normalized DTM.", + "docs_url": "https://beratool.github.io/beratools/raster2products/", + "tools": [ + { + "name": "Normalized DTM from DTM Raster", + "info": "Normalized DTM (micro-topography) from a DTM raster: the DTM minus the DTM smoothed by the mean or median of a circular moving window, so hummocks are positive and hollows negative. Takes one DTM or a folder of DTM files, read as one mosaic. The DTM is processed in tiles, each smoothed in parallel; no R needed.", + "batch_processing": false, + "tool_type": "python", + "tool_api": "ndtm_fr_dtmraster", + "cli_name": "ndtm_fr_dtmraster", + "entry": "beratools.modules.raster2products.ndtm_fr_dtmraster:ndtm_fr_dtmraster", + "icon": "", + "tech_link": "user/ndtm_fr_dtmraster/", + "parameters": [ + { + "variable": "in_dtm", + "accepts": "dtm", + "label": "DTM raster or folder", + "description": "Digital terrain model in a projected CRS, e.g. Merged_TIN_DTM.tif from Generate DTM from LiDAR Data or a GDAL .vrt of DTM tiles, or a folder of DTM GeoTIFFs on one grid (same CRS and cell size), read as one mosaic so the outputs join without seams. Where files overlap, the first in name order wins. The outputs have the DTM's cells.", + "type": "file", + "subtype": "raster", + "allow_directory": true, + "default": "", + "output": false, + "optional": false + }, + { + "variable": "out_folder", + "produces": { + "ndtm": [ + "ndtm_*m.tif" + ] + }, + "label": "Output folder", + "description": "Folder for ndtm___m.tif: one per DTM file, or one named after the DTM folder with Merge into one raster.", + "type": "directory", + "subtype": "file", + "default": "", + "output": true, + "optional": false + }, + { + "variable": "Smooth_by", + "label": "Smooth the DTM by", + "description": "'mean' or 'median' of the cells in the moving window.", + "type": "list", + "subtype": "text", + "data": [ + "mean", + "median" + ], + "default": "mean", + "output": false, + "optional": false + }, + { + "variable": "Min_ws", + "label": "Moving window size (m)", + "description": "Diameter of the circular moving window in metres, converted to the DTM's map units. It must be at least twice the cell size (a window 3 cells across).", + "type": "number", + "subtype": "float", + "default": 3.0, + "output": false, + "optional": false + }, + { + "variable": "merge_output", + "label": "Merge into one raster", + "description": "For a folder of DTM files: true writes one normalized DTM over all of them, named after the folder, and also the one per DTM file, each smoothed once for both; false writes only the one per DTM file, on its grid. The values are the same either way. A single DTM file always gives one output.", + "type": "list", + "subtype": "bool", + "data": [ + true, + false + ], + "default": false, + "output": false, + "optional": true + }, + { + "variable": "tile_size", + "label": "Tile size (cells)", + "description": "The DTM is read in square tiles of this many cells per side, one after another; each reads a buffer of the window's radius, so the tiles join with the same values as the whole DTM at once. Smaller tiles use less memory.", + "type": "number", + "subtype": "int", + "default": 2000, + "output": false, + "optional": true + } + ] + } + ] +} diff --git a/beratools/tools/canopy_footprint_absolute.py b/beratools/tools/canopy_footprint_absolute.py index b343d1e..49f919d 100644 --- a/beratools/tools/canopy_footprint_absolute.py +++ b/beratools/tools/canopy_footprint_absolute.py @@ -1,283 +1,20 @@ """ -Copyright (C) 2025 Applied Geospatial Research Group. +Deprecated: moved to beratools.modules.mapping. -This script is licensed under the GNU General Public License v3.0. -See for full license details. - -Author: Richard Zeng - -Description: - This script is part of the BERA Tools. - Webpage: https://github.com/BERATool/beratools - - The purpose of this script is to provide main interface for canopy footprint tool. +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -import logging -import time +import sys +import warnings -import geopandas as gpd -import pandas as pd +from beratools.modules.mapping import canopy_footprint_absolute as _moved -from beratools.core.algo_canopy_footprint_absolute import ( - CanopyFootprintRequest, - CanopyFootprintResult, - FootprintCanopyAdaptive, - cast_request_types, - generate_absolute_line_class_list, - merge_footprints_by_original_line, - process_single_absolute_line, - save_aux_layers, - save_main_footprint, +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" CanopyFootprintResult: - """Run absolute footprint workflow using shared request/result contracts.""" - - in_file, in_layer = sp_common.decode_file_layer(req.in_line) - - corridor_thresh = req.corridor_thresh if req.corridor_thresh is not None else 3.0 - exp_shk_cell = req.exp_shk_cell if req.exp_shk_cell is not None else 0 - - footprint_list = [] - line_class_list = generate_absolute_line_class_list( - in_file, - req.in_chm, - corridor_thresh, - req.max_ln_width, - exp_shk_cell, - req.simplify_footprint_polygon, - req.footprint_simplify_length, - req.smooth_footprint_polygon, - req.footprint_polygon_smooth_iterations, - in_layer, - ) - - run_call_mode = req.call_mode - if isinstance(run_call_mode, str): - run_call_mode = CallMode(run_call_mode) - - feat_list = bt_base.execute_multiprocessing( - process_single_absolute_line, - line_class_list, - "Line footprint", - req.processes, - run_call_mode, - ) - - if feat_list: - for item in feat_list: - if item.footprint is not None: - footprint_list.append(item.footprint) - - result = CanopyFootprintResult( - stats={ - "line_count": len(line_class_list), - "success_count": len(footprint_list), - "fail_count": max(len(line_class_list) - len(footprint_list), 0), - } - ) - - if footprint_list: - result.footprints_gdf = gpd.GeoDataFrame(pd.concat(footprint_list)).reset_index(drop=True) - else: - result.messages.append("No footprints generated.") - - return result - - -def _run_adaptive_request(req: CanopyFootprintRequest) -> CanopyFootprintResult: - """Run adaptive footprint workflow using shared request/result contracts.""" - - result = CanopyFootprintResult() - run_call_mode = req.call_mode - if isinstance(run_call_mode, str): - run_call_mode = CallMode(run_call_mode) - - try: - footprint = FootprintCanopyAdaptive( - req.in_line, - req.in_chm, - max_line_width=req.max_ln_width if req.max_ln_width is not None else 32.0, - tree_radius=req.tree_radius if req.tree_radius is not None else 1.5, - max_line_dist=req.max_line_dist if req.max_line_dist is not None else 1.5, - canopy_avoidance=req.canopy_avoidance if req.canopy_avoidance is not None else 0.0, - exponent=req.exponent if req.exponent is not None else 1.0, - canopy_thresh_percentage=req.canopy_thresh_percentage - if req.canopy_thresh_percentage is not None - else 50.0, - exp_shk_cell=req.exp_shk_cell if req.exp_shk_cell is not None else 0, - simplify_footprint_polygon=req.simplify_footprint_polygon, - footprint_simplify_length=req.footprint_simplify_length, - smooth_footprint_polygon=req.smooth_footprint_polygon, - footprint_polygon_smooth_iterations=req.footprint_polygon_smooth_iterations, - ) - except Exception as err: - result.messages.append(f"Failed to initialize FootprintCanopyAdaptive: {err}") - return result - - try: - footprint.compute(req.processes, run_call_mode) - except Exception as err: - result.messages.append(f"Error in compute(): {err}") - import traceback - - traceback.print_exc() - return result - - if _is_valid_gdf(footprint, "footprints"): - result.footprints_gdf = footprint.footprints - else: - result.messages.append("No valid footprints to save.") - - if _is_valid_gdf(footprint, "lines_percentile"): - result.aux_layers["lines_percentile"] = gpd.GeoDataFrame(footprint.lines_percentile) - - lines = getattr(footprint, "lines", []) or [] - line_count = len(lines) - - if line_count > 0: - success_count = sum( - 1 for line in lines if hasattr(line, "footprint") and getattr(line, "footprint") is not None - ) - else: - success_count = 0 if result.footprints_gdf is None else int(len(result.footprints_gdf)) - - result.stats = { - "line_count": int(line_count), - "success_count": int(success_count), - "fail_count": int(max(line_count - success_count, 0)), - } - - return result - - -if __name__ == "__main__": - from beratools.utility.tool_args import compose_tool_kwargs - - start_time = time.time() - print("Footprint processing started") - kwargs = compose_tool_kwargs("canopy_footprint_absolute") - canopy_footprint_abs(**kwargs) - print("Elapsed time: {}".format(time.time() - start_time)) +sys.modules[__name__] = _moved diff --git a/beratools/tools/centerline.py b/beratools/tools/centerline.py index cddd915..c9c7aa2 100644 --- a/beratools/tools/centerline.py +++ b/beratools/tools/centerline.py @@ -1,482 +1,20 @@ """ -Copyright (C) 2025 Applied Geospatial Research Group. +Deprecated: moved to beratools.modules.mapping. -This script is licensed under the GNU General Public License v3.0. -See for full license details. - -Author: Richard Zeng - -Description: - This script is part of the BERA Tools. - Webpage: https://github.com/BERATool/beratools - - The purpose of this script is to provide main interface for centerline tool. +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -import logging -from pathlib import Path -import os -import geopandas as gpd -import pandas as pd -import rasterio -import beratools.core.algo_centerline as algo_centerline -import beratools.core.algo_common as algo_common -import beratools.core.constants as bt_const -import beratools.core.tool_geo_simplify as tool_geo_simplify -import beratools.utility.spatial_common as sp_common -import beratools.utility.unit_conversion as unit_conversion -from beratools.core.tool_base import execute_multiprocessing -from beratools.utility.tool_args import CallMode - -LOGGER_NAME="centerline" -logger = logging.getLogger(LOGGER_NAME) - - -def _to_bool(value): - if isinstance(value, bool): - return value - - if isinstance(value, str): - lowered = value.strip().lower() - if lowered in {"true", "1", "yes", "y", "on"}: - return True - if lowered in {"false", "0", "no", "n", "off"}: - return False - - return bool(value) - - -def generate_line_class_list( - in_vector, - in_raster, - line_radius, - layer=None, - proc_segments=True, - guided_strategy=bt_const.CENTERLINE_GUIDED_STRATEGY.value, - centerline_method=bt_const.CENTERLINE_METHOD.value, - lcp_simplify_enabled=False, - lcp_simplify_diameter=10.0, - lcp_smooth_enabled=False, - lcp_smooth_iterations=1, - chm_mode=bt_const.CENTERLINE_CHM_MODE.value, - chm_buffer_width=5.0, - chm_buffer_multiplier=0.5, - astar_corridor_line_bias_weight=0.1, - astar_corridor_distance_penalty_weight=0.2, - corridor_simplify_polygon=False, - corridor_simplify_length=0.5, - corridor_smooth_polygon=False, - corridor_polygon_smooth_iterations=1, -) -> list: - line_classes = [] - line_list = algo_common.prepare_lines_gdf(in_vector, layer, proc_segments, tag_source_rows=True) - - for item in line_list: - line_classes.append( - algo_centerline.SeedLine( - item, - in_raster, - proc_segments, - line_radius, - guided_strategy=guided_strategy, - centerline_method=centerline_method, - lcp_simplify_enabled=lcp_simplify_enabled, - lcp_simplify_diameter=lcp_simplify_diameter, - lcp_smooth_enabled=lcp_smooth_enabled, - lcp_smooth_iterations=lcp_smooth_iterations, - chm_mode=chm_mode, - chm_buffer_width=chm_buffer_width, - chm_buffer_multiplier=chm_buffer_multiplier, - astar_corridor_line_bias_weight=astar_corridor_line_bias_weight, - astar_corridor_distance_penalty_weight=astar_corridor_distance_penalty_weight, - corridor_simplify_polygon=corridor_simplify_polygon, - corridor_simplify_length=corridor_simplify_length, - corridor_smooth_polygon=corridor_smooth_polygon, - corridor_polygon_smooth_iterations=corridor_polygon_smooth_iterations, - ) - ) - - return line_classes - - -MERGE_ORDER_FIELD = "BT_MERGE_ORDER" - - -def _add_merge_order(gdf, merge_by_original_line): - """Number the pieces in the order they join: by input row and vertex, or along the original line.""" - if gdf is None or gdf.empty: - return gdf - gdf = gdf.copy() - if merge_by_original_line: - group_field = "OLnFID" - sort_fields = [algo_common.SOURCE_SEG_FIELD, algo_common.SOURCE_ROW_FIELD, "OLnSEG"] - else: - group_field = algo_common.SOURCE_ROW_FIELD - sort_fields = ["OLnSEG"] - ordered = gdf.sort_values(sort_fields, kind="stable") - gdf[MERGE_ORDER_FIELD] = ordered.groupby(group_field, sort=False).cumcount() - return gdf - - -def _restore_merged_ids(gdf, merge_by_original_line): - """Give merged rows their input OLnSEG back (or -1 for a whole original line) and drop helper fields.""" - if gdf is None or gdf.empty: - return gdf - gdf = gdf.copy() - if merge_by_original_line: - gdf["OLnSEG"] = -1 - elif algo_common.SOURCE_SEG_FIELD in gdf.columns: - gdf["OLnSEG"] = gdf[algo_common.SOURCE_SEG_FIELD] - return _drop_helper_fields(gdf) - - -def _drop_helper_fields(gdf): - if gdf is None: - return gdf - helper_fields = [algo_common.SOURCE_ROW_FIELD, algo_common.SOURCE_SEG_FIELD, MERGE_ORDER_FIELD] - return gdf.drop(columns=[f for f in helper_fields if f in gdf.columns]) - - -def process_single_line_class(seed_line): - try: - # OLnFID and OLnSEG are added in previous QC stage. - cid=(f"{seed_line.line['OLnFID'].iloc[0]}_" - f"{seed_line.line['OLnSEG'].iloc[0]}") - seed_line.compute() - return seed_line - except Exception: - logger.exception(f"FAILED PID={os.getpid()} FID={cid}") - raise - - -def centerline( - in_line, - in_raster, - line_radius, - proc_segments, - out_line, - merge_by_original_line=False, - centerline_method=bt_const.CENTERLINE_METHOD.value, - guided_strategy=bt_const.CENTERLINE_GUIDED_STRATEGY.value, - simplify_centerline=False, - simplify_diameter=10.0, - lcp_simplify_enabled=False, - lcp_simplify_diameter=10.0, - lcp_smooth_enabled=False, - lcp_smooth_iterations=1, - chm_mode=bt_const.CENTERLINE_CHM_MODE.value, - chm_buffer_width=5.0, - chm_buffer_multiplier=0.5, - astar_corridor_line_bias_weight=0.1, - astar_corridor_distance_penalty_weight=0.2, - corridor_simplify_polygon=False, - corridor_simplify_length=0.5, - corridor_smooth_polygon=False, - corridor_polygon_smooth_iterations=1, - use_angle_grouping=True, - processes=0, - call_mode=CallMode.CLI, - log_level="INFO", -): - """Run centerline extraction. - - guided_strategy modes: - - MAIN_ROUTE: unguided main-route extraction. - - PAIRWISE: endpoint-guided search over endpoint node pairs. - - VIRTUAL_NODES: endpoint-guided search using virtual source/destination graph nodes. - - DIRECT_INSERT: endpoint-guided search by inserting endpoints directly into the Voronoi graph. - """ - if isinstance(guided_strategy, str): - guided_strategy = bt_const.CenterlineStrategy(guided_strategy) - if isinstance(centerline_method, str): - centerline_method = bt_const.CenterlineMethod(centerline_method) - if isinstance(chm_mode, str): - chm_mode = bt_const.CenterlineChmMode(chm_mode) - - guided_strategy_value = guided_strategy.value - centerline_method_value = centerline_method.value - chm_mode_value = chm_mode.value - proc_segments = _to_bool(proc_segments) - merge_by_original_line = _to_bool(merge_by_original_line) - - in_file, in_layer = sp_common.decode_file_layer(in_line) - out_file, out_layer = sp_common.decode_file_layer(out_line) - simplify_enabled = _to_bool(simplify_centerline) - diameter = tool_geo_simplify.validate_diameter(simplify_diameter) - line_radius_m = float(line_radius) - - vec_crs_osr = sp_common.vector_crs(in_file, in_layer) - line_radius_native = unit_conversion.convert_meters_param_projected_from_osr( - vec_crs_osr, - line_radius_m, - "Line Processing Radius (m)", - ) - chm_buffer_width_native = unit_conversion.convert_meters_param_projected_from_osr( - vec_crs_osr, - float(chm_buffer_width), - "CHM Buffer Width (m)", - ) - - if not sp_common.compare_crs(vec_crs_osr, sp_common.raster_crs(in_raster)): - print("Line and CHM have different spatial references, please check.") - return - - with rasterio.open(in_raster) as src: - cell_size = max(abs(float(src.transform.a)), abs(float(src.transform.e)), ) - - if not sp_common.check_vector_raster_extent_overlap(in_file, in_layer, in_raster): - print("Input line extent does not overlap input raster extent.") - return - - line_gdf = gpd.read_file(in_file, layer=in_layer) - if not sp_common.check_vector_raster_overlap(line_gdf, in_raster): - print("Input line(s) do not overlap input raster.") - return - - line_class_list = generate_line_class_list( - in_file, - in_raster, - line_radius=line_radius_native, - layer=in_layer, - proc_segments=proc_segments, - guided_strategy=guided_strategy_value, - centerline_method=centerline_method_value, - lcp_simplify_enabled=_to_bool(lcp_simplify_enabled), - lcp_simplify_diameter=tool_geo_simplify.validate_diameter(lcp_simplify_diameter), - lcp_smooth_enabled=_to_bool(lcp_smooth_enabled), - lcp_smooth_iterations=int(lcp_smooth_iterations), - chm_mode=chm_mode_value, - chm_buffer_width=chm_buffer_width_native, - chm_buffer_multiplier=float(chm_buffer_multiplier), - astar_corridor_line_bias_weight=float(astar_corridor_line_bias_weight), - astar_corridor_distance_penalty_weight=float(astar_corridor_distance_penalty_weight), - corridor_simplify_polygon=_to_bool(corridor_simplify_polygon), - corridor_simplify_length=float(corridor_simplify_length), - corridor_smooth_polygon=_to_bool(corridor_smooth_polygon), - corridor_polygon_smooth_iterations=int(corridor_polygon_smooth_iterations), - ) - - print("{} lines to be processed.".format(len(line_class_list))) - - lc_path_list = [] - centerline_list = [] - corridor_poly_list = [] - result = execute_multiprocessing( - process_single_line_class, - line_class_list, - "Centerline", - processes, - call_mode, - logger_name = LOGGER_NAME) - if not result: - print("No centerlines found.") - return 1 - - for item in result: - lc_path_list.append(item.lc_path) - centerline_list.append(item.centerline) - corridor_poly_list.append(item.corridor_poly_gpd) - - # Concatenate the lists of GeoDataFrames into single GeoDataFrames - if len(lc_path_list) == 0 or len(centerline_list) == 0 or len(corridor_poly_list) == 0: - print("No centerline generated.") - return 1 - - lc_path_list = pd.concat(lc_path_list, ignore_index=True) - centerline_list = pd.concat(centerline_list, ignore_index=True) - corridor_polys = pd.concat(corridor_poly_list, ignore_index=True) - - # Make sure they remain GeoDataFrames: - lc_path_gdf = gpd.GeoDataFrame(lc_path_list, - geometry="geometry",crs=line_gdf.crs,) - - centerline_gdf = gpd.GeoDataFrame(centerline_list, - geometry="geometry",crs=line_gdf.crs,) - - corridor_gdf = gpd.GeoDataFrame(corridor_polys, - geometry="geometry",crs=line_gdf.crs,) - - # Save the concatenated GeoDataFrames to the shapefile/gpkg - logger.info("Clean geometries....") - centerline_gdf = algo_common.clean_geometries( - centerline_gdf, - stage="output", - out_file=out_file, - layer="rejected_output_centerlines",) - - lc_path_gdf = algo_common.clean_geometries( - lc_path_gdf, - stage="lcp_segments", - out_file=out_file, - layer="rejected_lcp_segments", - ) - - corridor_gdf = algo_common.clean_geometries( - corridor_gdf, - stage="corridor_segments", - out_file=out_file, - layer="rejected_corridor_segments", - ) - logger.info("Clean geometries....Done") - - dissolved_cl_orig=centerline_gdf - dissolved_lcp_orig=lc_path_gdf - dissolved_corridor_orig=corridor_gdf - # whole lines need no merging, so they are saved as they are - dissolved_cl = centerline_gdf - dissolved_lcp = lc_path_gdf - dissolved_corridor = corridor_gdf - aux_file = algo_common.get_aux_path(out_file) - if proc_segments or merge_by_original_line: - logger.info("Dissolving segments...") - dissolved_cl_orig, dissolved_lcp_orig, dissolved_corridor_orig = ( - _add_merge_order(gdf, merge_by_original_line) - for gdf in (centerline_gdf, lc_path_gdf, corridor_gdf) - ) - group_field = "OLnFID" if merge_by_original_line else algo_common.SOURCE_ROW_FIELD - - dissolved_cl = ( - algo_common.merge_lines_by_original_id( - line_gdf=dissolved_cl_orig, - group_field=group_field, - order_field=MERGE_ORDER_FIELD, - max_bridge_gap=max( - cell_size * 1.5, - 0.5, - ), - geometry_count_field=( - "merged_centerline_part_count" - ), - ) - ) - - dissolved_cl = algo_common.clean_geometries( - dissolved_cl, - stage="merged_centerlines", - out_file=out_file, - layer="rejected_merged_centerline_geometry", - ) - - dissolved_lcp = ( - algo_common.merge_lines_by_original_id( - line_gdf=dissolved_lcp_orig, - group_field=group_field, - order_field=MERGE_ORDER_FIELD, - max_bridge_gap=max( - cell_size * 0.75, - 0.05, - ), - geometry_count_field=( - "merged_lcp_part_count" - ), - ) - ) - - dissolved_corridor = ( - algo_common.merge_corridors_by_original_id( - dissolved_corridor_orig, - group_field=group_field, - order_field=MERGE_ORDER_FIELD, - ) - ) - - - if dissolved_cl is None or dissolved_cl.empty: - print("No centerlines remained after merging.") - return 1 - - valid_mask = dissolved_cl.geometry.apply( - lambda geom: not algo_common._is_degenerate_line( - geom, - min_length=max(cell_size, 1.0), - endpoint_tolerance=max(cell_size * 0.01,1e-6,), - min_straightness=0.10, - stage="final",)) - - rejected_final = dissolved_cl.loc[~valid_mask].copy() - dissolved_cl = dissolved_cl.loc[valid_mask].copy() - - if not rejected_final.empty: - rejected_final["BT_REJECT_REASON"] = ( - "degenerate_after_merge") - - rejected_final.to_file(aux_file, - layer="rejected_merged_centerlines",overwrite=True,) - - if dissolved_cl.empty: - print("All merged centerlines failed final QC.") - return 1 - - logger.info("Dissolving segments...Done") - - dissolved_cl, dissolved_lcp, dissolved_corridor = ( - _restore_merged_ids(gdf, merge_by_original_line) - for gdf in (dissolved_cl, dissolved_lcp, dissolved_corridor) - ) - centerline_gdf, lc_path_gdf, corridor_gdf = ( - _drop_helper_fields(gdf) for gdf in (centerline_gdf, lc_path_gdf, corridor_gdf) - ) - - if simplify_enabled and diameter > 0: - temp_file = tool_geo_simplify.build_temp_output_same_folder( - out_file, - prefix=f"{Path(out_file).stem}_centerline_tmp_", - ) - # geo-simplify recreates its --output file, so never point it at out_file - # directly or every other layer in the GeoPackage is wiped. - temp_out_file = tool_geo_simplify.build_temp_output_same_folder( - out_file, - prefix=f"{Path(out_file).stem}_centerline_simplified_tmp_", - ) - temp_layer = "centerline_temp" - try: - dissolved_cl.to_file(temp_file.as_posix(), layer=temp_layer,overwrite=True) - temp_out_file.unlink() - tool_geo_simplify.run_reduce_bend( - input_file=temp_file, - in_layer=temp_layer, - output_file=temp_out_file.as_posix(), - out_layer=out_layer, - diameter=diameter, - smooth_line=True, - ) - simplified_cl = gpd.read_file(temp_out_file, layer=out_layer) - algo_common.drop_layer_if_exists(out_file, out_layer) - simplified_cl.to_file(out_file, layer=out_layer) - finally: - for path in (temp_file, temp_out_file): - if path.exists(): - path.unlink() - else: - if simplify_enabled and diameter == 0: - print("Centerline simplify enabled with diameter 0; skipping simplify step.") - if Path(out_file).exists(): - algo_common.drop_layer_if_exists(out_file,out_layer) - dissolved_cl.to_file(out_file, layer=out_layer) - - print(f"Saved centerlines to: {out_file}") - - aux_file = algo_common.get_aux_path(out_file) - print(f"Saved auxiliary data to: {aux_file}") - - # Save lc_path_list and corridor_polys to the new GeoPackage with '_aux' suffix - if proc_segments: - centerline_gdf.to_file(aux_file,layer="centerline_segments",overwrite=True) - lc_path_gdf.to_file(aux_file,layer="least_cost_path_segments",overwrite=True) - corridor_gdf.to_file(aux_file,layer="corridor_polygon_segments",overwrite=True) - - dissolved_lcp.to_file(aux_file, layer="dissolved_lcp",overwrite=True) - dissolved_corridor.to_file(aux_file, layer="dissolved_corridor",overwrite=True) - - return 0 - - -if __name__ == "__main__": - import time +import sys +import warnings - from beratools.utility.tool_args import compose_tool_kwargs +from beratools.modules.mapping import centerline as _moved - start_time = time.time() - kwargs = compose_tool_kwargs("centerline") - centerline(**kwargs) - print("Elapsed time: {}".format(time.time() - start_time)) +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" for full license details. - -Author: Richard Zeng - -Description: - This script is part of the BERA Tools. - Webpage: https://github.com/BERATool/beratools - - The purpose of this script is to provide main interface for line grouping tool. +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -import logging -import time -from datetime import datetime, timezone -from dataclasses import dataclass -from typing import Optional +import sys +import warnings -import geopandas as gpd +from beratools.modules.mapping import check_seed_line as _moved -import beratools.core.constants as bt_const -import beratools.core.algo_common as algo_common -from beratools.core.algo_check_seed_line import ( - _choose_anchor, - _clean_line_geometries_min_length_m, - _clip_to_chm_footprint, - _default_close_distance_m, - _densify_linestring, - _densify_long_lines, - _geometry_length_meters, - _interp_coord, - _iter_line_parts, - _normalize_to_lines, - _parse_line_id, - _preclean_lines_full, - _snap_close_endpoints, - _trim_short_terminal_segments, - qc_merge_multilinestring, - qc_split_lines_at_intersections, +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" {out_count}") - elif skipped_steps is not None: - _record_skipped_step(skipped_steps, step_idx, step_name, skipped_reason) - logger.debug( - "Step %s - %s skipped (%s): %s -> %s", - step_idx, - step_name, - skipped_reason, - in_count, - out_count, - ) - return - - if elapsed is None: - print(f"✓ {label} {in_count} -> {out_count}") - return - - print(f"✓ {label} {in_count} -> {out_count} {elapsed:.3f}s") - - -def _print_skipped_summary(skipped_steps): - if not skipped_steps: - return - - option_order = { - "Clip to CHM footprint": 0, - "Remove short lines": 1, - "Preclean vertices": 2, - "Snap close endpoints": 3, - "Group lines": 4, - "Densify long lines": 5, - "Apply Seed Line Correction": 6, - } - skipped_steps = sorted( - skipped_steps, - key=lambda item: (option_order.get(item[1], 99), item[0]), - ) - - lines = [] - for _, step_name, _ in skipped_steps: - label = step_name.ljust(34) - lines.append(f"↷ {label} skipped") - print("\n".join(lines)) - - -def _print_qc_summary(qc_summary, aux_file): - if qc_summary["total"] > 0: - print("QC Report Summary:") - print(f" Short lines: {qc_summary['short_line']} issues") - print(f" Close vertices: {qc_summary['close_vertices']} issues") - print(f" Unsnapped endpoints: {qc_summary['unsnapped_endpoint']} issues") - print(f" Self-crossing: {qc_summary['self_crossing']} issues") - print(f" Overlapping lines: {qc_summary['overlap']} issues") - print(f" CHM NoData vertices: {qc_summary.get('chm_nodata_vertex', 0)} issues") - print(f" {'-' * 35}") - print(f" Total issues: {qc_summary['total']}") - print(f" Details saved to: {aux_file} (layer: qc_report_issues)") - else: - print("QC Report: No issues found.") - - -def _record_skipped_step(skipped_steps, step_idx, step_name, reason): - if skipped_steps is None: - return - - if any(existing_step_name == step_name for _, existing_step_name, _ in skipped_steps): - return - - skipped_steps.append((step_idx, step_name, reason)) - - -def _bail_if_empty(gdf, step_name, out_file, out_layer, in_count, skipped_steps=None): - if not gdf.empty: - return False - - if skipped_steps: - _print_skipped_summary(skipped_steps) - - logger.warning( - "Seed line QC early return after '%s' produced empty output (%s -> 0).", - step_name, - in_count, - ) - print("QC Report skipped: output became empty before Step 12.") - _write_output(gdf.iloc[0:0].copy(), out_file, out_layer) - return True - - -def _step_timer(): - return time.perf_counter() - - -def _elapsed(start_t): - return time.perf_counter() - start_t - - -def _convert_slc_meter_params_to_native_units(lines_gdf, search_distance_m, line_radius_m): - """Convert SLC meter parameters to source CRS linear units.""" - search_distance_native = unit_conversion.convert_meters_param_projected( - lines_gdf, - search_distance_m, - "Apply Seed Line Correction search distance (m)", - min_value=bt_const.SMALL_BUFFER, - ) - line_radius_native = unit_conversion.convert_meters_param_projected( - lines_gdf, - line_radius_m, - "Apply Seed Line Correction line radius (m)", - min_value=bt_const.SMALL_BUFFER, - ) - return search_distance_native, line_radius_native - - -def check_seed_line( - in_line, - in_raster, - out_line, - chm_footprint_shrink=15.0, - clip_to_chm_footprint=True, - remove_short_lines=False, - minimum_line_length=5.0, - preclean_vertices=True, - preclean_close_distance=None, - preclean_angle_tolerance=10.0, - snap_close_endpoints=False, - snap_tolerance=5.0, - group_lines=False, - densify_long_lines=False, - max_segment_length=bt_const.LP_SEGMENT_LENGTH, - use_angle_grouping=True, - warn_nodata_vertices=True, - nodata_vertex_search_radius=10.0, - check_internal_vertices=False, - apply_seed_line_correction=False, - slc_search_distance=5.0, - slc_line_radius=15.0, - slc_optimize_internal_vertices=False, - processes=0, - call_mode=CallMode.CLI, - log_level="INFO", -): - from beratools.core.algo_line_grouping import LineGrouping - - level_name = str(log_level).upper() - level_value = getattr(logging, level_name, logging.INFO) - verbose_steps = level_value <= logging.DEBUG - logger.setLevel(level_value) - for handler in logging.getLogger().handlers: - if isinstance(handler, logging.StreamHandler): - handler.setLevel(level_value) - - config = SeedLineQCConfig( - chm_footprint_shrink=float(chm_footprint_shrink), - clip_to_chm_footprint=_to_bool(clip_to_chm_footprint), - remove_short_lines=_to_bool(remove_short_lines), - minimum_line_length=float(minimum_line_length), - preclean_vertices=_to_bool(preclean_vertices), - preclean_close_distance=None - if preclean_close_distance in (None, "", "none") - else float(preclean_close_distance), - preclean_angle_tolerance=float(preclean_angle_tolerance), - snap_close_endpoints=_to_bool(snap_close_endpoints), - snap_tolerance=float(snap_tolerance), - group_lines=_to_bool(group_lines), - densify_long_lines=_to_bool(densify_long_lines), - max_segment_length=float(max_segment_length), - use_angle_grouping=_to_bool(use_angle_grouping), - warn_nodata_vertices=_to_bool(warn_nodata_vertices), - nodata_vertex_search_radius=float(nodata_vertex_search_radius), - check_internal_vertices=_to_bool(check_internal_vertices), - apply_seed_line_correction=_to_bool(apply_seed_line_correction), - slc_search_distance=float(slc_search_distance), - slc_line_radius=float(slc_line_radius), - slc_optimize_internal_vertices=_to_bool(slc_optimize_internal_vertices), - ) - - skipped_steps = [] - - in_file, in_layer = sp_common.decode_file_layer(in_line) - out_file, out_layer = sp_common.decode_file_layer(out_line) - aux_file = algo_common.get_aux_path(out_file) - effective_preclean_close_distance = ( - _default_close_distance_m(in_raster) - if config.preclean_close_distance is None - else float(config.preclean_close_distance) - ) - - qc_manifest = { - "qc_removed_input_cleanup": { - "layer_name": "qc_removed_input_cleanup", - "step": 0, - "step_name": "input cleanup", - "reason": "Invalid, null, or empty geometries removed during input hygiene", - "feature_count": 0, - "written": 0, - "notes": "not triggered", - }, - "qc_removed_cleanup": { - "layer_name": "qc_removed_cleanup", - "step": 2, - "step_name": "geometry cleanup", - "reason": "Null, empty, or too-short lines removed in cleanup", - "feature_count": 0, - "written": 0, - "notes": "not triggered", - }, - "qc_removed_short": { - "layer_name": "qc_removed_short", - "step": 4, - "step_name": "short line removal", - "reason": "Lines below user minimum length", - "feature_count": 0, - "written": 0, - "notes": "disabled", - }, - "qc_removed_clipped": { - "layer_name": "qc_removed_clipped", - "step": 3, - "step_name": "CHM footprint clipping", - "reason": "Lines outside shrunken CHM footprint", - "feature_count": 0, - "written": 0, - "notes": "not triggered", - }, - "chm_footprint": { - "layer_name": "chm_footprint", - "step": 3, - "step_name": "CHM footprint clipping", - "reason": "Shrunken CHM footprint used for clipping", - "feature_count": 0, - "written": 0, - "notes": "not triggered", - }, - "qc_removed_post_clip": { - "layer_name": "qc_removed_post_clip", - "step": 5, - "step_name": "post-clip normalize + cleanup", - "reason": "Fragments removed after clipping and normalization", - "feature_count": 0, - "written": 0, - "notes": "not triggered", - }, - "qc_removed_preclean": { - "layer_name": "qc_removed_preclean", - "step": 6, - "step_name": "preclean vertices", - "reason": "Removes near-duplicate endpoint vertices and simplifies close interior vertices with angle-aware bend preservation.", - "feature_count": 0, - "written": 0, - "notes": "not triggered", - }, - "qc_removed_final": { - "layer_name": "qc_removed_final", - "step": 11, - "step_name": "final cleanup", - "reason": "Remaining invalid/empty/too-short lines", - "feature_count": 0, - "written": 0, - "notes": "not triggered", - }, - "qc_report_issues": { - "layer_name": "qc_report_issues", - "step": 12, - "step_name": "QC report", - "reason": "Post-processing QC check results (using 2x thresholds)", - "feature_count": 0, - "written": 0, - "notes": "not triggered", - }, - } - - def _mark_layer(layer_name, layer_gdf, notes=None): - if layer_name not in qc_manifest: - return - count = 0 if layer_gdf is None else len(layer_gdf) - qc_manifest[layer_name]["feature_count"] = int(count) - qc_manifest[layer_name]["written"] = 1 if count > 0 else 0 - qc_manifest[layer_name]["notes"] = notes or ("written" if count > 0 else "empty") - if count > 0: - algo_common.save_aux_layer(layer_gdf, out_file, layer_name) - - def _has_rows(layer_gdf): - return layer_gdf is not None and hasattr(layer_gdf, "empty") and not layer_gdf.empty - - def _ensure_gdf(obj, fallback_crs): - if isinstance(obj, gpd.GeoDataFrame): - return obj - return gpd.GeoDataFrame(obj, crs=fallback_crs) - - def _persist_qc_tables(input_count, output_count): - manifest_rows = [qc_manifest[key] for key in qc_manifest.keys()] - algo_common.save_aux_table(manifest_rows, out_file, "qc_manifest", overwrite=True) - summary_row = { - "tool_name": "check_seed_line", - "run_timestamp_utc": datetime.now(timezone.utc).isoformat(), - "input_line": in_line, - "input_raster": in_raster, - "output_line": out_line, - "aux_gpkg": aux_file, - "clip_to_chm_footprint": int(config.clip_to_chm_footprint), - "chm_footprint_shrink_m": float(config.chm_footprint_shrink), - "remove_short_lines": int(config.remove_short_lines), - "minimum_line_length_m": float(config.minimum_line_length), - "preclean_vertices": int(config.preclean_vertices), - "preclean_mode": "full", - "preclean_close_distance_m": float(effective_preclean_close_distance), - "preclean_angle_tolerance_deg": float(config.preclean_angle_tolerance), - "snap_close_endpoints": int(config.snap_close_endpoints), - "snap_tolerance_m": float(config.snap_tolerance), - "group_lines": int(config.group_lines), - "densify_long_lines": int(config.densify_long_lines), - "max_segment_length_m": float(config.max_segment_length), - "warn_nodata_vertices": int(config.warn_nodata_vertices), - "nodata_vertex_search_radius_m": float(config.nodata_vertex_search_radius), - "check_internal_vertices": int(config.check_internal_vertices), - "apply_seed_line_correction": int(config.apply_seed_line_correction), - "slc_search_distance": float(config.slc_search_distance), - "slc_line_radius": float(config.slc_line_radius), - "slc_optimize_internal_vertices": int(config.slc_optimize_internal_vertices), - "input_feature_count": int(input_count), - "output_feature_count": int(output_count), - } - algo_common.save_aux_table([summary_row], out_file, "qc_run_summary", overwrite=True) - - if in_raster: - if not sp_common.compare_crs( - sp_common.vector_crs(in_file, in_layer), sp_common.raster_crs(in_raster) - ): - raise ValueError("Input line and raster CRS do not match.") - - gdf = gpd.read_file(in_file, layer=in_layer) - if ( - config.clip_to_chm_footprint - and in_raster - and not sp_common.seedlines_within_chm_footprint(gdf, in_raster) - ): - raise ValueError("Input line(s) do not overlap input raster.") - if "fid" in gdf.columns: - gdf = gdf.rename(columns={"fid": "orig_fid"}) - input_count = len(gdf) - gdf = algo_common.clean_geometries( - gdf, - stage="input", - out_file=out_file, - layer="qc_removed_input_cleanup", - ).reset_index(drop=True) - input_cleanup_removed_count = input_count - len(gdf) - qc_manifest["qc_removed_input_cleanup"]["feature_count"] = int(max(input_cleanup_removed_count, 0)) - qc_manifest["qc_removed_input_cleanup"]["written"] = 1 if input_cleanup_removed_count > 0 else 0 - qc_manifest["qc_removed_input_cleanup"]["notes"] = ( - "written" if input_cleanup_removed_count > 0 else "empty" - ) - - logger.info( - "Seed line QC start: %s feature(s), input cleanup removed %s feature(s)", - len(gdf), - input_cleanup_removed_count, - ) - - step_name = "Normalize multiline seed lines" - in_count = len(gdf) - t0 = _step_timer() - gdf = qc_merge_multilinestring(gdf) - _log_step( - 1, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps - ) - if _bail_if_empty( - gdf, - step_name, - out_file, - out_layer, - in_count, - skipped_steps=skipped_steps, - ): - _persist_qc_tables(input_count, 0) - return - - step_name = "Geometry cleanup" - in_count = len(gdf) - t0 = _step_timer() - gdf, removed_gdf = _clean_line_geometries_min_length_m(gdf, bt_const.SMALL_BUFFER) - gdf = gdf.reset_index(drop=True) - _mark_layer("qc_removed_cleanup", removed_gdf, notes="written" if _has_rows(removed_gdf) else "empty") - _log_step( - 2, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps - ) - if _bail_if_empty( - gdf, - step_name, - out_file, - out_layer, - in_count, - skipped_steps=skipped_steps, - ): - _persist_qc_tables(input_count, 0) - return - - step_name = "Clip to CHM footprint" - in_count = len(gdf) - if config.clip_to_chm_footprint: - if in_raster: - t0 = _step_timer() - gdf, removed_gdf, footprint = _clip_to_chm_footprint(gdf, in_raster, config.chm_footprint_shrink) - _mark_layer( - "qc_removed_clipped", removed_gdf, notes="written" if _has_rows(removed_gdf) else "empty" - ) - footprint_gdf = gpd.GeoDataFrame( - [{"source": "chm_footprint_shrunken"}], geometry=[footprint], crs=gdf.crs - ) - _mark_layer("chm_footprint", footprint_gdf, notes="written") - _log_step( - 3, - step_name, - in_count, - len(gdf), - _elapsed(t0), - verbose=verbose_steps, - skipped_steps=skipped_steps, - ) - if _bail_if_empty( - gdf, - step_name, - out_file, - out_layer, - in_count, - skipped_steps=skipped_steps, - ): - _persist_qc_tables(input_count, 0) - return - else: - qc_manifest["qc_removed_clipped"]["notes"] = "enabled but missing in_raster" - qc_manifest["chm_footprint"]["notes"] = "enabled but missing in_raster" - logger.error( - "CHM footprint clipping enabled but 'in_raster' is missing; continuing without footprint clip." - ) - _log_step( - 3, - step_name, - in_count, - in_count, - skipped_reason="enabled but missing in_raster", - verbose=verbose_steps, - skipped_steps=skipped_steps, - ) - else: - qc_manifest["qc_removed_clipped"]["notes"] = "disabled" - qc_manifest["chm_footprint"]["notes"] = "disabled" - _log_step( - 3, - step_name, - in_count, - in_count, - skipped_reason="disabled", - verbose=verbose_steps, - skipped_steps=skipped_steps, - ) - - step_name = "Remove short lines" - in_count = len(gdf) - if config.remove_short_lines: - t0 = _step_timer() - gdf, removed_gdf = _clean_line_geometries_min_length_m(gdf, config.minimum_line_length) - gdf = gdf.reset_index(drop=True) - _mark_layer("qc_removed_short", removed_gdf, notes="written" if _has_rows(removed_gdf) else "empty") - _log_step( - 4, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps - ) - if _bail_if_empty( - gdf, - step_name, - out_file, - out_layer, - in_count, - skipped_steps=skipped_steps, - ): - _persist_qc_tables(input_count, 0) - return - else: - qc_manifest["qc_removed_short"]["notes"] = "disabled" - _log_step( - 4, - step_name, - in_count, - in_count, - skipped_reason="disabled", - verbose=verbose_steps, - skipped_steps=skipped_steps, - ) - - step_name = "Post-clip cleanup" - in_count = len(gdf) - t0 = _step_timer() - gdf = _normalize_to_lines(gdf) - gdf, removed_gdf = _clean_line_geometries_min_length_m(gdf, bt_const.SMALL_BUFFER) - gdf = gdf.reset_index(drop=True) - _mark_layer("qc_removed_post_clip", removed_gdf, notes="written" if _has_rows(removed_gdf) else "empty") - _log_step( - 5, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps - ) - if _bail_if_empty( - gdf, - step_name, - out_file, - out_layer, - in_count, - skipped_steps=skipped_steps, - ): - _persist_qc_tables(input_count, 0) - return - - step_name = "Preclean vertices" - in_count = len(gdf) - if config.preclean_vertices: - t0 = _step_timer() - gdf, removed_gdf = _preclean_lines_full( - gdf, - close_distance_m=effective_preclean_close_distance, - angle_tol_deg=config.preclean_angle_tolerance, - ) - gdf.geometry = gdf.geometry.apply( - lambda g: _trim_short_terminal_segments( - g, - min_segment_length=config.minimum_line_length - ) - ) - gdf = gdf.reset_index(drop=True) - - _mark_layer( - "qc_removed_preclean", removed_gdf, notes="written" if _has_rows(removed_gdf) else "empty" - ) - _log_step( - 6, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps - ) - if _bail_if_empty( - gdf, - step_name, - out_file, - out_layer, - in_count, - skipped_steps=skipped_steps, - ): - _persist_qc_tables(input_count, 0) - return - else: - qc_manifest["qc_removed_preclean"]["notes"] = "disabled" - _log_step( - 6, - step_name, - in_count, - in_count, - skipped_reason="disabled", - verbose=verbose_steps, - skipped_steps=skipped_steps, - ) - - step_name = "Snap close endpoints" - in_count = len(gdf) - if config.snap_close_endpoints: - t0 = _step_timer() - effective_tolerance = config.snap_tolerance - if config.remove_short_lines: - effective_tolerance = max(effective_tolerance, config.minimum_line_length) - gdf = _snap_close_endpoints(gdf, effective_tolerance).reset_index(drop=True) - _log_step( - 7, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps - ) - if _bail_if_empty( - gdf, - step_name, - out_file, - out_layer, - in_count, - skipped_steps=skipped_steps, - ): - _persist_qc_tables(input_count, 0) - return - else: - _log_step( - 7, - step_name, - in_count, - in_count, - skipped_reason="disabled", - verbose=verbose_steps, - skipped_steps=skipped_steps, - ) - - step_name = "Split lines at intersections" - in_count = len(gdf) - t0 = _step_timer() - prev_crs = gdf.crs - split_out = qc_split_lines_at_intersections(gdf) - gdf = _ensure_gdf(split_out, prev_crs) - split_min_length = config.minimum_line_length if config.remove_short_lines else bt_const.SMALL_BUFFER - gdf, removed_gdf = _clean_line_geometries_min_length_m(gdf, split_min_length) - # pieces keep their line's OLnSEG, so number them along each original line - if "OLnFID" in gdf.columns and "OLnSEG" in gdf.columns: - gdf = gdf.sort_values(["OLnFID", "OLnSEG"], kind="stable").reset_index(drop=True) - gdf["OLnSEG"] = gdf.groupby("OLnFID").cumcount() - gdf = gdf.reset_index(drop=True) - _log_step( - 8, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps - ) - if _bail_if_empty( - gdf, - step_name, - out_file, - out_layer, - in_count, - skipped_steps=skipped_steps, - ): - _persist_qc_tables(input_count, 0) - return - - step_name = "Group lines" - in_count = len(gdf) - if config.group_lines: - t0 = _step_timer() - lg = LineGrouping(gdf, use_angle_grouping=config.use_angle_grouping) - lg.run_grouping() - gdf = _ensure_gdf(lg.lines, gdf.crs).reset_index(drop=True) - _log_step( - 9, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps - ) - if _bail_if_empty( - gdf, - step_name, - out_file, - out_layer, - in_count, - skipped_steps=skipped_steps, - ): - _persist_qc_tables(input_count, 0) - return - else: - gdf = _ensure_gdf(gdf, gdf.crs).reset_index(drop=True) - gdf[bt_const.BT_GROUP] = list(range(len(gdf))) - _log_step( - 9, - step_name, - in_count, - len(gdf), - skipped_reason="disabled; assigned unique BT_GROUP", - verbose=verbose_steps, - skipped_steps=skipped_steps, - ) - - step_name = "Densify long lines" - in_count = len(gdf) - if config.densify_long_lines: - t0 = _step_timer() - gdf = _densify_long_lines(gdf, config.max_segment_length).reset_index(drop=True) - _log_step( - 10, - step_name, - in_count, - len(gdf), - _elapsed(t0), - verbose=verbose_steps, - skipped_steps=skipped_steps, - ) - if _bail_if_empty( - gdf, - step_name, - out_file, - out_layer, - in_count, - skipped_steps=skipped_steps, - ): - _persist_qc_tables(input_count, 0) - return - else: - _log_step( - 10, - step_name, - in_count, - in_count, - skipped_reason="disabled", - verbose=verbose_steps, - skipped_steps=skipped_steps, - ) - - step_name = "Apply Seed Line Correction" - in_count = len(gdf) - if config.apply_seed_line_correction: - from beratools.core.algo_seed_line_correction import SeedLineCorrection - - print("Starting Seed Line Correction...", flush=True) - - slc_search_distance_native, slc_line_radius_native = _convert_slc_meter_params_to_native_units( - gdf, - config.slc_search_distance, - config.slc_line_radius, - ) - - t0 = _step_timer() - try: - slc = SeedLineCorrection( - in_file, - in_raster, - slc_search_distance_native, - slc_line_radius_native, - processes, - call_mode, - layer=in_layer, - optimize_internal_vertices=config.slc_optimize_internal_vertices, - ) - slc.prepare_lines(lines_gdf=gdf) - slc.group_vertices() - gdf = _ensure_gdf(slc.optimize(), gdf.crs).reset_index(drop=True) - debug_layers = slc.get_debug_layers() - algo_common.save_aux_layer(debug_layers.get("lc_paths"), out_file, "lc_paths") - algo_common.save_aux_layer(debug_layers.get("anchors"), out_file, "anchors") - algo_common.save_aux_layer(debug_layers.get("vertices"), out_file, "vertices") - except Exception: - logger.exception("Apply Seed Line Correction failed; QC report step was not reached.") - raise - _log_step( - 11, - step_name, - in_count, - len(gdf), - _elapsed(t0), - verbose=verbose_steps, - skipped_steps=skipped_steps, - ) - if _bail_if_empty( - gdf, - step_name, - out_file, - out_layer, - in_count, - skipped_steps=skipped_steps, - ): - _persist_qc_tables(input_count, 0) - return - else: - _log_step( - 11, - step_name, - in_count, - in_count, - skipped_reason="disabled", - verbose=verbose_steps, - skipped_steps=skipped_steps, - ) - - gdf, removed_gdf = _clean_line_geometries_min_length_m(gdf, bt_const.SMALL_BUFFER) - gdf = gdf.reset_index(drop=True) - _mark_layer("qc_removed_final", removed_gdf, notes="written" if _has_rows(removed_gdf) else "empty") - - step_name = "Generate QC Report" - from beratools.core.algo_check_seed_line_validate import generate_qc_report - - print("Running final validation pass to detect remaining issues after all previous steps...") - t0 = _step_timer() - qc_issues_gdf, qc_summary = generate_qc_report( - gdf, - min_length_m=config.minimum_line_length * 2.0, - close_distance_m=effective_preclean_close_distance * 2.0, - snap_tolerance_m=config.snap_tolerance * 2.0, - in_raster=in_raster, - warn_nodata_vertices=config.warn_nodata_vertices, - nodata_vertex_search_radius_m=config.nodata_vertex_search_radius, - check_internal_vertices=config.check_internal_vertices, - ) - _mark_layer("qc_report_issues", qc_issues_gdf) - _log_step( - 12, - step_name, - len(gdf), - qc_summary["total"], - _elapsed(t0), - verbose=verbose_steps, - skipped_steps=skipped_steps, - ) - _print_qc_summary(qc_summary, aux_file) - - if not verbose_steps and skipped_steps: - _print_skipped_summary(skipped_steps) - - _write_output(gdf, out_file, out_layer) - _persist_qc_tables(input_count, len(gdf)) - print(f"Output saved to file: {out_file}, layer: {out_layer}") - - -if __name__ == "__main__": - from beratools.utility.tool_args import compose_tool_kwargs - - start_time = time.time() - kwargs = compose_tool_kwargs("check_seed_line") - check_seed_line(**kwargs) - print("Elapsed time: {}".format(time.time() - start_time)) +sys.modules[__name__] = _moved diff --git a/beratools/tools/common.py b/beratools/tools/common.py index e78ccd1..0a3c9e9 100644 --- a/beratools/tools/common.py +++ b/beratools/tools/common.py @@ -1,336 +1,20 @@ """ -Copyright (C) 2025 Applied Geospatial Research Group. +Deprecated: moved to beratools.modules.mapping. -This script is licensed under the GNU General Public License v3.0. -See for full license details. - -Author: Richard Zeng, Maverick Fong - -Description: - This script is part of the BERA Tools. - Webpage: https://github.com/BERATool/beratools - - This file is intended to be hosting common spatial classes/functions for BERA Tools +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -import geopandas as gpd -import numpy as np -import shapely -import shapely.geometry as sh_geom -import shapely.ops as sh_ops -import xarray as xr -import xrspatial -from scipy import ndimage - -import beratools.core.constants as bt_const - -PARALLEL_MODE = bt_const.ParallelMode.MULTIPROCESSING - -def remove_nan_from_array(matrix): - with np.nditer(matrix, op_flags=["readwrite"]) as it: - for x in it: - if np.isnan(x[...]): - x[...] = bt_const.BT_NODATA_COST - -def split_into_equal_Nth_segments(df, seg_length): - odf = df - crs = odf.crs - if "OLnSEG" not in odf.columns.array: - df["OLnSEG"] = np.nan - df = odf.assign(geometry=odf.apply(lambda x: cut_line_by_length(x.geometry, seg_length), axis=1)) - df = df.explode() - - df["OLnSEG"] = df.groupby("OLnFID").cumcount() - gdf = gpd.GeoDataFrame(df, geometry=df.geometry, crs=crs) - gdf = gdf.sort_values(by=["OLnFID", "OLnSEG"]) - gdf = gdf.reset_index(drop=True) - - if "shape_leng" in gdf.columns.array: - gdf["shape_leng"] = gdf.geometry.length - elif "LENGTH" in gdf.columns.array: - gdf["LENGTH"] = gdf.geometry.length - else: - gdf["shape_leng"] = gdf.geometry.length - return gdf - - -def cut_line_by_length(line, length, merge_threshold=0.5): - """ - Split line into segments of equal length. - - Merge the last segment with the second-to-last if its length - is smaller than the given threshold. - - Args: - line : LineString - Line to be split by distance along the line. - length : float - Length of each segment to cut. - merge_threshold : float, optional - Threshold below which the last segment is merged with the previous one. Default is 0.5. - - Returns: - List of LineString objects - A list containing the resulting line segments. - - Example: - ">>> from shapely.geometry import LineString - ">>> line = LineString([(0, 0), (10, 0)]) - ">>> segments = cut_line_by_length(line, 3, merge_threshold=1) - ">>> for segment in segments: - ">>> print(f"Segment: {segment}, Length: {segment.length}") - - Output: - Segment: LINESTRING (0 0, 3 0), Length: 3.0 - Segment: LINESTRING (3 0, 6 0), Length: 3.0 - Segment: LINESTRING (6 0, 9 0), Length: 3.0 - Segment: LINESTRING (9 0, 10 0), Length: 1.0 - - After merging the last segment with the second-to-last segment: - - Output: - Segment: LINESTRING (0 0, 3 0), Length: 3.0 - Segment: LINESTRING (3 0, 6 0), Length: 3.0 - Segment: LINESTRING (6 0, 10 0), Length: 4.0 - - """ - if line.has_z: - # Remove the Z component of the line if it exists - line = sh_ops.transform(lambda x, y, z=None: (x, y), line) - - if shapely.is_empty(line): - return [] - - # Segment the line based on the specified distance - line = shapely.segmentize(line, length) - lines = [] - end_pt = None - - while line.length > length: - coords = list(line.coords) - - for i, p in enumerate(coords): - p_dist = line.project(sh_geom.Point(p)) - - # Check if the distance matches closely and split the line - if abs(p_dist - length) < 1e-9: # Use a small epsilon value - lines.append(sh_geom.LineString(coords[: i + 1])) - line = sh_geom.LineString(coords[i:]) - end_pt = None - break - elif p_dist > length: - end_pt = line.interpolate(length) - lines.append(sh_geom.LineString(coords[:i] + list(end_pt.coords))) - line = sh_geom.LineString(list(end_pt.coords) + coords[i:]) - break - - if end_pt: - lines.append(line) - - # Handle the threshold condition: merge the last segment if its length is below the threshold - if len(lines) > 1: - if lines[-1].length < merge_threshold: - # Merge the last segment with the second-to-last one - lines[-2] = sh_geom.LineString(list(lines[-2].coords) + list(lines[-1].coords)) - lines.pop() # Remove the last segment after merging - - return lines - -def chk_df_multipart(df:gpd.GeoDataFrame, - chk_shp_in_string:str)-> tuple[gpd.GeoDataFrame , bool]: - """ - This function is check the input geopandas.GeoDataFrame object contains multipart geometry. - If multipart geometry is found, function will try to explode and return single geometry and - a boolean of multipart is found or not. - Args: - df: Any geopandas.GeoDataFrame like - chk_shp_in_string: String that the input GeoDataFrame geometry type, i.e. 'Point', 'Polygon', 'LineString' - - Returns: - - """ - try: - found = False - if str.upper(chk_shp_in_string) in [x.upper() for x in df.geom_type.values]: - found = True - df = df.explode() - if type(df) is gpd.geodataframe.GeoDataFrame: - df["OLnSEG"] = df.groupby("OLnFID").cumcount() - df = df.sort_values(by=["OLnFID", "OLnSEG"]) - df = df.reset_index(drop=True) - else: - found = False - return df, found - except Exception as e: - print(e) - return df, True - - -def dyn_fs_raster_stdmean(canopy_ndarray, kernel, nodata): - # This function uses xrspatial which can handle large data but slow - mask = canopy_ndarray.mask - in_ndarray = np.ma.where(mask == True, np.nan, canopy_ndarray) - result_ndarray = xrspatial.focal.focal_stats( - xr.DataArray(in_ndarray.data), kernel, stats_funcs=["std", "mean"] - ) - - # Assign std and mean ndarray (return array contain nan value) - reshape_std_ndarray = result_ndarray[0].data - reshape_mean_ndarray = result_ndarray[1].data - - return reshape_std_ndarray, reshape_mean_ndarray - - -def dyn_smooth_cost(canopy_ndarray, max_line_dist, sampling): - mask = canopy_ndarray.mask - in_ndarray = np.ma.where(mask == True, np.nan, canopy_ndarray) - # scipy way to do Euclidean distance transform - euc_dist_array = ndimage.distance_transform_edt( - np.logical_not(np.isnan(in_ndarray.data)), sampling=sampling - ) - euc_dist_array[mask == True] = np.nan - smooth1 = float(max_line_dist) - euc_dist_array - smooth1[smooth1 <= 0.0] = 0.0 - smooth_cost_array = smooth1 / float(max_line_dist) - - return smooth_cost_array - - -def dyn_np_cost_raster(canopy_ndarray, cc_mean, cc_std, cc_smooth, avoidance, cost_raster_exponent): - aM1a = cc_mean - cc_std - aM1b = cc_mean + cc_std - aM1 = np.divide(aM1a, aM1b, where=aM1b != 0, out=np.zeros(aM1a.shape, dtype=float)) - aM = (1 + aM1) / 2 - aaM = cc_mean + cc_std - bM = np.where(aaM <= 0, 0, aM) - cM = bM * (1 - avoidance) + (cc_smooth * avoidance) - dM = np.where(canopy_ndarray.data == 1, 1, cM) - eM = np.exp(dM) - result = np.power(eM, float(cost_raster_exponent)) - - return result - - -def dyn_np_cc_map(in_chm, canopy_ht_threshold, nodata): - canopy_ndarray = np.ma.where(in_chm >= canopy_ht_threshold, 1.0, 0.0).astype(float) - canopy_ndarray.fill_value = nodata - - return canopy_ndarray - - -def generate_line_args_DFP_NoClip( - line_seg, - work_in_bufferL, - work_in_bufferC, - in_chm_obj, - in_chm, - tree_radius, - max_line_dist, - canopy_avoidance, - exponent, - work_in_bufferR, - canopy_thresh_percentage, - exp_shk_cell -): - line_argsL = [] - line_argsR = [] - line_argsC = [] - line_id = 0 - total = len(work_in_bufferC)+len(work_in_bufferL)+len(work_in_bufferR) - for record in range(0, len(work_in_bufferC)): - line_bufferC = work_in_bufferC.loc[record, "geometry"] - nodata = bt_const.BT_NODATA - line_argsC.append( - [ - in_chm, - float(work_in_bufferC.loc[record, "DynCanTh"]), - float(tree_radius), - float(max_line_dist), - float(canopy_avoidance), - float(exponent), - in_chm_obj.res, - nodata, - line_seg.iloc[[record]], - in_chm_obj.meta.copy(), - line_id, - 10, - "Center", - canopy_thresh_percentage, - line_bufferC, - exp_shk_cell - ] - ) - - step = line_id + 1 - print(f' "PROGRESS_LABEL Preparing... {step} of {total}" ', flush=True) - print(f" {(step / total) * 100}% ", flush=True) - line_id += 1 - - line_id = 0 - - for record in range(0, len(work_in_bufferL)): - line_bufferL = work_in_bufferL.loc[record, "geometry"] - LCut = work_in_bufferL.loc[record, "LDist_Cut"] - - nodata = bt_const.BT_NODATA - line_argsL.append( - [ - in_chm, - float(work_in_bufferL.loc[record, "DynCanTh"]), - float(tree_radius), - float(max_line_dist), - float(canopy_avoidance), - float(exponent), - in_chm_obj.res, - nodata, - line_seg.iloc[[record]], - in_chm_obj.meta.copy(), - line_id, - LCut, - "Left", - canopy_thresh_percentage, - line_bufferL, - exp_shk_cell - ] - ) - - step = line_id + 1+ len(work_in_bufferC) - print(f' "PROGRESS_LABEL Preparing... {step} of {total}" ', flush=True) - print(f" {(step / total) * 100}% ", flush=True) - line_id += 1 - - line_id = 0 - for record in range(0, len(work_in_bufferR)): - line_bufferR = work_in_bufferR.loc[record, "geometry"] - RCut = work_in_bufferR.loc[record, "RDist_Cut"] - - nodata = bt_const.BT_NODATA - # TODO deal with inherited nodata and BT_NODATA_COST - # TODO convert nodata to BT_NODATA_COST - line_argsR.append( - [ - in_chm, - float(work_in_bufferR.loc[record, "DynCanTh"]), - float(tree_radius), - float(max_line_dist), - float(canopy_avoidance), - float(exponent), - in_chm_obj.res, - nodata, - line_seg.iloc[[record]], - in_chm_obj.meta.copy(), - line_id, - RCut, - "Right", - canopy_thresh_percentage, - line_bufferR, - exp_shk_cell - ] - ) - step = line_id + 1 + len(work_in_bufferC)+len(work_in_bufferL) - print(f' "PROGRESS_LABEL Preparing... {step} of {total}" ', flush=True) - print(f" {(step / total) * 100}% ", flush=True) +import sys +import warnings - line_id += 1 +from beratools.modules.mapping import common as _moved - return line_argsL, line_argsR, line_argsC +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" for full license details. - -Author: Richard Zeng, Maverick Fong - -Description: - This script is part of the BERA Tools. - Webpage: https://github.com/BERATool/beratools - - This file hosts the ground_footprint tool. +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -import logging -import math -from itertools import chain - -import geopandas as gpd -import numpy as np -import pandas as pd -import pyogrio.errors -import shapely.geometry as sh_geom -import shapely.ops as sh_ops - -import beratools.core.algo_common as algo_common -import beratools.core.constants as bt_const -import beratools.utility.spatial_common as sp_common -import beratools.utility.unit_conversion as unit_conversion -from beratools.core.algo_line_grouping import LineGrouping -from beratools.core.algo_merge_lines import custom_line_merge -from beratools.core.algo_split_with_lines import LineSplitter -from beratools.core.tool_base import execute_multiprocessing -from beratools.utility.tool_args import CallMode - -LOGGER_NAME="ground_footprint" -logger = logging.getLogger(LOGGER_NAME) - -FP_FIXED_WIDTH_DEFAULT = 5.0 - - -def prepare_line_args(line_gdf, poly_gdf, n_samples, offset, width_percentile): - """ - Generate arguments for each line in the GeoDataFrame. - - Args: - line_gdf - poly_gdf - n_samples - offset - - Returns: - line_args : list - row : - inter_poly : - n_samples : - offset : - width_percentile : - - """ - spatial_index = poly_gdf.sindex - line_args = [] - - for idx in line_gdf.index: - row = line_gdf.loc[[idx]] - line = row.geometry.iloc[0] - - # Skip rows where geometry is None - if line is None: - print(row) - continue - - inter_poly = poly_gdf.loc[spatial_index.query(line)] - if bt_const.BT_GROUP in inter_poly.columns: - inter_poly = inter_poly[inter_poly[bt_const.BT_GROUP] == row[bt_const.BT_GROUP].values[0]] - - try: - line_args.append([row, inter_poly, n_samples, offset, width_percentile]) - except Exception as e: - print(e) - - return line_args - - -# Calculating Line Widths -def generate_sample_points(line, n_samples=10): - """ - Generate evenly spaced points along a line. - - Args: - line (LineString): The line along which to generate points. - n_samples (int): The number of points to generate (default is 10). - - Returns: - list: List of shapely Point objects. - - """ - # TODO: determine line type - try: - pts = line.coords - except Exception as e: # TODO: check the code - print(e) - line = sh_ops.linemerge(line) - tuple_coord = sh_geom.mapping(line)["coordinates"] - pts = list(chain(*tuple_coord)) - - return [sh_geom.Point(item) for item in pts] - - -def process_single_line(line_arg): - row = line_arg[0] - inter_poly = line_arg[1] - n_samples = line_arg[2] - offset = line_arg[3] - width_percentile = line_arg[4] - - # TODO: deal with case when inter_poly is empty - try: - widths, line, perp_lines, perp_lines_original = calculate_average_width( - row.iloc[0].geometry, inter_poly, offset, n_samples - ) - except Exception as e: - print(e) - return None - - # Calculate the 75th percentile width - # filter zeros in width array - arr_filter = [False if math.isclose(i, 0.0) else True for i in widths] - widths = widths[arr_filter] - - q3_width = FP_FIXED_WIDTH_DEFAULT - q4_width = FP_FIXED_WIDTH_DEFAULT - try: - # TODO: check the code. widths is empty - if len(widths) > 0: - q3_width = np.percentile(widths, width_percentile) - q4_width = np.percentile(widths, 90) - except Exception as e: - print(e) - - # Store the 75th percentile width as a new attribute - row["avg_width"] = q3_width - row["max_width"] = q4_width - - row["geometry"] = line - try: - row["perp_lines"] = perp_lines - row["perp_lines_original"] = perp_lines_original - except Exception as e: - print(e) - - return row - - -def generate_fixed_width_footprint(line_gdf, max_width=False): - """ - Create a buffer around each line. - - In the GeoDataFrame using its 'max_width' attribute and - saves the resulting polygons in a new shapefile. - - Args: - line_gdf: GeoDataFrame containing LineString with 'max_width' attribute. - max_width: Use max width or not to produce buffer. - - """ - # Create a new GeoDataFrame with the buffer polygons - buffer_gdf = line_gdf.copy(deep=True) - - mean_avg_width = line_gdf["avg_width"].mean() - mean_max_width = line_gdf["max_width"].mean() - - # Use .loc to avoid chained assignment - line_gdf.loc[line_gdf["avg_width"].isna(), "avg_width"] = mean_avg_width - line_gdf.loc[line_gdf["max_width"].isna(), "max_width"] = mean_max_width - - line_gdf.loc[line_gdf["avg_width"] == 0.0, "avg_width"] = mean_avg_width - line_gdf.loc[line_gdf["max_width"] == 0.0, "max_width"] = mean_max_width - - if not max_width: - print("Using quantile 75% width") - buffer_gdf["geometry"] = line_gdf.apply( - lambda row: row.geometry.buffer(row.avg_width / 2) if row.geometry is not None else None, - axis=1, - ) - else: - print("Using quantile 90% + 20% width") - buffer_gdf["geometry"] = line_gdf.apply( - lambda row: row.geometry.buffer(row.max_width * 1.2 / 2) if row.geometry is not None else None, - axis=1, - ) - - return buffer_gdf - - -def calculate_average_width(line, in_poly, offset, n_samples): - """Calculate the average width of a polygon perpendicular to the given line.""" - # Smooth the line - try: - line = line.simplify(0.1) - - valid_widths = 0 - sample_points = generate_sample_points(line, n_samples=n_samples) - sample_points_pairs = list(zip(sample_points[:-2], sample_points[1:-1], sample_points[2:])) - widths = np.zeros(len(sample_points_pairs)) - perp_lines = [] - perp_lines_original = [] - except Exception as e: - print(e) - - try: - for i, points in enumerate(sample_points_pairs): - try: - perp_line = algo_common.generate_perpendicular_line_precise(points, offset=offset) - perp_lines_original.append(perp_line) - except Exception as e: - print(f"Failed to generate perpendicular at index {i}: {e}") - perp_lines_original.append(None) - continue - - try: - polygon_intersect = in_poly.iloc[in_poly.sindex.query(perp_line)] - intersections = polygon_intersect.intersection(perp_line) - except Exception as e: - print(f"Failed intersection at index {i}: {e}") - intersections = [] - - line_list = [] - for inter in intersections: - if inter.is_empty: - continue - - if isinstance(inter, sh_geom.GeometryCollection): - for item in inter.geoms: - if isinstance(item, sh_geom.LineString): - line_list.append(item) - elif isinstance(inter, sh_geom.MultiLineString): - line_list += list(inter.geoms) - else: - line_list.append(inter) - - perp_lines += line_list - - if isinstance(line_list, sh_geom.GeometryCollection): - print("Found 2: GeometryCollection") - - for item in line_list: - widths[i] = max(widths[i], item.length) - valid_widths += 1 - - # Todo: check missing perpendicular lines - # if len(perp_lines_original) < len(sample_points_pairs): - # print(f"Missing perpendicular at index {i}") - - except Exception as e: - print(f"loop: {e}") - - return ( - widths, - line, - sh_geom.MultiLineString(perp_lines), - sh_geom.MultiLineString(perp_lines_original), - ) - - -def ground_footprint( - in_line, - in_footprint, - n_samples, - offset, - max_width, - out_footprint, - in_layer_lc_path="least_cost_path", - merge_group=True, - merge_by_original_line=False, - width_percentile=75, - trim_output=True, - processes=0, - call_mode=CallMode.CLI, - log_level="INFO", -): - in_file, in_layer = sp_common.decode_file_layer(in_line) - in_fp_file, in_layer_fp = sp_common.decode_file_layer(in_footprint) - out_file, out_layer = sp_common.decode_file_layer(out_footprint) - - n_samples = int(n_samples) - offset = float(offset) - width_percentile = int(width_percentile) - - if not sp_common.check_vector_vector_extent_overlap(in_file, in_layer, in_fp_file, in_layer_fp): - print("Input line extent does not overlap input footprint extent.") - return - - # TODO: refactor this code for better line quality check - line_gdf = gpd.read_file(in_file, layer=in_layer) - if "fid" in line_gdf.columns: - line_gdf = line_gdf.rename(columns={"fid": "orig_fid"}) - line_gdf = algo_common.clean_geometries(line_gdf, stage="input") - line_gdf = line_gdf.reset_index(drop=True) - offset = unit_conversion.convert_meters_param_projected( - line_gdf, - offset, - "Perpendicular line length (m)", - min_value=bt_const.SMALL_BUFFER, - ) - - # group by original line, as the centerline tool merges, so pieces share one footprint - merge_by_original_line = str(merge_by_original_line).strip().lower() in ("true", "1", "yes") - if merge_by_original_line and "OLnFID" not in line_gdf.columns: - print("[Warning]: OLnFID not found in input lines; lines are not merged by original line.") - merge_by_original_line = False - if merge_by_original_line: - line_gdf[bt_const.BT_GROUP] = line_gdf["OLnFID"] - - if bt_const.BT_GROUP not in line_gdf.columns: - line_gdf[bt_const.BT_GROUP] = range(1, len(line_gdf) + 1) - - use_least_cost_path = True - try: - lc_path_gdf = gpd.read_file(in_file, layer=in_layer_lc_path) - if "fid" in lc_path_gdf.columns: - lc_path_gdf = lc_path_gdf.rename(columns={"fid": "orig_fid"}) - lc_path_gdf = algo_common.clean_geometries(lc_path_gdf, stage="input") - lc_path_gdf = lc_path_gdf.reset_index(drop=True) - if merge_by_original_line and "OLnFID" in lc_path_gdf.columns: - lc_path_gdf[bt_const.BT_GROUP] = lc_path_gdf["OLnFID"] - except (ValueError, OSError, pyogrio.errors.DataLayerError): - print(f"Layer '{in_layer_lc_path}' not found in {in_file}, skipping least cost path logic.") - use_least_cost_path = False - - if not merge_group: - line_gdf["geometry"] = line_gdf.geometry.apply(custom_line_merge) - if use_least_cost_path: - lc_path_gdf["geometry"] = lc_path_gdf.geometry.apply(custom_line_merge) - - # read footprints and remove holes - poly_gdf = gpd.read_file(in_fp_file, layer=in_layer_fp) - if "fid" in poly_gdf.columns: - poly_gdf = poly_gdf.rename(columns={"fid": "orig_fid"}) - poly_gdf = algo_common.clean_geometries(poly_gdf, stage="input") - poly_gdf = poly_gdf.reset_index(drop=True) - poly_gdf["geometry"] = poly_gdf["geometry"].apply(algo_common.remove_holes) - # polygons are matched to lines by BT_GROUP, so keep their groups the same as the lines' - if merge_by_original_line and "OLnFID" in poly_gdf.columns: - poly_gdf[bt_const.BT_GROUP] = poly_gdf["OLnFID"] - - if not sp_common.compare_crs( - sp_common.vector_crs(in_file, in_layer), sp_common.vector_crs(in_fp_file, in_layer_fp) - ): - print("Input line and footprint have different spatial references, please check.") - return - - if not sp_common.check_vector_vector_overlap(line_gdf, poly_gdf): - print("Input line(s) do not overlap input footprint.") - return - - # merge group and/or split lines at intersections - merged_line_gdf = line_gdf.copy(deep=True) - if merge_group: - lg = LineGrouping(line_gdf, merge_group) - lg.run_grouping() - merged_line_gdf = lg.run_line_merge() - else: - try: - lg = LineGrouping(line_gdf, not merge_group) - lg.run_grouping() - merged_line_gdf = lg.run_line_merge() - splitter = LineSplitter(merged_line_gdf) - splitter.process() - splitter.save_to_geopackage( - out_footprint, - line_layer="split_centerline", - intersection_layer="inter_points", - invalid_layer="invalid_splits", - ) - - # least cost path merge and split - if use_least_cost_path: - lg_leastcost = LineGrouping(lc_path_gdf, not merge_group) - lg_leastcost.run_grouping() - merged_lc_path_gdf = lg_leastcost.run_line_merge() - splitter_leastcost = LineSplitter(merged_lc_path_gdf) - splitter_leastcost.process(splitter.intersection_gdf) - - splitter_leastcost.save_to_geopackage( - out_footprint, - line_layer="split_leastcost", - ) - - lg = LineGrouping(splitter.split_lines_gdf, merge_group) - lg.run_grouping() - merged_line_gdf = lg.run_line_merge() - except ValueError as e: - print(f"Exception: ground_footprint: {e}") - - # save original merged lines - merged_line_gdf = algo_common.clean_geometries( - merged_line_gdf, - stage="output", - out_file=out_file, - layer="rejected_output_ground_merged_lines", - ) - merged_line_gdf.to_file(out_file, layer="merged_lines_original") - - # prepare line arguments - line_args = prepare_line_args(merged_line_gdf, poly_gdf, n_samples, offset, width_percentile) - - out_lines = execute_multiprocessing( - process_single_line, line_args, "Fixed footprint", processes, call_mode - ) - line_attr = pd.concat(out_lines) - - # Ensure BT_GROUP is present in line_attr - if bt_const.BT_GROUP not in line_attr.columns: - raise ValueError("BT_GROUP column is required in line_attr but is missing.") - - # update avg_width and max_width by max value of group - if not merge_group: - group_max = ( - line_attr.groupby(bt_const.BT_GROUP).agg({"avg_width": "max", "max_width": "max"}).reset_index() - ) - - # Merge the result back to the original dataframe based on 'group' - line_attr = line_attr.merge(group_max, on=bt_const.BT_GROUP, suffixes=("", "_max")) - - # Overwrite the original columns directly with the max values - line_attr["avg_width"] = line_attr["avg_width_max"] - line_attr["max_width"] = line_attr["max_width_max"] - - # Drop the temporary max columns - line_attr.drop(columns=["avg_width_max", "max_width_max"], inplace=True) - - # create fixed width footprint (always assign buffer_gdf) - print("Step: Generating fixed width footprints") - buffer_gdf = generate_fixed_width_footprint(line_attr, max_width=max_width) - - # reserve all layers for output - perp_lines_gdf = buffer_gdf.copy(deep=True) - perp_lines_original_gdf = buffer_gdf.copy(deep=True) - - # Save untrimmed fixed width footprint - buffer_gdf = buffer_gdf.drop(columns=["perp_lines"]) - buffer_gdf = buffer_gdf.drop(columns=["perp_lines_original"]) - buffer_gdf = buffer_gdf.set_crs(perp_lines_gdf.crs, allow_override=True) - buffer_gdf.reset_index(inplace=True, drop=True) - - untrimmed_footprint = "untrimmed_footprint" - buffer_gdf = algo_common.clean_geometries( - buffer_gdf, - stage="output", - out_file=out_file, - layer="rejected_output_ground_untrimmed_footprint", - ) - buffer_gdf.to_file(out_file, layer=untrimmed_footprint) - print(f"Untrimmed fixed width footprint saved as '{untrimmed_footprint}'") - - # trim lines and footprints - if trim_output: - lg.run_cleanup(buffer_gdf) - - # Ensure only polygons are saved in clean_footprint - def ensure_polygons(gdf, buffer_width=0.01): - gdf["geometry"] = gdf["geometry"].apply( - lambda geom: geom.buffer(buffer_width) - if geom.geom_type in ["LineString", "MultiLineString"] - else geom - ) - gdf = gdf[gdf.geometry.type.isin(["Polygon", "MultiPolygon"])] - return gdf - - # Patch: after trimming, ensure polygons in clean_footprint layer - if hasattr(lg, "merged_lines_trimmed") and lg.merged_lines_trimmed is not None: - lg.merged_lines_trimmed = ensure_polygons(lg.merged_lines_trimmed) - print("Step: Saving trimmed outputs") - lg.save_file(out_file, out_layer) - else: - print("Skipping line and footprint trimming per user option.") - - # perpendicular lines - layer = "perp_lines" - out_aux_gpkg = algo_common.get_aux_path(out_file) - perp_lines_gdf = perp_lines_gdf.set_geometry("perp_lines") - perp_lines_gdf = perp_lines_gdf.drop(columns=["perp_lines_original"]) - perp_lines_gdf = perp_lines_gdf.drop(columns=["geometry"]) - perp_lines_gdf = perp_lines_gdf.set_crs(buffer_gdf.crs, allow_override=True) - perp_lines_gdf.to_file(out_aux_gpkg, layer=layer) - - layer = "perp_lines_original" - perp_lines_original_gdf = perp_lines_original_gdf.set_geometry("perp_lines_original") - perp_lines_original_gdf = perp_lines_original_gdf.drop(columns=["perp_lines"]) - perp_lines_original_gdf = perp_lines_original_gdf.drop(columns=["geometry"]) - perp_lines_original_gdf = perp_lines_original_gdf.set_crs(buffer_gdf.crs, allow_override=True) - perp_lines_original_gdf.to_file(out_aux_gpkg, layer=layer) - - layer = "centerline_simplified" - # Drop perp_lines_original column if present to avoid export warnings - if "perp_lines_original" in line_attr.columns: - line_attr = line_attr.drop(columns=["perp_lines_original"]) - line_attr = line_attr.drop(columns="perp_lines") - line_attr.to_file(out_aux_gpkg, layer=layer) - - # save footprints without holes - poly_gdf.to_file(out_aux_gpkg, layer="footprint_no_holes") - print("Step: Finished fixed width footprint tool") - - -if __name__ == "__main__": - import time +import sys +import warnings - from beratools.utility.tool_args import compose_tool_kwargs +from beratools.modules.mapping import ground_footprint as _moved - start_time = time.time() - kwargs = compose_tool_kwargs("ground_footprint") - ground_footprint(**kwargs) - print("Elapsed time: {}".format(time.time() - start_time)) +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(". -# -# --------------------------------------------------------------------------- -# -# line_footprint_relative.py -# Script Author: Maverick Fong -# Date: 2023-May -# Use open sources python library for produce dynamic footprint -# from dynamic canopy and cost raster with lines and CHM input. -# Prerequisite: Line feature class must have the attribute Fields: "OLnFID" adn CHM raster -# line_footprint_relative.py -# This script is part of the BERA toolset -# Webpage: https://github.com/ -# -# Purpose: Creates dynamic footprint polygons for each input line based on a least -# cost corridor method and individual line thresholds. -# -# --------------------------------------------------------------------------- - -from beratools.core.line_footprint_functions import * -from beratools.core.canopy_threshold_relative import * -from beratools.utility.spatial_common import decode_file_layer -import time -from pathlib import Path - - -def line_footprint_relative( - in_line, - in_chm, - max_ln_width, - exp_shk_cell, - out_footprint, - out_centerline, - off_ln_dist, - canopy_percentile, - canopy_thresh_percentage, - tree_radius, - max_line_dist, - canopy_avoidance, - exponent, - processes, - call_mode, - log_level, - merge_by_original_line=False, -): - """Create canopy footprint polygons using per-line relative canopy thresholds. - - Runs in two steps. First, `main_canopy_threshold_relative` samples the CHM on - both sides of each input line and derives an individual canopy threshold - height from the surrounding forest. Second, `main_line_footprint_relative` - builds a canopy and cost raster per line and traces a least cost corridor - to produce the footprint polygons and, optionally, centerlines. Results are - written to `out_footprint` and `out_centerline`; if the threshold step - fails, an error is printed and nothing is written. - - Numeric arguments may be passed as strings (as they are from the GUI) and - are converted before use. - - Args: - in_line: Input line file. - in_chm: CHM raster used to calculate the surrounding forest percentile - and to build the canopy and cost rasters. - max_ln_width: Maximum processing width for input lines. A large value - increases processing time; a small value may clip the footprint. - exp_shk_cell: Cell range used to expand and shrink the corridor before - polygons are generated, to remove small artifacts. Use 0 when the - cell size is 1 m or larger. - out_footprint: Output footprint polygon file. - out_centerline: Optional output centerline file. - off_ln_dist: Offset distance from input lines. Currently not used. - canopy_percentile: Nth percentile of the surrounding forest height. - canopy_thresh_percentage: Percentage of the canopy percentile height - used as the canopy threshold. - tree_radius: Radius of canopy influence in the cost raster. Smooths the - canopy so gaps in sparse vegetation are not taken as footprint. - max_line_dist: Maximum euclidean distance from canopy, a second - smoothing factor that centers the line in the footprint. - canopy_avoidance: Weight between tree search radius (near 0) and - euclidean distance (near 1) in the cost raster. - exponent: Exponent applied to the cost of vegetated areas. - processes: Number of parallel processes. - call_mode: How the tool was invoked (see `CallMode`). - log_level: Logging level. Currently not used. - merge_by_original_line: Merge footprints and centerlines sharing an original - line ID (OLnFID) into one feature; otherwise keep one per input line. - """ - verbose = True if call_mode == CallMode.GUI.value else False - - # Write the intermediate dynamic centerline as a layer in the output footprint's file, - # so no extra file is created and input data folders are never written to. - in_file, in_layer = decode_file_layer(in_line) - out_ft_file = decode_file_layer(out_footprint)[0] - dyn_layer = "DynCanTh_" + (in_layer or Path(in_file).stem) - if Path(out_ft_file).suffix.lower() != ".gpkg": - # a shapefile holds one layer, so use a GeoPackage beside it - out_ft_file = Path(out_ft_file).with_name(dyn_layer + ".gpkg").as_posix() - out_dyn_centerline = f"{out_ft_file}|{dyn_layer}" - - dy_cl_line = main_canopy_threshold_relative( - in_line=in_line, - in_chm=in_chm, - canopy_percentile=int(float(canopy_percentile)), - canopy_thresh_percentage=int(float(canopy_thresh_percentage)), - full_step=bool(True), - processes=int(float(processes)), - out_dyn_centerline=out_dyn_centerline, - ) - - if not dy_cl_line: - print("[error]: main_canopy_threshold_relative did not return a valid path. Aborting footprint step.") - return - - main_line_footprint_relative( - in_line=dy_cl_line, - in_chm=in_chm, - max_ln_width=float(max_ln_width), - out_footprint=out_footprint or "", - out_centerline=out_centerline or "", - exp_shk_cell=int(float(exp_shk_cell)), - tree_radius=float(tree_radius), - max_line_dist=float(max_line_dist), - canopy_avoidance=float(canopy_avoidance), - exponent=float(exponent), - full_step=bool(True), - canopy_thresh_percentage=int(float(canopy_thresh_percentage)), - processes=int(float(processes)), - merge_by_original_line=str(merge_by_original_line).strip().lower() in ("true", "1", "yes"), - ) - -if __name__ == "__main__": - from beratools.utility.tool_args import CallMode, compose_tool_kwargs - start_time = time.time() - print("[info]: Dynamic CC and Footprint processing started") - print("[info]: Current time: {}".format(time.strftime("%d %b %Y %H:%M:%S", time.localtime()))) - - args=compose_tool_kwargs("line_footprint_relative") - - line_footprint_relative(**args) - - print("{}%".format(100)) - print("[info]: Dynamic CC and Footprint processes finished") - print("[info]: Current time: {}".format(time.strftime("%d %b %Y %H:%M:%S", time.localtime()))) - print("[info]: Total processing time (seconds): {}".format(round(time.time() - start_time, 3))) +""" +Deprecated: moved to beratools.modules.mapping. + +Kept so old imports keep working, with a DeprecationWarning, until it is removed. +""" + +import sys +import warnings + +from beratools.modules.mapping import line_footprint_relative as _moved + +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" for full license details. - -Author: Richard Zeng - -Description: - This script is part of the BERA Tools. - Webpage: https://github.com/BERATool/beratools - - The purpose of this script is the public interface for vertex optimization. +Kept so old imports keep working, with a DeprecationWarning, until it is removed. """ -import logging - -import beratools.core.algo_vertex_optimization as bt_vo -import beratools.utility.spatial_common as sp_common -from beratools.utility.tool_args import CallMode - -LOGGER_NAME="vertex_optimization" -logger = logging.getLogger(LOGGER_NAME) - -def vertex_optimization( - in_line, - in_raster, - search_distance, - line_radius, - out_line, - optimize_internal_vertices=False, - processes=0, - call_mode=CallMode.CLI, - log_level="INFO", -): - if isinstance(optimize_internal_vertices, str): - optimize_internal_vertices = optimize_internal_vertices.lower() in ["true", "1", "yes"] - - in_file, in_layer = sp_common.decode_file_layer(in_line) - if not sp_common.compare_crs(sp_common.vector_crs(in_file,in_layer), sp_common.raster_crs(in_raster)): - return - - vg = bt_vo.VertexGrouping( - in_file, - in_raster, - search_distance, - line_radius, - processes, - call_mode, - layer=in_layer, - optimize_internal_vertices=optimize_internal_vertices, - ) - vg.create_all_vertex_groups() - vg.compute() - vg.update_all_lines() - vg.save_all_layers(out_line) - - -if __name__ == "__main__": - import time +import sys +import warnings - from beratools.utility.tool_args import compose_tool_kwargs +from beratools.modules.mapping import vertex_optimization as _moved - start_time = time.time() - kwargs = compose_tool_kwargs("vertex_optimization") - vertex_optimization(**kwargs) - print("Elapsed time: {}".format(time.time() - start_time)) +# skip_file_prefixes points the warning at the importing line, past the import machinery, so a +# script that imports this old path sees it +warnings.warn( + f"{__name__} is deprecated and will be removed in a future release; import {_moved.__name__} instead", + DeprecationWarning, + stacklevel=2, + skip_file_prefixes=(" None: def configure_gdal_proj_environment(): """Set GDAL_DATA and PROJ_LIB for Conda environments.""" - prefix = Path(sys.prefix) if sys.platform.startswith("win"): @@ -71,4 +70,26 @@ def configure_gdal_proj_environment(): os.environ["PROJ_LIB"] = str(proj_data) print(f"GDAL_DATA = {os.environ.get('GDAL_DATA')}") - print(f"PROJ_LIB = {os.environ.get('PROJ_LIB')}") \ No newline at end of file + print(f"PROJ_LIB = {os.environ.get('PROJ_LIB')}") + + +def put_conda_dlls_on_path() -> None: + """ + Put the conda environment's DLL folders at the front of PATH on Windows. + + Activating the environment sets them; started without it (e.g. from an IDE), numpy's MKL can + load an older VC++ runtime from another conda install on PATH and Python stops with + 0xC06D007F. The folders are moved to the front even when PATH has them, as an IDE may list + them after another conda install. Call this before numpy is imported. Processes started later + inherit the PATH. + """ + if os.name != "nt": + return + prefix = Path(sys.prefix) + folders = [str((prefix / d).resolve()) for d in (".", "Library/mingw-w64/bin", "Library/usr/bin", + "Library/bin", "Scripts")] + folders = [f for f in folders if os.path.isdir(f)] + wanted = {f.lower() for f in folders} + rest = [p for p in os.environ.get("PATH", "").split(os.pathsep) + if p and p.rstrip("\\").lower() not in wanted] + os.environ["PATH"] = os.pathsep.join(folders + rest) diff --git a/beratools/utility/faulthandler_pause.py b/beratools/utility/faulthandler_pause.py new file mode 100644 index 0000000..8d754e5 --- /dev/null +++ b/beratools/utility/faulthandler_pause.py @@ -0,0 +1,34 @@ +""" +Copyright (C) 2025 Applied Geospatial Research Group. + +This script is licensed under the GNU General Public License v3.0. +See for full license details. + +Description: + faulthandler_paused(): faulthandler off for a block of code, and back on after if it was on. + + On Windows, faulthandler (on under pytest, or with python -X faulthandler) sees every access + violation before the program's own handlers do, also one the program raises on purpose and + catches itself, and prints "Windows fatal exception: access violation" with a traceback, though + nothing failed. Three imports do that: rpy2.robjects, which starts R, scipy.fft (scipy's + compiled FFT, imported by xrspatial through dask), and scipy.stats (through scipy.optimize, in + the PAR analysis). They run with faulthandler paused, so the message isn't printed for them, + while it still reports a real crash anywhere else. +""" + +import faulthandler +from contextlib import contextmanager + + +@contextmanager +def faulthandler_paused(): + on = faulthandler.is_enabled() + faulthandler.disable() + try: + yield + finally: + if on: + try: + faulthandler.enable(all_threads=True) + except (AttributeError, OSError, RuntimeError, ValueError): # stderr without a file + pass diff --git a/beratools/utility/field_checks.py b/beratools/utility/field_checks.py new file mode 100644 index 0000000..80fa890 --- /dev/null +++ b/beratools/utility/field_checks.py @@ -0,0 +1,45 @@ +""" +Checks of attribute fields that the GUI runs before a tool starts. + +A tool parameter names one with "field_check" in its tools.json, e.g. "field_check": "year". They +live in the frame so that the GUI never imports a module's code. +""" + +import numpy as np +import pandas as pd + +MIN_YEAR = 1900 + + +def to_years(values): + """Values as float years: numbers, numeric text or dates; NaN where not a year in [1900, now].""" + series = pd.Series(values) + if pd.api.types.is_datetime64_any_dtype(series): + years = series.dt.year.astype(float) + else: + years = pd.to_numeric(series, errors="coerce").astype(float) + whole = np.isclose(years, np.round(years)) + years = years.where(whole) + return years + + +def check_year_values(values, current_year): + """ + Check a field of years. + + Returns (error, warning): error when no value is a year between 1900 and `current_year`, + warning when some values are empty or out of that range; each is '' when there is none. They + complete "Field 'X' ." and "Field 'X': ." in the GUI. + """ + years = to_years(values) + total = len(years) + valid = years.between(MIN_YEAR, current_year) + count = int(valid.sum()) + if total == 0: + return "is empty", "" + if count == 0: + return f"has no years between {MIN_YEAR} and {current_year}", "" + if count < total: + bad = total - count + return "", f"{bad} of {total} values are empty or not years between {MIN_YEAR} and {current_year}" + return "", "" diff --git a/beratools/utility/spatial_common.py b/beratools/utility/spatial_common.py index 0b6008e..c614ccc 100644 --- a/beratools/utility/spatial_common.py +++ b/beratools/utility/spatial_common.py @@ -13,12 +13,18 @@ This file is intended to be hosting common spatial classes/functions for BERA Tools """ +import json +import math +import tempfile import warnings +from pathlib import Path import geopandas as gpd import numpy as np import pyproj import rasterio +import shapely.geometry as sh_geom +import shapely.ops as sh_ops from osgeo import gdal, ogr, osr, version_info from pyogrio import set_gdal_config_options from rasterio import mask @@ -38,6 +44,8 @@ gdal.SetConfigOption("CPL_LOG", "NUL") # GDAL warning warnings.filterwarnings("ignore") # suppress warnings warnings.simplefilter(action="ignore", category=UserWarning) # suppress Pandas UserWarning + # but still show that an old beratools import path is deprecated (see beratools/core, beratools/tools) + warnings.filterwarnings("default", message=r"beratools\.\S+ is deprecated", category=DeprecationWarning) def clip_raster( @@ -119,7 +127,7 @@ def vector_crs(in_vector, gpd_layer): vec_crs = None # open input vector data as GeoDataFrame - if gpd_layer != None: + if gpd_layer is not None: gpd_vector = gpd.GeoDataFrame.from_file(in_vector, layer=gpd_layer) else: gpd_vector = gpd.GeoDataFrame.from_file(in_vector) @@ -305,7 +313,8 @@ def get_raster_extent(in_raster): def check_vector_raster_extent_overlap(in_vector, in_layer, in_raster) -> bool: - """Fast extent precheck for vector/raster overlap. + """ + Fast extent precheck for vector/raster overlap. Returns False only for definite disjoint extents. Returns True when overlap exists or extents cannot be determined. @@ -320,7 +329,8 @@ def check_vector_raster_extent_overlap(in_vector, in_layer, in_raster) -> bool: def check_vector_vector_extent_overlap(in_vector1, in_layer1, in_vector2, in_layer2) -> bool: - """Fast extent precheck for vector/vector overlap. + """ + Fast extent precheck for vector/vector overlap. Returns False only for definite disjoint extents. Returns True when overlap exists or extents cannot be determined. @@ -336,8 +346,6 @@ def check_vector_vector_extent_overlap(in_vector1, in_layer1, in_vector2, in_lay def check_vector_raster_overlap(gdf, in_raster) -> bool: """Check whether vector geometries overlap a raster footprint.""" - from beratools.core.algo_common import generate_raster_footprint - if gdf is None or gdf.empty: return False @@ -384,3 +392,65 @@ def seedlines_within_chm_footprint(gdf, in_raster) -> bool: return True return check_vector_raster_overlap(gdf, in_raster) + + +# focalMat-style rounding of radius / cell size down lost a ring of the window when the cell size +# is stored rounded (a 3 m window on 0.25 m cells of a DTM in feet came to 5.9999998 cells), so a +# millionth is added to the radius: the window reaches radius * RADIUS_SLACK. The same factor as +# SMOOTH_RADIUS_SLACK in r_scripts_collection.r. +RADIUS_SLACK = 1 + 1e-6 + + +def window_reach(radius): + """How far the window reaches from a cell's centre, in the units of radius.""" + return radius * RADIUS_SLACK + + +def circle_kernel(radius, res_x, res_y): + """ + Circular window: the cells whose centres lie within radius (map units) of the centre cell. + + A boolean array of 2 * floor(reach / res_y) + 1 rows by 2 * floor(reach / res_x) + 1 columns. + It is a true circle on cells that aren't square (terra's focalMat "circle" isn't: it measures + rows in steps of the cell width too). + """ + reach = window_reach(radius) + nx, ny = int(math.floor(reach / res_x)), int(math.floor(reach / res_y)) + dy, dx = np.mgrid[-ny : ny + 1, -nx : nx + 1] + return np.hypot(dx * res_x, dy * res_y) <= reach + + +def generate_raster_footprint(in_raster, latlon=True): + inter_img = "image_overview.tif" + + src_ds = gdal.Open(in_raster) + width, height = src_ds.RasterXSize, src_ds.RasterYSize + src_crs = src_ds.GetSpatialRef().ExportToWkt() + + geom = None + with tempfile.TemporaryDirectory() as tmp_folder: + if bt_const.BT_DEBUGGING: + print("Temporary folder: {}".format(tmp_folder)) + + if max(width, height) <= 1024: + inter_img = in_raster + else: + if width >= height: + options = gdal.TranslateOptions(width=1024, height=0) + else: + options = gdal.TranslateOptions(width=0, height=1024) + + inter_img = Path(tmp_folder).joinpath(inter_img).as_posix() + gdal.Translate(inter_img, src_ds, options=options) + + shapes = gdal.Footprint("", inter_img, dstSRS=src_crs, format="MEM") + target_feat = shapes.GetLayer(0).GetNextFeature() + geom = sh_geom.shape(json.loads(target_feat.GetGeometryRef().ExportToJson())) + + if geom is not None and latlon: + out_crs = pyproj.CRS("EPSG:4326") + transformer = pyproj.Transformer.from_crs(pyproj.CRS(src_crs), out_crs) + + geom = sh_ops.transform(transformer.transform, geom) + + return geom \ No newline at end of file diff --git a/beratools/utility/tool_args.py b/beratools/utility/tool_args.py index e94a70a..a50dfbc 100644 --- a/beratools/utility/tool_args.py +++ b/beratools/utility/tool_args.py @@ -7,6 +7,37 @@ import sys from enum import Enum +_TRUE_WORDS = frozenset({"true", "1", "yes", "y", "on"}) +_FALSE_WORDS = frozenset({"false", "0", "no", "n", "off"}) + + +def to_bool(value, strict=False): + """ + Convert a tool argument (bool, string or other) to a bool. + + Strings are matched case-insensitively against true/false words + ("true/1/yes/y/on", "false/0/no/n/off"). Non-strings fall back to + ``bool(value)``. + + Args: + value: Value to convert. + strict: If True, raise ``ValueError`` for anything that is not a bool + or a recognised true/false word. If False, unrecognised strings + are treated as False. + + """ + if isinstance(value, bool): + return value + if isinstance(value, str): + lowered = value.strip().lower() + if lowered in _TRUE_WORDS: + return True + if lowered in _FALSE_WORDS or not strict: + return False + elif not strict: + return bool(value) + raise ValueError(f"Invalid boolean value: {value!r}") + # TODO: Consider using StrEnum from Python 3.11+ class StrEnum(str, Enum): @@ -30,7 +61,7 @@ def compose_tool_kwargs(tool_api): - Detects mode from --input presence - GUI: unpacks --input JSON, adds common args from CLI flags - - CLI: parses all args from beratools.json definitions with validation + - CLI: parses all args from the tool's tools.json definitions with validation - Returns: complete kwargs dict with all parameters Note: In CLI mode, argparse automatically prints help and exits @@ -41,7 +72,7 @@ def compose_tool_kwargs(tool_api): bt_data = BTData() tool_name = bt_data.get_bera_tool_name(tool_api) if tool_name is None: - raise ValueError(f"Tool API '{tool_api}' not found in beratools.json") + raise ValueError(f"Tool API '{tool_api}' not found in any module's tools.json") tool_api_name = tool_api mode_parser = argparse.ArgumentParser(add_help=False) @@ -66,7 +97,7 @@ def compose_tool_kwargs(tool_api): else: # CLI MODE: parse tool params from CLI args with validation - # Load parameter definitions from beratools.json + # Load parameter definitions from tools.json tool_params = bt_data.get_bera_tool_params(tool_name) # Helper: Separate parameters by type @@ -79,7 +110,9 @@ def compose_tool_kwargs(tool_api): # Build usage string with only required parameters required_flags = " ".join([f"--{p.get('variable')}" for p in required_params]) - custom_usage = f"python {tool_api_name}.py {required_flags}" if required_flags else f"python {tool_api_name}.py" + custom_usage = ( + f"python {tool_api_name}.py {required_flags}" if required_flags else f"python {tool_api_name}.py" + ) full_parser = argparse.ArgumentParser( prog=tool_name, diff --git a/docs/base.yml b/docs/base.yml new file mode 100644 index 0000000..2273751 --- /dev/null +++ b/docs/base.yml @@ -0,0 +1,104 @@ +# Settings shared by every BERA Tools docs site: the frame site (docs/mkdocs.yml) and one site +# per module (beratools/modules//docs/mkdocs.yml). Each site INHERITs this file and adds +# its own site_name, site_url, nav and edit_uri. Build with `zensical`, not `mkdocs`. +# +# The logo, favicon and extra CSS come from the frame site, so module sites need no copies of them; +# the frame site points them at its own files instead. + +theme: + name: material + palette: + - media: "(prefers-color-scheme)" + primary: blue + accent: blue + toggle: + icon: material/brightness-auto + name: "Switch to light mode" + - media: "(prefers-color-scheme: light)" + scheme: default + primary: blue + accent: blue + toggle: + icon: material/brightness-7 + name: "Switch to dark mode" + - media: "(prefers-color-scheme: dark)" + scheme: slate + primary: blue + accent: blue + toggle: + icon: material/brightness-4 + name: "Switch to system preference" + + features: + - navigation.tabs # top-level tabs in the header + - navigation.top # keep nav in header + - content.code.copy # optional niceties + - content.action.edit + font: + text: Inter + code: JetBrains Mono + favicon: https://beratool.github.io/beratools/icons/bera_logo.png + logo: https://beratool.github.io/beratools/icons/bera_logo.svg + +repo_url: https://github.com/BERATool/beratools +repo_name: BERA Tools + +markdown_extensions: + - admonition + - attr_list + - def_list + - pymdownx.tasklist: + custom_checkbox: true + - pymdownx.tabbed: + alternate_style: true + - pymdownx.superfences: + custom_fences: + - name: mermaid + class: mermaid + format: !!python/name:pymdownx.superfences.fence_code_format + - pymdownx.emoji: + emoji_index: !!python/name:material.extensions.emoji.twemoji + emoji_generator: !!python/name:material.extensions.emoji.to_svg + +extra_css: + - https://beratool.github.io/beratools/css/extra.css + +docs_dir: files +watch: + - files + +plugins: + - search + - mkdocstrings: + handlers: + python: + # beratools is installed (editable) in the docs environment, so no `paths` are needed + options: + # --- Docstring parsing --- + docstring_style: google + docstring_options: + ignore_init_summary: true # don't duplicate __init__ summaries + + # --- Visibility and member organization --- + filters: ["!^_"] # exclude private members + members_order: source # preserve code order + inherited_members: false # avoid clutter unless needed + + # --- Signature and linking --- + separate_signature: true + show_signature_annotations: true + signature_crossrefs: true + merge_init_into_class: true + + # --- Page rendering --- + show_source: false + show_root_toc_entry: true + + inventories: + - url: https://docs.python.org/3/objects.inv + domains: [py, std] + - url: https://typing-extensions.readthedocs.io/en/latest/objects.inv + - url: https://geopandas.org/en/stable/objects.inv + - url: https://shapely.readthedocs.io/en/stable/objects.inv + - url: https://numpy.org/doc/stable/objects.inv + - url: https://pandas.pydata.org/pandas-docs/stable/objects.inv diff --git a/docs/files/api.md b/docs/files/api.md index e603e34..beb08ef 100644 --- a/docs/files/api.md +++ b/docs/files/api.md @@ -1,76 +1,7 @@ # Python API Reference -This page documents the main Python modules in BERA Tools using mkdocstrings. - -## Tools API - -::: beratools.tools.check_seed_line -::: beratools.tools.vertex_optimization -::: beratools.tools.centerline -::: beratools.tools.canopy_footprint_absolute -::: beratools.tools.line_footprint_relative - options: - members: - - line_footprint_relative -::: beratools.tools.ground_footprint - -## Core Algorithms - -::: beratools.core.algo_centerline - options: - members: - - CenterlineParams - - CenterlineStatus - - EndPointAnchorResult - - centerline_is_valid - - snap_end_to_end - - find_centerline - - find_corridor_polygon - - process_single_centerline - - find_centerlines - - regenerate_centerline - - SeedLine - - orient_to_split -::: beratools.core.line_footprint_functions - options: - members: - - dyn_canopy_cost_raster - - split_line_fc - - split_line_npart - - split_into_segments - - split_into_equal_nth_segments - - generate_line_args - - find_corridor_threshold - - process_single_line_relative - - multiprocessing_footprint_relative - - main_line_footprint_relative -::: beratools.core.canopy_threshold_relative - options: - members: - - OperationCancelledException - - main_canopy_threshold_relative - - rate_of_change - - multiprocessing_RofC - - split_line_fc - - split_into_segments - - multiprocessing_percentile - - cal_percentile_ring - - copyparallel_lineLRC - -## Common Tool Utilities - -::: beratools.tools.common - options: - members: - - remove_nan_from_array - - split_into_equal_Nth_segments - - cut_line_by_length - - chk_df_multipart - - dyn_fs_raster_stdmean - - dyn_smooth_cost - - dyn_np_cost_raster - - dyn_np_cc_map - - generate_line_args_DFP_NoClip +This page documents the frame's Python API. Each module's API is on its own site +(see [Modules](user_guide.md#modules)). ## Pipeline diff --git a/docs/files/developer/add_new_tool.md b/docs/files/developer/add_new_tool.md index 3984994..867481b 100644 --- a/docs/files/developer/add_new_tool.md +++ b/docs/files/developer/add_new_tool.md @@ -7,7 +7,8 @@ For runtime internals (CLI/GUI call modes, argument composition, multiprocessing ## 1) Create the tool script -Add a new script in `beratools/tools` (you can start from `tool_template.py`). +Add a new script in its module's folder, `beratools/modules//` (you can start from +`beratools/core/tool_template.py`). Typical API pattern: @@ -27,15 +28,56 @@ if __name__ == "__main__": ## 2) Register in GUI metadata -Update `beratools/gui/assets/beratools.json` and add your tool definition in the proper category. +Add your tool definition to the `tools` list of its module's file, +`beratools/modules//tools.json` (`mapping`, `pc2products`, `raster2products`, ...). At minimum, define: -- `name`, `info`, `tool_type`, `tool_api`, `icon`, `tech_link` +- `name`, `info`, `tool_api`, `cli_name`, `entry`, `tech_link`, and optionally `tool_type` and `icon` - parameter list (`variable`, `label`, `description`, `type`, `subtype`, `default`, `output`, `optional`) `tool_api` must match the module name and the string passed to `compose_tool_kwargs`, or the tool -stops with `Tool API '' not found in beratools.json`. +stops with `Tool API '' not found in any module's tools.json`. `cli_name` is the `bt` +subcommand and `entry` is the function to run, as `package.module:function`, for example +`beratools.modules.mapping.my_tool:my_tool`. + +Each file is checked against `beratools/gui/assets/module.schema.json` when the frame starts. A +file with an unknown or misspelled key, a missing field, a name, `tool_api` or `cli_name` that +another module already uses, or a `depends_on` or `field_of` that names no variable of the tool is +skipped with a warning that names the problem, and its tools don't appear. `tests/test_registry.py` +fails on the same problems. Add the tool's `cli_name` to `CLI_NAMES` in its module's +`tests/test__tools_json.py`. + +### Work in progress + +A tool that isn't ready to release gets `"status": "wip"` in its `tools.json` entry (or at the top +of the file, for a whole module). It is then left out of the GUI, the `bt` CLI and pipelines unless +the environment variable `BERATOOLS_WIP` is `1`, and with it set the GUI shows it in italics. To +keep its code out of the packages too, add its files to both exclude lists in `pyproject.toml` and +to `$wipPaths` in `packaging/build.ps1`, and keep its doc page out of the module's `docs/files`; +`tests/test_wip.py` checks these. To release it, delete its `"status": "wip"` and undo those steps. + +### Field parameters + +A `text` parameter that names a field of a vector input can show that layer's fields in a +drop-down. Add `field_of` with the `variable` of the vector input; add `"field_check": "year"` to +also check that the field holds years: + +```json +{ + "variable": "year_field", + "field_of": "in_line", + "field_check": "year", + "type": "text", + "subtype": "string", + ... +} +``` + +The list refreshes when the input file or layer changes, and a name can still be typed. A field that +isn't in the layer, or a year field with no years between 1900 and the current year, blocks **Run**; +a year field with some empty or invalid values shows a warning. The command line still takes the +field as text. ### Taking part in pipelines @@ -44,28 +86,31 @@ earlier step's output, tag the parameters with a *kind*: - an input parameter gets `"accepts": ""`; - an output parameter gets `"produces": {"": [patterns]}`. An empty list means the output value - itself (an output file such as `lines.gpkg|centerline`); otherwise the + itself (an output file such as `lines.gpkg|centerline`, or a folder of point clouds); otherwise the pipeline uses the first glob pattern that matches files in the output folder, newest file first. ```json -{"variable": "in_line", "accepts": "line", ...} +{"variable": "in_chm", "accepts": "chm", ...} {"variable": "out_line", "produces": {"line": []}, ...} {"variable": "out_folder", "produces": {"dtm": ["Merged_*_DTM.tif", "*_DTM.tif"]}, ...} ``` -The kinds in use are `line` and `footprint`; add a new one when a tool writes something new. `tests/test_pipeline.py` checks that every +The kinds in use are `line`, `footprint`, `chm`, `las`, `dtm`, `dsm`, `microform`, `water` and +`dtw`; add a new one when a tool writes something new. `tests/test_cross_module.py` checks that every accepted kind has a producer. For the pipeline to stop when your tool fails, exit with a non-zero code (`sys.exit(1)` or an uncaught exception), not a plain `exit()`. ### Adding the CLI subcommand -In `beratools/cli/entry.py`, add a short alias to `TOOL_ALIASES` (for example -`"my_tool": "my_tool"`) and teach `_resolve_tool_function` to import and return the tool function. +The `cli_name` and `entry` fields of the tool's `tools.json` entry make the subcommand: `bt +` imports the `entry` function and calls it. No code change is needed in +`beratools/cli/entry.py`. -## 3) Keep tools thin; move heavy logic to core +## 3) Keep tools thin; move heavy logic to an algorithm file -- Put high-level tool wiring in `beratools/tools/*` -- Put algorithm-heavy logic in `beratools/core/*` +- Put high-level tool wiring in `beratools/modules//my_tool.py` +- Put algorithm-heavy logic in `beratools/modules//algo_my_tool.py` +- Import only frame code (`beratools/core`, `beratools/utility`) and your own module, not another module This keeps code easier to test and maintain. @@ -74,18 +119,106 @@ This keeps code easier to test and maintain. Run help and a sample execution before validating in GUI: ```bash -python beratools/tools/my_tool.py --help +python beratools/modules//my_tool.py --help ``` Then test via GUI once CLI behavior is stable. ## 5) Add docs and tests -- Add/update user docs if end-user behavior changed -- Add/update technical docs for algorithm/runtime internals -- Add tests in `tests/` for new behavior and edge cases +- Add the tool's page to its module's docs site: `beratools/modules//docs/files/user/.md`, + listed in the `nav` of `beratools/modules//docs/mkdocs.yml`, with a row in the tool table of + the site's `index.md` and the tool's module in its `api.md` +- Set the tool's `tech_link` in `tools.json` to that page's path, e.g. `user/my_tool/` +- Add technical pages for algorithm/runtime internals under the module's `docs/files/technical/` +- Add tests for new behavior and edge cases to the module's tests folder, + `beratools/modules//tests/`, and any sample data they need to its `tests/data/` ## 6) Submit PR - Follow branching and contribution guidance in [Development](development.md) - Request review and ensure CI passes + +## Adding a PC2Products (R) tool + +A PC2Products tool is a thin Python wrapper that validates its inputs and calls an R function through +rpy2. The steps above still apply; these are the differences. + +### Write the R function + +Add the processing function to `beratools/modules/pc2products/r_scripts_collection.r`. Follow the existing +functions: read the input folder as a lidR `LAScatalog`, drop noise with `filter = "-drop_class 7"`, +take the most workers from Python as `r_common.r_max_workers(processes)`, and call +`mosaic_catalog_outputs` to merge tiled raster outputs. Take `free_mem` and `tiling` arguments +(pass `r_common.free_memory()` and `r_common.check_tiling(tiling)` from Python) and call +`apply_tiling(ctg, tiling, max_workers, free_mem, paste0(out_folder, "/{*}_suffix"), bytes_per_point = ...)` +instead of starting workers yourself. It sets the catalog's tiles and output template, starts as +many workers as fit in the free memory, gives them the other allowed processes as lidR threads +(`start_workers`), and has each output written whole (`write_outputs_whole`); reset the plan with +`on.exit(reset_plan(), add = TRUE)`. `bytes_per_point` is the memory your algorithm needs per +point: measure the peak committed memory of one tile at two sizes and see the figures after +`BYTES_PER_POINT` in the script for how the others were measured. A function that starts workers +without `apply_tiling` should start them with `start_workers(workers, max_workers)`. +Also take a `skip_existing` argument and pass it to `apply_tiling`, then call +`select_tiles(ctg, skip_existing, function(save) paste0(save, ".tif"))`, giving the files each +tile writes (pass `res = cell_size` for a raster output), and run the catalog with +`catalog_run(ctg, function(ctg) rasterize_terrain(ctg, ...))`. Tiles can differ in size with the +data's density, and the files or tiles too large for the run's workers are processed with fewer, +so `catalog_run` makes one lidR run (a round) per size and worker count, starting each round's +workers, and it stops with the error of a tile that fails; with `skip_existing`, a rerun skips the +tiles whose outputs are complete. + +```r +my_function <- function(in_las_folder, out_folder, max_workers, free_mem, tiling = "auto", + skip_existing = FALSE) { + ... +} +``` + +### Create the Python wrapper + +Add `beratools/modules/pc2products/rpy_my_tool.py`. `configure_r_environment()` must run **before** `r_common` is +imported, because it sets up `R_HOME` and the DLL search path that rpy2 needs. +`rpy_find_cellsize.py` is the smallest complete example. + +```python +import os + +from beratools.utility.tool_args import compose_tool_kwargs +from beratools.modules.pc2products.r_interface import configure_r_environment +configure_r_environment() +import beratools.modules.pc2products.r_common as r_common + + +def rpy_my_tool(in_las_folder, out_folder, processes=0, tiling="auto", skip_existing=False, **kwargs): + r_common.check_las_files_existence(in_las_folder) + r_common.check_las_out_folder_existence(out_folder) + r_common.check_r_packages_installation(["lidR", "rlas", "future", "terra"]) + + r_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "r_scripts_collection.r") + r_common.r["source"](r_script) + r_common.robjects.globalenv["my_function"]( + in_las_folder, out_folder, r_common.r_max_workers(processes), r_common.free_memory(), + r_common.check_tiling(tiling), bool(skip_existing)) + + +if __name__ == "__main__": + kwargs = compose_tool_kwargs("rpy_my_tool") + rpy_my_tool(**kwargs) +``` + +`check_r_packages_installation` installs any missing R packages from CRAN the first time the tool +runs, so list every package the R function uses. + +### Register, document and test it + +- Add the tool to `beratools/modules/pc2products/tools.json`. +- Add a page under `beratools/modules/pc2products/docs/files/user/`, add it to the User Guide + section of `nav` in `beratools/modules/pc2products/docs/mkdocs.yml`, add the module to that + site's `api.md`, and add a row to the tool tables in its `index.md` and + `technical/pc2products_overview.md`. Set `tech_link` to the page's path, e.g. `user/my_tool/`. +- `tests/test_cli_entry.py` checks every tool's `bt` subcommand against the registry by itself. If the + tool's values need converting or checking, add a case to + `beratools/modules/pc2products/tests/test_cli_pc2products.py`, and add a case to + `beratools/modules/pc2products/tests/test_r_tools.py` that runs on the sample tiles in its + `data/LiDAR/` folder. diff --git a/docs/files/developer/contributing.md b/docs/files/developer/contributing.md index d051533..ebb8188 100644 --- a/docs/files/developer/contributing.md +++ b/docs/files/developer/contributing.md @@ -39,6 +39,7 @@ We appreciate your help in making BERA Tools better! If you encounter a issue or 2. When submitting a new issue, include as much detail as possible: - BERA Tools version + - R version (`R --version`), for issues with the PC2Products (LiDAR) tools - Operating system - Python version - Any error messages from the console diff --git a/docs/files/developer/dev_standards.md b/docs/files/developer/dev_standards.md index e2b1317..fd1127a 100644 --- a/docs/files/developer/dev_standards.md +++ b/docs/files/developer/dev_standards.md @@ -37,3 +37,17 @@ Mypy can be run with: ``` bash mypy . ``` + +## R Code + +The processing for every PC2Products tool lives in `beratools/modules/pc2products/r_scripts_collection.r`. + +- Keep one R function per algorithm variant (for example `dtm_by_tin`, `dtm_by_knnidw`, + `dtm_by_kriging`), and call it from the tool's Python wrapper. +- Take the most workers as an argument from Python (`r_common.r_max_workers`) rather than + detecting cores in R, and start the workers with `apply_tiling` (or `start_workers`), which + sizes them for the free memory and shares the other cores out as lidR threads. +- Use the shared helpers (`detect_normalized`, `detect_ground_classified`, `mosaic_catalog_outputs`) + instead of copying their logic. +- List every R package a function needs in the wrapper's `check_r_packages_installation` call, and + add new packages to the R package table on the installation page. diff --git a/docs/files/developer/development.md b/docs/files/developer/development.md index 912d94c..233548c 100644 --- a/docs/files/developer/development.md +++ b/docs/files/developer/development.md @@ -40,7 +40,7 @@ A manual conda environment setup for local development (without using environmen 1. Install dependencies individually: ```bash - conda install -c conda-forge dask "gdal>=3.12,<4" geopandas networkit "pyogrio>=0.12.0" pyqt "rasterio>=1.5.0" "scikit-image>=0.24.0" tqdm xarray-spatial + conda install -c conda-forge dask "gdal>=3.12,<4" geopandas networkit "pyogrio>=0.12.0" pyqt "rasterio>=1.5.0" "scikit-image>=0.24.0" tqdm xarray-spatial numba ``` This approach avoids installing the released beratools package and uses only the dependencies listed in [`environment.yml`](https://github.com/BERATool/beratools/blob/main/environment.yml). @@ -58,6 +58,20 @@ Activate your conda or pixi environment, then run: The editable mode (`-e`) allows you to make changes to the source code and have them reflected immediately without needing to reinstall the package. +### R for the PC2Products tools + +`environment.yml` and `pixi.toml` include R 4.5.x and rpy2 for the PC2Products (LiDAR) tools; the +R packages are installed from CRAN by the tools the first time they run. To install every R package +up front and check that they load, run: + +```bash +python -m pytest beratools/modules/pc2products/tests/test_r_environment.py -v +``` + +On Linux, CRAN packages such as `sf` and `terra` are compiled from source, which needs the GDAL, GEOS, +PROJ and udunits development libraries (for example `libgdal-dev libgeos-dev libproj-dev libudunits2-dev` +on Ubuntu). See [Installation](../user/installation.md#r-for-the-pc2products-lidar-tools). + ## Testing your changes Install testing dependencies if not already installed: diff --git a/docs/files/developer/documentation.md b/docs/files/developer/documentation.md index a1baec4..0601f32 100644 --- a/docs/files/developer/documentation.md +++ b/docs/files/developer/documentation.md @@ -1,27 +1,60 @@ # Documentation -BERA Tools uses [Zensical](https://zensical.org/) for user, developer, and API documentation. The documentation source files are written in Markdown and are located in the `docs/` folder of the GitHub repository. Zensical reads the existing `mkdocs.yml` through its supported compatibility layer; use the `zensical` CLI rather than invoking `mkdocs` directly. +BERA Tools uses [Zensical](https://zensical.org/) for user, developer, and API documentation. The pages are written in Markdown. Zensical reads each site's `mkdocs.yml` through its supported compatibility layer; use the `zensical` CLI rather than invoking `mkdocs` directly. + +## One site per publication + +The docs are split into sites, one per thing that is published: the frame site and one site per module. The public `BERATool/beratools` repository deploys them all to its GitHub Pages: the frame site at the root and each module's site under `//`. Anywhere else, such as a fork, the sites are only built. + +| Site | Config | Public URL | +|------|--------|------------| +| Frame: home, installation, GUI, `bt`, pipelines, developer and technical guides, frame API | `docs/mkdocs.yml` | `https://beratool.github.io/beratools/` | +| Mapping | `beratools/modules/mapping/docs/mkdocs.yml` | `https://beratool.github.io/beratools/mapping/` | +| PC2Products | `beratools/modules/pc2products/docs/mkdocs.yml` | `https://beratool.github.io/beratools/pc2products/` | +| Raster2Products | `beratools/modules/raster2products/docs/mkdocs.yml` | `https://beratool.github.io/beratools/raster2products/` | + +A repository has one Pages site, so each module's site is built separately and served under `//` of the frame site, named after the module's folder (`mapping`, `pc2products`, …). A new module's site is published there with no other change. + +Every site inherits the shared settings (theme, Markdown extensions, mkdocstrings) from `docs/base.yml` and adds its own `site_name`, `site_url`, `nav` and `edit_uri`. Module sites take the logo and CSS from the frame site. ## Documentation File Structure ```bash docs/ -├── files/ # Main documentation folder -│ ├── api.md # API reference -│ ├── developer_guide.md # Developer guide -│ ├── index.md # Documentation homepage -│ ├── overview.md # Project overview -│ ├── requirements.txt # Python requirements for Zensical -│ ├── user_guide.md # User guide -│ │ -│ ├── css/ # Custom CSS for docs -│ ├── developer/ # Developer-specific docs -│ ├── icons/ # Project and documentation icons -│ ├── screenshots/ # Screenshots for guides and docs -│ ├── user/ # User-specific documentation -├── mkdocs.yml # Zensical-compatible configuration file +├── base.yml # settings shared by every site +├── mkdocs.yml # the frame site +└── files/ + ├── api.md # frame API reference + ├── developer_guide.md # Developer guide + ├── index.md # Documentation homepage + ├── overview.md # Project overview + ├── requirements.txt # Python requirements for Zensical + ├── user_guide.md # User guide, with the list of modules + ├── css/ # Custom CSS, also used by the module sites + ├── developer/ # Developer-specific docs + ├── icons/ # Project and documentation icons + ├── screenshots/ # Screenshots for the frame pages + ├── technical/ # Architecture and algorithm overview + └── user/ # Installation + +beratools/modules//docs/ +├── mkdocs.yml # the module's site +└── files/ + ├── index.md # the module's home page and tool table + ├── api.md # the module's API reference + ├── user/ # one page per tool + ├── technical/ # the module's technical pages + └── screenshots/ # screenshots for the module's pages ``` +The module docs are not shipped in the package: `pyproject.toml` excludes `beratools/modules/*/docs` from the wheel and sdist. + +## Links between pages and sites + +- Within a site, link pages by their relative `.md` path, e.g. `[DTM](dtm.md)`. +- To another site, use its full URL, e.g. `[Installation](https://beratool.github.io/beratools/user/installation/)`. A relative link to a page of another site fails the strict build. +- Each tool's `tech_link` in `tools.json` (the GUI's help button) is a path on its module's site, such as `user/dtm/`, which the frame resolves against the module's `docs_url`. `tests/test_registry.py` checks that each one names a page that exists. + ## Contribution Guidelines To contribute to the documentation, please follow these guidelines: @@ -50,24 +83,25 @@ Activate the development environment described in the [local development setup]( python -m pip install ".[doc]" ``` -2. Serve the documentation locally. This starts a development server that automatically rebuilds when files change: +2. Serve a site locally. This starts a development server that automatically rebuilds when files change: ```console zensical serve -f docs/mkdocs.yml + zensical serve -f beratools/modules/pc2products/docs/mkdocs.yml ``` Open `http://127.0.0.1:8000` to preview the site. -3. Build the documentation. This generates the static site in `docs/site/`: +3. Build every site the way CI does. Each one is written to a `site/` folder next to its `mkdocs.yml`: ```console - zensical build -f docs/mkdocs.yml + for site in docs/mkdocs.yml beratools/modules/*/docs/mkdocs.yml; do zensical build --strict -f "$site"; done ``` ## Deployment -The documentation is automatically validated and deployed to GitHub Pages using `.github/workflows/mkdocs-gh-pages.yml`. +`.github/workflows/docs.yml` builds every site in strict mode on pull requests that change the docs, the code (the API pages are built from it) or the build environment. In the public `BERATool/beratools` repository it also runs on pushes to `main`: it puts the sites together, the frame site at the root and each module's site under `//`, and deploys them to GitHub Pages. Anywhere else it only builds them. `tests/test_docs_sites.py` checks that each module's `site_url` and `docs_url` match that layout. -Pull requests that change documentation inputs run a Zensical build without deploying. Matching pushes to `main` build `docs/site` once, upload it as a GitHub Pages artifact, and deploy that artifact in a separate job with Pages permissions. The workflow uses the Pixi setup action and also watches `pixi.toml` and `pixi.lock` because they define the build environment. Superseded runs on the same PR or branch are cancelled. The published site is available at `https://beratool.github.io/beratools/`. +The public repository's Pages are set to deploy from GitHub Actions: ![Doc Deployment Config](../screenshots/gh_pages_config.png) diff --git a/docs/files/developer/maintainer.md b/docs/files/developer/maintainer.md index ab63428..3946c6b 100644 --- a/docs/files/developer/maintainer.md +++ b/docs/files/developer/maintainer.md @@ -12,7 +12,7 @@ to ensure a smooth and secure development process. ## Protect Branches -branch protection rules help us enforce certain workflows in our repository. We can use them to: +Branch protection rules help us enforce certain workflows in our repository. We can use them to: - Apply protection to main branch - Require pull requests before merging @@ -27,30 +27,32 @@ branch protection rules help us enforce certain workflows in our repository. We GitHub Actions allow you to automate workflows directly in our repository. BERA Tools uses GitHub Actions for CI/CD pipelines, including: -Here is a summary of the actions defined in all workflow files in `.github/workflows`, grouped by trigger type: +For the steps of a release, see [Making a release](publishing.md#making-a-release). -### Push to main +Here is a summary of the actions defined in all workflow files in `.github/workflows`, grouped by trigger type: -- __mkdocs-gh-pages.yml__ - - Summary: Zensical validation and deployment workflow for documentation inputs. - - Trigger: On pull requests and pushes to `main` affecting documentation, its dependencies, or the workflow. - - Builds with Zensical and deploys the generated artifact to GitHub Pages on pushes. - - Builds once per run; only the deployment job has Pages write and OIDC permissions. Pixi configuration changes also trigger a rebuild. +### Docs +- __docs.yml__ + - Summary: builds every docs site (the frame site and one per module) with Zensical in strict mode, and in `BERATool/beratools` deploys them as one GitHub Pages site, with each module's site under `//`. + - Trigger: On pull requests to `main` affecting the docs, the code (the API pages are built from it), the Pixi configuration or the workflow; on pushes to `main` in `BERATool/beratools`; also by hand. + - Deploys only in `BERATool/beratools` (see [Documentation](documentation.md#deployment)). + ### Automatic integration tests - __python-integration-tests.yml__ - Summary: Workflow integration tests using Pixi and pytest. - Trigger: On pushes to `main` and qualifying pull requests targeting `main` when application, test, Pixi/project configuration, or workflow files change. - - Runs `tests/test_workflow.py` in the Pixi-managed Python 3.12 environment with terminal coverage reporting. + - Runs `beratools/modules/mapping/tests/test_workflow.py` in the Pixi-managed Python 3.12 environment with terminal coverage reporting. - Tests the push commit or PR test-merge commit using the Pixi setup action. + - Then installs the system GDAL/GEOS/PROJ/udunits libraries and runs `beratools/modules/pc2products/tests/test_r_environment.py` (which installs the R packages into the pixi R) and `beratools/modules/pc2products/tests/test_r_workflow.py` for the PC2Products tools. The timeout is 60 minutes to leave room for the R packages. ### Manual (workflow_dispatch) - __python-compatibility-tests.yml__ - Summary: Manual Python compatibility grid using tox inside micromamba environments with conda-forge GDAL. - Trigger: Manually triggered via `workflow_dispatch`. - - Runs `tests/test_workflow.py` through tox under Python 3.12, 3.13, and 3.14 without relying on Ubuntu apt GDAL. + - Runs `beratools/modules/mapping/tests/test_workflow.py` through tox under Python 3.12, 3.13, and 3.14 without relying on Ubuntu apt GDAL. - Installs Python graph bindings as `python-igraph` before the project's `--no-deps` installation. Run this matrix before releases or after dependency changes. - __build-win-installer.yml__ diff --git a/docs/files/developer/publishing.md b/docs/files/developer/publishing.md index 2794040..09f0099 100644 --- a/docs/files/developer/publishing.md +++ b/docs/files/developer/publishing.md @@ -1,6 +1,6 @@ # Publishing BERA Tools -PyPI, Conda, and Windows installer releases are manually dispatched using the workflow on `main`, with a release tag selecting the source to build. Older tags are supported. Pushing a version tag does not start publishing. Windows signing is currently off by default; uncheck **Skip SignPath** to enable it for a run. +PyPI, Conda, and Windows installer releases are manually dispatched using the workflow on `main`, with a release tag selecting the source to build. Tags from 0.7.0 on can be built again (see [Versioning](#versioning)). Pushing a version tag does not start publishing. Windows signing is currently off by default; uncheck **Skip SignPath** to enable it for a run. ## Versioning @@ -12,6 +12,18 @@ BERA Tools Versioning follows [PEP440](https://peps.python.org/pep-0440/): `majo | **Minor** | This is reserved for releases that introduce new functionality. | | **Patch** | This is reserved for releases that only include bug fixes. | +The version is set in one place, `__version__` in `beratools/__init__.py`. The wheel, the source distribution, the Conda package, the Windows installer and the GUI's About box all read it, and each module's `requires_frame` is checked against it. Every module's `tools.json` `version` is the same; `tests/test_registry.py` checks it. A release tag must equal `__version__`: the PyPI, Anaconda and installer workflows stop when it doesn't. + +Before 0.7.0 the version came from the git tag. The Anaconda workflow can't rebuild those older tags, because their `__version__` doesn't match the tag; PyPI and the installer still can. + +## Making a release + +1. In a pull request to `main`, set `__version__` in `beratools/__init__.py` and `"version"` in every `beratools/modules/*/tools.json` to the new version, and merge it once CI passes. +2. Tag the merge commit with the version, for example `git tag 0.7.0` and `git push origin 0.7.0`, or create the tag with a GitHub Release. +3. Dispatch [Publish to PyPI](#pypi-publication), [Publish to Anaconda](#anaconda-publication) and [Build Windows Installer](#production-release) from `main` with the tag, as described below. +4. The docs site is deployed by `docs.yml` on the push to `main`; there is nothing else to do for it. +5. Check the release on [PyPI](https://pypi.org/project/BERATools/), [Anaconda](https://anaconda.org/bera_tools/beratools) and the GitHub Release, which has the installer. + ## Packaging BERA Tools BERA Tools is packaged for distribution on both PyPI and Anaconda. Conda uses `python-igraph` for the Python bindings; the corresponding PyPI dependency is named `igraph`. Keep the Conda recipe, `environment.yml`, `pixi.toml`, and compatibility workflow consistent with this naming. @@ -31,7 +43,7 @@ All three publishing workflows use native `actions/checkout` to select the input | Input | Source | Publication | | --- | --- | --- | | Empty release tag | Selected branch's commit when the run started | Actions artifacts only | -| Existing numeric tag, dispatched from `main` | Exact commit of that tag, including older tags | Enabled after build checks pass | +| Existing numeric tag, dispatched from `main` | Exact commit of that tag, including older tags from 0.7.0 on | Enabled after build checks pass | | Malformed or nonexistent tag, unmerged tag, or tag supplied from another branch | Validation fails before building | Disabled | A release tag must match `major.minor.patch` and its commit must be an ancestor of, or equal to, the `main` commit that launched the run. There is no latest-tag or exact-current-commit restriction. Tags are resolved to commit SHAs before checkout. Blank inputs never switch to a tag and never publish, even if the selected commit is tagged. diff --git a/docs/files/developer/testing.md b/docs/files/developer/testing.md index 7afe34a..a886b38 100644 --- a/docs/files/developer/testing.md +++ b/docs/files/developer/testing.md @@ -4,11 +4,11 @@ BERA Tools employs a `pytest` framework to ensure code quality and reliability. ## Testing Workflows -- **pytest**: Tests use pytest and are located in the `tests` directory. The automated workflows described below run only `tests/test_workflow.py`, not the complete test suite. -- **Automatic integration testing**: The `python-integration-tests.yml` workflow runs `tests/test_workflow.py` on pushes to `main` and on qualifying pull requests targeting `main` when its configured path filters match. -- **Coverage**: Coverage from `tests/test_workflow.py` is printed in the GitHub Actions job log; it is not uploaded to an external service. +- **pytest**: Tests use pytest. The frame's tests are in `tests/`, and each module's tests are in `beratools/modules//tests/`. The automated workflows described below run only `beratools/modules/mapping/tests/test_workflow.py`, not the complete test suite. +- **Automatic integration testing**: The `python-integration-tests.yml` workflow runs `beratools/modules/mapping/tests/test_workflow.py`, then `beratools/modules/pc2products/tests/test_r_environment.py` and `beratools/modules/pc2products/tests/test_r_workflow.py` for the PC2Products tools, on pushes to `main` and on qualifying pull requests targeting `main` when its configured path filters match. +- **Coverage**: Coverage from `beratools/modules/mapping/tests/test_workflow.py` is printed in the GitHub Actions job log; it is not uploaded to an external service. - **Runtime environment**: The automatic integration workflow uses the Pixi-managed Python 3.12/GDAL environment. -- **Manual compatibility testing**: The dispatch-only `python-compatibility-tests.yml` workflow runs `tests/test_workflow.py` through tox in Python 3.12, 3.13, and 3.14 micromamba environments with conda-forge GDAL. +- **Manual compatibility testing**: The dispatch-only `python-compatibility-tests.yml` workflow runs `beratools/modules/mapping/tests/test_workflow.py` through tox in Python 3.12, 3.13, and 3.14 micromamba environments with conda-forge GDAL. ## Running Tests Locally @@ -23,7 +23,7 @@ To run tests locally, follow these steps: 2. Run all the test suite using `pytest`: === "Run All tests" - Discover and execute all tests in the `tests` directory. + Discover and execute all tests in `tests/` and `beratools/modules/*/tests/`. ```bash pytest ``` @@ -31,27 +31,47 @@ To run tests locally, follow these steps: === "Run a test file" Run a specific test file: ```bash - pytest tests/path/to/test_tools.py + pytest beratools/modules/mapping/tests/test_tools.py ``` === "Run a test function" Run a specific test function within a file: ```bash - pytest tests/path/to/test_tools.py::test_function_name + pytest beratools/modules/mapping/tests/test_tools.py::test_function_name ``` -### Pipeline tests +### PC2Products (R) tests -`tests/test_pipeline.py` covers pipeline linking, saving, loading and running, and -`tests/pytest_qt/test_pipeline_panel.py` covers the Pipeline tab in the GUI. +The PC2Products tools need R (see [Installation](../user/installation.md)). Their sample tiles are in +`beratools/modules/pc2products/tests/data/LiDAR/`; the tools write rasters to +`beratools/modules/pc2products/tests/data/LiDAR/Raster_Output/` and point clouds to +`beratools/modules/pc2products/tests/data/LiDAR/Classified_PC/` and `beratools/modules/pc2products/tests/data/LiDAR/Normalized_PC/`, all git-ignored. + +| Tests | What they cover | Needs R | +|-------|-----------------|---------| +| `beratools/modules/pc2products/tests/test_r_tools.py` | Runs each LiDAR tool on the sample tiles and checks the output | Yes | +| `beratools/modules/pc2products/tests/test_r_workflow.py` | Runs CSF classification, DTM, DSM, normalization, CHM (from the normalized tiles) and hummock/hollow in sequence, checking each tool's output, then deletes the outputs | Yes | +| `beratools/modules/pc2products/tests/test_r_environment.py` | Installs any missing R packages the tools need, then checks that they load | Yes | +| `beratools/modules/pc2products/tests/test_surface_water.py`, `beratools/modules/pc2products/tests/test_dtw.py`, `beratools/modules/pc2products/tests/test_seismic_line_analysis.py` | Run the raster tools on synthetic inputs with a known answer, built by `beratools/modules/pc2products/tests/synthetic_data.py` | Yes | +| `tests/pytest_qt/test_r_tool_forms.py` | GUI forms for each PC2Products tool, and GUI-to-validation round trips | No | + +```bash +python -m pytest beratools/modules/pc2products/tests/test_r_tools.py beratools/modules/pc2products/tests/test_r_environment.py -v +``` + +The first run of the R tests installs the R packages into the environment's R, so it can take a while. + +!!! note "Windows: run the R tests from PowerShell or cmd" + Run the R tests from **PowerShell or cmd, not Git Bash**. Under Git Bash, rpy2's + `R CMD config` call picks up Git's `sh`, fails, and rpy2 can't start R. ## GitHub Actions BERA Tools uses GitHub Actions to automate testing and deployment processes. This document describes the various workflows set up in the repository to ensure code quality and streamline releases. -1. **python-compatibility-tests.yml**: This dispatch-only workflow runs `tests/test_workflow.py` through tox under Python 3.12, 3.13, and 3.14 in micromamba environments with conda-forge GDAL and native geospatial libraries. +1. **python-compatibility-tests.yml**: This dispatch-only workflow runs `beratools/modules/mapping/tests/test_workflow.py` through tox under Python 3.12, 3.13, and 3.14 in micromamba environments with conda-forge GDAL and native geospatial libraries. -2. **python-integration-tests.yml**: This automatic workflow runs `tests/test_workflow.py` with terminal coverage on pushes to `main` and qualifying pull requests targeting `main`. +2. **python-integration-tests.yml**: This automatic workflow runs `beratools/modules/mapping/tests/test_workflow.py` with terminal coverage on pushes to `main` and qualifying pull requests targeting `main`. It then installs the system GDAL/GEOS/PROJ/udunits libraries and runs `beratools/modules/pc2products/tests/test_r_environment.py`, which installs the R packages into the pixi R, and `beratools/modules/pc2products/tests/test_r_workflow.py`. The job's timeout is 60 minutes to leave room for the R packages. Refer to the [Maintainer Guide](./maintainer.md#automatic-integration-tests) for more information on these workflows. @@ -61,11 +81,13 @@ It is required to write tests when contributing to BERA Tools. follow these guid ### conftest.py -The `conftest.py` file in the `tests` directory contains shared fixtures and configurations for the test suite. You can add common setup code here that can be reused across multiple test files. +`tests/conftest.py` holds the fixtures and configuration of the frame's tests, and each module's `tests/conftest.py` holds its own, so a module's tests also run on their own. Put setup code that several test files share in the `conftest.py` next to them. ### Test Organization -Tests are organized in the `tests` directory. Each module or tool should have a corresponding test file. . +The frame's tests (core, GUI, CLI and registry) are in `tests/`. A module's tests are in `beratools/modules//tests/`, with their sample data in its `tests/data/`. Tests that use tools of more than one module go in `tests/test_cross_module.py`. Each tool should have a corresponding test file. + +The module test folders have no `__init__.py`, so give a helper module a name that no other test folder uses, such as `mapping_test_utils.py`. ### Naming Conventions @@ -73,4 +95,4 @@ Test files should be named with the prefix `test_` which can be detected by pyte ### Writing Tests -When writing tests, use assertions to verify that the code behaves as expected. Utilize fixtures from `conftest.py` for setup and cleanup operations. +When writing tests, use assertions to verify that the code behaves as expected. Utilize fixtures from the `conftest.py` files for setup and cleanup operations. diff --git a/docs/files/developer/tool_template.md b/docs/files/developer/tool_template.md index 1f7c0c9..7a67db1 100644 --- a/docs/files/developer/tool_template.md +++ b/docs/files/developer/tool_template.md @@ -1,6 +1,8 @@ # Tool Template (Reference) -This page remains as a reference pointer for historical links and the sample `tool_template.py` workflow. +The sample tool `beratools/core/tool_template.py` is part of the frame: it uses only frame code +(`tool_base`, `tool_args`, `spatial_common`), so it ships with the frame and changes with its tool API. +Copy it into your module's folder to start a new tool. ## Recommended reading @@ -16,6 +18,89 @@ This page remains as a reference pointer for historical links and the sample `to - optional multiprocessing through `execute_multiprocessing` - separation of lightweight tool wrappers from heavy core logic +## Sample `tools.json` + +The Feature Buffer tool in `tool_template.py` is not in the GUI toolbox. Its entry below is a sample +module file in the format that modules use, checked by `beratools/gui/assets/module.schema.json`. +The frame loads only the module files in `beratools/modules/` (see +[How to Add a New Tool](add_new_tool.md)), so `tool_template.py` no longer runs on its own. + +```json +{ + "module": "sample", + "version": "0.1.0", + "requires_frame": ">=0.7", + "category": "Sample", + "description": "A sample module with one tool.", + "tools": [ + { + "name": "Feature Buffer", + "info": "Buffer the features of a vector layer.", + "tool_type": "python", + "tool_api": "tool_template", + "cli_name": "buffer", + "entry": "sample.tool_template:tool_template", + "icon": "tool_template.gif", + "tech_link": "developer/tool_template.md", + "parameters": [ + { + "variable": "in_feature", + "label": "Input Feature Class", + "description": "Input vector layer.", + "type": "file", + "subtype": "vector", + "default": "", + "output": false, + "optional": false + }, + { + "variable": "buffer_dist", + "label": "Buffer Distance (m)", + "description": "Buffer distance around each input feature.", + "type": "number", + "subtype": "float", + "default": 10, + "unit": "m", + "output": false, + "optional": false + }, + { + "variable": "out_feature", + "label": "Output Buffered Features", + "description": "Output buffered features.", + "type": "file", + "subtype": "vector", + "default": "", + "output": true, + "optional": false + } + ] + } + ] +} +``` + +What the module-level fields and the tool fields `cli_name` and `entry` do: + +| Field | Meaning | +|---|---| +| `module` | The module's id and Python package name. | +| `version` | The module's own version. | +| `requires_frame` | The frame versions the module works with, as a PEP 440 specifier. | +| `cli_name` | The `bt` subcommand, e.g. `bt buffer`. Unique across all modules. | +| `entry` | `package.module:function` that the frame imports to run the tool. | + +The schema rejects unknown or misspelled keys, so check a new file against it before adding it. + +## PC2Products (R) tools + +`beratools/modules/pc2products/rpy_find_cellsize.py` is the smallest complete PC2Products tool. It shows: + +- calling `configure_r_environment()` before importing `r_common` +- checking the inputs and installing the R packages the tool needs +- sourcing `r_scripts_collection.r` and calling an R function from `robjects.globalenv` +- metadata-driven argument composition via `compose_tool_kwargs` + ## Where to place content - Put contributor step-by-step instructions in `developer/add_new_tool.md` diff --git a/docs/files/developer_guide.md b/docs/files/developer_guide.md index ac9deeb..fa68254 100644 --- a/docs/files/developer_guide.md +++ b/docs/files/developer_guide.md @@ -11,6 +11,7 @@ project is broken up like so. │ ├── cli │ ├── core │ ├── gui +│ ├── modules # mapping, pc2products, raster2products, ... │ ├── tools │ └── utility ├── docs @@ -18,16 +19,18 @@ project is broken up like so. ├── examples ├── notebooks ├── tests +│ └── data/LiDAR # sample LAS tiles for the PC2Products tools ``` Directory | Description -------------------- | ----------- `beratools/cli` | The `bt` / `beratools` command (`entry.py`), with one subcommand per tool. -`beratools/core` | Core algorithms and logic, and user-built pipelines (`pipeline.py`). -`beratools/gui` | GUI components and assets; `assets/beratools.json` defines every tool and its parameters. -`beratools/tools` | Tool implementations. +`beratools/core` | Frame code shared by every module: tool running and multiprocessing (`tool_base.py`), user-built pipelines (`pipeline.py`), the tool registry that merges the modules' `tools.json` files (`registry.py`) and the sample tool to start from (`tool_template.py`). Its old algorithm files only redirect to the modules. +`beratools/gui` | GUI components and assets, including `assets/module.schema.json`. +`beratools/modules` | One folder per module (`mapping`, `pc2products`, `raster2products`, ...), each with its tool entry points, their algorithms (`algo_*.py`) and a `tools.json` file checked against `gui/assets/module.schema.json`. `pc2products` also holds the R functions its tools call (`r_scripts_collection.r`) and the R helpers (`r_interface.py`, `r_common.py`). +`beratools/tools` | Redirects from the old tool paths, so old imports keep working. `beratools/utility` | Argument composition (`tool_args.py`), environment checks and spatial helpers. -`examples` | Example workflows. +`examples` | Example workflows, including `pc2products_pipeline.py`. `docs/files/developer` | Developer documentation. `notebooks` | Example notebooks and configs. `tests` | Unit and integration tests. \ No newline at end of file diff --git a/docs/files/index.md b/docs/files/index.md index 9989aef..f7163e5 100644 --- a/docs/files/index.md +++ b/docs/files/index.md @@ -9,6 +9,23 @@ Given that the process of manually digitizing detailed small-scale solution is preferred for large-scale application areas. Additionally, high-resolution CHMs allow for improved forest line spatial analysis. +## PC2Products (LiDAR) tools + +The **PC2Products** (Point Cloud to Products) category turns LiDAR point clouds (`.las` / `.laz`) +into raster products such as a **DTM**, **DSM**, **CHM** and **hummock/hollow** maps. It also +includes tools for checking the input data, classifying ground points, mapping surface water and +depth to water, and comparing seismic lines with the surrounding peatland. + +![DTM, DSM, height relative to the smoothed terrain, and hummock/hollow classes produced from the sample tiles](screenshots/pc2products_outputs.png) + +*Rasters produced from the sample tiles in `modules/pc2products/tests/data/LiDAR/` (ground-classified with CSF first, cell +size 0.3 m). Top: DTM and DSM, both built with TIN. Bottom: the hummock/hollow tool's two outputs, +using `Smooth_by = median`, `Min_ws = 3` and `lawn_range = 0.1`.* + +These tools call R functions in `r_scripts_collection.r` through [rpy2](https://rpy2.github.io/), +using [lidR](https://r-lidar.github.io/lidRbook/) for the processing. The CHM they make can feed the +mapping tools directly, for example in a GUI pipeline. + ## Credit This tool is part of the [**Boreal Ecosystem Recovery and Assessment (BERA)**](http://www.beraproject.org/) Project, and is being actively developed by the [**Applied Geospatial Research Group**](https://www.appliedgrg.ca/). @@ -40,6 +57,11 @@ The Forest Line Mapper: A Semi-Automated Tool for Mapping Linear Disturbances in Gustavo Lopes Queiroz, Gregory J. McDermid, Mir Mustafizur Rahman, and Julia Linke. _Remote Sens._ 2020, 12(24), 4176. [https://doi.org/10.3390/rs12244176](https://doi.org/10.3390/rs12244176) +Surface Water Mapping, Depth-to-Water from Surface Water and Seismic Line Disturbance Analysis follow +Chan, Dabros & McDermid (2026), +[*Microtopographic and Hydrological Response to Repeated Seismic Line Disturbance in a Boreal Fen of +Northern Alberta, Canada*](https://doi.org/10.3390/f17040489), *Forests* 17, 489. + ## License BERA Tools is release under the GPL 3.0 (GNU General Public License diff --git a/docs/files/overview.md b/docs/files/overview.md index 2eeaed1..e2aa782 100644 --- a/docs/files/overview.md +++ b/docs/files/overview.md @@ -15,12 +15,16 @@ linear disturbances in forests. - Automatic centerline generation - Multiple footprint methods: absolute, relative, fixed-width - Small, scriptable command-line tools for batch processing +- LiDAR point cloud processing (PC2Products): ground classification, DTM, height normalization, + CHM/DSM, hummock/hollow mapping, surface water, depth to water and seismic line statistics +- Raster processing (Raster2Products): normalized DTM from a DTM raster - Drag-and-drop pipelines in the GUI that chain tools and link each step's inputs to earlier outputs ## Data Formats & Conventions - Supported vector: GeoPackage, Shapefile - Supported raster: GeoTIFF +- Supported point clouds: LAS / LAZ, read from a folder as a lidR `LAScatalog` - Vector layers in a GeoPackage are given as `file.gpkg|layer` - Use a projected coordinate system in metres @@ -35,10 +39,37 @@ linear disturbances in forests. | Tool | Details | |------|---------| -| [Check Seed Line](user/check_seed_line.md) | Groups and splits input lines for seed line quality control. | -| [Vertex Optimization](user/vertex_optimization.md) | Optimizes line vertices using raster data for improved delineation. | -| [Centerline](user/centerline.md) | Generates centerlines from input lines and raster data. | -| [Line Footprint (Absolute)](user/canopy_footprint_abs.md) | Generates line footprints based on absolute canopy thresholds. | -| [Line Footprint (Relative)](user/canopy_footprint_rel.md) | Creates dynamic line footprints using least-cost corridor and relative thresholds. | -| [Line Footprint (Fixed Width)](user/ground_footprint.md) | Computes fixed-width line footprints and associated statistics. | +| [Check Seed Line](https://beratool.github.io/beratools/mapping/user/check_seed_line/) | Groups and splits input lines for seed line quality control. | +| [Vertex Optimization](https://beratool.github.io/beratools/mapping/user/vertex_optimization/) | Optimizes line vertices using raster data for improved delineation. | +| [Centerline](https://beratool.github.io/beratools/mapping/user/centerline/) | Generates centerlines from input lines and raster data. | +| [Line Footprint (Absolute)](https://beratool.github.io/beratools/mapping/user/canopy_footprint_abs/) | Generates line footprints based on absolute canopy thresholds. | +| [Line Footprint (Relative)](https://beratool.github.io/beratools/mapping/user/canopy_footprint_rel/) | Creates dynamic line footprints using least-cost corridor and relative thresholds. | +| [Line Footprint (Fixed Width)](https://beratool.github.io/beratools/mapping/user/ground_footprint/) | Computes fixed-width line footprints and associated statistics. | +### PC2Products (LiDAR) + +These tools run R and [lidR](https://r-lidar.github.io/lidRbook/) through +[rpy2](https://rpy2.github.io/), so they need R in the environment (see +[Installation](user/installation.md)). + +| Tool | `bt` subcommand | Details | +|------|-----------------|---------| +| [LiDAR data info](https://beratool.github.io/beratools/pc2products/user/las_info/) | `las_info` | Prints the CRS, extent, density and normalization status of a dataset. | +| [Raster Cell size from LiDAR data](https://beratool.github.io/beratools/pc2products/user/cellsize/) | `cellsize` | Recommends a raster cell size from the point density. | +| [Ground Classify Using CSF](https://beratool.github.io/beratools/pc2products/user/gnd_csf/) | `gnd_csf` | Classifies ground points with the Cloth Simulation Filter. | +| [Generate DTM from LiDAR Data](https://beratool.github.io/beratools/pc2products/user/dtm/) | `dtm` | Builds a bare-earth DTM with TIN, IDW or kriging. | +| [Normalize LiDAR Data](https://beratool.github.io/beratools/pc2products/user/normalize/) | `normalize` | Subtracts the terrain so that Z is height above ground. | +| [Generate CHM or DSM from LiDAR Data](https://beratool.github.io/beratools/pc2products/user/chm_dsm/) | `chm_dsm` | Builds a CHM from normalized data, or a DSM from the original data. | +| [Detect Hummock and Hollow from LiDAR Data](https://beratool.github.io/beratools/pc2products/user/hummock_hollow/) | `hh` | Maps hummocks, hollows and lawns relative to a smoothed terrain. | +| [Surface Water Mapping](https://beratool.github.io/beratools/pc2products/user/surface_water/) | `surface_water` | Classifies surface water from a true-colour orthomosaic. | +| [Depth-to-Water from Surface Water](https://beratool.github.io/beratools/pc2products/user/dtw/) | `dtw` | Kriges a water table from surface water and computes depth to water. | +| [Seismic Line Disturbance Analysis](https://beratool.github.io/beratools/pc2products/user/seismic_line_analysis/) | `line_analysis` | Compares seismic line segments with the surrounding peatland by disturbance class. | + +### Raster2Products + +These tools make rasters from other rasters, such as a DTM. They run in Python and need no R; they +read large rasters in tiles and process each tile in parallel. + +| Tool | `bt` subcommand | Details | +|------|-----------------|---------| +| [Normalized DTM from DTM Raster](https://beratool.github.io/beratools/raster2products/user/ndtm_fr_dtmraster/) | `ndtm_fr_dtmraster` | Subtracts a smoothed DTM from a DTM, so hummocks are positive and hollows negative. | diff --git a/docs/files/screenshots/pc2products_outputs.png b/docs/files/screenshots/pc2products_outputs.png new file mode 100644 index 0000000..422d9a7 Binary files /dev/null and b/docs/files/screenshots/pc2products_outputs.png differ diff --git a/docs/files/technical/algorithm_overview.md b/docs/files/technical/algorithm_overview.md index 7759f20..d3d28b4 100644 --- a/docs/files/technical/algorithm_overview.md +++ b/docs/files/technical/algorithm_overview.md @@ -12,7 +12,7 @@ BERA Tools processes line mapping in a staged pipeline: - Vector and raster inputs should use compatible CRS. - Distance-based operations assume projected units (meters). -- Tool scripts act as thin interfaces; core logic lives in `beratools/core`. +- Tool scripts act as thin interfaces; core logic lives in each module's `algo_*.py` files under `beratools/modules`. ## Where to go next @@ -20,10 +20,18 @@ BERA Tools processes line mapping in a staged pipeline: - [System Overview](architecture/system_overview.md) - [Execution Pipeline](architecture/execution_pipeline.md) - [Tool Runtime Model](architecture/tool_runtime_model.md) -- Algorithms: - - [Check Seed Lines](algorithms/check_seed_line.md) - - [Vertex Optimization](algorithms/vertex_optimization.md) - - [Centerline](algorithms/centerline.md) - - [Canopy Footprint (Absolute)](algorithms/canopy_footprint_absolute.md) - - [Canopy Footprint (Relative)](algorithms/canopy_footprint_relative.md) - - [Ground Footprint](algorithms/ground_footprint.md) +- Mapping tools: + - [Check Seed Lines](https://beratool.github.io/beratools/mapping/technical/algorithms/check_seed_line/) + - [Vertex Optimization](https://beratool.github.io/beratools/mapping/technical/algorithms/vertex_optimization/) + - [Centerline](https://beratool.github.io/beratools/mapping/technical/algorithms/centerline/) + - [Smooth Centerline](https://beratool.github.io/beratools/mapping/technical/algorithms/smooth_centerline/) + - [Canopy Footprint (Absolute)](https://beratool.github.io/beratools/mapping/technical/algorithms/canopy_footprint_absolute/) + - [Canopy Footprint (Relative)](https://beratool.github.io/beratools/mapping/technical/algorithms/canopy_footprint_relative/) + - [Ground Footprint](https://beratool.github.io/beratools/mapping/technical/algorithms/ground_footprint/) + - [Footprint Plots and Subplots](https://beratool.github.io/beratools/mapping/technical/algorithms/footprint_plots/) +- PC2Products (LiDAR) tools: + - [PC2Products Tool Overview](https://beratool.github.io/beratools/pc2products/technical/pc2products_overview/) + - [How the PC2Products Tools Run](https://beratool.github.io/beratools/pc2products/technical/tool_behaviour/) + - [How the LiDAR Tools Tile a Point Cloud](https://beratool.github.io/beratools/pc2products/technical/lidar_density_tiling/) +- Raster2Products tools: + - [Raster Smoothing and Normalized DTM](https://beratool.github.io/beratools/raster2products/technical/algorithms/raster_smoothing/) diff --git a/docs/files/technical/architecture/execution_pipeline.md b/docs/files/technical/architecture/execution_pipeline.md index dc570ed..b7e7723 100644 --- a/docs/files/technical/architecture/execution_pipeline.md +++ b/docs/files/technical/architecture/execution_pipeline.md @@ -83,7 +83,7 @@ Run the selected tool’s core processing logic. **Main actions** -- Tool wrapper dispatches to core modules in `beratools/core`. +- Tool wrapper dispatches to its module's algorithms (`beratools/modules//algo_*.py`). - Optional multiprocessing is used for suitable workloads. **Inputs** @@ -127,6 +127,28 @@ flowchart LR D --> E[Ground Footprint] ``` +The PC2Products (LiDAR) tools follow the same stages, but stage 3 checks that the input folder holds +LAS/LAZ files and installs any missing R packages, stage 4 runs the tool's R function tile by tile +with parallel R workers, and stage 5 merges per-tile rasters into a `Merged_*.tif` mosaic. A typical +chain: + +```mermaid +flowchart LR + A[LiDAR data info] --> B[Ground Classify Using CSF] + B --> C[Generate DTM] + B --> D[Normalize LiDAR Data] + D --> E[Generate CHM or DSM] + B --> F[Detect Hummock and Hollow] + E --> G[Surface Water Mapping] + C --> H[Depth-to-Water] + G --> H + C --> I[Seismic Line Disturbance Analysis] + F --> I + H --> I +``` + +The CHM can also be the CHM raster input of the mapping tools above, for example in a GUI pipeline. + ## Failure points to monitor | Failure signal | Likely cause | Pipeline stage | Mitigation | @@ -135,5 +157,10 @@ flowchart LR | CRS mismatch or geographic CRS used for meter-based operations | Mixed layer CRS or unprojected data in distance/area workflows | Preprocessing and validation | Reproject all layers to a suitable projected CRS before running tools | | Most features removed unexpectedly | Over-aggressive thresholds/filters | Core algorithm execution | Revisit parameter thresholds and test with a smaller AOI for calibration | | Missing raster coverage for clipping/corridor steps | AOI extends beyond raster bounds or wrong raster source | Preprocessing and validation / Core algorithm execution | Verify raster extent and alignment with vector AOI before processing | +| Error finding R, or rpy2 fails to import (PC2Products tools) | R not installed in the environment, or `R_HOME` points elsewhere | Preprocessing and validation | See [How R is located](https://beratool.github.io/beratools/pc2products/technical/tool_behaviour/#how-r-is-located); run from an activated environment | +| `R packages could not be installed` | No internet access, or missing system libraries on Linux | Preprocessing and validation | Run `beratools/modules/pc2products/tests/test_r_environment.py`; install the GDAL/GEOS/PROJ/udunits development libraries | +| Hummock/hollow stops without output, or a CHM comes out as a DSM | Input not ground-classified, or not height-normalized | Core algorithm execution | Run Ground Classify Using CSF, then Normalize LiDAR Data; check with LiDAR data info | +| Out of memory or very slow LiDAR processing | Too many R workers for a small cell size | Core algorithm execution | Lower `processes`; the TIN and kriging DTM tools already halve the workers below a 1 m cell size | +| Missing CRS reported as `Unknown` | LAS files without a CRS | Preprocessing and validation | Assign the CRS to the LAS files before processing | See also: [Tool Runtime Model](tool_runtime_model.md) diff --git a/docs/files/technical/architecture/system_overview.md b/docs/files/technical/architecture/system_overview.md index bf4dc77..10841c3 100644 --- a/docs/files/technical/architecture/system_overview.md +++ b/docs/files/technical/architecture/system_overview.md @@ -2,22 +2,28 @@ BERA Tools is organized into clear layers: -- `beratools/tools`: thin tool entry points (CLI/GUI-facing) -- `beratools/core`: core algorithms and processing logic, and user-built pipelines (`pipeline.py`) +- `beratools/modules`: one folder per module (`mapping`, `pc2products`, `raster2products`, ...) with its + tool entry points, their algorithms and its `tools.json`; the PC2Products LiDAR tools (`rpy_*.py`) call R + processing in `r_scripts_collection.r` +- `beratools/core`: frame code: tool running, the tool registry and user-built pipelines (`pipeline.py`) - `beratools/cli`: the `bt` command - `beratools/gui`: desktop GUI and parameter widgets - `beratools/utility`: shared helpers (arguments, environment checks, spatial helpers) ## Design principles -- **Separation of concerns**: tool wrappers stay lightweight; heavy logic remains in core modules. +- **Separation of concerns**: tool wrappers stay lightweight; heavy logic stays in each module's `algo_*.py` files. - **Single source of tool metadata**: GUI and CLI parameter behavior derives from tool configuration. - **Consistent execution model**: tools support CLI and GUI call modes with shared runtime behaviors. ## Module responsibilities -- `tools/*`: validate/collect inputs, call corresponding core logic, write outputs. -- `core/*`: geometric/raster algorithms, optimization, line processing. +- `modules//.py`: validate/collect inputs, call the module's algorithms, write outputs. +- `modules//algo_*.py`: geometric/raster algorithms, optimization, line processing. +- `modules//tools.json`: the module's tools and their parameters, merged by `core/registry.py`. +- `modules/pc2products/rpy_*.py`: validate inputs, check R packages, call the tool's R function through rpy2. +- `modules/pc2products/r_interface.py`, `modules/pc2products/r_common.py`: locate R and connect rpy2. +- `core/tool_base.py`: multiprocessing shared by the tools. - `core/pipeline.py`: save, load, link and run pipelines of tool steps. - `cli/*`: the `bt` subcommands, built from tool metadata. - `gui/*`: exposes tools and parameters for interactive use. diff --git a/docs/files/technical/architecture/tool_runtime_model.md b/docs/files/technical/architecture/tool_runtime_model.md index 3b0c67c..caa3600 100644 --- a/docs/files/technical/architecture/tool_runtime_model.md +++ b/docs/files/technical/architecture/tool_runtime_model.md @@ -57,16 +57,16 @@ flowchart TD Node legend: -1. **Load schema**: load tool parameter metadata from `gui/assets/beratools.json`. +1. **Load schema**: load tool parameter metadata from the merged registry of the modules' `beratools/modules/*/tools.json` files (`core/registry.py`). 2. **Build tool args**: create required/optional CLI arguments from metadata. 3. **Add framework args**: append `--processes`, `--call_mode`, and `--log_level`. -4. **Resolve tool function**: map `tool_api` to function under `beratools.tools.*`. +4. **Resolve tool function**: import the function named by the tool's `entry` field. 5. **Call tool function**: execute the selected tool with parsed arguments. ### Alias and argument model -- Alias mapping is defined in `TOOL_ALIASES`. -- Tool parameter definitions (required/optional flags, defaults, choices, numeric/list typing) come from `gui/assets/beratools.json`. +- Each subcommand is the tool's `cli_name` field in its `tools.json`. +- Tool parameter definitions (required/optional flags, defaults, choices, numeric/list typing) come from the tool's `tools.json` entry. - Shared runtime flags are added to every tool command: - `--processes` - `--call_mode` @@ -80,6 +80,7 @@ This keeps CLI behavior aligned with GUI metadata while preserving a concise com beratools list-tools beratools centerline --help beratools check_line --in_line seed_lines.gpkg --out_line qc_lines.gpkg --processes 4 +beratools dtm --in_las_folder tests/data/LiDAR --out_folder tests/data/LiDAR/Raster_Output --style tin --processes 4 ``` ## Multiprocessing model @@ -94,10 +95,37 @@ Key behavior: - Fall back to sequential mode when one process is used - Keep progress/log behavior consistent with `call_mode` +## PC2Products (R) tools + +The PC2Products LiDAR tools (`rpy_*.py`) expose a function shaped like: + +```python +def rpy_tool_name(in_las_folder, out_folder, ..., processes=0, **kwargs) +``` + +`processes` is shared with the other tools; `call_mode` and `log_level` arrive through `**kwargs`. +Each module calls `configure_r_environment()` before it imports rpy2, so that R can be found (see +[How R is located](https://beratool.github.io/beratools/pc2products/technical/tool_behaviour/#how-r-is-located)). + +These tools do their parallel work in R, not in Python: + +- `r_common.r_max_workers(processes)` turns the requested `processes` into the most R processes: + `0` or less means every CPU core, and the count is capped at the number of cores. +- The R function calls `apply_tiling`, which starts as many workers as fit in the free memory + (`future::plan(multisession)`), gives them the other processes as lidR threads, and processes + the `LAScatalog` tile by tile. +- The R output streams to the console, or to the GUI log when the GUI runs the tool. Lines of the + form `R_PROGRESS:` drive the GUI progress bar. + +See [How all the tools behave](https://beratool.github.io/beratools/pc2products/technical/tool_behaviour/#how-all-the-tools-behave) for the details. + ## Separation of concerns -- `beratools/tools/*`: input wiring and dispatch -- `beratools/core/*`: heavy processing and algorithm implementation +- `beratools/modules//.py`: input wiring and dispatch +- `beratools/modules//algo_*.py`: heavy processing and algorithm implementation +- `beratools/core/*`: frame code shared by every module (tool running, registry, pipelines) +- `beratools/modules/pc2products/r_scripts_collection.r`: the processing for the PC2Products tools, with lidR, terra + and the other R packages This structure keeps tool wrappers small and makes algorithm logic easier to test and maintain. diff --git a/docs/files/technical_guide.md b/docs/files/technical_guide.md index d6bd0ee..d1df5e6 100644 --- a/docs/files/technical_guide.md +++ b/docs/files/technical_guide.md @@ -11,10 +11,15 @@ This section documents **how BERA Tools works internally**. - **Architecture**: high-level modules and interactions - **Execution pipeline**: input handling to output generation - **Tool runtime model**: CLI/GUI call modes, argument composition, multiprocessing -- **Algorithms**: per-tool method summaries, assumptions, edge cases +- **Mapping tools**: per-tool method summaries, assumptions, edge cases +- **PC2Products (LiDAR) tools**: the Python wrappers, the R functions they call, how R is located, + and how the tools run ## Reading order 1. [Algorithm Overview](technical/algorithm_overview.md) 2. Architecture pages -3. Per-tool algorithm pages +3. Mapping tools: the per-tool algorithm pages +4. PC2Products (LiDAR) tools: [PC2Products Tool Overview](https://beratool.github.io/beratools/pc2products/technical/pc2products_overview/), + [How the PC2Products Tools Run](https://beratool.github.io/beratools/pc2products/technical/tool_behaviour/) and + [How the LiDAR Tools Tile a Point Cloud](https://beratool.github.io/beratools/pc2products/technical/lidar_density_tiling/) diff --git a/docs/files/user/installation.md b/docs/files/user/installation.md index be9a4c0..d8374bb 100644 --- a/docs/files/user/installation.md +++ b/docs/files/user/installation.md @@ -60,10 +60,68 @@ pip install "gdal @ https://github.com/cgohlke/geospatial-wheels/releases/downlo pip install beratools ``` +## R for the PC2Products (LiDAR) tools + +The PC2Products tools (the `rpy_*` tools in the **PC2Products** category) run R through +[rpy2](https://rpy2.github.io/). The other tools don't need R. + +- **conda** and **pixi**: `environment.yml` and `pixi.toml` already include `r-base` 4.5.x and rpy2. +- **pip**: install R 4.5 yourself, then install the `r` extra: + + ```bash + pip install "beratools[r]" + ``` + +On the R side the environments contain only R and rpy2. Every R package comes from CRAN, installed by +the tools into the environment's R the first time they need it (see +[How all the tools behave](https://beratool.github.io/beratools/pc2products/technical/tool_behaviour/#how-all-the-tools-behave)). + +R is held at 4.5.x because conda-forge builds rpy2 for R 4.5 on Linux and macOS only, and for +nothing newer than R 4.4 on Windows, which is why rpy2 comes from PyPI on Windows. `pixi.toml` +covers `win-64`, `linux-64`, `osx-64` and `osx-arm64`, and takes rpy2 from conda-forge on Linux and +macOS. conda-forge has no R 4.5 builds of `lidR`, `rlas` and `RCSF` for `osx-arm64`, so on Apple +Silicon the tools compile them from CRAN on first use, which needs the Xcode Command Line Tools +(`xcode-select --install`). `environment.yml` installs rpy2 from PyPI on every platform, and PyPI has no Linux wheels, so +on Linux pip compiles rpy2 and needs a C compiler; prefer pixi there, or run +`conda install -c conda-forge rpy2` in the environment instead. Use Python 3.12 (or 3.14) on +Windows: `rpy2-rinterface` 3.6.7 has no Python 3.13 Windows wheel. On Windows, CRAN provides +prebuilt packages for R 4.5. On Linux, CRAN packages such as `sf` and `terra` are compiled from +source, which needs the GDAL, GEOS, PROJ and udunits development libraries (for example +`libgdal-dev libgeos-dev libproj-dev libudunits2-dev` on Ubuntu) and takes a while on the first run; +`pixi.toml` takes prebuilt conda-forge builds of them on `linux-64` instead. + +To install every R package up front and confirm that they load, run the R environment test from a +source checkout: + +```bash +python -m pytest beratools/modules/pc2products/tests/test_r_environment.py -v +``` + +The tools install these R packages the first time they need them: + +| R package | Purpose | +|-----------|---------| +| `lidR` | LAScatalog processing, `rasterize_terrain`, `rasterize_canopy` | +| `rlas` | Reading LAS/LAZ files | +| `future` | Parallel processing of catalogs | +| `future.mirai` | Optional: faster hand-out of tiles to the R workers; installed by the LiDAR tools when missing | +| `terra` | Raster output and mosaicking | +| `sf`, `units` | CRS, area and map-unit reporting | +| `RCSF` | Cloth Simulation Filter for ground classification | +| `gstat` | Kriging interpolation (DTM and water table) | +| `sp`, `raster`, `stars` | Spatial and raster support | +| `ggplot2` | Plots from Seismic Line Disturbance Analysis | +| `rpart` | Decision tree in Surface Water Mapping | + !!! note "Windows" Run the tools from an *activated* environment. If you call the environment's `python.exe` directly without activating it, GDAL can fail to load its DLLs. +!!! note "Windows: rpy2 and Git Bash" + Run the PC2Products tools and the R tests from **PowerShell or cmd, not Git Bash**. Under Git + Bash, rpy2 crashes while locating R (`IndexError` in `rpy2/situation`), because Git Bash's `sh` + makes `R CMD config` return empty output instead of failing. + ## Verify Installation After installation, verify that BERA Tools is installed correctly: diff --git a/docs/files/user_guide.md b/docs/files/user_guide.md index cf9f9cb..e3714eb 100644 --- a/docs/files/user_guide.md +++ b/docs/files/user_guide.md @@ -13,6 +13,16 @@ Start working with BERA Tools using example data. [Download latest example data](https://github.com/BERATool/beratools/releases/latest/download/test_data.zip) +## Modules + +The tools come in modules. Each module has its own site with its tool pages, technical notes and API. + +| Module | Tools | +|--------|-------| +| [Mapping](https://beratool.github.io/beratools/mapping/) | Line quality control, vertex optimization, centerlines and footprints | +| [PC2Products (LiDAR)](https://beratool.github.io/beratools/pc2products/) | LiDAR point cloud processing: ground, DTM, CHM/DSM, hummocks and hollows, surface water | +| [Raster2Products](https://beratool.github.io/beratools/raster2products/) | Rasters from other rasters, such as a normalized DTM | + ## Main GUI BERA Tools provide a light weight GUI to use tools. @@ -37,16 +47,23 @@ graph TD A --> C["Centerline"] C --> D1["Canopy Footprint
Absolute"] C --> D2["Canopy Footprint
Relative"] + C --> S["Smooth Centerline"] + S --> D1 + S --> D2 D1 --> E["Ground Footprint"] D2 --> E["Ground Footprint"] - %% Style optional step (Vertex Optimization) + E --> F["Footprint Plots
and Subplots"] + %% Style optional steps (Vertex Optimization, Smooth Centerline) style B fill:#eee,stroke:#aaa,color:#666,stroke-width:1px,stroke-dasharray:5 5; - click A "../user/check_seed_line" "Check Seed Line" - click B "../user/vertex_optimization" "Vertex Optimization" - click C "../user/centerline" "Centerline" - click D1 "../user/canopy_footprint_abs" "Canopy Footprint Absolute" - click D2 "../user/line_footprint_rel" "Canopy Footprint Relative" - click E "../user/ground_footprint" "Ground Footprint" + style S fill:#eee,stroke:#aaa,color:#666,stroke-width:1px,stroke-dasharray:5 5; + click A "https://beratool.github.io/beratools/mapping/user/check_seed_line/" "Check Seed Line" + click B "https://beratool.github.io/beratools/mapping/user/vertex_optimization/" "Vertex Optimization" + click C "https://beratool.github.io/beratools/mapping/user/centerline/" "Centerline" + click D1 "https://beratool.github.io/beratools/mapping/user/canopy_footprint_abs/" "Canopy Footprint Absolute" + click D2 "https://beratool.github.io/beratools/mapping/user/canopy_footprint_rel/" "Canopy Footprint Relative" + click E "https://beratool.github.io/beratools/mapping/user/ground_footprint/" "Ground Footprint" + click S "https://beratool.github.io/beratools/mapping/user/smooth_centerline/" "Smooth Centerline" + click F "https://beratool.github.io/beratools/mapping/user/footprint_plots/" "Footprint Plots and Subplots" ``` ## Running the tools @@ -64,13 +81,13 @@ graph TD bt centerline --in_line "|" --in_raster --out_line "|centerline" --proc_segments True -p 4 ``` - `bt` (also available as `beratools`) reads each tool's parameters from `beratools.json`, converts + `bt` (also available as `beratools`) reads each tool's parameters from its module's `tools.json`, converts values to the right type and rejects anything that isn't one of a list parameter's allowed values. === "Python module" ```bash - python -m beratools.tools.centerline --in_line "|" --in_raster --out_line "|centerline" --proc_segments True + python -m beratools.modules.mapping.centerline --in_line "|" --in_raster --out_line "|centerline" --proc_segments True ``` `-p/--processes` sets the requested number of workers, and `-l/--log_level` sets the log level. @@ -125,7 +142,7 @@ python -m beratools.core.pipeline my_pipeline.json --processes 4 A step only counts as failed if its tool exits with an error. If a tool prints a warning and stops normally instead, the next step then fails on its missing input, so check the log. -Which inputs can link to which outputs is set in `beratools.json`, so new tools can join pipelines +Which inputs can link to which outputs is set in each module's `tools.json`, so new tools can join pipelines without code changes. See [Taking part in pipelines](developer/add_new_tool.md#taking-part-in-pipelines). ## Data Preparation diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 39e3738..5daa76c 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -1,86 +1,32 @@ -# Zensical compatibility configuration. Build with `zensical`, not `mkdocs`. +# The frame site: home, installation, GUI, CLI and pipeline guides, developer and technical guides, +# and the frame API. Each module has its own site (beratools/modules//docs/mkdocs.yml), +# linked from the Modules section. Shared settings are in base.yml. Build with `zensical`, not `mkdocs`. +INHERIT: base.yml + site_name: BERA Tools Guide +site_url: https://beratool.github.io/beratools/ +edit_uri: edit/main/docs/files/ +# The frame site serves the logo and CSS the module sites point at theme: - name: material - repo_url: https://github.com/BERATool/beratools - repo_name: GitHub - palette: - - media: "(prefers-color-scheme)" - primary: blue - accent: blue - toggle: - icon: material/brightness-auto - name: "Switch to light mode" - - media: "(prefers-color-scheme: light)" - scheme: default - primary: blue - accent: blue - toggle: - icon: material/brightness-7 - name: "Switch to dark mode" - - media: "(prefers-color-scheme: dark)" - scheme: slate - primary: blue - accent: blue - toggle: - icon: material/brightness-4 - name: "Switch to system preference" - - features: - - navigation.tabs # top-level tabs in the header - - navigation.top # keep nav in header - - content.code.copy # optional niceties - - content.action.edit - font: - text: Inter - code: JetBrains Mono favicon: icons/bera_logo.png logo: icons/bera_logo.svg -repo_url: https://github.com/BERATool/beratools -repo_name: BERA Tools -edit_uri: edit/main/docs/files/ - -markdown_extensions: - - admonition - - attr_list - - def_list - - pymdownx.tasklist: - custom_checkbox: true - - pymdownx.tabbed: - alternate_style: true - - pymdownx.superfences: - custom_fences: - - name: mermaid - class: mermaid - format: !!python/name:pymdownx.superfences.fence_code_format - - pymdownx.emoji: - emoji_index: !!python/name:material.extensions.emoji.twemoji - emoji_generator: !!python/name:material.extensions.emoji.to_svg - extra_css: - css/extra.css -docs_dir: files -watch: - - files - -# page tree here +# page tree nav: - - Home: + - Home: - index.md - overview.md - - User Guide: + - User Guide: - user_guide.md - user/installation.md - - Tools: - - user/check_seed_line.md - - user/vertex_optimization.md - - user/centerline.md - - user/canopy_footprint_abs.md - - user/canopy_footprint_rel.md - - user/ground_footprint.md + - Modules: + - Mapping: https://beratool.github.io/beratools/mapping/ + - PC2Products (LiDAR): https://beratool.github.io/beratools/pc2products/ + - Raster2Products: https://beratool.github.io/beratools/raster2products/ - Developer Guide: - developer_guide.md - developer/contributing.md @@ -99,47 +45,4 @@ nav: - technical/architecture/system_overview.md - technical/architecture/execution_pipeline.md - technical/architecture/tool_runtime_model.md - - Algorithms: - - technical/algorithms/check_seed_line.md - - technical/algorithms/vertex_optimization.md - - technical/algorithms/centerline.md - - technical/algorithms/canopy_footprint_absolute.md - - technical/algorithms/canopy_footprint_relative.md - - technical/algorithms/ground_footprint.md - API Reference: api.md - -plugins: - - search - - mkdocstrings: - handlers: - python: - paths: [..] # read beratools from the repo root, no install needed - options: - # --- Docstring parsing --- - docstring_style: google - docstring_options: - ignore_init_summary: true # don't duplicate __init__ summaries - - # --- Visibility and member organization --- - filters: ["!^_"] # exclude private members - members_order: source # preserve code order - inherited_members: false # avoid clutter unless needed - - # --- Signature and linking --- - separate_signature: true - show_signature_annotations: true - signature_crossrefs: true - merge_init_into_class: true - - # --- Page rendering --- - show_source: false - show_root_toc_entry: true - - inventories: - - url: https://docs.python.org/3/objects.inv - domains: [py, std] - - url: https://typing-extensions.readthedocs.io/en/latest/objects.inv - - url: https://geopandas.org/en/stable/objects.inv - - url: https://shapely.readthedocs.io/en/stable/objects.inv - - url: https://numpy.org/doc/stable/objects.inv - - url: https://pandas.pydata.org/pandas-docs/stable/objects.inv diff --git a/environment.yml b/environment.yml index 0121c08..05ec55c 100644 --- a/environment.yml +++ b/environment.yml @@ -6,7 +6,8 @@ channels: - conda-forge - bera_tools dependencies: - - python>=3.12,<3.14 + # 3.12: rpy2-rinterface 3.6.7 has no Python 3.13 Windows wheel, so pip would try to compile it + - python=3.12 - dask - gdal>=3.12,<4 - geopandas @@ -19,10 +20,24 @@ dependencies: - scikit-image>=0.24.0 - tqdm - xarray-spatial + - numba - tabulate + - jsonschema + - packaging - python-igraph - psutil + - laspy + - lazrs-python + - scipy - hydra-core - pip + # R for the PC2Products LiDAR tools: they install the R packages they need (lidR, terra, sf, ...) on first use + - r-base>=4.5,<4.6 + - pip: + # conda-forge has no win-64 rpy2 build for R 4.5, so install it from PyPI. + # PyPI has no Linux wheels, so on Linux pip compiles rpy2 (needs a C compiler). On Linux and + # macOS, pixi.toml is the easier route, or replace this line with conda-forge's rpy2: + # conda install -n bera -c conda-forge rpy2 + - rpy2 variables: {} diff --git a/examples/README.md b/examples/README.md index 45cff4e..d400571 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,6 +1,8 @@ # Examples - [Full Workflow (Hydra)](#full-workflow-example-hydra): `full_workflow.py` + `config.yaml`, runs the line mapping tools. +- [PC2Products Workflow (Hydra)](#pc2products-workflow-example-hydra): `pc2products_workflow.py` + `pc2products_config.yaml`, runs the LiDAR tools from raw tiles to rasters. +- [DTM, DSM and CHM Pipeline](#dtm-dsm-and-chm-pipeline): `pc2products_pipeline.py`, checks the LiDAR data and runs only the steps it needs. # Full Workflow Example (Hydra) @@ -73,3 +75,143 @@ Outputs are written to paths defined in `config.yaml`, including: - `centerline.gpkg|centerline` - `footprint_abs.gpkg|footprint_abs` - `footprint_ground.gpkg|footprint_ground` + +# PC2Products Workflow Example (Hydra) + +`pc2products_workflow.py` is a [Hydra](https://hydra.cc/)-driven example that runs the PC2Products +(LiDAR) tools in sequence, from raw LiDAR tiles to raster products: + +| Step | Tool | Reads | Writes | +|------|------|-------|--------| +| `las_info` | LiDAR data info | `DATA_DIR` | Console only | +| `cellsize` | Raster Cell size from LiDAR data | `DATA_DIR` | Console only | +| `gnd_csf` | Ground Classify Using CSF | `DATA_DIR` | `CLASSIFIED_DIR` | +| `dtm` | Generate DTM from LiDAR Data | `CLASSIFIED_DIR` | `RASTER_DIR` | +| `chm_dsm` | Generate CHM or DSM from LiDAR Data | `CLASSIFIED_DIR` | `RASTER_DIR` | +| `hh` | Detect Hummock and Hollow from LiDAR Data | `CLASSIFIED_DIR` | `RASTER_DIR` | + +Steps always run in this order. `steps_to_run` only chooses which of them run. + +## Files + +- `pc2products_workflow.py`: workflow entrypoint. +- `pc2products_config.yaml`: Hydra config for folders, step selection and each tool's arguments + (`args_`). + +## Requirements + +An environment with R (see [Installation](../docs/files/user/installation.md#r-for-the-pc2products-lidar-tools)). +Both `environment.yml` and `pixi.toml` include what the workflow needs: `hydra-core` (which brings in +`omegaconf`), `rpy2`, `psutil` and R. + +## Configure Input Data + +`pc2products_config.yaml` defines three folders: + +| Key | Default | Contents | +|-----|---------|----------| +| `DATA_DIR` | `tests/data/LiDAR` | Input LAS/LAZ tiles | +| `CLASSIFIED_DIR` | `${DATA_DIR}/Classified_PC` | Ground-classified tiles written by `gnd_csf` | +| `RASTER_DIR` | `${DATA_DIR}/Raster_Output` | DTM, CHM/DSM and hummock/hollow rasters | + +The defaults point at the sample tiles, so the workflow runs as-is from the repository root. +Relative paths are resolved from the folder you run the script from (`hydra.job.chdir` is `false`). + +If your data is already ground-classified, skip `gnd_csf` and point `CLASSIFIED_DIR` at the input +folder: + +```bash +python examples/pc2products_workflow.py steps_to_run=[dtm,chm_dsm,hh] CLASSIFIED_DIR=D:/my_data/LiDAR +``` + +## Run + +From the repository root: + +```bash +python examples/pc2products_workflow.py +``` + +Run with Hydra overrides: + +```bash +python examples/pc2products_workflow.py processes=4 +python examples/pc2products_workflow.py steps_to_run=[gnd_csf,dtm] +python examples/pc2products_workflow.py DATA_DIR=D:/my_data/LiDAR +``` + +## Common Overrides + +- `processes=`: number of worker processes. `null` (the default) uses all CPU cores, and the + tools then apply their own limits. +- `steps_to_run=[...]`: run only the selected steps. An unknown step name stops the workflow before + anything runs. +- Any tool argument, for example: + +```bash +python examples/pc2products_workflow.py args_dtm.style=kriging +python examples/pc2products_workflow.py args_chm_dsm.style=pitfree +python examples/pc2products_workflow.py args_hh.Min_ws=5.0 args_hh.lawn_range=0.2 +python examples/pc2products_workflow.py args_gnd_csf.rigidness=3 +``` + +## Output + +With the default `style: tin` and `Smooth_by: median`, `Min_ws: 3.0`: + +- `CLASSIFIED_DIR`: `_csfgnd_upto30cm_cloth100cm_soft.las` for each input tile. +- `RASTER_DIR`: + - `_csfgnd_upto30cm_cloth100cm_soft_TIN_DTM.tif` and `Merged_TIN_DTM.tif` + - `_csfgnd_upto30cm_cloth100cm_soft_TIN_DSM.tif` and `Merged_TIN_DSM.tif` (`_CHM` instead of `_DSM` if the + data is height-normalized) + - `CHH__csfgnd_upto30cm_cloth100cm_soft_median_3m.tif`, `HH__csfgnd_upto30cm_cloth100cm_soft_median_3m.tif`, + `Merged_CHH_median_3m.tif` and `Merged_HH_median_3m.tif` + +Hydra also writes its run log and resolved config to `outputs//