Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .github/workflows/publish_to_anaconda.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ jobs:
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"

# Build the tagged source with the recipe from the dispatched commit, so packaging
# fixes can be released for an existing tag without moving it.
- name: Use recipe from workflow commit
if: steps.source.outputs.publish == 'true'
run: |
set -euo pipefail
git checkout "$GITHUB_SHA" -- packaging/recipe.yaml
printf -- '- Recipe commit: `%s`\n' "$GITHUB_SHA" >> "$GITHUB_STEP_SUMMARY"

# Disable Pixi cache to avoid pixi.lock lookup
- name: Setup Pixi
uses: prefix-dev/[email protected]
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/python-compatibility-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ jobs:
dask
gdal>=3.12,<4
geopandas
pandas>=2.0,<3.0
pandas
networkit
numpy>=1.26,<2.4
pandas
Expand All @@ -46,13 +46,13 @@ jobs:
scikit-image>=0.24
tqdm
xarray-spatial
pandarallel
python-igraph
tabulate
pip
pytest
pytest-qt
tox
psutil
condarc: |
channel_priority: strict
channels:
Expand Down
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,16 @@ The **Pipeline** tab, next to **Tool history** in the GUI, chains tools into ste
another. Drag tools in from the tool tree, set each step's parameters in the tool form, and link a
step's inputs to an earlier step's output. Each input links to the latest earlier step that makes what
it needs, for example the checked lines from **Check Seed Lines** into **Centerline**, and the
links are reset whenever a step is added, moved or removed. Pipelines save as `.json` files and also
run without the GUI:
links are reset whenever a step is added, moved or removed.

![BERA Tools Pipeline panel](docs/files/screenshots/bt_pipeline.png)

The example above chains the six mapping tools into a ground footprint workflow. Each step lists the
step it reads from (`← step 5`), and the selected step's linked inputs are shown under
**Inputs from earlier steps** and greyed out in the tool form. Use **Run Pipeline** to run all steps
in order.

Pipelines save as `.json` files and also run without the GUI:

```bash
$ python -m beratools.core.pipeline my_pipeline.json --processes 4
Expand Down
26 changes: 26 additions & 0 deletions beratools/core/algo_canopy_footprint_absolute.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ class CanopyFootprintRequest:
footprint_simplify_length: float = 0.5
smooth_footprint_polygon: bool = False
footprint_polygon_smooth_iterations: int = 1
merge_by_original_line: bool = False


@dataclass
Expand Down Expand Up @@ -95,6 +96,7 @@ def cast_request_types(request: CanopyFootprintRequest) -> CanopyFootprintReques
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

Expand All @@ -111,6 +113,28 @@ def _to_bool(value):
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,
*,
Expand Down Expand Up @@ -412,6 +436,7 @@ def compute(self):
# 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()
Expand Down Expand Up @@ -839,6 +864,7 @@ def compute(self):
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"],
Expand Down
3 changes: 3 additions & 0 deletions beratools/core/algo_centerline.py
Original file line number Diff line number Diff line change
Expand Up @@ -1115,6 +1115,9 @@ def compute(self):
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)
Expand Down
33 changes: 31 additions & 2 deletions beratools/core/algo_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,17 +372,46 @@ def lines_gdf_to_list(gdf):
return out_list


def prepare_lines_gdf(file_path, layer=None, proc_segments=True):
# 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.
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)

Expand Down
9 changes: 5 additions & 4 deletions beratools/core/algo_merge_lines.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,14 @@ def custom_line_merge(geom):
return geom


def run_line_merge(in_line_gdf, merge_group):
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 bt_const.BT_GROUP not in in_line_gdf.columns:
if group_field not in in_line_gdf.columns:
in_line_gdf = in_line_gdf.copy()
in_line_gdf[bt_const.BT_GROUP] = range(1, len(in_line_gdf) + 1)
out_line_gdf = in_line_gdf.dissolve(by=bt_const.BT_GROUP, as_index=False)
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()):
Expand Down
9 changes: 5 additions & 4 deletions beratools/core/algo_seed_line_correction.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ def prepare_lines(self, lines_gdf=None):
).remove_close_vertices(lines_gdf)

if self.optimize_internal_vertices:
self.line_list = algo_common.split_lines_to_segments(lines_gdf)
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)

Expand Down Expand Up @@ -542,11 +542,12 @@ def get_optimized_lines(self):

lines = pd.concat(self.line_list, ignore_index=True)

if self.optimize_internal_vertices and "BT_UID" in lines.columns:
if self.optimize_internal_vertices and bt_const.BT_UID in lines.columns:
import beratools.core.algo_merge_lines as algo_merge_lines

lines[bt_const.BT_GROUP] = lines["BT_UID"]
lines = algo_merge_lines.run_line_merge(lines, merge_group=True)
# 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
Expand Down
9 changes: 5 additions & 4 deletions beratools/core/algo_vertex_optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,7 @@ def create_all_vertex_groups(self):
self.min_segment_length,
self.angle_tol,
)
self.line_list = algo_common.split_lines_to_segments(lines_gdf)
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(
Expand Down Expand Up @@ -518,9 +518,10 @@ def save_all_layers(self, line_file):

lines = pd.concat(self.line_list, ignore_index=True)

if self.optimize_internal_vertices and "BT_UID" in lines.columns:
lines[bt_const.BT_GROUP] = lines["BT_UID"]
lines = algo_merge_lines.run_line_merge(lines, merge_group=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,
Expand Down
92 changes: 46 additions & 46 deletions beratools/core/canopy_threshold_relative.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import math
import os.path
from functools import partial
from multiprocessing.pool import Pool
from pathlib import Path

import pandas as pd
from pandarallel import pandarallel

from beratools.core.constants import *
from beratools.tools.common import *
Expand All @@ -16,6 +16,39 @@ class OperationCancelledException(Exception):
pass


def multiringbuffer(geom, nrings: int, ringdist: int) -> 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,
Expand Down Expand Up @@ -92,46 +125,19 @@ def main_canopy_threshold_relative(

print("Create ring buffer for input line to find the forest edge....")

def multiringbuffer(df: gpd.GeoDataFrame,
nrings:int,
ringdist:int)->list:
"""
Buffers an input dataframes 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 = df["geometry"].buffer(
nrings + ring, single_sided=True, cap_style="flat"
) # Create one big buffer
small_ring = df["geometry"].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

# Create a column with the rings as a list
print("Create rings buffer to forest edge on one side....")
pandarallel.initialize(progress_bar=False,nb_workers=processes)
worklnbuffer_df_l_ring["mgeometry"] = worklnbuffer_df_l_ring.parallel_apply(
lambda x: multiringbuffer(df=x, nrings=1, ringdist=15), axis=1
)
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")
Expand All @@ -143,12 +149,6 @@ def multiringbuffer(df: gpd.GeoDataFrame,
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("Create rings buffer to forest edge on the other side....")
pandarallel.initialize(progress_bar=False, nb_workers=processes)
worklnbuffer_df_r_ring["mgeometry"] = worklnbuffer_df_r_ring.parallel_apply(
lambda x: multiringbuffer(df=x, nrings=-1, ringdist=-15), axis=1
)

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 = (
Expand Down
Loading
Loading