BERATools 0.6.0__tar.gz → 0.6.2__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.2}/PKG-INFO +15 -7
  2. {beratools-0.6.0 → beratools-0.6.2}/README.md +12 -4
  3. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_canopy_footprint_absolute.py +26 -0
  4. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_centerline.py +3 -0
  5. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_common.py +31 -2
  6. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_merge_lines.py +5 -4
  7. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_seed_line_correction.py +5 -4
  8. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_vertex_optimization.py +5 -4
  9. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/canopy_threshold_relative.py +46 -46
  10. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/line_footprint_functions.py +19 -4
  11. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/assets/beratools.json +45 -1
  12. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/bt_gui_main.py +1 -2
  13. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/tool_widgets.py +52 -56
  14. {beratools-0.6.0 → beratools-0.6.2}/beratools/tools/canopy_footprint_absolute.py +7 -0
  15. {beratools-0.6.0 → beratools-0.6.2}/beratools/tools/centerline.py +79 -11
  16. {beratools-0.6.0 → beratools-0.6.2}/beratools/tools/check_seed_line.py +4 -0
  17. {beratools-0.6.0 → beratools-0.6.2}/beratools/tools/ground_footprint.py +14 -0
  18. {beratools-0.6.0 → beratools-0.6.2}/beratools/tools/line_footprint_relative.py +17 -1
  19. {beratools-0.6.0 → beratools-0.6.2}/pyproject.toml +2 -2
  20. {beratools-0.6.0 → beratools-0.6.2}/.gitignore +0 -0
  21. {beratools-0.6.0 → beratools-0.6.2}/LICENSE +0 -0
  22. {beratools-0.6.0 → beratools-0.6.2}/beratools/__init__.py +0 -0
  23. {beratools-0.6.0 → beratools-0.6.2}/beratools/cli/__init__.py +0 -0
  24. {beratools-0.6.0 → beratools-0.6.2}/beratools/cli/entry.py +0 -0
  25. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/__init__.py +0 -0
  26. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_astar.py +0 -0
  27. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_check_seed_line.py +0 -0
  28. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_check_seed_line_validate.py +0 -0
  29. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_cost.py +0 -0
  30. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_dijkstra.py +0 -0
  31. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_geometry.py +0 -0
  32. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_line_grouping.py +0 -0
  33. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_split_with_lines.py +0 -0
  34. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/algo_vertex_preclean.py +0 -0
  35. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/alt_spatial_common.py +0 -0
  36. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/constants.py +0 -0
  37. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/logger.py +0 -0
  38. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/pipeline.py +0 -0
  39. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/tool_base.py +0 -0
  40. {beratools-0.6.0 → beratools-0.6.2}/beratools/core/tool_geo_simplify.py +0 -0
  41. {beratools-0.6.0 → beratools-0.6.2}/beratools/external/__init__.py +0 -0
  42. {beratools-0.6.0 → beratools-0.6.2}/beratools/external/geo_simplify/geo-simplify-linux-x64 +0 -0
  43. {beratools-0.6.0 → beratools-0.6.2}/beratools/external/geo_simplify/geo-simplify-win-x64.exe +0 -0
  44. {beratools-0.6.0 → beratools-0.6.2}/beratools/external/polygon_centerline/LICENSE.md +0 -0
  45. {beratools-0.6.0 → beratools-0.6.2}/beratools/external/polygon_centerline/UPSTREAM.md +0 -0
  46. {beratools-0.6.0 → beratools-0.6.2}/beratools/external/polygon_centerline/__init__.py +0 -0
  47. {beratools-0.6.0 → beratools-0.6.2}/beratools/external/polygon_centerline/_src.py +0 -0
  48. {beratools-0.6.0 → beratools-0.6.2}/beratools/external/polygon_centerline/exceptions.py +0 -0
  49. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/assets/BERALogo.ico +0 -0
  50. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/assets/BERALogo.png +0 -0
  51. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/assets/BERA_GUI_Main.png +0 -0
  52. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/assets/BERA_Splash.gif +0 -0
  53. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/assets/BERA_WizardImage.png +0 -0
  54. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/assets/closed.gif +0 -0
  55. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/assets/closed.png +0 -0
  56. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/assets/gui.json +0 -0
  57. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/assets/open.gif +0 -0
  58. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/assets/open.png +0 -0
  59. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/assets/tool.gif +0 -0
  60. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/assets/tool.png +0 -0
  61. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/bt_data.py +0 -0
  62. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/geometry_types.py +0 -0
  63. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/main.py +0 -0
  64. {beratools-0.6.0 → beratools-0.6.2}/beratools/gui/pipeline_panel.py +0 -0
  65. {beratools-0.6.0 → beratools-0.6.2}/beratools/tools/__init__.py +0 -0
  66. {beratools-0.6.0 → beratools-0.6.2}/beratools/tools/common.py +0 -0
  67. {beratools-0.6.0 → beratools-0.6.2}/beratools/tools/tool_template.py +0 -0
  68. {beratools-0.6.0 → beratools-0.6.2}/beratools/tools/vertex_optimization.py +0 -0
  69. {beratools-0.6.0 → beratools-0.6.2}/beratools/utility/env_checks.py +0 -0
  70. {beratools-0.6.0 → beratools-0.6.2}/beratools/utility/spatial_common.py +0 -0
  71. {beratools-0.6.0 → beratools-0.6.2}/beratools/utility/tool_args.py +0 -0
  72. {beratools-0.6.0 → beratools-0.6.2}/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.2
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
@@ -59,8 +59,8 @@ BERA Tools is successor of [Forest Line Mapper](https://github.com/appliedgrg/fl
59
59
 
60
60
  [![Python Integration Tests](https://img.shields.io/github/actions/workflow/status/BERATool/beratools/python-integration-tests.yml?branch=main)](https://github.com/BERATool/beratools/actions/workflows/python-integration-tests.yml)
61
61
  [![GitHub Pages](https://img.shields.io/github/deployments/BERATool/beratools/github-pages?label=docs)](https://beratool.github.io/beratools/)
62
- [![Conda Version](https://img.shields.io/conda/v/AppliedGRG/beratools)](https://anaconda.org/AppliedGRG/beratools)
63
- [![PyPI](https://img.shields.io/pypi/v/BERATools)](https://pypi.org/project/BERATools/)
62
+ [![Conda Version](https://img.shields.io/conda/v/bera_tools/beratools?cacheSeconds=3600)](https://anaconda.org/bera_tools/beratools)
63
+ [![PyPI](https://img.shields.io/pypi/v/BERATools?cacheSeconds=3600)](https://pypi.org/project/BERATools/)
64
64
  [![Python Version](https://img.shields.io/badge/python-3.12--3.14-blue)](https://www.python.org/downloads/)
65
65
  [![License: GPL-3.0](https://img.shields.io/badge/License-GPL%203.0-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
66
66
 
@@ -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
@@ -6,8 +6,8 @@ BERA Tools is successor of [Forest Line Mapper](https://github.com/appliedgrg/fl
6
6
 
7
7
  [![Python Integration Tests](https://img.shields.io/github/actions/workflow/status/BERATool/beratools/python-integration-tests.yml?branch=main)](https://github.com/BERATool/beratools/actions/workflows/python-integration-tests.yml)
8
8
  [![GitHub Pages](https://img.shields.io/github/deployments/BERATool/beratools/github-pages?label=docs)](https://beratool.github.io/beratools/)
9
- [![Conda Version](https://img.shields.io/conda/v/AppliedGRG/beratools)](https://anaconda.org/AppliedGRG/beratools)
10
- [![PyPI](https://img.shields.io/pypi/v/BERATools)](https://pypi.org/project/BERATools/)
9
+ [![Conda Version](https://img.shields.io/conda/v/bera_tools/beratools?cacheSeconds=3600)](https://anaconda.org/bera_tools/beratools)
10
+ [![PyPI](https://img.shields.io/pypi/v/BERATools?cacheSeconds=3600)](https://pypi.org/project/BERATools/)
11
11
  [![Python Version](https://img.shields.io/badge/python-3.12--3.14-blue)](https://www.python.org/downloads/)
12
12
  [![License: GPL-3.0](https://img.shields.io/badge/License-GPL%203.0-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
13
13
 
@@ -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)