BERATools 0.6.0__tar.gz → 0.6.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. {beratools-0.6.0 → beratools-0.6.1}/PKG-INFO +13 -5
  2. {beratools-0.6.0 → beratools-0.6.1}/README.md +10 -2
  3. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_canopy_footprint_absolute.py +26 -0
  4. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_centerline.py +3 -0
  5. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_common.py +31 -2
  6. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_merge_lines.py +5 -4
  7. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_seed_line_correction.py +5 -4
  8. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_vertex_optimization.py +5 -4
  9. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/canopy_threshold_relative.py +46 -46
  10. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/line_footprint_functions.py +19 -4
  11. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/assets/beratools.json +45 -1
  12. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/bt_gui_main.py +1 -2
  13. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/tool_widgets.py +52 -56
  14. {beratools-0.6.0 → beratools-0.6.1}/beratools/tools/canopy_footprint_absolute.py +7 -0
  15. {beratools-0.6.0 → beratools-0.6.1}/beratools/tools/centerline.py +79 -11
  16. {beratools-0.6.0 → beratools-0.6.1}/beratools/tools/check_seed_line.py +4 -0
  17. {beratools-0.6.0 → beratools-0.6.1}/beratools/tools/ground_footprint.py +14 -0
  18. {beratools-0.6.0 → beratools-0.6.1}/beratools/tools/line_footprint_relative.py +17 -1
  19. {beratools-0.6.0 → beratools-0.6.1}/pyproject.toml +2 -2
  20. {beratools-0.6.0 → beratools-0.6.1}/.gitignore +0 -0
  21. {beratools-0.6.0 → beratools-0.6.1}/LICENSE +0 -0
  22. {beratools-0.6.0 → beratools-0.6.1}/beratools/__init__.py +0 -0
  23. {beratools-0.6.0 → beratools-0.6.1}/beratools/cli/__init__.py +0 -0
  24. {beratools-0.6.0 → beratools-0.6.1}/beratools/cli/entry.py +0 -0
  25. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/__init__.py +0 -0
  26. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_astar.py +0 -0
  27. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_check_seed_line.py +0 -0
  28. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_check_seed_line_validate.py +0 -0
  29. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_cost.py +0 -0
  30. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_dijkstra.py +0 -0
  31. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_geometry.py +0 -0
  32. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_line_grouping.py +0 -0
  33. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_split_with_lines.py +0 -0
  34. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/algo_vertex_preclean.py +0 -0
  35. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/alt_spatial_common.py +0 -0
  36. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/constants.py +0 -0
  37. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/logger.py +0 -0
  38. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/pipeline.py +0 -0
  39. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/tool_base.py +0 -0
  40. {beratools-0.6.0 → beratools-0.6.1}/beratools/core/tool_geo_simplify.py +0 -0
  41. {beratools-0.6.0 → beratools-0.6.1}/beratools/external/__init__.py +0 -0
  42. {beratools-0.6.0 → beratools-0.6.1}/beratools/external/geo_simplify/geo-simplify-linux-x64 +0 -0
  43. {beratools-0.6.0 → beratools-0.6.1}/beratools/external/geo_simplify/geo-simplify-win-x64.exe +0 -0
  44. {beratools-0.6.0 → beratools-0.6.1}/beratools/external/polygon_centerline/LICENSE.md +0 -0
  45. {beratools-0.6.0 → beratools-0.6.1}/beratools/external/polygon_centerline/UPSTREAM.md +0 -0
  46. {beratools-0.6.0 → beratools-0.6.1}/beratools/external/polygon_centerline/__init__.py +0 -0
  47. {beratools-0.6.0 → beratools-0.6.1}/beratools/external/polygon_centerline/_src.py +0 -0
  48. {beratools-0.6.0 → beratools-0.6.1}/beratools/external/polygon_centerline/exceptions.py +0 -0
  49. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/assets/BERALogo.ico +0 -0
  50. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/assets/BERALogo.png +0 -0
  51. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/assets/BERA_GUI_Main.png +0 -0
  52. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/assets/BERA_Splash.gif +0 -0
  53. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/assets/BERA_WizardImage.png +0 -0
  54. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/assets/closed.gif +0 -0
  55. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/assets/closed.png +0 -0
  56. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/assets/gui.json +0 -0
  57. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/assets/open.gif +0 -0
  58. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/assets/open.png +0 -0
  59. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/assets/tool.gif +0 -0
  60. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/assets/tool.png +0 -0
  61. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/bt_data.py +0 -0
  62. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/geometry_types.py +0 -0
  63. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/main.py +0 -0
  64. {beratools-0.6.0 → beratools-0.6.1}/beratools/gui/pipeline_panel.py +0 -0
  65. {beratools-0.6.0 → beratools-0.6.1}/beratools/tools/__init__.py +0 -0
  66. {beratools-0.6.0 → beratools-0.6.1}/beratools/tools/common.py +0 -0
  67. {beratools-0.6.0 → beratools-0.6.1}/beratools/tools/tool_template.py +0 -0
  68. {beratools-0.6.0 → beratools-0.6.1}/beratools/tools/vertex_optimization.py +0 -0
  69. {beratools-0.6.0 → beratools-0.6.1}/beratools/utility/env_checks.py +0 -0
  70. {beratools-0.6.0 → beratools-0.6.1}/beratools/utility/spatial_common.py +0 -0
  71. {beratools-0.6.0 → beratools-0.6.1}/beratools/utility/tool_args.py +0 -0
  72. {beratools-0.6.0 → beratools-0.6.1}/beratools/utility/unit_conversion.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: BERATools
3
- Version: 0.6.0
3
+ Version: 0.6.1
4
4
  Summary: An advanced forest line feature analysis platform
5
5
  Project-URL: Homepage, https://github.com/BERATool/beratools
6
6
  Author-email: AppliedGRG <appliedgrg@gmail.com>, Richard Zeng <richardqzeng@gmail.com>
@@ -20,8 +20,8 @@ Requires-Dist: geopandas
20
20
  Requires-Dist: igraph
21
21
  Requires-Dist: networkit
22
22
  Requires-Dist: numpy<2.4,>=1.26
23
- Requires-Dist: pandarallel
24
- Requires-Dist: pandas<3,>=2.0
23
+ Requires-Dist: pandas>=2.0
24
+ Requires-Dist: psutil
25
25
  Requires-Dist: pyogrio>=0.12.0
26
26
  Requires-Dist: pyqt5
27
27
  Requires-Dist: rasterio>=1.5.0
@@ -110,8 +110,16 @@ The **Pipeline** tab, next to **Tool history** in the GUI, chains tools into ste
110
110
  another. Drag tools in from the tool tree, set each step's parameters in the tool form, and link a
111
111
  step's inputs to an earlier step's output. Each input links to the latest earlier step that makes what
112
112
  it needs, for example the checked lines from **Check Seed Lines** into **Centerline**, and the
113
- links are reset whenever a step is added, moved or removed. Pipelines save as `.json` files and also
114
- run without the GUI:
113
+ links are reset whenever a step is added, moved or removed.
114
+
115
+ ![BERA Tools Pipeline panel](docs/files/screenshots/bt_pipeline.png)
116
+
117
+ The example above chains the six mapping tools into a ground footprint workflow. Each step lists the
118
+ step it reads from (`← step 5`), and the selected step's linked inputs are shown under
119
+ **Inputs from earlier steps** and greyed out in the tool form. Use **Run Pipeline** to run all steps
120
+ in order.
121
+
122
+ Pipelines save as `.json` files and also run without the GUI:
115
123
 
116
124
  ```bash
117
125
  $ python -m beratools.core.pipeline my_pipeline.json --processes 4
@@ -57,8 +57,16 @@ The **Pipeline** tab, next to **Tool history** in the GUI, chains tools into ste
57
57
  another. Drag tools in from the tool tree, set each step's parameters in the tool form, and link a
58
58
  step's inputs to an earlier step's output. Each input links to the latest earlier step that makes what
59
59
  it needs, for example the checked lines from **Check Seed Lines** into **Centerline**, and the
60
- links are reset whenever a step is added, moved or removed. Pipelines save as `.json` files and also
61
- run without the GUI:
60
+ links are reset whenever a step is added, moved or removed.
61
+
62
+ ![BERA Tools Pipeline panel](docs/files/screenshots/bt_pipeline.png)
63
+
64
+ The example above chains the six mapping tools into a ground footprint workflow. Each step lists the
65
+ step it reads from (`← step 5`), and the selected step's linked inputs are shown under
66
+ **Inputs from earlier steps** and greyed out in the tool form. Use **Run Pipeline** to run all steps
67
+ in order.
68
+
69
+ Pipelines save as `.json` files and also run without the GUI:
62
70
 
63
71
  ```bash
64
72
  $ python -m beratools.core.pipeline my_pipeline.json --processes 4
@@ -59,6 +59,7 @@ class CanopyFootprintRequest:
59
59
  footprint_simplify_length: float = 0.5
60
60
  smooth_footprint_polygon: bool = False
61
61
  footprint_polygon_smooth_iterations: int = 1
62
+ merge_by_original_line: bool = False
62
63
 
63
64
 
64
65
  @dataclass
@@ -95,6 +96,7 @@ def cast_request_types(request: CanopyFootprintRequest) -> CanopyFootprintReques
95
96
  request.footprint_simplify_length = float(request.footprint_simplify_length)
96
97
  request.smooth_footprint_polygon = _to_bool(request.smooth_footprint_polygon)
97
98
  request.footprint_polygon_smooth_iterations = int(request.footprint_polygon_smooth_iterations)
99
+ request.merge_by_original_line = _to_bool(request.merge_by_original_line)
98
100
 
99
101
  return request
100
102
 
@@ -111,6 +113,28 @@ def _to_bool(value):
111
113
  return bool(value)
112
114
 
113
115
 
116
+ def copy_line_ids(footprint, line):
117
+ """Carry the source line's OLnFID/OLnSEG onto its footprint, so footprints can be merged per line."""
118
+ if footprint is None or line is None:
119
+ return footprint
120
+ for field in ("OLnFID", "OLnSEG"):
121
+ if field in line.columns:
122
+ footprint[field] = line[field].iloc[0]
123
+ return footprint
124
+
125
+
126
+ def merge_footprints_by_original_line(footprints_gdf, printer=print):
127
+ """Dissolve footprints sharing an OLnFID into one, as the centerline tool merges lines."""
128
+ if footprints_gdf is None or footprints_gdf.empty:
129
+ return footprints_gdf
130
+ if "OLnFID" not in footprints_gdf.columns:
131
+ printer("[Warning]: OLnFID not found in input lines; footprints are not merged.")
132
+ return footprints_gdf
133
+ merged = footprints_gdf.dissolve(by="OLnFID", as_index=False)
134
+ merged["OLnSEG"] = -1
135
+ return merged
136
+
137
+
114
138
  def process_footprint_polygon_gdf(
115
139
  footprint_gdf,
116
140
  *,
@@ -412,6 +436,7 @@ class LineInfo:
412
436
  # Transfer group value to footprint if present
413
437
  if bt_const.BT_GROUP in self.line.columns:
414
438
  self.footprint[bt_const.BT_GROUP] = self.line[bt_const.BT_GROUP].iloc[0]
439
+ copy_line_ids(self.footprint, self.line)
415
440
 
416
441
  def _build_rings_with_percentiles(self):
417
442
  self.prepare_ring_buffer()
@@ -839,6 +864,7 @@ class FootprintCanopyAbsolute:
839
864
  smooth_footprint_polygon=self.smooth_footprint_polygon,
840
865
  footprint_polygon_smooth_iterations=self.footprint_polygon_smooth_iterations,
841
866
  )
867
+ copy_line_ids(self.footprint, self.line_seg)
842
868
  self.postprocess_output(
843
869
  corridor_thresh,
844
870
  raster["out_transform"],
@@ -1115,6 +1115,9 @@ class SeedLine:
1115
1115
  self.corridor_poly_gpd["cl_status_name"] = status.name
1116
1116
  self.corridor_poly_gpd["OLnFID"] = self.lc_path["OLnFID"]
1117
1117
  self.corridor_poly_gpd["OLnSEG"] = self.lc_path["OLnSEG"]
1118
+ for field in (algo_common.SOURCE_ROW_FIELD, algo_common.SOURCE_SEG_FIELD):
1119
+ if field in self.lc_path.columns:
1120
+ self.corridor_poly_gpd[field] = self.lc_path[field]
1118
1121
 
1119
1122
  def _set_fallback_outputs(self, lc_path, centerline, status, corridor_geometry=None):
1120
1123
  status = CenterlineStatus(status)
@@ -372,17 +372,46 @@ def lines_gdf_to_list(gdf):
372
372
  return out_list
373
373
 
374
374
 
375
- def prepare_lines_gdf(file_path, layer=None, proc_segments=True):
375
+ # remember which input row (and its OLnSEG) each processed piece came from
376
+ SOURCE_ROW_FIELD = "BT_SRC_ROW"
377
+ SOURCE_SEG_FIELD = "BT_SRC_SEG"
378
+
379
+
380
+ def keep_source_seg(gdf):
381
+ """Remember each row's OLnSEG before split_lines_to_segments renumbers it per vertex."""
382
+ if gdf is not None and "OLnSEG" in gdf.columns:
383
+ gdf = gdf.copy()
384
+ gdf[SOURCE_SEG_FIELD] = gdf["OLnSEG"]
385
+ return gdf
386
+
387
+
388
+ def restore_source_seg(gdf):
389
+ """Put back the OLnSEG saved by keep_source_seg once the segments are merged into their rows."""
390
+ if gdf is not None and SOURCE_SEG_FIELD in gdf.columns:
391
+ gdf = gdf.copy()
392
+ gdf["OLnSEG"] = gdf[SOURCE_SEG_FIELD]
393
+ gdf = gdf.drop(columns=SOURCE_SEG_FIELD)
394
+ return gdf
395
+
396
+
397
+ def prepare_lines_gdf(file_path, layer=None, proc_segments=True, tag_source_rows=False):
376
398
  """
377
399
  Split lines at vertices or return original rows.
378
400
 
379
- It handles for MultiLineString.
401
+ It handles for MultiLineString. With tag_source_rows, OLnFID/OLnSEG are added if missing
402
+ and each row records its input row and OLnSEG, so pieces can be merged back to it.
380
403
 
381
404
  """
382
405
  gdf = read_geospatial_file(file_path, layer=layer)
383
406
  if gdf is None:
384
407
  return []
385
408
 
409
+ if tag_source_rows:
410
+ gdf, _ = chk_df_multipart(gdf, "LineString")
411
+ gdf = gdf.reset_index(drop=True)
412
+ gdf[SOURCE_ROW_FIELD] = gdf.index
413
+ gdf[SOURCE_SEG_FIELD] = gdf["OLnSEG"]
414
+
386
415
  if proc_segments:
387
416
  return split_lines_to_segments(gdf)
388
417
 
@@ -52,13 +52,14 @@ def custom_line_merge(geom):
52
52
  return geom
53
53
 
54
54
 
55
- def run_line_merge(in_line_gdf, merge_group):
55
+ def run_line_merge(in_line_gdf, merge_group, group_field=bt_const.BT_GROUP):
56
+ """Merge lines sharing a group_field value into one line (BT_GROUP by default)."""
56
57
  out_line_gdf = in_line_gdf
57
58
  if merge_group:
58
- if bt_const.BT_GROUP not in in_line_gdf.columns:
59
+ if group_field not in in_line_gdf.columns:
59
60
  in_line_gdf = in_line_gdf.copy()
60
- in_line_gdf[bt_const.BT_GROUP] = range(1, len(in_line_gdf) + 1)
61
- out_line_gdf = in_line_gdf.dissolve(by=bt_const.BT_GROUP, as_index=False)
61
+ in_line_gdf[group_field] = range(1, len(in_line_gdf) + 1)
62
+ out_line_gdf = in_line_gdf.dissolve(by=group_field, as_index=False)
62
63
 
63
64
  out_line_gdf.geometry = out_line_gdf.geometry.apply(safe_linemerge)
64
65
  for i, row in enumerate(out_line_gdf.itertuples()):
@@ -460,7 +460,7 @@ class SeedLineCorrection:
460
460
  ).remove_close_vertices(lines_gdf)
461
461
 
462
462
  if self.optimize_internal_vertices:
463
- self.line_list = algo_common.split_lines_to_segments(lines_gdf)
463
+ self.line_list = algo_common.split_lines_to_segments(algo_common.keep_source_seg(lines_gdf))
464
464
  else:
465
465
  self.line_list = algo_common.lines_gdf_to_list(lines_gdf)
466
466
 
@@ -542,11 +542,12 @@ class SeedLineCorrection:
542
542
 
543
543
  lines = pd.concat(self.line_list, ignore_index=True)
544
544
 
545
- if self.optimize_internal_vertices and "BT_UID" in lines.columns:
545
+ if self.optimize_internal_vertices and bt_const.BT_UID in lines.columns:
546
546
  import beratools.core.algo_merge_lines as algo_merge_lines
547
547
 
548
- lines[bt_const.BT_GROUP] = lines["BT_UID"]
549
- lines = algo_merge_lines.run_line_merge(lines, merge_group=True)
548
+ # join the segments back into their input rows, keeping each row's BT_GROUP
549
+ lines = algo_merge_lines.run_line_merge(lines, merge_group=True, group_field=bt_const.BT_UID)
550
+ lines = algo_common.restore_source_seg(lines)
550
551
 
551
552
  if "length" not in lines.columns:
552
553
  lines["length"] = lines.geometry.length
@@ -442,7 +442,7 @@ class VertexGrouping:
442
442
  self.min_segment_length,
443
443
  self.angle_tol,
444
444
  )
445
- self.line_list = algo_common.split_lines_to_segments(lines_gdf)
445
+ self.line_list = algo_common.split_lines_to_segments(algo_common.keep_source_seg(lines_gdf))
446
446
  else:
447
447
  lines_gdf = algo_common.read_geospatial_file(self.in_line, layer=self.in_layer)
448
448
  lines_gdf = algo_vertex_preclean.preclean_vertices(
@@ -518,9 +518,10 @@ class VertexGrouping:
518
518
 
519
519
  lines = pd.concat(self.line_list, ignore_index=True)
520
520
 
521
- if self.optimize_internal_vertices and "BT_UID" in lines.columns:
522
- lines[bt_const.BT_GROUP] = lines["BT_UID"]
523
- lines = algo_merge_lines.run_line_merge(lines, merge_group=True)
521
+ if self.optimize_internal_vertices and bt_const.BT_UID in lines.columns:
522
+ # join the segments back into their input rows, keeping each row's BT_GROUP
523
+ lines = algo_merge_lines.run_line_merge(lines, merge_group=True, group_field=bt_const.BT_UID)
524
+ lines = algo_common.restore_source_seg(lines)
524
525
 
525
526
  lines = algo_common.clean_geometries(
526
527
  lines,
@@ -1,10 +1,10 @@
1
1
  import math
2
2
  import os.path
3
+ from functools import partial
3
4
  from multiprocessing.pool import Pool
4
5
  from pathlib import Path
5
6
 
6
7
  import pandas as pd
7
- from pandarallel import pandarallel
8
8
 
9
9
  from beratools.core.constants import *
10
10
  from beratools.tools.common import *
@@ -16,6 +16,39 @@ class OperationCancelledException(Exception):
16
16
  pass
17
17
 
18
18
 
19
+ def multiringbuffer(geom, nrings: int, ringdist: int) -> list:
20
+ """
21
+ Buffers an input geometry nring (number of rings) times, with a distance between
22
+ rings of ringdist and returns a list of non overlapping buffers
23
+ """
24
+ import numpy as np
25
+ rings = [] # A list to hold the individual buffers
26
+ for ring in np.arange(0, ringdist, nrings): # For each ring (1, 2, 3, ..., nrings)
27
+ big_ring = geom.buffer(
28
+ nrings + ring, single_sided=True, cap_style="flat"
29
+ ) # Create one big buffer
30
+ small_ring = geom.buffer(
31
+ ring, single_sided=True, cap_style="flat"
32
+ ) # Create one smaller one
33
+ the_ring = big_ring.difference(small_ring) # Difference the big with the small to create a ring
34
+ if (
35
+ ~shapely.is_empty(the_ring)
36
+ or ~shapely.is_missing(the_ring)
37
+ or not None
38
+ or ~the_ring.area == 0
39
+ ):
40
+ if isinstance(the_ring, shapely.MultiPolygon) or isinstance(the_ring, shapely.Polygon):
41
+ rings.append(the_ring) # Append the ring to the rings list
42
+ else:
43
+ if isinstance(the_ring, shapely.GeometryCollection):
44
+ for i in range(0, len(the_ring.geoms)):
45
+ if not isinstance(the_ring.geoms[i], shapely.LineString):
46
+ rings.append(the_ring.geoms[i])
47
+ print(" {}% ".format((ring / ringdist) * 100))
48
+
49
+ return rings # return the list
50
+
51
+
19
52
  def main_canopy_threshold_relative(
20
53
  in_line: str,
21
54
  in_chm: str,
@@ -92,46 +125,19 @@ def main_canopy_threshold_relative(
92
125
 
93
126
  print("Create ring buffer for input line to find the forest edge....")
94
127
 
95
- def multiringbuffer(df: gpd.GeoDataFrame,
96
- nrings:int,
97
- ringdist:int)->list:
98
- """
99
- Buffers an input dataframes geometry nring (number of rings) times, with a distance between
100
- rings of ringdist and returns a list of non overlapping buffers
101
- """
102
- import numpy as np
103
- rings = [] # A list to hold the individual buffers
104
- for ring in np.arange(0, ringdist, nrings): # For each ring (1, 2, 3, ..., nrings)
105
- big_ring = df["geometry"].buffer(
106
- nrings + ring, single_sided=True, cap_style="flat"
107
- ) # Create one big buffer
108
- small_ring = df["geometry"].buffer(
109
- ring, single_sided=True, cap_style="flat"
110
- ) # Create one smaller one
111
- the_ring = big_ring.difference(small_ring) # Difference the big with the small to create a ring
112
- if (
113
- ~shapely.is_empty(the_ring)
114
- or ~shapely.is_missing(the_ring)
115
- or not None
116
- or ~the_ring.area == 0
117
- ):
118
- if isinstance(the_ring, shapely.MultiPolygon) or isinstance(the_ring, shapely.Polygon):
119
- rings.append(the_ring) # Append the ring to the rings list
120
- else:
121
- if isinstance(the_ring, shapely.GeometryCollection):
122
- for i in range(0, len(the_ring.geoms)):
123
- if not isinstance(the_ring.geoms[i], shapely.LineString):
124
- rings.append(the_ring.geoms[i])
125
- print(" {}% ".format((ring / ringdist) * 100))
126
-
127
- return rings # return the list
128
-
129
128
  # Create a column with the rings as a list
130
- print("Create rings buffer to forest edge on one side....")
131
- pandarallel.initialize(progress_bar=False,nb_workers=processes)
132
- worklnbuffer_df_l_ring["mgeometry"] = worklnbuffer_df_l_ring.parallel_apply(
133
- lambda x: multiringbuffer(df=x, nrings=1, ringdist=15), axis=1
134
- )
129
+ print("Create rings buffer to forest edge on both side of centerlines....")
130
+ with Pool(processes) as pool:
131
+ worklnbuffer_df_l_ring["mgeometry"] = pool.map(
132
+ partial(multiringbuffer, nrings=1, ringdist=15),
133
+ worklnbuffer_df_l_ring.geometry,
134
+ chunksize=max(1, len(worklnbuffer_df_l_ring) // (processes * 4)),
135
+ )
136
+ worklnbuffer_df_r_ring["mgeometry"] = pool.map(
137
+ partial(multiringbuffer, nrings=-1, ringdist=-15),
138
+ worklnbuffer_df_r_ring.geometry,
139
+ chunksize=max(1, len(worklnbuffer_df_r_ring) // (processes * 4)),
140
+ )
135
141
 
136
142
  # Explode to create a row for each ring
137
143
  worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.explode("mgeometry")
@@ -143,12 +149,6 @@ def main_canopy_threshold_relative(
143
149
  worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.sort_values(by=["OLnFID", "OLnSEG", "iRing"])
144
150
  worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.reset_index(drop=True)
145
151
 
146
- print("Create rings buffer to forest edge on the other side....")
147
- pandarallel.initialize(progress_bar=False, nb_workers=processes)
148
- worklnbuffer_df_r_ring["mgeometry"] = worklnbuffer_df_r_ring.parallel_apply(
149
- lambda x: multiringbuffer(df=x, nrings=-1, ringdist=-15), axis=1
150
- )
151
-
152
152
  worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.explode("mgeometry") # Explode to create a row for each ring
153
153
  worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.set_geometry("mgeometry")
154
154
  worklnbuffer_df_r_ring = (
@@ -37,6 +37,7 @@ from skimage.graph import MCP_Flexible
37
37
  from pathlib import Path
38
38
  from xrspatial import convolution
39
39
 
40
+ import beratools.core.algo_common as algo_common
40
41
  from beratools.core.algo_centerline import *
41
42
  from beratools.core.canopy_threshold_relative import OperationCancelledException
42
43
  from beratools.core.constants import *
@@ -571,7 +572,6 @@ def process_single_line_relative(segment):
571
572
  # BERA proposed Binary morphology Shrink
572
573
  # fileShrink = ndimage.binary_erosion((Expanded),iterations=Exp_Shk_cell,border_value=1)
573
574
  else:
574
- print("No Expand And Shrink cell performed.")
575
575
 
576
576
  file_shrink = raster_class
577
577
 
@@ -649,6 +649,7 @@ def main_line_footprint_relative(
649
649
  canopy_thresh_percentage:int,
650
650
  processes:int,
651
651
  debug_mode:bool=BT_DEBUGGING,
652
+ merge_by_original_line:bool=False,
652
653
  )-> None:
653
654
  """
654
655
  This function take the centerlines with forest canopy height and distance to edge to generate
@@ -665,6 +666,8 @@ def main_line_footprint_relative(
665
666
  canopy_avoidance: 0 < Ratio < 1 of importance between canopy search radius and Euclidean distance
666
667
  exponent: Affects the cost of vegetated areas in an exponential fashion
667
668
  canopy_thresh_percentage: Percentage as integer range 1-100
669
+ merge_by_original_line: Merge outputs sharing an OLnFID into one feature, otherwise
670
+ keep one footprint and centerline per input line (OLnFID, OLnSEG)
668
671
 
669
672
  Returns:
670
673
  New saved footprints and/or with smoothed centerlines dataset(s).
@@ -839,9 +842,13 @@ def main_line_footprint_relative(
839
842
  resultsR = resultsR.reset_index(drop=True)
840
843
  #
841
844
 
845
+ # one output per input line, or per original line when merging, as in the centerline tool
846
+ dissolve_keys = ["OLnFID"] if merge_by_original_line else ["OLnFID", "OLnSEG"]
842
847
  resultsAll = GeoDataFrame(pd.concat([resultsL, resultsR],ignore_index=True))
843
- dissolved_results = resultsAll.dissolve(by="OLnFID", as_index=False)
848
+ dissolved_results = resultsAll.dissolve(by=dissolve_keys, as_index=False)
844
849
  dissolved_results["geometry"] = dissolved_results["geometry"].buffer(-0.005)
850
+ if merge_by_original_line:
851
+ dissolved_results["OLnSEG"] = -1
845
852
  print("[info]: Saving output ...")
846
853
  out_ft_file, layer = decode_file_layer(out_footprint)
847
854
  dissolved_results.to_file(out_ft_file, layer=layer)
@@ -855,7 +862,7 @@ def main_line_footprint_relative(
855
862
  resultsCR["geometry"] = resultsCR["geometry"].buffer(0.005)
856
863
 
857
864
  resultsCLR = GeoDataFrame(pd.concat([resultsCL, resultsCR]))
858
- resultsCLR = resultsCLR.dissolve(by="OLnFID", as_index=False)
865
+ resultsCLR = resultsCLR.dissolve(by=dissolve_keys, as_index=False)
859
866
  resultsCLR = resultsCLR.sort_values(by=["OLnFID", "OLnSEG"])
860
867
  resultsCLR = resultsCLR.reset_index(drop=True)
861
868
  resultsCLR["geometry"] = resultsCLR["geometry"].buffer(-0.005)
@@ -863,13 +870,21 @@ def main_line_footprint_relative(
863
870
  # save lines to file
864
871
  if out_centerline:
865
872
  out_cl_file, layer = decode_file_layer(out_centerline)
866
- poly_centerline_gpd = find_centerlines(resultsCLR, line_seg, processes)
873
+ guide_lines = line_seg
874
+ if merge_by_original_line:
875
+ # corridor polygons are dissolved per OLnFID, so guide each by all pieces of its original line
876
+ guide_lines = algo_common.merge_lines_by_original_id(
877
+ line_seg, group_field="OLnFID", order_field="OLnSEG"
878
+ ).drop(columns="OLnSEG")
879
+ poly_centerline_gpd = find_centerlines(resultsCLR, guide_lines, processes)
867
880
  poly_gpd = poly_centerline_gpd.copy()
868
881
  centerline_gpd = poly_centerline_gpd.copy()
869
882
 
870
883
  centerline_gpd = centerline_gpd.set_geometry("centerline")
871
884
  centerline_gpd = centerline_gpd.drop(columns=["geometry"])
872
885
  centerline_gpd.crs = poly_centerline_gpd.crs
886
+ if merge_by_original_line:
887
+ centerline_gpd["OLnSEG"] = -1
873
888
 
874
889
  # save polygons from smooth centerline for debug
875
890
  if debug_mode:
@@ -487,7 +487,7 @@
487
487
  {
488
488
  "variable": "proc_segments",
489
489
  "label": "Process Segments",
490
- "description": "Process each segment between vertices separately",
490
+ "description": "Process each segment between vertices separately, then merge the segments back into one centerline per input line",
491
491
  "type": "list",
492
492
  "subtype": "bool",
493
493
  "data": [true, false],
@@ -495,6 +495,17 @@
495
495
  "output": false,
496
496
  "optional": false
497
497
  },
498
+ {
499
+ "variable": "merge_by_original_line",
500
+ "label": "Merge by Original Line",
501
+ "description": "Merge centerlines that share an original line ID (OLnFID) into one line, e.g. lines split at intersections by Check Seed Lines",
502
+ "type": "list",
503
+ "subtype": "bool",
504
+ "data": [true, false],
505
+ "default": false,
506
+ "output": false,
507
+ "optional": true
508
+ },
498
509
  {
499
510
  "variable": "centerline_method",
500
511
  "label": "Centerline Method",
@@ -890,6 +901,17 @@
890
901
  "condition": true
891
902
  }
892
903
  },
904
+ {
905
+ "variable": "merge_by_original_line",
906
+ "label": "Merge by Original Line",
907
+ "description": "Merge footprints that share an original line ID (OLnFID) into one feature, e.g. lines split at intersections by Check Seed Lines",
908
+ "type": "list",
909
+ "subtype": "bool",
910
+ "data": [true, false],
911
+ "default": false,
912
+ "output": false,
913
+ "optional": true
914
+ },
893
915
  {
894
916
  "variable": "out_footprint",
895
917
  "produces": {
@@ -980,6 +1002,17 @@
980
1002
  "output": true,
981
1003
  "optional": true
982
1004
  },
1005
+ {
1006
+ "variable": "merge_by_original_line",
1007
+ "label": "Merge by Original Line",
1008
+ "description": "Merge footprints and centerlines that share an original line ID (OLnFID) into one feature, e.g. lines split at intersections by Check Seed Lines",
1009
+ "type": "list",
1010
+ "subtype": "bool",
1011
+ "data": [true, false],
1012
+ "default": false,
1013
+ "output": false,
1014
+ "optional": true
1015
+ },
983
1016
  {
984
1017
  "variable": "off_ln_dist",
985
1018
  "label": "Offset Line Distance",
@@ -1114,6 +1147,17 @@
1114
1147
  "output": false,
1115
1148
  "optional": true
1116
1149
  },
1150
+ {
1151
+ "variable": "merge_by_original_line",
1152
+ "label": "Merge by Original Line",
1153
+ "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",
1154
+ "type": "list",
1155
+ "subtype": "bool",
1156
+ "data": [true, false],
1157
+ "default": false,
1158
+ "output": false,
1159
+ "optional": true
1160
+ },
1117
1161
  {
1118
1162
  "variable": "out_footprint",
1119
1163
  "produces": {
@@ -478,9 +478,8 @@ class MainWindow(QtWidgets.QMainWindow):
478
478
 
479
479
  # ToolWidgets
480
480
  tool_args = bt.get_bera_tool_args(self.tool_name)
481
+ # saved history is loaded as-is; inputs that can't be found are flagged in red
481
482
  self.tool_widget = ToolWidgets(self.tool_name, tool_args, bt.show_advanced, bt_data_obj=bt)
482
- # at startup, history inputs that no longer exist start empty instead of flagged
483
- self.tool_widget.clear_missing_inputs()
484
483
  self.tool_scroll_area = QtWidgets.QScrollArea()
485
484
  self.tool_scroll_area.setWidgetResizable(True)
486
485
  self.tool_scroll_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
@@ -80,7 +80,8 @@ class ToolWidgets(QtWidgets.QWidget):
80
80
  param_missing = True
81
81
  continue
82
82
  v = widget.get_value()
83
- if v:
83
+ # get_value() returns {variable: ""} for an empty field, which is truthy
84
+ if v and (widget.optional or not self._is_empty_value(widget, v.get(widget.variable))):
84
85
  args.update(v)
85
86
  else:
86
87
  print(f"[Missing argument]: {widget.name} not specified.", "missing")
@@ -189,7 +190,13 @@ class ToolWidgets(QtWidgets.QWidget):
189
190
  self.widget_list.append(widget)
190
191
 
191
192
  self._configure_widget_dependencies()
192
- self._clear_output_paths_for_missing_input_history()
193
+
194
+ @classmethod
195
+ def _is_empty_value(cls, widget, value):
196
+ # an output with a layer but no path encodes as "|layer", so check the path itself
197
+ if isinstance(widget, FileSelector):
198
+ return not cls._extract_file_selector_path(value)
199
+ return value is None or value == ""
193
200
 
194
201
  @staticmethod
195
202
  def _extract_file_selector_path(value):
@@ -201,34 +208,6 @@ class ToolWidgets(QtWidgets.QWidget):
201
208
  return value
202
209
  return ""
203
210
 
204
- def _clear_output_paths_for_missing_input_history(self):
205
- missing_input_paths = set()
206
-
207
- for widget in self.widget_list:
208
- if not isinstance(widget, FileSelector) or widget.output:
209
- continue
210
- if widget.missing_input_error:
211
- missing_input_paths.add(self._extract_file_selector_path(widget.value))
212
-
213
- if not missing_input_paths:
214
- return
215
-
216
- for widget in self.widget_list:
217
- if not isinstance(widget, FileSelector) or not widget.output:
218
- continue
219
- current_path = widget.value.get("path", "") if widget.is_vector else widget.value
220
- if current_path in missing_input_paths:
221
- if widget.is_vector:
222
- widget.set_value({"path": "", "layer": ""})
223
- else:
224
- widget.set_value("")
225
-
226
- def clear_missing_inputs(self):
227
- """Empty input paths that don't exist, so stale history shows blank fields instead of flagged ones."""
228
- for widget in self.widget_list:
229
- if isinstance(widget, FileSelector) and widget.missing_input_error:
230
- widget.set_value({"path": "", "layer": ""} if widget.is_vector else "")
231
-
232
211
  def update_widgets(self, values_dict):
233
212
  for key, value in values_dict.items():
234
213
  for item in self.widget_list:
@@ -603,17 +582,8 @@ class FileSelector(QtWidgets.QWidget):
603
582
  # Input: keep a saved file that no longer exists; it is flagged in the form
604
583
  if not Path(path).exists():
605
584
  return
606
- elif ext == "gpkg":
607
- try:
608
- layers_dict = get_layers(path)
609
- if layer:
610
- valid_layers = [str(k) for k in layers_dict.keys()]
611
- if layer not in valid_layers:
612
- self.value = {"path": "", "layer": ""}
613
- print(f"[Error] Invalid Layer: Layer '{layer}' not found in file: {path}")
614
- except Exception:
615
- self.value = {"path": "", "layer": ""}
616
- print(f"[Error] Layer Error: Could not load layers from file: {path}")
585
+ elif ext == "gpkg" and layer and self._missing_gpkg_layer(path, layer):
586
+ print(f"[Error] Invalid Layer: Layer '{layer}' not found in file: {path}")
617
587
 
618
588
  def setup_ui(self):
619
589
  self.layout = QtWidgets.QHBoxLayout()
@@ -649,13 +619,13 @@ class FileSelector(QtWidgets.QWidget):
649
619
  for layer_name, geometry_type in layers_dict.items():
650
620
  self.layer_combo.addItem(f"{layer_name} ({geometry_type})")
651
621
  self.layer_combo.setVisible(True)
652
- if requested_layer:
653
- index = self._find_layer_index_by_name(requested_layer)
654
- if index >= 0:
655
- self.layer_combo.setCurrentIndex(index)
656
- self.value["layer"] = requested_layer
622
+ index = self._find_layer_index_by_name(requested_layer)
623
+ if index >= 0:
624
+ self.layer_combo.setCurrentIndex(index)
657
625
  self.layer_combo.blockSignals(False)
658
- self.set_layer(self.layer_combo.currentText())
626
+ # a saved layer that's gone is kept, not swapped for the first one
627
+ if index >= 0 or not requested_layer:
628
+ self.set_layer(self.layer_combo.currentText())
659
629
  except Exception:
660
630
  self.layer_combo.blockSignals(False)
661
631
  self.layer_combo.clear()
@@ -707,19 +677,38 @@ class FileSelector(QtWidgets.QWidget):
707
677
  self.in_file.setStyleSheet("")
708
678
  self.in_file.setToolTip(self.description)
709
679
 
680
+ @staticmethod
681
+ def _missing_gpkg_layer(path, layer):
682
+ try:
683
+ return layer not in {str(k) for k in get_layers(path).keys()}
684
+ except Exception:
685
+ return True
686
+
710
687
  def _update_missing_input_warning(self):
711
- """Flag an input path that doesn't exist, keeping it so it can be seen and fixed."""
688
+ """Flag an input path or layer that doesn't exist, keeping it so it can be seen and fixed."""
712
689
  path = self.value.get("path", "") if self.is_vector else self.value
690
+ layer = self.value.get("layer", "") if self.is_vector else ""
713
691
  was_missing = bool(self.missing_input_error)
714
- if path and isinstance(path, str) and not self.output and not Path(path).exists():
715
- kind = "Folder" if self.is_directory else "File"
716
- self.missing_input_error = f"{kind} not found: {path}"
717
- self.in_file.setStyleSheet("QLineEdit { background-color: #f8d7da; }")
718
- self.in_file.setToolTip(self.missing_input_error)
719
- return
692
+ if path and isinstance(path, str) and not self.output:
693
+ if not Path(path).exists():
694
+ kind = "Folder" if self.is_directory else "File"
695
+ self.missing_input_error = f"{kind} not found: {path}"
696
+ elif layer and path.lower().endswith(".gpkg") and self._missing_gpkg_layer(path, layer):
697
+ self.missing_input_error = f"Layer '{layer}' not found in: {path}"
698
+ self.layer_combo.setStyleSheet("QComboBox { background-color: #f8d7da; }")
699
+ self.layer_combo.setToolTip(self.missing_input_error)
700
+ else:
701
+ self.missing_input_error = ""
702
+ if self.missing_input_error:
703
+ self.in_file.setStyleSheet("QLineEdit { background-color: #f8d7da; }")
704
+ self.in_file.setToolTip(self.missing_input_error)
705
+ return
720
706
 
721
707
  self.missing_input_error = ""
722
708
  if was_missing:
709
+ if not self.output:
710
+ self.layer_combo.setStyleSheet("")
711
+ self.layer_combo.setToolTip("Select layer")
723
712
  if self.input_geometry_error:
724
713
  self.in_file.setToolTip(self.input_geometry_error)
725
714
  else:
@@ -802,8 +791,13 @@ class FileSelector(QtWidgets.QWidget):
802
791
  self.layer_combo.setCurrentText(selected_layer)
803
792
  else:
804
793
  index = self._find_layer_index_by_name(selected_layer)
805
- if index >= 0:
806
- self.layer_combo.setCurrentIndex(index)
794
+ if index < 0 and not is_output and self._loading:
795
+ # keep a saved layer that's gone so it is flagged instead of silently replaced
796
+ if self.layer_combo.itemText(0) == self.NO_COMPATIBLE_LAYER_TEXT:
797
+ self.layer_combo.clear()
798
+ self.layer_combo.insertItem(0, selected_layer)
799
+ index = 0
800
+ self.layer_combo.setCurrentIndex(index)
807
801
  self.layer_combo.adjustSize()
808
802
  self._update_layer_overwrite_warning()
809
803
  if self.is_vector and not is_output:
@@ -1174,6 +1168,8 @@ class FileSelector(QtWidgets.QWidget):
1174
1168
  else:
1175
1169
  self.selected_layer = layer
1176
1170
  self._update_layer_overwrite_warning()
1171
+ if not self.output:
1172
+ self._update_missing_input_warning()
1177
1173
 
1178
1174
  def get_value(self):
1179
1175
  #Return the folder directly:
@@ -25,6 +25,7 @@ from beratools.core.algo_canopy_footprint_absolute import (
25
25
  FootprintCanopyAdaptive,
26
26
  cast_request_types,
27
27
  generate_absolute_line_class_list,
28
+ merge_footprints_by_original_line,
28
29
  process_single_absolute_line,
29
30
  save_aux_layers,
30
31
  save_main_footprint,
@@ -63,6 +64,7 @@ def canopy_footprint_abs(
63
64
  footprint_simplify_length=0.5,
64
65
  smooth_footprint_polygon=False,
65
66
  footprint_polygon_smooth_iterations=1,
67
+ merge_by_original_line=False,
66
68
  processes=0,
67
69
  call_mode=CallMode.CLI,
68
70
  log_level="INFO",
@@ -89,6 +91,7 @@ def canopy_footprint_abs(
89
91
  footprint_simplify_length=footprint_simplify_length,
90
92
  smooth_footprint_polygon=smooth_footprint_polygon,
91
93
  footprint_polygon_smooth_iterations=footprint_polygon_smooth_iterations,
94
+ merge_by_original_line=merge_by_original_line,
92
95
  processes=processes,
93
96
  call_mode=call_mode,
94
97
  log_level=log_level,
@@ -135,6 +138,10 @@ def canopy_footprint_abs(
135
138
  for message in result.messages:
136
139
  print(message)
137
140
 
141
+ # one footprint per input line, or per original line when merging, as in the centerline tool
142
+ if request.merge_by_original_line:
143
+ result.footprints_gdf = merge_footprints_by_original_line(result.footprints_gdf, printer=print)
144
+
138
145
  save_main_footprint(
139
146
  result,
140
147
  request.out_footprint,
@@ -69,7 +69,7 @@ def generate_line_class_list(
69
69
  corridor_polygon_smooth_iterations=1,
70
70
  ) -> list:
71
71
  line_classes = []
72
- line_list = algo_common.prepare_lines_gdf(in_vector, layer, proc_segments)
72
+ line_list = algo_common.prepare_lines_gdf(in_vector, layer, proc_segments, tag_source_rows=True)
73
73
 
74
74
  for item in line_list:
75
75
  line_classes.append(
@@ -99,6 +99,44 @@ def generate_line_class_list(
99
99
  return line_classes
100
100
 
101
101
 
102
+ MERGE_ORDER_FIELD = "BT_MERGE_ORDER"
103
+
104
+
105
+ def _add_merge_order(gdf, merge_by_original_line):
106
+ """Number the pieces in the order they join: by input row and vertex, or along the original line."""
107
+ if gdf is None or gdf.empty:
108
+ return gdf
109
+ gdf = gdf.copy()
110
+ if merge_by_original_line:
111
+ group_field = "OLnFID"
112
+ sort_fields = [algo_common.SOURCE_SEG_FIELD, algo_common.SOURCE_ROW_FIELD, "OLnSEG"]
113
+ else:
114
+ group_field = algo_common.SOURCE_ROW_FIELD
115
+ sort_fields = ["OLnSEG"]
116
+ ordered = gdf.sort_values(sort_fields, kind="stable")
117
+ gdf[MERGE_ORDER_FIELD] = ordered.groupby(group_field, sort=False).cumcount()
118
+ return gdf
119
+
120
+
121
+ def _restore_merged_ids(gdf, merge_by_original_line):
122
+ """Give merged rows their input OLnSEG back (or -1 for a whole original line) and drop helper fields."""
123
+ if gdf is None or gdf.empty:
124
+ return gdf
125
+ gdf = gdf.copy()
126
+ if merge_by_original_line:
127
+ gdf["OLnSEG"] = -1
128
+ elif algo_common.SOURCE_SEG_FIELD in gdf.columns:
129
+ gdf["OLnSEG"] = gdf[algo_common.SOURCE_SEG_FIELD]
130
+ return _drop_helper_fields(gdf)
131
+
132
+
133
+ def _drop_helper_fields(gdf):
134
+ if gdf is None:
135
+ return gdf
136
+ helper_fields = [algo_common.SOURCE_ROW_FIELD, algo_common.SOURCE_SEG_FIELD, MERGE_ORDER_FIELD]
137
+ return gdf.drop(columns=[f for f in helper_fields if f in gdf.columns])
138
+
139
+
102
140
  def process_single_line_class(seed_line):
103
141
  try:
104
142
  # OLnFID and OLnSEG are added in previous QC stage.
@@ -117,6 +155,7 @@ def centerline(
117
155
  line_radius,
118
156
  proc_segments,
119
157
  out_line,
158
+ merge_by_original_line=False,
120
159
  centerline_method=bt_const.CENTERLINE_METHOD.value,
121
160
  guided_strategy=bt_const.CENTERLINE_GUIDED_STRATEGY.value,
122
161
  simplify_centerline=False,
@@ -158,6 +197,7 @@ def centerline(
158
197
  centerline_method_value = centerline_method.value
159
198
  chm_mode_value = chm_mode.value
160
199
  proc_segments = _to_bool(proc_segments)
200
+ merge_by_original_line = _to_bool(merge_by_original_line)
161
201
 
162
202
  in_file, in_layer = sp_common.decode_file_layer(in_line)
163
203
  out_file, out_layer = sp_common.decode_file_layer(out_line)
@@ -282,15 +322,24 @@ def centerline(
282
322
  dissolved_cl_orig=centerline_gdf
283
323
  dissolved_lcp_orig=lc_path_gdf
284
324
  dissolved_corridor_orig=corridor_gdf
325
+ # whole lines need no merging, so they are saved as they are
326
+ dissolved_cl = centerline_gdf
327
+ dissolved_lcp = lc_path_gdf
328
+ dissolved_corridor = corridor_gdf
285
329
  aux_file = algo_common.get_aux_path(out_file)
286
- if proc_segments:
330
+ if proc_segments or merge_by_original_line:
287
331
  logger.info("Dissolving segments...")
332
+ dissolved_cl_orig, dissolved_lcp_orig, dissolved_corridor_orig = (
333
+ _add_merge_order(gdf, merge_by_original_line)
334
+ for gdf in (centerline_gdf, lc_path_gdf, corridor_gdf)
335
+ )
336
+ group_field = "OLnFID" if merge_by_original_line else algo_common.SOURCE_ROW_FIELD
288
337
 
289
338
  dissolved_cl = (
290
339
  algo_common.merge_lines_by_original_id(
291
340
  line_gdf=dissolved_cl_orig,
292
- group_field="OLnFID",
293
- order_field="OLnSEG",
341
+ group_field=group_field,
342
+ order_field=MERGE_ORDER_FIELD,
294
343
  max_bridge_gap=max(
295
344
  cell_size * 1.5,
296
345
  0.5,
@@ -311,8 +360,8 @@ def centerline(
311
360
  dissolved_lcp = (
312
361
  algo_common.merge_lines_by_original_id(
313
362
  line_gdf=dissolved_lcp_orig,
314
- group_field="OLnFID",
315
- order_field="OLnSEG",
363
+ group_field=group_field,
364
+ order_field=MERGE_ORDER_FIELD,
316
365
  max_bridge_gap=max(
317
366
  cell_size * 0.75,
318
367
  0.05,
@@ -326,8 +375,8 @@ def centerline(
326
375
  dissolved_corridor = (
327
376
  algo_common.merge_corridors_by_original_id(
328
377
  dissolved_corridor_orig,
329
- group_field="OLnFID",
330
- order_field="OLnSEG",
378
+ group_field=group_field,
379
+ order_field=MERGE_ORDER_FIELD,
331
380
  )
332
381
  )
333
382
 
@@ -360,25 +409,44 @@ def centerline(
360
409
 
361
410
  logger.info("Dissolving segments...Done")
362
411
 
412
+ dissolved_cl, dissolved_lcp, dissolved_corridor = (
413
+ _restore_merged_ids(gdf, merge_by_original_line)
414
+ for gdf in (dissolved_cl, dissolved_lcp, dissolved_corridor)
415
+ )
416
+ centerline_gdf, lc_path_gdf, corridor_gdf = (
417
+ _drop_helper_fields(gdf) for gdf in (centerline_gdf, lc_path_gdf, corridor_gdf)
418
+ )
419
+
363
420
  if simplify_enabled and diameter > 0:
364
421
  temp_file = tool_geo_simplify.build_temp_output_same_folder(
365
422
  out_file,
366
423
  prefix=f"{Path(out_file).stem}_centerline_tmp_",
367
424
  )
425
+ # geo-simplify recreates its --output file, so never point it at out_file
426
+ # directly or every other layer in the GeoPackage is wiped.
427
+ temp_out_file = tool_geo_simplify.build_temp_output_same_folder(
428
+ out_file,
429
+ prefix=f"{Path(out_file).stem}_centerline_simplified_tmp_",
430
+ )
368
431
  temp_layer = "centerline_temp"
369
432
  try:
370
433
  dissolved_cl.to_file(temp_file.as_posix(), layer=temp_layer,overwrite=True)
434
+ temp_out_file.unlink()
371
435
  tool_geo_simplify.run_reduce_bend(
372
436
  input_file=temp_file,
373
437
  in_layer=temp_layer,
374
- output_file=out_file,
438
+ output_file=temp_out_file.as_posix(),
375
439
  out_layer=out_layer,
376
440
  diameter=diameter,
377
441
  smooth_line=True,
378
442
  )
443
+ simplified_cl = gpd.read_file(temp_out_file, layer=out_layer)
444
+ algo_common.drop_layer_if_exists(out_file, out_layer)
445
+ simplified_cl.to_file(out_file, layer=out_layer)
379
446
  finally:
380
- if temp_file.exists():
381
- temp_file.unlink()
447
+ for path in (temp_file, temp_out_file):
448
+ if path.exists():
449
+ path.unlink()
382
450
  else:
383
451
  if simplify_enabled and diameter == 0:
384
452
  print("Centerline simplify enabled with diameter 0; skipping simplify step.")
@@ -697,6 +697,10 @@ def check_seed_line(
697
697
  gdf = _ensure_gdf(split_out, prev_crs)
698
698
  split_min_length = config.minimum_line_length if config.remove_short_lines else bt_const.SMALL_BUFFER
699
699
  gdf, removed_gdf = _clean_line_geometries_min_length_m(gdf, split_min_length)
700
+ # pieces keep their line's OLnSEG, so number them along each original line
701
+ if "OLnFID" in gdf.columns and "OLnSEG" in gdf.columns:
702
+ gdf = gdf.sort_values(["OLnFID", "OLnSEG"], kind="stable").reset_index(drop=True)
703
+ gdf["OLnSEG"] = gdf.groupby("OLnFID").cumcount()
700
704
  gdf = gdf.reset_index(drop=True)
701
705
  _log_step(
702
706
  8, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps
@@ -273,6 +273,7 @@ def ground_footprint(
273
273
  out_footprint,
274
274
  in_layer_lc_path="least_cost_path",
275
275
  merge_group=True,
276
+ merge_by_original_line=False,
276
277
  width_percentile=75,
277
278
  trim_output=True,
278
279
  processes=0,
@@ -304,6 +305,14 @@ def ground_footprint(
304
305
  min_value=bt_const.SMALL_BUFFER,
305
306
  )
306
307
 
308
+ # group by original line, as the centerline tool merges, so pieces share one footprint
309
+ merge_by_original_line = str(merge_by_original_line).strip().lower() in ("true", "1", "yes")
310
+ if merge_by_original_line and "OLnFID" not in line_gdf.columns:
311
+ print("[Warning]: OLnFID not found in input lines; lines are not merged by original line.")
312
+ merge_by_original_line = False
313
+ if merge_by_original_line:
314
+ line_gdf[bt_const.BT_GROUP] = line_gdf["OLnFID"]
315
+
307
316
  if bt_const.BT_GROUP not in line_gdf.columns:
308
317
  line_gdf[bt_const.BT_GROUP] = range(1, len(line_gdf) + 1)
309
318
 
@@ -314,6 +323,8 @@ def ground_footprint(
314
323
  lc_path_gdf = lc_path_gdf.rename(columns={"fid": "orig_fid"})
315
324
  lc_path_gdf = algo_common.clean_geometries(lc_path_gdf, stage="input")
316
325
  lc_path_gdf = lc_path_gdf.reset_index(drop=True)
326
+ if merge_by_original_line and "OLnFID" in lc_path_gdf.columns:
327
+ lc_path_gdf[bt_const.BT_GROUP] = lc_path_gdf["OLnFID"]
317
328
  except (ValueError, OSError, pyogrio.errors.DataLayerError):
318
329
  print(f"Layer '{in_layer_lc_path}' not found in {in_file}, skipping least cost path logic.")
319
330
  use_least_cost_path = False
@@ -330,6 +341,9 @@ def ground_footprint(
330
341
  poly_gdf = algo_common.clean_geometries(poly_gdf, stage="input")
331
342
  poly_gdf = poly_gdf.reset_index(drop=True)
332
343
  poly_gdf["geometry"] = poly_gdf["geometry"].apply(algo_common.remove_holes)
344
+ # polygons are matched to lines by BT_GROUP, so keep their groups the same as the lines'
345
+ if merge_by_original_line and "OLnFID" in poly_gdf.columns:
346
+ poly_gdf[bt_const.BT_GROUP] = poly_gdf["OLnFID"]
333
347
 
334
348
  if not sp_common.compare_crs(
335
349
  sp_common.vector_crs(in_file, in_layer), sp_common.vector_crs(in_fp_file, in_layer_fp)
@@ -32,7 +32,9 @@
32
32
 
33
33
  from beratools.core.line_footprint_functions import *
34
34
  from beratools.core.canopy_threshold_relative import *
35
+ from beratools.utility.spatial_common import decode_file_layer
35
36
  import time
37
+ from pathlib import Path
36
38
 
37
39
 
38
40
  def line_footprint_relative(
@@ -52,6 +54,7 @@ def line_footprint_relative(
52
54
  processes,
53
55
  call_mode,
54
56
  log_level,
57
+ merge_by_original_line=False,
55
58
  ):
56
59
  """Create canopy footprint polygons using per-line relative canopy thresholds.
57
60
 
@@ -91,9 +94,21 @@ def line_footprint_relative(
91
94
  processes: Number of parallel processes.
92
95
  call_mode: How the tool was invoked (see `CallMode`).
93
96
  log_level: Logging level. Currently not used.
97
+ merge_by_original_line: Merge footprints and centerlines sharing an original
98
+ line ID (OLnFID) into one feature; otherwise keep one per input line.
94
99
  """
95
100
  verbose = True if call_mode == CallMode.GUI.value else False
96
101
 
102
+ # Write the intermediate dynamic centerline as a layer in the output footprint's file,
103
+ # so no extra file is created and input data folders are never written to.
104
+ in_file, in_layer = decode_file_layer(in_line)
105
+ out_ft_file = decode_file_layer(out_footprint)[0]
106
+ dyn_layer = "DynCanTh_" + (in_layer or Path(in_file).stem)
107
+ if Path(out_ft_file).suffix.lower() != ".gpkg":
108
+ # a shapefile holds one layer, so use a GeoPackage beside it
109
+ out_ft_file = Path(out_ft_file).with_name(dyn_layer + ".gpkg").as_posix()
110
+ out_dyn_centerline = f"{out_ft_file}|{dyn_layer}"
111
+
97
112
  dy_cl_line = main_canopy_threshold_relative(
98
113
  in_line=in_line,
99
114
  in_chm=in_chm,
@@ -101,7 +116,7 @@ def line_footprint_relative(
101
116
  canopy_thresh_percentage=int(float(canopy_thresh_percentage)),
102
117
  full_step=bool(True),
103
118
  processes=int(float(processes)),
104
-
119
+ out_dyn_centerline=out_dyn_centerline,
105
120
  )
106
121
 
107
122
  if not dy_cl_line:
@@ -122,6 +137,7 @@ def line_footprint_relative(
122
137
  full_step=bool(True),
123
138
  canopy_thresh_percentage=int(float(canopy_thresh_percentage)),
124
139
  processes=int(float(processes)),
140
+ merge_by_original_line=str(merge_by_original_line).strip().lower() in ("true", "1", "yes"),
125
141
  )
126
142
 
127
143
  if __name__ == "__main__":
@@ -29,7 +29,7 @@ classifiers = [
29
29
  dependencies = [
30
30
  "gdal>=3.12,<4; platform_system != 'Windows'",
31
31
  "geopandas",
32
- "pandas>=2.0,<3",
32
+ "pandas>=2.0",
33
33
  "networkit",
34
34
  "numpy>=1.26,<2.4",
35
35
  "pyogrio>=0.12.0",
@@ -39,8 +39,8 @@ dependencies = [
39
39
  "tabulate",
40
40
  "tqdm",
41
41
  "xarray-spatial",
42
- "pandarallel",
43
42
  "igraph",
43
+ "psutil"
44
44
  ]
45
45
 
46
46
  [project.optional-dependencies]
File without changes
File without changes