diff --git a/.github/workflows/publish_to_anaconda.yml b/.github/workflows/publish_to_anaconda.yml index da68f2c..248c1cf 100644 --- a/.github/workflows/publish_to_anaconda.yml +++ b/.github/workflows/publish_to_anaconda.yml @@ -53,6 +53,15 @@ jobs: printf '### Publishing source\n\n- Mode: `%s`\n- Tag: `%s`\n- Source commit: `%s`\n- Workflow commit: `%s`\n' \ "$mode" "${tag:-none}" "$source_sha" "$GITHUB_SHA" >> "$GITHUB_STEP_SUMMARY" + # Build the tagged source with the recipe from the dispatched commit, so packaging + # fixes can be released for an existing tag without moving it. + - name: Use recipe from workflow commit + if: steps.source.outputs.publish == 'true' + run: | + set -euo pipefail + git checkout "$GITHUB_SHA" -- packaging/recipe.yaml + printf -- '- Recipe commit: `%s`\n' "$GITHUB_SHA" >> "$GITHUB_STEP_SUMMARY" + # Disable Pixi cache to avoid pixi.lock lookup - name: Setup Pixi uses: prefix-dev/setup-pixi@v0.8.1 diff --git a/.github/workflows/python-compatibility-tests.yml b/.github/workflows/python-compatibility-tests.yml index a714e2d..e138eee 100644 --- a/.github/workflows/python-compatibility-tests.yml +++ b/.github/workflows/python-compatibility-tests.yml @@ -36,7 +36,7 @@ jobs: dask gdal>=3.12,<4 geopandas - pandas>=2.0,<3.0 + pandas networkit numpy>=1.26,<2.4 pandas @@ -46,13 +46,13 @@ jobs: scikit-image>=0.24 tqdm xarray-spatial - pandarallel python-igraph tabulate pip pytest pytest-qt tox + psutil condarc: | channel_priority: strict channels: diff --git a/README.md b/README.md index 3cdc69f..ed8a8a8 100644 --- a/README.md +++ b/README.md @@ -57,8 +57,16 @@ The **Pipeline** tab, next to **Tool history** in the GUI, chains tools into ste another. Drag tools in from the tool tree, set each step's parameters in the tool form, and link a step's inputs to an earlier step's output. Each input links to the latest earlier step that makes what it needs, for example the checked lines from **Check Seed Lines** into **Centerline**, and the -links are reset whenever a step is added, moved or removed. Pipelines save as `.json` files and also -run without the GUI: +links are reset whenever a step is added, moved or removed. + +![BERA Tools Pipeline panel](docs/files/screenshots/bt_pipeline.png) + +The example above chains the six mapping tools into a ground footprint workflow. Each step lists the +step it reads from (`← step 5`), and the selected step's linked inputs are shown under +**Inputs from earlier steps** and greyed out in the tool form. Use **Run Pipeline** to run all steps +in order. + +Pipelines save as `.json` files and also run without the GUI: ```bash $ python -m beratools.core.pipeline my_pipeline.json --processes 4 diff --git a/beratools/core/algo_canopy_footprint_absolute.py b/beratools/core/algo_canopy_footprint_absolute.py index 192d8c8..5b51294 100644 --- a/beratools/core/algo_canopy_footprint_absolute.py +++ b/beratools/core/algo_canopy_footprint_absolute.py @@ -59,6 +59,7 @@ class CanopyFootprintRequest: footprint_simplify_length: float = 0.5 smooth_footprint_polygon: bool = False footprint_polygon_smooth_iterations: int = 1 + merge_by_original_line: bool = False @dataclass @@ -95,6 +96,7 @@ def cast_request_types(request: CanopyFootprintRequest) -> CanopyFootprintReques request.footprint_simplify_length = float(request.footprint_simplify_length) request.smooth_footprint_polygon = _to_bool(request.smooth_footprint_polygon) request.footprint_polygon_smooth_iterations = int(request.footprint_polygon_smooth_iterations) + request.merge_by_original_line = _to_bool(request.merge_by_original_line) return request @@ -111,6 +113,28 @@ def _to_bool(value): return bool(value) +def copy_line_ids(footprint, line): + """Carry the source line's OLnFID/OLnSEG onto its footprint, so footprints can be merged per line.""" + if footprint is None or line is None: + return footprint + for field in ("OLnFID", "OLnSEG"): + if field in line.columns: + footprint[field] = line[field].iloc[0] + return footprint + + +def merge_footprints_by_original_line(footprints_gdf, printer=print): + """Dissolve footprints sharing an OLnFID into one, as the centerline tool merges lines.""" + if footprints_gdf is None or footprints_gdf.empty: + return footprints_gdf + if "OLnFID" not in footprints_gdf.columns: + printer("[Warning]: OLnFID not found in input lines; footprints are not merged.") + return footprints_gdf + merged = footprints_gdf.dissolve(by="OLnFID", as_index=False) + merged["OLnSEG"] = -1 + return merged + + def process_footprint_polygon_gdf( footprint_gdf, *, @@ -412,6 +436,7 @@ def compute(self): # Transfer group value to footprint if present if bt_const.BT_GROUP in self.line.columns: self.footprint[bt_const.BT_GROUP] = self.line[bt_const.BT_GROUP].iloc[0] + copy_line_ids(self.footprint, self.line) def _build_rings_with_percentiles(self): self.prepare_ring_buffer() @@ -839,6 +864,7 @@ def compute(self): smooth_footprint_polygon=self.smooth_footprint_polygon, footprint_polygon_smooth_iterations=self.footprint_polygon_smooth_iterations, ) + copy_line_ids(self.footprint, self.line_seg) self.postprocess_output( corridor_thresh, raster["out_transform"], diff --git a/beratools/core/algo_centerline.py b/beratools/core/algo_centerline.py index 6305268..3fb75ed 100644 --- a/beratools/core/algo_centerline.py +++ b/beratools/core/algo_centerline.py @@ -1115,6 +1115,9 @@ def compute(self): self.corridor_poly_gpd["cl_status_name"] = status.name self.corridor_poly_gpd["OLnFID"] = self.lc_path["OLnFID"] self.corridor_poly_gpd["OLnSEG"] = self.lc_path["OLnSEG"] + for field in (algo_common.SOURCE_ROW_FIELD, algo_common.SOURCE_SEG_FIELD): + if field in self.lc_path.columns: + self.corridor_poly_gpd[field] = self.lc_path[field] def _set_fallback_outputs(self, lc_path, centerline, status, corridor_geometry=None): status = CenterlineStatus(status) diff --git a/beratools/core/algo_common.py b/beratools/core/algo_common.py index 61543bc..3ec7585 100644 --- a/beratools/core/algo_common.py +++ b/beratools/core/algo_common.py @@ -372,17 +372,46 @@ def lines_gdf_to_list(gdf): return out_list -def prepare_lines_gdf(file_path, layer=None, proc_segments=True): +# remember which input row (and its OLnSEG) each processed piece came from +SOURCE_ROW_FIELD = "BT_SRC_ROW" +SOURCE_SEG_FIELD = "BT_SRC_SEG" + + +def keep_source_seg(gdf): + """Remember each row's OLnSEG before split_lines_to_segments renumbers it per vertex.""" + if gdf is not None and "OLnSEG" in gdf.columns: + gdf = gdf.copy() + gdf[SOURCE_SEG_FIELD] = gdf["OLnSEG"] + return gdf + + +def restore_source_seg(gdf): + """Put back the OLnSEG saved by keep_source_seg once the segments are merged into their rows.""" + if gdf is not None and SOURCE_SEG_FIELD in gdf.columns: + gdf = gdf.copy() + gdf["OLnSEG"] = gdf[SOURCE_SEG_FIELD] + gdf = gdf.drop(columns=SOURCE_SEG_FIELD) + return gdf + + +def prepare_lines_gdf(file_path, layer=None, proc_segments=True, tag_source_rows=False): """ Split lines at vertices or return original rows. - It handles for MultiLineString. + It handles for MultiLineString. With tag_source_rows, OLnFID/OLnSEG are added if missing + and each row records its input row and OLnSEG, so pieces can be merged back to it. """ gdf = read_geospatial_file(file_path, layer=layer) if gdf is None: return [] + if tag_source_rows: + gdf, _ = chk_df_multipart(gdf, "LineString") + gdf = gdf.reset_index(drop=True) + gdf[SOURCE_ROW_FIELD] = gdf.index + gdf[SOURCE_SEG_FIELD] = gdf["OLnSEG"] + if proc_segments: return split_lines_to_segments(gdf) diff --git a/beratools/core/algo_merge_lines.py b/beratools/core/algo_merge_lines.py index 653e9a5..3a9158a 100644 --- a/beratools/core/algo_merge_lines.py +++ b/beratools/core/algo_merge_lines.py @@ -52,13 +52,14 @@ def custom_line_merge(geom): return geom -def run_line_merge(in_line_gdf, merge_group): +def run_line_merge(in_line_gdf, merge_group, group_field=bt_const.BT_GROUP): + """Merge lines sharing a group_field value into one line (BT_GROUP by default).""" out_line_gdf = in_line_gdf if merge_group: - if bt_const.BT_GROUP not in in_line_gdf.columns: + if group_field not in in_line_gdf.columns: in_line_gdf = in_line_gdf.copy() - in_line_gdf[bt_const.BT_GROUP] = range(1, len(in_line_gdf) + 1) - out_line_gdf = in_line_gdf.dissolve(by=bt_const.BT_GROUP, as_index=False) + in_line_gdf[group_field] = range(1, len(in_line_gdf) + 1) + out_line_gdf = in_line_gdf.dissolve(by=group_field, as_index=False) out_line_gdf.geometry = out_line_gdf.geometry.apply(safe_linemerge) for i, row in enumerate(out_line_gdf.itertuples()): diff --git a/beratools/core/algo_seed_line_correction.py b/beratools/core/algo_seed_line_correction.py index 46ea0c1..d6bc5ee 100644 --- a/beratools/core/algo_seed_line_correction.py +++ b/beratools/core/algo_seed_line_correction.py @@ -460,7 +460,7 @@ def prepare_lines(self, lines_gdf=None): ).remove_close_vertices(lines_gdf) if self.optimize_internal_vertices: - self.line_list = algo_common.split_lines_to_segments(lines_gdf) + self.line_list = algo_common.split_lines_to_segments(algo_common.keep_source_seg(lines_gdf)) else: self.line_list = algo_common.lines_gdf_to_list(lines_gdf) @@ -542,11 +542,12 @@ def get_optimized_lines(self): lines = pd.concat(self.line_list, ignore_index=True) - if self.optimize_internal_vertices and "BT_UID" in lines.columns: + if self.optimize_internal_vertices and bt_const.BT_UID in lines.columns: import beratools.core.algo_merge_lines as algo_merge_lines - lines[bt_const.BT_GROUP] = lines["BT_UID"] - lines = algo_merge_lines.run_line_merge(lines, merge_group=True) + # join the segments back into their input rows, keeping each row's BT_GROUP + lines = algo_merge_lines.run_line_merge(lines, merge_group=True, group_field=bt_const.BT_UID) + lines = algo_common.restore_source_seg(lines) if "length" not in lines.columns: lines["length"] = lines.geometry.length diff --git a/beratools/core/algo_vertex_optimization.py b/beratools/core/algo_vertex_optimization.py index 77a7e15..fe19a7f 100644 --- a/beratools/core/algo_vertex_optimization.py +++ b/beratools/core/algo_vertex_optimization.py @@ -442,7 +442,7 @@ def create_all_vertex_groups(self): self.min_segment_length, self.angle_tol, ) - self.line_list = algo_common.split_lines_to_segments(lines_gdf) + self.line_list = algo_common.split_lines_to_segments(algo_common.keep_source_seg(lines_gdf)) else: lines_gdf = algo_common.read_geospatial_file(self.in_line, layer=self.in_layer) lines_gdf = algo_vertex_preclean.preclean_vertices( @@ -518,9 +518,10 @@ def save_all_layers(self, line_file): lines = pd.concat(self.line_list, ignore_index=True) - if self.optimize_internal_vertices and "BT_UID" in lines.columns: - lines[bt_const.BT_GROUP] = lines["BT_UID"] - lines = algo_merge_lines.run_line_merge(lines, merge_group=True) + if self.optimize_internal_vertices and bt_const.BT_UID in lines.columns: + # join the segments back into their input rows, keeping each row's BT_GROUP + lines = algo_merge_lines.run_line_merge(lines, merge_group=True, group_field=bt_const.BT_UID) + lines = algo_common.restore_source_seg(lines) lines = algo_common.clean_geometries( lines, diff --git a/beratools/core/canopy_threshold_relative.py b/beratools/core/canopy_threshold_relative.py index f093d34..5d3106b 100644 --- a/beratools/core/canopy_threshold_relative.py +++ b/beratools/core/canopy_threshold_relative.py @@ -1,10 +1,10 @@ import math import os.path +from functools import partial from multiprocessing.pool import Pool from pathlib import Path import pandas as pd -from pandarallel import pandarallel from beratools.core.constants import * from beratools.tools.common import * @@ -16,6 +16,39 @@ class OperationCancelledException(Exception): pass +def multiringbuffer(geom, nrings: int, ringdist: int) -> list: + """ + Buffers an input geometry nring (number of rings) times, with a distance between + rings of ringdist and returns a list of non overlapping buffers + """ + import numpy as np + rings = [] # A list to hold the individual buffers + for ring in np.arange(0, ringdist, nrings): # For each ring (1, 2, 3, ..., nrings) + big_ring = geom.buffer( + nrings + ring, single_sided=True, cap_style="flat" + ) # Create one big buffer + small_ring = geom.buffer( + ring, single_sided=True, cap_style="flat" + ) # Create one smaller one + the_ring = big_ring.difference(small_ring) # Difference the big with the small to create a ring + if ( + ~shapely.is_empty(the_ring) + or ~shapely.is_missing(the_ring) + or not None + or ~the_ring.area == 0 + ): + if isinstance(the_ring, shapely.MultiPolygon) or isinstance(the_ring, shapely.Polygon): + rings.append(the_ring) # Append the ring to the rings list + else: + if isinstance(the_ring, shapely.GeometryCollection): + for i in range(0, len(the_ring.geoms)): + if not isinstance(the_ring.geoms[i], shapely.LineString): + rings.append(the_ring.geoms[i]) + print(" {}% ".format((ring / ringdist) * 100)) + + return rings # return the list + + def main_canopy_threshold_relative( in_line: str, in_chm: str, @@ -92,46 +125,19 @@ def main_canopy_threshold_relative( print("Create ring buffer for input line to find the forest edge....") - def multiringbuffer(df: gpd.GeoDataFrame, - nrings:int, - ringdist:int)->list: - """ - Buffers an input dataframes geometry nring (number of rings) times, with a distance between - rings of ringdist and returns a list of non overlapping buffers - """ - import numpy as np - rings = [] # A list to hold the individual buffers - for ring in np.arange(0, ringdist, nrings): # For each ring (1, 2, 3, ..., nrings) - big_ring = df["geometry"].buffer( - nrings + ring, single_sided=True, cap_style="flat" - ) # Create one big buffer - small_ring = df["geometry"].buffer( - ring, single_sided=True, cap_style="flat" - ) # Create one smaller one - the_ring = big_ring.difference(small_ring) # Difference the big with the small to create a ring - if ( - ~shapely.is_empty(the_ring) - or ~shapely.is_missing(the_ring) - or not None - or ~the_ring.area == 0 - ): - if isinstance(the_ring, shapely.MultiPolygon) or isinstance(the_ring, shapely.Polygon): - rings.append(the_ring) # Append the ring to the rings list - else: - if isinstance(the_ring, shapely.GeometryCollection): - for i in range(0, len(the_ring.geoms)): - if not isinstance(the_ring.geoms[i], shapely.LineString): - rings.append(the_ring.geoms[i]) - print(" {}% ".format((ring / ringdist) * 100)) - - return rings # return the list - # Create a column with the rings as a list - print("Create rings buffer to forest edge on one side....") - pandarallel.initialize(progress_bar=False,nb_workers=processes) - worklnbuffer_df_l_ring["mgeometry"] = worklnbuffer_df_l_ring.parallel_apply( - lambda x: multiringbuffer(df=x, nrings=1, ringdist=15), axis=1 - ) + print("Create rings buffer to forest edge on both side of centerlines....") + with Pool(processes) as pool: + worklnbuffer_df_l_ring["mgeometry"] = pool.map( + partial(multiringbuffer, nrings=1, ringdist=15), + worklnbuffer_df_l_ring.geometry, + chunksize=max(1, len(worklnbuffer_df_l_ring) // (processes * 4)), + ) + worklnbuffer_df_r_ring["mgeometry"] = pool.map( + partial(multiringbuffer, nrings=-1, ringdist=-15), + worklnbuffer_df_r_ring.geometry, + chunksize=max(1, len(worklnbuffer_df_r_ring) // (processes * 4)), + ) # Explode to create a row for each ring worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.explode("mgeometry") @@ -143,12 +149,6 @@ def multiringbuffer(df: gpd.GeoDataFrame, worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.sort_values(by=["OLnFID", "OLnSEG", "iRing"]) worklnbuffer_df_l_ring = worklnbuffer_df_l_ring.reset_index(drop=True) - print("Create rings buffer to forest edge on the other side....") - pandarallel.initialize(progress_bar=False, nb_workers=processes) - worklnbuffer_df_r_ring["mgeometry"] = worklnbuffer_df_r_ring.parallel_apply( - lambda x: multiringbuffer(df=x, nrings=-1, ringdist=-15), axis=1 - ) - worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.explode("mgeometry") # Explode to create a row for each ring worklnbuffer_df_r_ring = worklnbuffer_df_r_ring.set_geometry("mgeometry") worklnbuffer_df_r_ring = ( diff --git a/beratools/core/line_footprint_functions.py b/beratools/core/line_footprint_functions.py index 3bf4e48..7e986c9 100644 --- a/beratools/core/line_footprint_functions.py +++ b/beratools/core/line_footprint_functions.py @@ -37,6 +37,7 @@ from pathlib import Path from xrspatial import convolution +import beratools.core.algo_common as algo_common from beratools.core.algo_centerline import * from beratools.core.canopy_threshold_relative import OperationCancelledException from beratools.core.constants import * @@ -571,7 +572,6 @@ def process_single_line_relative(segment): # BERA proposed Binary morphology Shrink # fileShrink = ndimage.binary_erosion((Expanded),iterations=Exp_Shk_cell,border_value=1) else: - print("No Expand And Shrink cell performed.") file_shrink = raster_class @@ -649,6 +649,7 @@ def main_line_footprint_relative( canopy_thresh_percentage:int, processes:int, debug_mode:bool=BT_DEBUGGING, + merge_by_original_line:bool=False, )-> None: """ This function take the centerlines with forest canopy height and distance to edge to generate @@ -665,6 +666,8 @@ def main_line_footprint_relative( canopy_avoidance: 0 < Ratio < 1 of importance between canopy search radius and Euclidean distance exponent: Affects the cost of vegetated areas in an exponential fashion canopy_thresh_percentage: Percentage as integer range 1-100 + merge_by_original_line: Merge outputs sharing an OLnFID into one feature, otherwise + keep one footprint and centerline per input line (OLnFID, OLnSEG) Returns: New saved footprints and/or with smoothed centerlines dataset(s). @@ -839,9 +842,13 @@ def main_line_footprint_relative( resultsR = resultsR.reset_index(drop=True) # + # one output per input line, or per original line when merging, as in the centerline tool + dissolve_keys = ["OLnFID"] if merge_by_original_line else ["OLnFID", "OLnSEG"] resultsAll = GeoDataFrame(pd.concat([resultsL, resultsR],ignore_index=True)) - dissolved_results = resultsAll.dissolve(by="OLnFID", as_index=False) + dissolved_results = resultsAll.dissolve(by=dissolve_keys, as_index=False) dissolved_results["geometry"] = dissolved_results["geometry"].buffer(-0.005) + if merge_by_original_line: + dissolved_results["OLnSEG"] = -1 print("[info]: Saving output ...") out_ft_file, layer = decode_file_layer(out_footprint) dissolved_results.to_file(out_ft_file, layer=layer) @@ -855,7 +862,7 @@ def main_line_footprint_relative( resultsCR["geometry"] = resultsCR["geometry"].buffer(0.005) resultsCLR = GeoDataFrame(pd.concat([resultsCL, resultsCR])) - resultsCLR = resultsCLR.dissolve(by="OLnFID", as_index=False) + resultsCLR = resultsCLR.dissolve(by=dissolve_keys, as_index=False) resultsCLR = resultsCLR.sort_values(by=["OLnFID", "OLnSEG"]) resultsCLR = resultsCLR.reset_index(drop=True) resultsCLR["geometry"] = resultsCLR["geometry"].buffer(-0.005) @@ -863,13 +870,21 @@ def main_line_footprint_relative( # save lines to file if out_centerline: out_cl_file, layer = decode_file_layer(out_centerline) - poly_centerline_gpd = find_centerlines(resultsCLR, line_seg, processes) + guide_lines = line_seg + if merge_by_original_line: + # corridor polygons are dissolved per OLnFID, so guide each by all pieces of its original line + guide_lines = algo_common.merge_lines_by_original_id( + line_seg, group_field="OLnFID", order_field="OLnSEG" + ).drop(columns="OLnSEG") + poly_centerline_gpd = find_centerlines(resultsCLR, guide_lines, processes) poly_gpd = poly_centerline_gpd.copy() centerline_gpd = poly_centerline_gpd.copy() centerline_gpd = centerline_gpd.set_geometry("centerline") centerline_gpd = centerline_gpd.drop(columns=["geometry"]) centerline_gpd.crs = poly_centerline_gpd.crs + if merge_by_original_line: + centerline_gpd["OLnSEG"] = -1 # save polygons from smooth centerline for debug if debug_mode: diff --git a/beratools/gui/assets/beratools.json b/beratools/gui/assets/beratools.json index 1a6239a..87bc869 100644 --- a/beratools/gui/assets/beratools.json +++ b/beratools/gui/assets/beratools.json @@ -487,7 +487,7 @@ { "variable": "proc_segments", "label": "Process Segments", - "description": "Process each segment between vertices separately", + "description": "Process each segment between vertices separately, then merge the segments back into one centerline per input line", "type": "list", "subtype": "bool", "data": [true, false], @@ -495,6 +495,17 @@ "output": false, "optional": false }, + { + "variable": "merge_by_original_line", + "label": "Merge by Original Line", + "description": "Merge centerlines that share an original line ID (OLnFID) into one line, e.g. lines split at intersections by Check Seed Lines", + "type": "list", + "subtype": "bool", + "data": [true, false], + "default": false, + "output": false, + "optional": true + }, { "variable": "centerline_method", "label": "Centerline Method", @@ -890,6 +901,17 @@ "condition": true } }, + { + "variable": "merge_by_original_line", + "label": "Merge by Original Line", + "description": "Merge footprints that share an original line ID (OLnFID) into one feature, e.g. lines split at intersections by Check Seed Lines", + "type": "list", + "subtype": "bool", + "data": [true, false], + "default": false, + "output": false, + "optional": true + }, { "variable": "out_footprint", "produces": { @@ -980,6 +1002,17 @@ "output": true, "optional": true }, + { + "variable": "merge_by_original_line", + "label": "Merge by Original Line", + "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", + "type": "list", + "subtype": "bool", + "data": [true, false], + "default": false, + "output": false, + "optional": true + }, { "variable": "off_ln_dist", "label": "Offset Line Distance", @@ -1114,6 +1147,17 @@ "output": false, "optional": true }, + { + "variable": "merge_by_original_line", + "label": "Merge by Original Line", + "description": "Merge lines and footprints that share an original line ID (OLnFID) into one feature, e.g. lines split at intersections by Check Seed Lines", + "type": "list", + "subtype": "bool", + "data": [true, false], + "default": false, + "output": false, + "optional": true + }, { "variable": "out_footprint", "produces": { diff --git a/beratools/gui/bt_gui_main.py b/beratools/gui/bt_gui_main.py index c6d570b..cb62984 100644 --- a/beratools/gui/bt_gui_main.py +++ b/beratools/gui/bt_gui_main.py @@ -478,9 +478,8 @@ def __init__(self): # ToolWidgets tool_args = bt.get_bera_tool_args(self.tool_name) + # saved history is loaded as-is; inputs that can't be found are flagged in red self.tool_widget = ToolWidgets(self.tool_name, tool_args, bt.show_advanced, bt_data_obj=bt) - # at startup, history inputs that no longer exist start empty instead of flagged - self.tool_widget.clear_missing_inputs() self.tool_scroll_area = QtWidgets.QScrollArea() self.tool_scroll_area.setWidgetResizable(True) self.tool_scroll_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) diff --git a/beratools/gui/tool_widgets.py b/beratools/gui/tool_widgets.py index 1df59d3..d82882c 100644 --- a/beratools/gui/tool_widgets.py +++ b/beratools/gui/tool_widgets.py @@ -80,7 +80,8 @@ def get_widgets_arguments(self): param_missing = True continue v = widget.get_value() - if v: + # get_value() returns {variable: ""} for an empty field, which is truthy + if v and (widget.optional or not self._is_empty_value(widget, v.get(widget.variable))): args.update(v) else: print(f"[Missing argument]: {widget.name} not specified.", "missing") @@ -189,7 +190,13 @@ def create_widgets(self, tool_args): self.widget_list.append(widget) self._configure_widget_dependencies() - self._clear_output_paths_for_missing_input_history() + + @classmethod + def _is_empty_value(cls, widget, value): + # an output with a layer but no path encodes as "|layer", so check the path itself + if isinstance(widget, FileSelector): + return not cls._extract_file_selector_path(value) + return value is None or value == "" @staticmethod def _extract_file_selector_path(value): @@ -201,34 +208,6 @@ def _extract_file_selector_path(value): return value return "" - def _clear_output_paths_for_missing_input_history(self): - missing_input_paths = set() - - for widget in self.widget_list: - if not isinstance(widget, FileSelector) or widget.output: - continue - if widget.missing_input_error: - missing_input_paths.add(self._extract_file_selector_path(widget.value)) - - if not missing_input_paths: - return - - for widget in self.widget_list: - if not isinstance(widget, FileSelector) or not widget.output: - continue - current_path = widget.value.get("path", "") if widget.is_vector else widget.value - if current_path in missing_input_paths: - if widget.is_vector: - widget.set_value({"path": "", "layer": ""}) - else: - widget.set_value("") - - def clear_missing_inputs(self): - """Empty input paths that don't exist, so stale history shows blank fields instead of flagged ones.""" - for widget in self.widget_list: - if isinstance(widget, FileSelector) and widget.missing_input_error: - widget.set_value({"path": "", "layer": ""} if widget.is_vector else "") - def update_widgets(self, values_dict): for key, value in values_dict.items(): for item in self.widget_list: @@ -603,17 +582,8 @@ def handle_vector_io(self): # Input: keep a saved file that no longer exists; it is flagged in the form if not Path(path).exists(): return - elif ext == "gpkg": - try: - layers_dict = get_layers(path) - if layer: - valid_layers = [str(k) for k in layers_dict.keys()] - if layer not in valid_layers: - self.value = {"path": "", "layer": ""} - print(f"[Error] Invalid Layer: Layer '{layer}' not found in file: {path}") - except Exception: - self.value = {"path": "", "layer": ""} - print(f"[Error] Layer Error: Could not load layers from file: {path}") + elif ext == "gpkg" and layer and self._missing_gpkg_layer(path, layer): + print(f"[Error] Invalid Layer: Layer '{layer}' not found in file: {path}") def setup_ui(self): self.layout = QtWidgets.QHBoxLayout() @@ -649,13 +619,13 @@ def setup_ui(self): for layer_name, geometry_type in layers_dict.items(): self.layer_combo.addItem(f"{layer_name} ({geometry_type})") self.layer_combo.setVisible(True) - if requested_layer: - index = self._find_layer_index_by_name(requested_layer) - if index >= 0: - self.layer_combo.setCurrentIndex(index) - self.value["layer"] = requested_layer + index = self._find_layer_index_by_name(requested_layer) + if index >= 0: + self.layer_combo.setCurrentIndex(index) self.layer_combo.blockSignals(False) - self.set_layer(self.layer_combo.currentText()) + # a saved layer that's gone is kept, not swapped for the first one + if index >= 0 or not requested_layer: + self.set_layer(self.layer_combo.currentText()) except Exception: self.layer_combo.blockSignals(False) self.layer_combo.clear() @@ -707,19 +677,38 @@ def _clear_input_geometry_warning(self): self.in_file.setStyleSheet("") self.in_file.setToolTip(self.description) + @staticmethod + def _missing_gpkg_layer(path, layer): + try: + return layer not in {str(k) for k in get_layers(path).keys()} + except Exception: + return True + def _update_missing_input_warning(self): - """Flag an input path that doesn't exist, keeping it so it can be seen and fixed.""" + """Flag an input path or layer that doesn't exist, keeping it so it can be seen and fixed.""" path = self.value.get("path", "") if self.is_vector else self.value + layer = self.value.get("layer", "") if self.is_vector else "" was_missing = bool(self.missing_input_error) - if path and isinstance(path, str) and not self.output and not Path(path).exists(): - kind = "Folder" if self.is_directory else "File" - self.missing_input_error = f"{kind} not found: {path}" - self.in_file.setStyleSheet("QLineEdit { background-color: #f8d7da; }") - self.in_file.setToolTip(self.missing_input_error) - return + if path and isinstance(path, str) and not self.output: + if not Path(path).exists(): + kind = "Folder" if self.is_directory else "File" + self.missing_input_error = f"{kind} not found: {path}" + elif layer and path.lower().endswith(".gpkg") and self._missing_gpkg_layer(path, layer): + self.missing_input_error = f"Layer '{layer}' not found in: {path}" + self.layer_combo.setStyleSheet("QComboBox { background-color: #f8d7da; }") + self.layer_combo.setToolTip(self.missing_input_error) + else: + self.missing_input_error = "" + if self.missing_input_error: + self.in_file.setStyleSheet("QLineEdit { background-color: #f8d7da; }") + self.in_file.setToolTip(self.missing_input_error) + return self.missing_input_error = "" if was_missing: + if not self.output: + self.layer_combo.setStyleSheet("") + self.layer_combo.setToolTip("Select layer") if self.input_geometry_error: self.in_file.setToolTip(self.input_geometry_error) else: @@ -802,8 +791,13 @@ def _on_vector_path_changed(self, path, is_output, selected_layer=""): self.layer_combo.setCurrentText(selected_layer) else: index = self._find_layer_index_by_name(selected_layer) - if index >= 0: - self.layer_combo.setCurrentIndex(index) + if index < 0 and not is_output and self._loading: + # keep a saved layer that's gone so it is flagged instead of silently replaced + if self.layer_combo.itemText(0) == self.NO_COMPATIBLE_LAYER_TEXT: + self.layer_combo.clear() + self.layer_combo.insertItem(0, selected_layer) + index = 0 + self.layer_combo.setCurrentIndex(index) self.layer_combo.adjustSize() self._update_layer_overwrite_warning() if self.is_vector and not is_output: @@ -1174,6 +1168,8 @@ def set_layer(self, layer): else: self.selected_layer = layer self._update_layer_overwrite_warning() + if not self.output: + self._update_missing_input_warning() def get_value(self): #Return the folder directly: diff --git a/beratools/tools/canopy_footprint_absolute.py b/beratools/tools/canopy_footprint_absolute.py index b048d54..b343d1e 100644 --- a/beratools/tools/canopy_footprint_absolute.py +++ b/beratools/tools/canopy_footprint_absolute.py @@ -25,6 +25,7 @@ FootprintCanopyAdaptive, cast_request_types, generate_absolute_line_class_list, + merge_footprints_by_original_line, process_single_absolute_line, save_aux_layers, save_main_footprint, @@ -63,6 +64,7 @@ def canopy_footprint_abs( footprint_simplify_length=0.5, smooth_footprint_polygon=False, footprint_polygon_smooth_iterations=1, + merge_by_original_line=False, processes=0, call_mode=CallMode.CLI, log_level="INFO", @@ -89,6 +91,7 @@ def canopy_footprint_abs( footprint_simplify_length=footprint_simplify_length, smooth_footprint_polygon=smooth_footprint_polygon, footprint_polygon_smooth_iterations=footprint_polygon_smooth_iterations, + merge_by_original_line=merge_by_original_line, processes=processes, call_mode=call_mode, log_level=log_level, @@ -135,6 +138,10 @@ def canopy_footprint_abs( for message in result.messages: print(message) + # one footprint per input line, or per original line when merging, as in the centerline tool + if request.merge_by_original_line: + result.footprints_gdf = merge_footprints_by_original_line(result.footprints_gdf, printer=print) + save_main_footprint( result, request.out_footprint, diff --git a/beratools/tools/centerline.py b/beratools/tools/centerline.py index c5a22ef..cddd915 100644 --- a/beratools/tools/centerline.py +++ b/beratools/tools/centerline.py @@ -69,7 +69,7 @@ def generate_line_class_list( corridor_polygon_smooth_iterations=1, ) -> list: line_classes = [] - line_list = algo_common.prepare_lines_gdf(in_vector, layer, proc_segments) + line_list = algo_common.prepare_lines_gdf(in_vector, layer, proc_segments, tag_source_rows=True) for item in line_list: line_classes.append( @@ -99,6 +99,44 @@ def generate_line_class_list( return line_classes +MERGE_ORDER_FIELD = "BT_MERGE_ORDER" + + +def _add_merge_order(gdf, merge_by_original_line): + """Number the pieces in the order they join: by input row and vertex, or along the original line.""" + if gdf is None or gdf.empty: + return gdf + gdf = gdf.copy() + if merge_by_original_line: + group_field = "OLnFID" + sort_fields = [algo_common.SOURCE_SEG_FIELD, algo_common.SOURCE_ROW_FIELD, "OLnSEG"] + else: + group_field = algo_common.SOURCE_ROW_FIELD + sort_fields = ["OLnSEG"] + ordered = gdf.sort_values(sort_fields, kind="stable") + gdf[MERGE_ORDER_FIELD] = ordered.groupby(group_field, sort=False).cumcount() + return gdf + + +def _restore_merged_ids(gdf, merge_by_original_line): + """Give merged rows their input OLnSEG back (or -1 for a whole original line) and drop helper fields.""" + if gdf is None or gdf.empty: + return gdf + gdf = gdf.copy() + if merge_by_original_line: + gdf["OLnSEG"] = -1 + elif algo_common.SOURCE_SEG_FIELD in gdf.columns: + gdf["OLnSEG"] = gdf[algo_common.SOURCE_SEG_FIELD] + return _drop_helper_fields(gdf) + + +def _drop_helper_fields(gdf): + if gdf is None: + return gdf + helper_fields = [algo_common.SOURCE_ROW_FIELD, algo_common.SOURCE_SEG_FIELD, MERGE_ORDER_FIELD] + return gdf.drop(columns=[f for f in helper_fields if f in gdf.columns]) + + def process_single_line_class(seed_line): try: # OLnFID and OLnSEG are added in previous QC stage. @@ -117,6 +155,7 @@ def centerline( line_radius, proc_segments, out_line, + merge_by_original_line=False, centerline_method=bt_const.CENTERLINE_METHOD.value, guided_strategy=bt_const.CENTERLINE_GUIDED_STRATEGY.value, simplify_centerline=False, @@ -158,6 +197,7 @@ def centerline( centerline_method_value = centerline_method.value chm_mode_value = chm_mode.value proc_segments = _to_bool(proc_segments) + merge_by_original_line = _to_bool(merge_by_original_line) in_file, in_layer = sp_common.decode_file_layer(in_line) out_file, out_layer = sp_common.decode_file_layer(out_line) @@ -282,15 +322,24 @@ def centerline( dissolved_cl_orig=centerline_gdf dissolved_lcp_orig=lc_path_gdf dissolved_corridor_orig=corridor_gdf + # whole lines need no merging, so they are saved as they are + dissolved_cl = centerline_gdf + dissolved_lcp = lc_path_gdf + dissolved_corridor = corridor_gdf aux_file = algo_common.get_aux_path(out_file) - if proc_segments: + if proc_segments or merge_by_original_line: logger.info("Dissolving segments...") + dissolved_cl_orig, dissolved_lcp_orig, dissolved_corridor_orig = ( + _add_merge_order(gdf, merge_by_original_line) + for gdf in (centerline_gdf, lc_path_gdf, corridor_gdf) + ) + group_field = "OLnFID" if merge_by_original_line else algo_common.SOURCE_ROW_FIELD dissolved_cl = ( algo_common.merge_lines_by_original_id( line_gdf=dissolved_cl_orig, - group_field="OLnFID", - order_field="OLnSEG", + group_field=group_field, + order_field=MERGE_ORDER_FIELD, max_bridge_gap=max( cell_size * 1.5, 0.5, @@ -311,8 +360,8 @@ def centerline( dissolved_lcp = ( algo_common.merge_lines_by_original_id( line_gdf=dissolved_lcp_orig, - group_field="OLnFID", - order_field="OLnSEG", + group_field=group_field, + order_field=MERGE_ORDER_FIELD, max_bridge_gap=max( cell_size * 0.75, 0.05, @@ -326,8 +375,8 @@ def centerline( dissolved_corridor = ( algo_common.merge_corridors_by_original_id( dissolved_corridor_orig, - group_field="OLnFID", - order_field="OLnSEG", + group_field=group_field, + order_field=MERGE_ORDER_FIELD, ) ) @@ -360,25 +409,44 @@ def centerline( logger.info("Dissolving segments...Done") + dissolved_cl, dissolved_lcp, dissolved_corridor = ( + _restore_merged_ids(gdf, merge_by_original_line) + for gdf in (dissolved_cl, dissolved_lcp, dissolved_corridor) + ) + centerline_gdf, lc_path_gdf, corridor_gdf = ( + _drop_helper_fields(gdf) for gdf in (centerline_gdf, lc_path_gdf, corridor_gdf) + ) + if simplify_enabled and diameter > 0: temp_file = tool_geo_simplify.build_temp_output_same_folder( out_file, prefix=f"{Path(out_file).stem}_centerline_tmp_", ) + # geo-simplify recreates its --output file, so never point it at out_file + # directly or every other layer in the GeoPackage is wiped. + temp_out_file = tool_geo_simplify.build_temp_output_same_folder( + out_file, + prefix=f"{Path(out_file).stem}_centerline_simplified_tmp_", + ) temp_layer = "centerline_temp" try: dissolved_cl.to_file(temp_file.as_posix(), layer=temp_layer,overwrite=True) + temp_out_file.unlink() tool_geo_simplify.run_reduce_bend( input_file=temp_file, in_layer=temp_layer, - output_file=out_file, + output_file=temp_out_file.as_posix(), out_layer=out_layer, diameter=diameter, smooth_line=True, ) + simplified_cl = gpd.read_file(temp_out_file, layer=out_layer) + algo_common.drop_layer_if_exists(out_file, out_layer) + simplified_cl.to_file(out_file, layer=out_layer) finally: - if temp_file.exists(): - temp_file.unlink() + for path in (temp_file, temp_out_file): + if path.exists(): + path.unlink() else: if simplify_enabled and diameter == 0: print("Centerline simplify enabled with diameter 0; skipping simplify step.") diff --git a/beratools/tools/check_seed_line.py b/beratools/tools/check_seed_line.py index 1627e43..18285c6 100644 --- a/beratools/tools/check_seed_line.py +++ b/beratools/tools/check_seed_line.py @@ -697,6 +697,10 @@ def _persist_qc_tables(input_count, output_count): gdf = _ensure_gdf(split_out, prev_crs) split_min_length = config.minimum_line_length if config.remove_short_lines else bt_const.SMALL_BUFFER gdf, removed_gdf = _clean_line_geometries_min_length_m(gdf, split_min_length) + # pieces keep their line's OLnSEG, so number them along each original line + if "OLnFID" in gdf.columns and "OLnSEG" in gdf.columns: + gdf = gdf.sort_values(["OLnFID", "OLnSEG"], kind="stable").reset_index(drop=True) + gdf["OLnSEG"] = gdf.groupby("OLnFID").cumcount() gdf = gdf.reset_index(drop=True) _log_step( 8, step_name, in_count, len(gdf), _elapsed(t0), verbose=verbose_steps, skipped_steps=skipped_steps diff --git a/beratools/tools/ground_footprint.py b/beratools/tools/ground_footprint.py index d4b9723..6571b9e 100644 --- a/beratools/tools/ground_footprint.py +++ b/beratools/tools/ground_footprint.py @@ -273,6 +273,7 @@ def ground_footprint( out_footprint, in_layer_lc_path="least_cost_path", merge_group=True, + merge_by_original_line=False, width_percentile=75, trim_output=True, processes=0, @@ -304,6 +305,14 @@ def ground_footprint( min_value=bt_const.SMALL_BUFFER, ) + # group by original line, as the centerline tool merges, so pieces share one footprint + merge_by_original_line = str(merge_by_original_line).strip().lower() in ("true", "1", "yes") + if merge_by_original_line and "OLnFID" not in line_gdf.columns: + print("[Warning]: OLnFID not found in input lines; lines are not merged by original line.") + merge_by_original_line = False + if merge_by_original_line: + line_gdf[bt_const.BT_GROUP] = line_gdf["OLnFID"] + if bt_const.BT_GROUP not in line_gdf.columns: line_gdf[bt_const.BT_GROUP] = range(1, len(line_gdf) + 1) @@ -314,6 +323,8 @@ def ground_footprint( lc_path_gdf = lc_path_gdf.rename(columns={"fid": "orig_fid"}) lc_path_gdf = algo_common.clean_geometries(lc_path_gdf, stage="input") lc_path_gdf = lc_path_gdf.reset_index(drop=True) + if merge_by_original_line and "OLnFID" in lc_path_gdf.columns: + lc_path_gdf[bt_const.BT_GROUP] = lc_path_gdf["OLnFID"] except (ValueError, OSError, pyogrio.errors.DataLayerError): print(f"Layer '{in_layer_lc_path}' not found in {in_file}, skipping least cost path logic.") use_least_cost_path = False @@ -330,6 +341,9 @@ def ground_footprint( poly_gdf = algo_common.clean_geometries(poly_gdf, stage="input") poly_gdf = poly_gdf.reset_index(drop=True) poly_gdf["geometry"] = poly_gdf["geometry"].apply(algo_common.remove_holes) + # polygons are matched to lines by BT_GROUP, so keep their groups the same as the lines' + if merge_by_original_line and "OLnFID" in poly_gdf.columns: + poly_gdf[bt_const.BT_GROUP] = poly_gdf["OLnFID"] if not sp_common.compare_crs( sp_common.vector_crs(in_file, in_layer), sp_common.vector_crs(in_fp_file, in_layer_fp) diff --git a/beratools/tools/line_footprint_relative.py b/beratools/tools/line_footprint_relative.py index dbbbce7..7ca7187 100644 --- a/beratools/tools/line_footprint_relative.py +++ b/beratools/tools/line_footprint_relative.py @@ -32,7 +32,9 @@ from beratools.core.line_footprint_functions import * from beratools.core.canopy_threshold_relative import * +from beratools.utility.spatial_common import decode_file_layer import time +from pathlib import Path def line_footprint_relative( @@ -52,6 +54,7 @@ def line_footprint_relative( processes, call_mode, log_level, + merge_by_original_line=False, ): """Create canopy footprint polygons using per-line relative canopy thresholds. @@ -91,9 +94,21 @@ def line_footprint_relative( processes: Number of parallel processes. call_mode: How the tool was invoked (see `CallMode`). log_level: Logging level. Currently not used. + merge_by_original_line: Merge footprints and centerlines sharing an original + line ID (OLnFID) into one feature; otherwise keep one per input line. """ verbose = True if call_mode == CallMode.GUI.value else False + # Write the intermediate dynamic centerline as a layer in the output footprint's file, + # so no extra file is created and input data folders are never written to. + in_file, in_layer = decode_file_layer(in_line) + out_ft_file = decode_file_layer(out_footprint)[0] + dyn_layer = "DynCanTh_" + (in_layer or Path(in_file).stem) + if Path(out_ft_file).suffix.lower() != ".gpkg": + # a shapefile holds one layer, so use a GeoPackage beside it + out_ft_file = Path(out_ft_file).with_name(dyn_layer + ".gpkg").as_posix() + out_dyn_centerline = f"{out_ft_file}|{dyn_layer}" + dy_cl_line = main_canopy_threshold_relative( in_line=in_line, in_chm=in_chm, @@ -101,7 +116,7 @@ def line_footprint_relative( canopy_thresh_percentage=int(float(canopy_thresh_percentage)), full_step=bool(True), processes=int(float(processes)), - + out_dyn_centerline=out_dyn_centerline, ) if not dy_cl_line: @@ -122,6 +137,7 @@ def line_footprint_relative( full_step=bool(True), canopy_thresh_percentage=int(float(canopy_thresh_percentage)), processes=int(float(processes)), + merge_by_original_line=str(merge_by_original_line).strip().lower() in ("true", "1", "yes"), ) if __name__ == "__main__": diff --git a/docs/files/screenshots/bt_pipeline.png b/docs/files/screenshots/bt_pipeline.png new file mode 100644 index 0000000..9baf86c Binary files /dev/null and b/docs/files/screenshots/bt_pipeline.png differ diff --git a/docs/files/user_guide.md b/docs/files/user_guide.md index 45023b5..cf9f9cb 100644 --- a/docs/files/user_guide.md +++ b/docs/files/user_guide.md @@ -80,6 +80,12 @@ graph TD The **Pipeline** tab, next to **Tool history** in the GUI, chains tools together so they run one after another, without writing a script. +![Pipeline panel](screenshots/bt_pipeline.png) + +The pipeline above chains the six mapping tools into a ground footprint workflow. **Ground Footprint** +is selected: its centerline and footprint inputs both link to step 5, and those fields are greyed out +in the tool form. + 1. **Add steps**: drag tools from **Tools available** into the Pipeline tab. Dragging over the tab switches to it. You can also select a tool and click the add button. Drag steps, or use the arrow buttons, to change their order. diff --git a/environment.yml b/environment.yml index 925bba3..786a3bf 100644 --- a/environment.yml +++ b/environment.yml @@ -10,7 +10,6 @@ dependencies: - dask - gdal>=3.12,<4 - geopandas - - pandas>=2.0,<3 - networkit - numpy>=1.26,<2.4 - pandas @@ -20,7 +19,6 @@ dependencies: - scikit-image>=0.24.0 - tqdm - xarray-spatial - - pandarallel - tabulate - python-igraph - psutil diff --git a/examples/config.yaml b/examples/config.yaml index de734e0..7bfa520 100644 --- a/examples/config.yaml +++ b/examples/config.yaml @@ -26,6 +26,7 @@ args_centerline: in_raster: ${DATA_DIR}/${CHM} line_radius: 15 proc_segments: true + merge_by_original_line: true out_line: ${DATA_DIR}/centerline.gpkg|centerline args_footprint_abs: diff --git a/packaging/recipe.yaml b/packaging/recipe.yaml index 2e76be1..82bd193 100644 --- a/packaging/recipe.yaml +++ b/packaging/recipe.yaml @@ -33,18 +33,19 @@ requirements: - dask - gdal >=3.12,<4 - geopandas + - pandas - networkit - numpy >=1.26,<2.4 - pyarrow - - pyogrio + - pyogrio >=0.12.0 - pyqt - - rasterio - - scikit-image + - rasterio >=1.5.0 + - scikit-image >=0.24.0 - tabulate - tqdm - xarray-spatial - - pandarallel - python-igraph + - psutil tests: - script: - pytest tests/test_workflow.py diff --git a/pixi.toml b/pixi.toml index 80d75e1..90c4429 100644 --- a/pixi.toml +++ b/pixi.toml @@ -15,7 +15,7 @@ python = "3.12.*" dask = "*" gdal = ">=3.12,<4" geopandas = "*" -pandas = ">=2.0,<3" +pandas = ">=2.0" networkit = "*" numpy = ">=1.26,<2.4" pyarrow = "*" @@ -31,7 +31,6 @@ pytest = "*" pytest-qt = "*" pytest-cov = "*" coverage = "*" -pandarallel = "*" python-igraph = "*" psutil = "*" hydra-core = "*" diff --git a/pyproject.toml b/pyproject.toml index 89ecd29..91fca9b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,7 +29,7 @@ classifiers = [ dependencies = [ "gdal>=3.12,<4; platform_system != 'Windows'", "geopandas", - "pandas>=2.0,<3", + "pandas>=2.0", "networkit", "numpy>=1.26,<2.4", "pyogrio>=0.12.0", @@ -39,8 +39,8 @@ dependencies = [ "tabulate", "tqdm", "xarray-spatial", - "pandarallel", "igraph", + "psutil" ] [project.optional-dependencies] diff --git a/tests/conftest.py b/tests/conftest.py index 245ee92..151d093 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -11,6 +11,13 @@ sys.path.insert(0, Path(__file__).parents[1].as_posix()) +# Unactivated conda envs on Windows (e.g. IDE runners) lack Library\bin on PATH, +# so MKL fails to load its runtime DLLs and numpy crashes with 0xC06D007F. +_conda_bin = Path(sys.prefix, "Library", "bin") +if sys.platform == "win32" and _conda_bin.is_dir(): + if str(_conda_bin).lower() not in os.environ.get("PATH", "").lower(): + os.environ["PATH"] = f"{_conda_bin}{os.pathsep}{os.environ.get('PATH', '')}" + def pytest_configure(config): # Ignore the FutureWarning for the specific warning from osgeo.osr @@ -60,6 +67,7 @@ def tool_arguments_integration(testdata_dir, available_cpu_cores): "in_raster": testdata_dir.joinpath("chm_aoi.tif").as_posix(), "line_radius": 15, "proc_segments": True, + "merge_by_original_line": True, "out_line": f"{testdata_dir.joinpath('integration_inter.gpkg').as_posix()}|centerline", "chm_mode": "current", "centerline_method": "astar" @@ -160,6 +168,7 @@ def tool_arguments_workflow(testdata_dir, available_cpu_cores): "in_raster": testdata_dir.joinpath("chm_aoi.tif").as_posix(), "line_radius": 15, "proc_segments": True, + "merge_by_original_line": True, "out_line": f"{testdata_dir.joinpath('workflow.gpkg').as_posix()}|centerline", }, "args_centerline_pairwise": { diff --git a/tests/pytest_qt/test_tool_forms.py b/tests/pytest_qt/test_tool_forms.py index c0ea557..ed7c261 100644 --- a/tests/pytest_qt/test_tool_forms.py +++ b/tests/pytest_qt/test_tool_forms.py @@ -414,7 +414,45 @@ def test_round_trip(self, make_tool_widget, testdata_dir, tmp_path): class TestMissingParams: - def test_defaults_provide_initial_arguments(self, make_tool_widget): + def _fill_check_seed_lines(self, tw, testdata_dir, tmp_path): + _set_widget_values( + tw, + { + "in_line": {"path": str(testdata_dir / "seed_lines_aoi.gpkg"), "layer": "seed_lines"}, + "in_raster": str(testdata_dir / "chm_aoi.tif"), + "out_line": {"path": str(tmp_path / "out.gpkg"), "layer": "checked"}, + }, + ) + + def test_empty_required_paths_are_rejected(self, make_tool_widget): tw = make_tool_widget("Check Seed Lines") - args = tw.get_widgets_arguments() - assert args is not None + # set explicitly: the form may start with saved paths from the user's settings + _find_widget(tw, "in_line").set_value({"path": "", "layer": ""}) + _find_widget(tw, "out_line").set_value({"path": "", "layer": ""}) + assert tw.get_widgets_arguments() is None + + def test_filled_required_paths_are_accepted(self, make_tool_widget, testdata_dir, tmp_path): + tw = make_tool_widget("Check Seed Lines") + self._fill_check_seed_lines(tw, testdata_dir, tmp_path) + assert tw.get_widgets_arguments() is not None + + def test_empty_required_input_is_rejected(self, make_tool_widget, testdata_dir, tmp_path): + tw = make_tool_widget("Check Seed Lines") + self._fill_check_seed_lines(tw, testdata_dir, tmp_path) + _find_widget(tw, "in_line").set_value({"path": "", "layer": ""}) + assert tw.get_widgets_arguments() is None + + def test_empty_required_output_path_is_rejected(self, make_tool_widget, testdata_dir, tmp_path): + tw = make_tool_widget("Check Seed Lines") + self._fill_check_seed_lines(tw, testdata_dir, tmp_path) + # a layer without a path encodes as "|checked", which must still count as empty + _find_widget(tw, "out_line").set_value({"path": "", "layer": "checked"}) + assert tw.get_widgets_arguments() is None + + def test_empty_optional_field_is_accepted(self, make_tool_widget, testdata_dir, tmp_path): + tw = make_tool_widget("Check Seed Lines") + self._fill_check_seed_lines(tw, testdata_dir, tmp_path) + in_raster = _find_widget(tw, "in_raster") + assert in_raster.optional + in_raster.set_value("") + assert tw.get_widgets_arguments() is not None diff --git a/tests/pytest_qt/test_tool_widgets.py b/tests/pytest_qt/test_tool_widgets.py index 4e9a0f0..14e028d 100644 --- a/tests/pytest_qt/test_tool_widgets.py +++ b/tests/pytest_qt/test_tool_widgets.py @@ -716,7 +716,7 @@ def test_optional_visible_when_advanced_on(self, make_tool_widget): if w.optional: assert not w.isHidden() - def test_missing_input_history_clears_same_output_path(self, qtbot, tmp_path): + def test_missing_input_history_keeps_same_output_path(self, qtbot, tmp_path): missing = str(tmp_path / "history_missing.gpkg") tool_args = [ { @@ -747,11 +747,10 @@ def test_missing_input_history_clears_same_output_path(self, qtbot, tmp_path): in_widget = next(w for w in tw.widget_list if w.variable == "in_line") out_widget = next(w for w in tw.widget_list if w.variable == "out_line") - # the missing input is kept and flagged; the output with the same path is cleared + # the missing input is kept and flagged; the saved output is loaded as-is assert in_widget.value["path"] == missing assert in_widget.missing_input_error - assert out_widget.value["path"] == "" - assert out_widget.value["layer"] == "" + assert out_widget.value == {"path": missing, "layer": "Result_layer"} def test_missing_input_is_kept_flagged_and_blocks_run(self, qtbot, tmp_path): missing = str(tmp_path / "gone.tif") @@ -814,21 +813,45 @@ def test_loading_existing_output_layer_does_not_pop_tooltip(self, qtbot, tmp_pat assert "overwritten" in widget.layer_combo.toolTip() show_text.assert_not_called() - def test_clear_missing_inputs_empties_only_missing_paths(self, qtbot, tmp_path): - existing = tmp_path / "here.tif" - existing.write_bytes(b"") - missing_vector = str(tmp_path / "gone.gpkg") + def test_missing_gpkg_layer_is_kept_flagged_and_blocks_run(self, qtbot, tmp_path): + import geopandas as gpd + from shapely.geometry import LineString + + gpkg = tmp_path / "lines.gpkg" + gpd.GeoDataFrame(geometry=[LineString([(0, 0), (1, 1)])], crs=3400).to_file(gpkg, layer="seed_lines") tool_args = [ { - "name": "Input raster", - "description": "Input raster", - "variable": "in_raster", - "parameter_type": {"ExistingFile": ["raster"]}, + "name": "Input line", + "description": "Input vector", + "variable": "in_line", + "parameter_type": {"ExistingFile": ["vector"]}, "optional": False, "default_value": "", - "saved_value": str(existing), + "saved_value": f"{gpkg}|seed_lines_vo", "output": False, }, + ] + + tw = ToolWidgets("Missing layer", tool_args, show_advanced=True) + qtbot.addWidget(tw) + widget = tw.widget_list[0] + + assert widget.value == {"path": str(gpkg), "layer": "seed_lines_vo"} + assert widget.layer_combo.currentText() == "seed_lines_vo" + assert "seed_lines_vo" in widget.missing_input_error + assert widget.in_file.styleSheet() + assert widget.layer_combo.styleSheet() + assert tw.get_widgets_arguments() is None + + # choosing a layer that exists clears the flag + widget.layer_combo.setCurrentIndex(widget._find_layer_index_by_name("seed_lines")) + assert widget.missing_input_error == "" + assert widget.in_file.styleSheet() == "" + assert widget.layer_combo.styleSheet() == "" + assert tw.get_widgets_arguments() == {"in_line": f"{gpkg}|seed_lines"} + + def test_no_history_starts_with_empty_paths(self, qtbot): + tool_args = [ { "name": "Input line", "description": "Input vector", @@ -836,18 +859,14 @@ def test_clear_missing_inputs_empties_only_missing_paths(self, qtbot, tmp_path): "parameter_type": {"ExistingFile": ["vector"]}, "optional": False, "default_value": "", - "saved_value": f"{missing_vector}|seed_lines", "output": False, }, ] - tw = ToolWidgets("Startup history", tool_args, show_advanced=True) + tw = ToolWidgets("No history", tool_args, show_advanced=True) qtbot.addWidget(tw) - tw.clear_missing_inputs() - - raster, line = tw.widget_list - assert raster.in_file.text() == str(existing) - assert line.value == {"path": "", "layer": ""} - assert line.in_file.text() == "" - assert line.missing_input_error == "" - assert line.in_file.styleSheet() == "" + widget = tw.widget_list[0] + + assert widget.in_file.text() == "" + assert widget.missing_input_error == "" + assert widget.in_file.styleSheet() == "" diff --git a/tests/test_check_seed_line_qc.py b/tests/test_check_seed_line_qc.py index 77e8e4b..2c73948 100644 --- a/tests/test_check_seed_line_qc.py +++ b/tests/test_check_seed_line_qc.py @@ -1421,3 +1421,47 @@ def test_schema_centerline_exposes_guided_strategy_parameter(): assert simplify_diameter["depends_on"]["variable"] == "simplify_centerline" assert simplify_diameter["depends_on"]["condition"] is True assert simplify_diameter["depends_on"]["mode"] == "inline" + + +def test_check_seed_line_numbers_split_pieces_along_each_line(tmp_path, monkeypatch): + # two crossing lines are split at the crossing into four pieces + in_gpkg = _write_seed_input( + tmp_path, + [LineString([(0.0, 50.0), (100.0, 50.0)]), LineString([(50.0, 0.0), (50.0, 100.0)])], + ) + out_gpkg = tmp_path / "seed_output.gpkg" + + monkeypatch.setattr(csl.sp_common, "vector_crs", lambda *_args, **_kwargs: object()) + monkeypatch.setattr(csl.sp_common, "raster_crs", lambda *_args, **_kwargs: object()) + monkeypatch.setattr(csl.sp_common, "compare_crs", lambda *_args, **_kwargs: True) + no_issues = { + "short_line": 0, + "close_vertices": 0, + "unsnapped_endpoint": 0, + "self_crossing": 0, + "overlap": 0, + "total": 0, + } + monkeypatch.setattr(acsl_report, "generate_qc_report", lambda gdf, *_args, **_kwargs: (None, no_issues)) + + csl.check_seed_line( + in_line=f"{in_gpkg.as_posix()}|seed_lines", + in_raster="", + out_line=f"{out_gpkg.as_posix()}|seed_checked", + clip_to_chm_footprint=False, + remove_short_lines=False, + preclean_vertices=False, + snap_close_endpoints=False, + group_lines=False, + densify_long_lines=False, + apply_seed_line_correction=False, + ) + + out = gpd.read_file(out_gpkg, layer="seed_checked") + assert len(out) == 4 + for _, group in out.groupby("OLnFID"): + group = group.sort_values("OLnSEG") + assert group["OLnSEG"].tolist() == [0, 1] + # segment 1 starts where segment 0 ends + first, second = group.geometry.tolist() + assert Point(first.coords[-1]).distance(Point(second.coords[0])) < 1e-6