BERATools 0.5.4__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 (73) hide show
  1. {beratools-0.5.4 → beratools-0.6.1}/.gitignore +3 -0
  2. {beratools-0.5.4 → beratools-0.6.1}/PKG-INFO +27 -3
  3. {beratools-0.5.4 → beratools-0.6.1}/README.md +24 -1
  4. {beratools-0.5.4 → beratools-0.6.1}/beratools/cli/entry.py +1 -0
  5. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_canopy_footprint_absolute.py +26 -0
  6. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_centerline.py +11 -4
  7. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_common.py +31 -2
  8. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_merge_lines.py +5 -4
  9. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_seed_line_correction.py +5 -4
  10. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_vertex_optimization.py +5 -4
  11. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/canopy_threshold_relative.py +46 -46
  12. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/line_footprint_functions.py +19 -4
  13. beratools-0.6.1/beratools/core/pipeline.py +249 -0
  14. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/assets/beratools.json +73 -1
  15. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/bt_data.py +10 -1
  16. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/bt_gui_main.py +226 -56
  17. beratools-0.6.1/beratools/gui/main.py +39 -0
  18. beratools-0.6.1/beratools/gui/pipeline_panel.py +320 -0
  19. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/tool_widgets.py +179 -74
  20. {beratools-0.5.4 → beratools-0.6.1}/beratools/tools/canopy_footprint_absolute.py +7 -0
  21. {beratools-0.5.4 → beratools-0.6.1}/beratools/tools/centerline.py +79 -11
  22. {beratools-0.5.4 → beratools-0.6.1}/beratools/tools/check_seed_line.py +4 -0
  23. {beratools-0.5.4 → beratools-0.6.1}/beratools/tools/ground_footprint.py +14 -0
  24. {beratools-0.5.4 → beratools-0.6.1}/beratools/tools/line_footprint_relative.py +55 -1
  25. {beratools-0.5.4 → beratools-0.6.1}/beratools/utility/env_checks.py +22 -1
  26. {beratools-0.5.4 → beratools-0.6.1}/beratools/utility/tool_args.py +2 -0
  27. {beratools-0.5.4 → beratools-0.6.1}/pyproject.toml +2 -1
  28. beratools-0.5.4/beratools/gui/main.py +0 -23
  29. {beratools-0.5.4 → beratools-0.6.1}/LICENSE +0 -0
  30. {beratools-0.5.4 → beratools-0.6.1}/beratools/__init__.py +0 -0
  31. {beratools-0.5.4 → beratools-0.6.1}/beratools/cli/__init__.py +0 -0
  32. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/__init__.py +0 -0
  33. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_astar.py +0 -0
  34. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_check_seed_line.py +0 -0
  35. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_check_seed_line_validate.py +0 -0
  36. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_cost.py +0 -0
  37. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_dijkstra.py +0 -0
  38. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_geometry.py +0 -0
  39. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_line_grouping.py +0 -0
  40. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_split_with_lines.py +0 -0
  41. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/algo_vertex_preclean.py +0 -0
  42. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/alt_spatial_common.py +0 -0
  43. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/constants.py +0 -0
  44. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/logger.py +0 -0
  45. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/tool_base.py +0 -0
  46. {beratools-0.5.4 → beratools-0.6.1}/beratools/core/tool_geo_simplify.py +0 -0
  47. {beratools-0.5.4 → beratools-0.6.1}/beratools/external/__init__.py +0 -0
  48. {beratools-0.5.4 → beratools-0.6.1}/beratools/external/geo_simplify/geo-simplify-linux-x64 +0 -0
  49. {beratools-0.5.4 → beratools-0.6.1}/beratools/external/geo_simplify/geo-simplify-win-x64.exe +0 -0
  50. {beratools-0.5.4 → beratools-0.6.1}/beratools/external/polygon_centerline/LICENSE.md +0 -0
  51. {beratools-0.5.4 → beratools-0.6.1}/beratools/external/polygon_centerline/UPSTREAM.md +0 -0
  52. {beratools-0.5.4 → beratools-0.6.1}/beratools/external/polygon_centerline/__init__.py +0 -0
  53. {beratools-0.5.4 → beratools-0.6.1}/beratools/external/polygon_centerline/_src.py +0 -0
  54. {beratools-0.5.4 → beratools-0.6.1}/beratools/external/polygon_centerline/exceptions.py +0 -0
  55. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/assets/BERALogo.ico +0 -0
  56. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/assets/BERALogo.png +0 -0
  57. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/assets/BERA_GUI_Main.png +0 -0
  58. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/assets/BERA_Splash.gif +0 -0
  59. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/assets/BERA_WizardImage.png +0 -0
  60. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/assets/closed.gif +0 -0
  61. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/assets/closed.png +0 -0
  62. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/assets/gui.json +0 -0
  63. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/assets/open.gif +0 -0
  64. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/assets/open.png +0 -0
  65. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/assets/tool.gif +0 -0
  66. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/assets/tool.png +0 -0
  67. {beratools-0.5.4 → beratools-0.6.1}/beratools/gui/geometry_types.py +0 -0
  68. {beratools-0.5.4 → beratools-0.6.1}/beratools/tools/__init__.py +0 -0
  69. {beratools-0.5.4 → beratools-0.6.1}/beratools/tools/common.py +0 -0
  70. {beratools-0.5.4 → beratools-0.6.1}/beratools/tools/tool_template.py +0 -0
  71. {beratools-0.5.4 → beratools-0.6.1}/beratools/tools/vertex_optimization.py +0 -0
  72. {beratools-0.5.4 → beratools-0.6.1}/beratools/utility/spatial_common.py +0 -0
  73. {beratools-0.5.4 → beratools-0.6.1}/beratools/utility/unit_conversion.py +0 -0
@@ -29,3 +29,6 @@ _build
29
29
  .aider.*
30
30
  .ignore
31
31
  /docs/site
32
+
33
+ # Hydra run logs from examples/full_workflow.py
34
+ outputs/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: BERATools
3
- Version: 0.5.4
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,7 +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
23
+ Requires-Dist: pandas>=2.0
24
+ Requires-Dist: psutil
24
25
  Requires-Dist: pyogrio>=0.12.0
25
26
  Requires-Dist: pyqt5
26
27
  Requires-Dist: rasterio>=1.5.0
@@ -74,7 +75,7 @@ Here are the ways to install BERA Tools:
74
75
 
75
76
  ### Windows Installer
76
77
 
77
- Windows installer is provided with releases. Check the [latest release](https://github.com/BERATool/beratools/releases/latest). Official Windows installers are signed under the BERA Tools [Code signing policy](CODE_SIGNING_POLICY.md).
78
+ Windows installer is provided with releases. Check the [latest release](https://github.com/BERATool/beratools/releases/latest). Signing is currently off by default; unsigned assets are named `beratools-installer-x.y.z-unsigned.exe` and identified as unsigned in the release notes. Windows may display an unknown-publisher or SmartScreen warning. Maintainers can enable SignPath per run according to the BERA Tools [Code signing policy](CODE_SIGNING_POLICY.md).
78
79
 
79
80
  ### Install with Anaconda
80
81
 
@@ -103,6 +104,29 @@ Install with Anaconda works on Windows, macOS, and Linux.
103
104
 
104
105
  For more information about installation, check the [BERA Tools Installation](https://beratool.github.io/beratools/user/installation/).
105
106
 
107
+ ## Pipelines
108
+
109
+ The **Pipeline** tab, next to **Tool history** in the GUI, chains tools into steps that run one after
110
+ another. Drag tools in from the tool tree, set each step's parameters in the tool form, and link a
111
+ step's inputs to an earlier step's output. Each input links to the latest earlier step that makes what
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.
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:
123
+
124
+ ```bash
125
+ $ python -m beratools.core.pipeline my_pipeline.json --processes 4
126
+ ```
127
+
128
+ See [Building a pipeline](https://beratool.github.io/beratools/user_guide/#building-a-pipeline).
129
+
106
130
  ## BERA Tools Guide
107
131
 
108
132
  Check the online [BERA Tools Guide](https://beratool.github.io/beratools/) for user, developer and technical guides.
@@ -22,7 +22,7 @@ Here are the ways to install BERA Tools:
22
22
 
23
23
  ### Windows Installer
24
24
 
25
- Windows installer is provided with releases. Check the [latest release](https://github.com/BERATool/beratools/releases/latest). Official Windows installers are signed under the BERA Tools [Code signing policy](CODE_SIGNING_POLICY.md).
25
+ Windows installer is provided with releases. Check the [latest release](https://github.com/BERATool/beratools/releases/latest). Signing is currently off by default; unsigned assets are named `beratools-installer-x.y.z-unsigned.exe` and identified as unsigned in the release notes. Windows may display an unknown-publisher or SmartScreen warning. Maintainers can enable SignPath per run according to the BERA Tools [Code signing policy](CODE_SIGNING_POLICY.md).
26
26
 
27
27
  ### Install with Anaconda
28
28
 
@@ -51,6 +51,29 @@ Install with Anaconda works on Windows, macOS, and Linux.
51
51
 
52
52
  For more information about installation, check the [BERA Tools Installation](https://beratool.github.io/beratools/user/installation/).
53
53
 
54
+ ## Pipelines
55
+
56
+ The **Pipeline** tab, next to **Tool history** in the GUI, chains tools into steps that run one after
57
+ another. Drag tools in from the tool tree, set each step's parameters in the tool form, and link a
58
+ step's inputs to an earlier step's output. Each input links to the latest earlier step that makes what
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.
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:
70
+
71
+ ```bash
72
+ $ python -m beratools.core.pipeline my_pipeline.json --processes 4
73
+ ```
74
+
75
+ See [Building a pipeline](https://beratool.github.io/beratools/user_guide/#building-a-pipeline).
76
+
54
77
  ## BERA Tools Guide
55
78
 
56
79
  Check the online [BERA Tools Guide](https://beratool.github.io/beratools/) for user, developer and technical guides.
@@ -201,6 +201,7 @@ def _resolve_tool_function(tool_api: str):
201
201
  def run_tool_command(args: argparse.Namespace) -> int:
202
202
  from beratools.utility import env_checks
203
203
 
204
+ env_checks.configure_gdal_proj_environment()
204
205
  env_checks.warn_gdal_proj_env()
205
206
 
206
207
  tool_api = args.tool_api
@@ -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"],
@@ -238,11 +238,15 @@ def snap_end_to_end(in_line, line_reference, max_snap_dist=None,cid=None):
238
238
  forward = False
239
239
 
240
240
  if forward:
241
- coords[0] = seed_start.coords[0]
242
- coords[-1] = seed_end.coords[0]
241
+ snap_start, snap_end = seed_start, seed_end
243
242
  else:
244
- coords[0] = seed_end.coords[0]
245
- coords[-1] = seed_start.coords[0]
243
+ snap_start, snap_end = seed_end, seed_start
244
+
245
+ # Only snap ends within max_snap_dist of their target
246
+ if max_snap_dist is None or cl_start.distance(snap_start) <= max_snap_dist:
247
+ coords[0] = snap_start.coords[0]
248
+ if max_snap_dist is None or cl_end.distance(snap_end) <= max_snap_dist:
249
+ coords[-1] = snap_end.coords[0]
246
250
  #
247
251
  # Safety check
248
252
  #
@@ -1111,6 +1115,9 @@ class SeedLine:
1111
1115
  self.corridor_poly_gpd["cl_status_name"] = status.name
1112
1116
  self.corridor_poly_gpd["OLnFID"] = self.lc_path["OLnFID"]
1113
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]
1114
1121
 
1115
1122
  def _set_fallback_outputs(self, lc_path, centerline, status, corridor_geometry=None):
1116
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: