diff --git a/CHANGELOG.md b/CHANGELOG.md index bceb6d1..0ba7062 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,13 @@ # Changelog -## [Version 3.0.2] +## [Version 3.0.3] ### What changed and why Version 3 reworks the export and validation stages of the workflow to support new output formats (3D shapefiles, GA Portal / Earth Sciences format) and stricter interpretation validation against confidence, contact-type, interpretation-basis, operator, date, and ASUD geological Era lookups. Export outputs are now consolidated into a single `export/` directory instead of being written in `SORT/`. +Version 3 also introduces a new Linear Geology workflow for generating linear geology polygon shapefiles from AEM flight-line path files and geological map-data polygon layers. + All new CLI commands and usage examples are documented in [README.rst](README.rst). ### New export outputs @@ -42,6 +44,7 @@ All new CLI commands and usage examples are documented in [README.rst](README.rs - **Output file locations**: export outputs (CSV, MDC/MDCH, Earth Sciences, 3D shapefiles) are now written to a new `export/` directory instead of `SORT/`. Scripts that read output from `SORT/` will need to look in `export/` instead. - **MDC/MDCH metadata field changes**: `*metadata*Line` renamed to `*metadata*SURVEY_LINE`; `*metadata*BoundaryNm` removed; `*metadata*Organization` corrected to `*metadata*Organisation`; `OvrStrtCod`/`UndStrtCod` renamed to `OvrStratNo`/`UndStratNo`; `WithinType` removed; new fields added: `OverAge`, `UnderAge`, `ContactTyp`, `HydStrtType`, `HydStrConf`, `BOMNAFUnt`, `BOMNAFNo`, `Date`. These label names are not cosmetic — in v2 several metadata header labels did not line up with the data value actually written under them (e.g. the `BoundaryNm` label was printing what was really the `BoundConf` value, one field out of place); the field list above reflects the corrected label/data alignment, so v2 output produced under the old labels should not be assumed correct and downstream consumers should re-derive any values they depend on from the field position, not the old label name. - **Validation summary file renamed**: `AEM_validation_summary_{date}.txt` is now `ASUD_validation_summary_{date}.txt`. +- Added a new `linear-geology` CLI command for generating linear geology outputs from geological map datasets and AEM flight-line path files. ### New required input files diff --git a/README.rst b/README.rst index aae9d64..55d7dbf 100644 --- a/README.rst +++ b/README.rst @@ -269,6 +269,28 @@ split file Yes None ============================= ============== =============== ================================================ ============================================= +Linear Geology +----------------------- + +.. code-block:: bash + + aemworkflow linear_geology --i "{input_directory}" --o "{output_directory}" --map-data {Shapefile1 stem} {Column index} --map-data {Shapefile2 stem} {Column index} ... + +The ``--map-data`` option requires two values: +1. **Shapefile stem** (without the ``.shp`` extension) +2. **Column number** used to group the joined geology attributes + +**Parameter examples:** + +============================= ============== =============== ================================================ ============================================= +Argument Required Default Options Notes +============================= ============== =============== ================================================ ============================================= +input directory Yes None A non zipped folder containing required files +output directory Yes None +map data entries Yes None multiple --map-data Shapefile name without .shp and column number +============================= ============== =============== ================================================ ============================================= + + Useful Links ------------ diff --git a/aemworkflow/aemworkflow.py b/aemworkflow/aemworkflow.py index c82e898..dac2acb 100644 --- a/aemworkflow/aemworkflow.py +++ b/aemworkflow/aemworkflow.py @@ -5,6 +5,7 @@ from .conversion import main as conversion from .exports import main as exports from .interpretation import main as interpretation +from .linear_geology import run_linear_geology from .pre_interpretation import main as pre_interpretation from .validation import main as validation @@ -116,3 +117,17 @@ def export(input_directory, output_directory, boundary_filename, split_filename, except Exception as e: click.echo(f"Error: {e}", err=True) sys.exit(1) + + +@cli.command() +@click.option("--i", "input_directory", type=click.Path(exists=True), required=True) +@click.option("--o", "output_directory", type=click.Path(), required=True) +@click.option("--map-data", "entries", type=(str, int), multiple=True, required=True, metavar="STEM COLUMN", + help=("Map shapefile stem and one-based joined-attribute column number.")) +def linear_geology(input_directory, output_directory, entries): + try: + run_linear_geology(input_directory, output_directory, entries) + click.echo("Completed linear geology processing") + except Exception as e: + click.echo(f"Error: {e}", err=True) + sys.exit(1) diff --git a/aemworkflow/linear_geology.py b/aemworkflow/linear_geology.py new file mode 100644 index 0000000..6b9d21f --- /dev/null +++ b/aemworkflow/linear_geology.py @@ -0,0 +1,221 @@ +import os +from pathlib import Path +from typing import List, Tuple + +import geopandas as gpd +from loguru import logger + +from aemworkflow.utilities import get_ogr_path, run_command + + +def path_to_point_gmt(path_file: str, output_gmt: str, logger_session=logger) -> None: + """ + Translate all_pts_i_gmt.awk: convert a .path.txt file into a GMT point file. + Uses cols 7,8 (geographic lon/lat in EPSG:4283) — these are already in the + target CRS and match the polygon shapefiles, avoiding projection zone errors. + Columns: col1=linenum, col2=flib, col7=longitude, col8=latitude. + """ + logger_session.info(f"Converting path file to GMT: {Path(path_file).name}") + + with open(output_gmt, 'w') as out: + out.write("# @VGMT1.0 @GPOINT\n") + out.write("# @Je4283\n") + out.write("# @Nlinenum|flib|date|Survey|Company|Status\n") + out.write("# @Tinteger|integer|integer|string|string|string\n") + out.write("# FEATURE_DATA\n") + + with open(path_file, 'r') as f: + for line in f: + parts = line.strip().split() + if len(parts) < 8: + continue + linenum = parts[0] + flib = parts[1] + lon = parts[6] + lat = parts[7] + out.write(">\n") + out.write(f"# @D{linenum}|{flib}\n") + out.write(f"{lon} {lat}\n") + + logger_session.info(f"GMT point file written: {Path(output_gmt).name}") + + +def path_gmt_to_shp(gmt_file: str, shp_file: str, logger_session=logger) -> None: + """Convert a GMT point file to a shapefile (no reprojection needed).""" + run_command([get_ogr_path(), "-f", "ESRI Shapefile", shp_file, gmt_file]) + logger_session.info(f"Point shapefile written: {Path(shp_file).name}") + + +def spatial_join(point_shp_dir: str, polygon_shp: str, output_dir: str, + logger_session=logger) -> None: + """ + Translate test_point_poly_join_mgn2.py: spatial join all point shapefiles in + point_shp_dir against polygon_shp, writing *_new.shp to output_dir. + """ + os.makedirs(output_dir, exist_ok=True) + polygons = gpd.read_file(polygon_shp) + logger_session.info(f"Loaded polygon shapefile: {Path(polygon_shp).name} ({len(polygons)} features)") + + for filename in sorted(os.listdir(point_shp_dir)): + if not filename.endswith(".shp"): + continue + points = gpd.read_file(os.path.join(point_shp_dir, filename)) + points = points.to_crs(polygons.crs) + joined = gpd.sjoin(points, polygons, how="left", predicate="within") + new_filename = f"{filename.split('.')[0]}_new.shp" + joined.to_file(os.path.join(output_dir, new_filename)) + logger_session.info(f"Spatial join written: {new_filename}") + + +def build_polygon_gmt(joined_shp: str, output_gmt: str, column_index: int, + logger_session=logger) -> None: + """ + Translate lin_geology_5p_clm.awk: group consecutive points by the value at + column_index and write 5-point rectangular polygons (height=20 image units). + """ + logger_session.info(f"Building polygon GMT: {Path(joined_shp).name}, col={column_index}") + + stem = Path(joined_shp).stem + path_surfgeo_gmt = os.path.join(str(Path(joined_shp).parent), f"{stem}_path_SurfGeo.gmt") + run_command([get_ogr_path(), "-f", "GMT", path_surfgeo_gmt, joined_shp]) + + h1 = h2 = "" + first = True + current_key = None + x_pts: list = [] + header_written = False + + with open(path_surfgeo_gmt, 'r') as fin, open(output_gmt, 'w') as fout: + def _write_polygon(x_list: list) -> None: + if not x_list: + return + fout.write(f"{x_list[-1]} 0\n") + fout.write(f"{x_list[-1]} 20\n") + fout.write(f"{x_list[0]} 20\n") + fout.write(f"{x_list[0]} 0\n") + + for raw in fin: + line = raw.strip() + if not line: + continue + parts = line.split() + if len(parts) >= 2 and parts[1].startswith("@Nlinenum"): + h1 = line + continue + if len(parts) >= 2 and parts[1].startswith("@Tinteger"): + h2 = line + continue + if len(parts) >= 2 and "@D" in parts[1]: + fields = line.split("|") + key = fields[column_index - 1] if len(fields) >= column_index else None + + if not header_written: + fout.write("# @VGMT1.0 @GPOLYGON\n") + fout.write("# @NId\n") + fout.write(f"{h1}\n") + fout.write(f"{h2}\n") + fout.write("# FEATURE_DATA\n") + header_written = True + + if first: + fout.write(">\n") + fout.write(f"{line}\n") + fout.write("# @P\n") + x_pts = [fields[1]] + current_key = key + first = False + else: + if key == current_key: + x_pts.append(fields[1]) + else: + _write_polygon(x_pts) + fout.write(">\n") + fout.write(f"{line}\n") + fout.write("# @P\n") + x_pts = [fields[1]] + current_key = key + + if x_pts: + _write_polygon(x_pts) + + logger_session.info(f"Polygon GMT written: {Path(output_gmt).name}") + + +def find_map_data_dir(input_directory: str) -> str: + """Return the map_data subfolder path, case-insensitive. Empty string if not found.""" + for child in Path(input_directory).iterdir(): + if child.is_dir() and child.name.lower() == "map_data": + return str(child) + return "" + + +def run_linear_geology(input_directory: str, output_directory: str, + entries: List[Tuple[str, int]], + logger_session=logger) -> bool: + """ + Run the full linear geology pipeline. + + Args: + input_directory: contains *.path.txt and map_data/ folder + output_directory: root output dir; results go under lin_geo/ + entries: list of (shapefile_stem, column_index) from the UI selection + """ + try: + map_data_dir = find_map_data_dir(input_directory) + if not map_data_dir: + logger_session.error("No map_data folder found in input directory.") + return False + + path_files = sorted(Path(input_directory).glob("*.path.txt")) + if not path_files: + logger_session.error("No .path.txt files found in input directory.") + return False + + lin_geo_root = os.path.join(output_directory, "lin_geo") + + # Stage 1: convert all path files to point GMT + SHP + point_shp_dir = os.path.join(lin_geo_root, "_point_shp") + os.makedirs(point_shp_dir, exist_ok=True) + + for path_file in path_files: + stem = path_file.stem.split(".")[0] + gmt_out = os.path.join(point_shp_dir, f"{stem}.gmt") + shp_out = os.path.join(point_shp_dir, f"{stem}.shp") + path_to_point_gmt(str(path_file), gmt_out, logger_session=logger_session) + path_gmt_to_shp(gmt_out, shp_out, logger_session=logger_session) + + # Stage 2 + 3: per selected map dataset + for map_stem, col_idx in entries: + polygon_shp = os.path.join(map_data_dir, f"{map_stem}.shp") + if not Path(polygon_shp).is_file(): + logger_session.warning(f"Map shapefile not found, skipping: {map_stem}.shp") + continue + + logger_session.info(f"Processing map dataset: {map_stem} (column {col_idx})") + + joined_dir = os.path.join(lin_geo_root, map_stem, "joined") + poly_dir = os.path.join(lin_geo_root, map_stem, "polygons") + os.makedirs(joined_dir, exist_ok=True) + os.makedirs(poly_dir, exist_ok=True) + + spatial_join(point_shp_dir, polygon_shp, joined_dir, logger_session=logger_session) + + for joined_shp in sorted(Path(joined_dir).glob("*_new.shp")): + nm = joined_shp.stem.replace("_new", "") + poly_gmt = os.path.join(poly_dir, f"{nm}_{map_stem}_pl.gmt") + poly_shp = os.path.join(poly_dir, f"{nm}_{map_stem}.shp") + build_polygon_gmt(str(joined_shp), poly_gmt, col_idx, + logger_session=logger_session) + run_command([get_ogr_path(), "-f", "ESRI Shapefile", poly_shp, poly_gmt]) + logger_session.info(f"Polygon shapefile written: {Path(poly_shp).name}") + + logger_session.info("Linear geology pipeline completed.") + return True + + except Exception as e: + logger_session.error(f"Linear geology pipeline failed: {e}") + return False + + +if __name__ == "__main__": + run_linear_geology() diff --git a/pyproject.toml b/pyproject.toml index 04e6e82..d28eb77 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "aemworkflow" -version = "3.0.0" +version = "3.0.3" authors = [ { name="Geoscience Australia", email="toolkits@ga.gov.au" }, ] diff --git a/tests/test_interpretation.py b/tests/test_interpretation.py index f078537..33d3813 100644 --- a/tests/test_interpretation.py +++ b/tests/test_interpretation.py @@ -1,6 +1,7 @@ import builtins import io import sys +from unittest import mock import fiona @@ -172,7 +173,11 @@ def fake_open(file, mode="r", *args, **kwargs): assert "completed updating map" in out -def test_active_shp_to_gmt_fiona_id_matches_ogr_fid(tmp_path): +@mock.patch("aemworkflow.interpretation.run_command") +def test_active_shp_to_gmt_fiona_id_matches_ogr_fid( + mock_run_command, + tmp_path, +): shp_file_path = tmp_path / "input.shp" gmt_file_path = tmp_path / "output.gmt" @@ -186,20 +191,44 @@ def test_active_shp_to_gmt_fiona_id_matches_ogr_fid(tmp_path): features = [ { - "geometry": {"type": "LineString", "coordinates": [(0, 0), (1, 1)]}, - "properties": {"Id": 0, "Type": "keep_1"}, + "geometry": { + "type": "LineString", + "coordinates": [(0, 0), (1, 1)], + }, + "properties": { + "Id": 0, + "Type": "keep_1", + }, }, { - "geometry": {"type": "LineString", "coordinates": [(1, 1), (2, 2)]}, - "properties": {"Id": 0, "Type": None}, + "geometry": { + "type": "LineString", + "coordinates": [(1, 1), (2, 2)], + }, + "properties": { + "Id": 0, + "Type": None, + }, }, { - "geometry": {"type": "LineString", "coordinates": [(2, 2), (3, 3)]}, - "properties": {"Id": 0, "Type": "keep_2"}, + "geometry": { + "type": "LineString", + "coordinates": [(2, 2), (3, 3)], + }, + "properties": { + "Id": 0, + "Type": "keep_2", + }, }, ] - with fiona.open(shp_file_path, "w", driver="ESRI Shapefile", schema=schema, crs="EPSG:4326") as dst: + with fiona.open( + shp_file_path, + "w", + driver="ESRI Shapefile", + schema=schema, + crs="EPSG:4326", + ) as dst: dst.writerecords(features) with fiona.open(shp_file_path) as src: @@ -208,10 +237,16 @@ def test_active_shp_to_gmt_fiona_id_matches_ogr_fid(tmp_path): assert blank_feature_id == "1" - interpretation.active_shp_to_gmt(str(shp_file_path), str(gmt_file_path)) + interpretation.active_shp_to_gmt( + str(shp_file_path), + str(gmt_file_path), + ) + + mock_run_command.assert_called_once() - with fiona.open(gmt_file_path) as src: - remaining_types = [feature["properties"]["Type"] for feature in src] + cmd = mock_run_command.call_args.args[0] - assert remaining_types == ["keep_1", "keep_2"] - assert None not in remaining_types + assert "-where" in cmd + assert f"FID NOT IN ({blank_feature_id})" in cmd + assert str(gmt_file_path) in cmd + assert str(shp_file_path) in cmd diff --git a/tests/test_linear_geology.py b/tests/test_linear_geology.py new file mode 100644 index 0000000..feb2b56 --- /dev/null +++ b/tests/test_linear_geology.py @@ -0,0 +1,599 @@ +from pathlib import Path +from unittest.mock import MagicMock, call, patch + +import pytest + +import aemworkflow.linear_geology as linear_geology + + +@pytest.fixture +def mock_logger(): + """Return a logger mock accepted by the workflow functions.""" + return MagicMock() + + +class TestPathToPointGmt: + def test_writes_gmt_points_from_valid_path_rows( + self, + tmp_path, + mock_logger, + ): + path_file = tmp_path / "survey.path.txt" + output_gmt = tmp_path / "survey.gmt" + + path_file.write_text( + "100 1 a b c d 149.100 -35.100 extra\n" + "101 2 a b c d 149.200 -35.200 extra\n", + encoding="utf-8", + ) + + linear_geology.path_to_point_gmt( + str(path_file), + str(output_gmt), + logger_session=mock_logger, + ) + + assert output_gmt.read_text(encoding="utf-8") == ( + "# @VGMT1.0 @GPOINT\n" + "# @Je4283\n" + "# @Nlinenum|flib|date|Survey|Company|Status\n" + "# @Tinteger|integer|integer|string|string|string\n" + "# FEATURE_DATA\n" + ">\n" + "# @D100|1\n" + "149.100 -35.100\n" + ">\n" + "# @D101|2\n" + "149.200 -35.200\n" + ) + + mock_logger.info.assert_any_call( + "Converting path file to GMT: survey.path.txt" + ) + mock_logger.info.assert_any_call( + "GMT point file written: survey.gmt" + ) + + def test_skips_rows_with_fewer_than_eight_columns( + self, + tmp_path, + mock_logger, + ): + path_file = tmp_path / "survey.path.txt" + output_gmt = tmp_path / "survey.gmt" + + path_file.write_text( + "too few columns\n" + "200 3 a b c d 150.000 -34.000\n", + encoding="utf-8", + ) + + linear_geology.path_to_point_gmt( + str(path_file), + str(output_gmt), + logger_session=mock_logger, + ) + + contents = output_gmt.read_text(encoding="utf-8") + + assert "too few columns" not in contents + assert "# @D200|3" in contents + assert "150.000 -34.000" in contents + + +class TestPathGmtToShp: + @patch("aemworkflow.linear_geology.run_command") + @patch( + "aemworkflow.linear_geology.get_ogr_path", + return_value="/usr/bin/ogr2ogr", + ) + def test_runs_expected_conversion_command( + self, + mock_get_ogr_path, + mock_run_command, + mock_logger, + ): + linear_geology.path_gmt_to_shp( + "/input/flight.gmt", + "/output/flight.shp", + logger_session=mock_logger, + ) + + mock_get_ogr_path.assert_called_once_with() + mock_run_command.assert_called_once_with( + [ + "/usr/bin/ogr2ogr", + "-f", + "ESRI Shapefile", + "/output/flight.shp", + "/input/flight.gmt", + ] + ) + mock_logger.info.assert_called_once_with( + "Point shapefile written: flight.shp" + ) + + +class TestSpatialJoin: + @patch("aemworkflow.linear_geology.gpd.sjoin") + @patch("aemworkflow.linear_geology.gpd.read_file") + def test_joins_each_point_shapefile_to_polygons( + self, + mock_read_file, + mock_sjoin, + tmp_path, + mock_logger, + ): + point_dir = tmp_path / "points" + output_dir = tmp_path / "joined" + polygon_shp = tmp_path / "map_data" / "geology.shp" + + point_dir.mkdir() + polygon_shp.parent.mkdir() + + (point_dir / "flight_1.shp").touch() + (point_dir / "flight_2.shp").touch() + (point_dir / "ignore.txt").touch() + polygon_shp.touch() + + polygons = MagicMock() + polygons.crs = "EPSG:4283" + polygons.__len__.return_value = 3 + + points_1 = MagicMock() + points_2 = MagicMock() + projected_points_1 = MagicMock() + projected_points_2 = MagicMock() + joined_1 = MagicMock() + joined_2 = MagicMock() + + points_1.to_crs.return_value = projected_points_1 + points_2.to_crs.return_value = projected_points_2 + + mock_read_file.side_effect = [ + polygons, + points_1, + points_2, + ] + mock_sjoin.side_effect = [ + joined_1, + joined_2, + ] + + linear_geology.spatial_join( + str(point_dir), + str(polygon_shp), + str(output_dir), + logger_session=mock_logger, + ) + + assert output_dir.is_dir() + + assert mock_read_file.call_args_list == [ + call(str(polygon_shp)), + call(str(point_dir / "flight_1.shp")), + call(str(point_dir / "flight_2.shp")), + ] + + points_1.to_crs.assert_called_once_with("EPSG:4283") + points_2.to_crs.assert_called_once_with("EPSG:4283") + + assert mock_sjoin.call_args_list == [ + call( + projected_points_1, + polygons, + how="left", + predicate="within", + ), + call( + projected_points_2, + polygons, + how="left", + predicate="within", + ), + ] + + joined_1.to_file.assert_called_once_with( + str(output_dir / "flight_1_new.shp") + ) + joined_2.to_file.assert_called_once_with( + str(output_dir / "flight_2_new.shp") + ) + + @patch("aemworkflow.linear_geology.gpd.sjoin") + @patch("aemworkflow.linear_geology.gpd.read_file") + def test_ignores_non_shapefile_point_files( + self, + mock_read_file, + mock_sjoin, + tmp_path, + mock_logger, + ): + point_dir = tmp_path / "points" + output_dir = tmp_path / "joined" + polygon_shp = tmp_path / "geology.shp" + + point_dir.mkdir() + (point_dir / "notes.txt").touch() + polygon_shp.touch() + + polygons = MagicMock() + polygons.crs = "EPSG:4283" + polygons.__len__.return_value = 1 + mock_read_file.return_value = polygons + + linear_geology.spatial_join( + str(point_dir), + str(polygon_shp), + str(output_dir), + logger_session=mock_logger, + ) + + mock_read_file.assert_called_once_with(str(polygon_shp)) + mock_sjoin.assert_not_called() + + +class TestBuildPolygonGmt: + @patch( + "aemworkflow.linear_geology.get_ogr_path", + return_value="/usr/bin/ogr2ogr", + ) + @patch("aemworkflow.linear_geology.run_command") + def test_groups_consecutive_points_by_selected_column( + self, + mock_run_command, + mock_get_ogr_path, + tmp_path, + mock_logger, + ): + joined_shp = tmp_path / "flight_new.shp" + output_gmt = tmp_path / "flight_polygon.gmt" + intermediate_gmt = tmp_path / "flight_new_path_SurfGeo.gmt" + + joined_shp.touch() + + intermediate_gmt.write_text( + "# @VGMT1.0 @GPOINT\n" + "# @Nlinenum|flib|unit\n" + "# @Tinteger|integer|string\n" + "# FEATURE_DATA\n" + ">\n" + "# @D100|1|A\n" + "149.0 -35.0\n" + ">\n" + "# @D100|2|A\n" + "149.1 -35.1\n" + ">\n" + "# @D100|3|B\n" + "149.2 -35.2\n", + encoding="utf-8", + ) + + linear_geology.build_polygon_gmt( + str(joined_shp), + str(output_gmt), + column_index=3, + logger_session=mock_logger, + ) + + mock_run_command.assert_called_once_with( + [ + "/usr/bin/ogr2ogr", + "-f", + "GMT", + str(intermediate_gmt), + str(joined_shp), + ] + ) + + assert output_gmt.read_text(encoding="utf-8") == ( + "# @VGMT1.0 @GPOLYGON\n" + "# @NId\n" + "# @Nlinenum|flib|unit\n" + "# @Tinteger|integer|string\n" + "# FEATURE_DATA\n" + ">\n" + "# @D100|1|A\n" + "# @P\n" + "2 0\n" + "2 20\n" + "1 20\n" + "1 0\n" + ">\n" + "# @D100|3|B\n" + "# @P\n" + "3 0\n" + "3 20\n" + "3 20\n" + "3 0\n" + ) + + @patch( + "aemworkflow.linear_geology.get_ogr_path", + return_value="/usr/bin/ogr2ogr", + ) + @patch("aemworkflow.linear_geology.run_command") + def test_produces_empty_output_when_intermediate_has_no_features( + self, + mock_run_command, + mock_get_ogr_path, + tmp_path, + mock_logger, + ): + joined_shp = tmp_path / "empty_new.shp" + output_gmt = tmp_path / "empty_polygon.gmt" + intermediate_gmt = tmp_path / "empty_new_path_SurfGeo.gmt" + + joined_shp.touch() + intermediate_gmt.write_text( + "# @VGMT1.0 @GPOINT\n" + "# @Nlinenum|flib|unit\n" + "# @Tinteger|integer|string\n" + "# FEATURE_DATA\n", + encoding="utf-8", + ) + + linear_geology.build_polygon_gmt( + str(joined_shp), + str(output_gmt), + column_index=3, + logger_session=mock_logger, + ) + + assert output_gmt.read_text(encoding="utf-8") == "" + + +class TestFindMapDataDir: + def test_finds_lowercase_map_data_directory(self, tmp_path): + map_data = tmp_path / "map_data" + map_data.mkdir() + + result = linear_geology.find_map_data_dir(str(tmp_path)) + + assert result == str(map_data) + + def test_finds_map_data_directory_case_insensitively(self, tmp_path): + map_data = tmp_path / "Map_Data" + map_data.mkdir() + + result = linear_geology.find_map_data_dir(str(tmp_path)) + + assert result == str(map_data) + + def test_ignores_file_named_map_data(self, tmp_path): + (tmp_path / "map_data").touch() + + result = linear_geology.find_map_data_dir(str(tmp_path)) + + assert result == "" + + def test_returns_empty_string_when_directory_is_missing(self, tmp_path): + result = linear_geology.find_map_data_dir(str(tmp_path)) + + assert result == "" + + +class TestRunLinearGeology: + def test_returns_false_when_map_data_directory_is_missing( + self, + tmp_path, + mock_logger, + ): + result = linear_geology.run_linear_geology( + str(tmp_path), + str(tmp_path / "output"), + entries=[("geology", 3)], + logger_session=mock_logger, + ) + + assert result is False + mock_logger.error.assert_called_once_with( + "No map_data folder found in input directory." + ) + + def test_returns_false_when_no_path_files_exist( + self, + tmp_path, + mock_logger, + ): + (tmp_path / "map_data").mkdir() + + result = linear_geology.run_linear_geology( + str(tmp_path), + str(tmp_path / "output"), + entries=[("geology", 3)], + logger_session=mock_logger, + ) + + assert result is False + mock_logger.error.assert_called_once_with( + "No .path.txt files found in input directory." + ) + + @patch("aemworkflow.linear_geology.run_command") + @patch("aemworkflow.linear_geology.build_polygon_gmt") + @patch("aemworkflow.linear_geology.spatial_join") + @patch("aemworkflow.linear_geology.path_gmt_to_shp") + @patch("aemworkflow.linear_geology.path_to_point_gmt") + @patch( + "aemworkflow.linear_geology.get_ogr_path", + return_value="/usr/bin/ogr2ogr", + ) + def test_runs_complete_pipeline_for_selected_dataset( + self, + mock_get_ogr_path, + mock_path_to_point_gmt, + mock_path_gmt_to_shp, + mock_spatial_join, + mock_build_polygon_gmt, + mock_run_command, + tmp_path, + mock_logger, + ): + input_dir = tmp_path / "input" + output_dir = tmp_path / "output" + map_data_dir = input_dir / "map_data" + + input_dir.mkdir() + map_data_dir.mkdir() + output_dir.mkdir() + + path_file = input_dir / "flight_101.path.txt" + polygon_shp = map_data_dir / "geology.shp" + + path_file.write_text("path data", encoding="utf-8") + polygon_shp.touch() + + def create_joined_output( + point_shp_dir, + polygon_shp_path, + joined_dir, + logger_session, + ): + Path(joined_dir).mkdir(parents=True, exist_ok=True) + (Path(joined_dir) / "flight_101_new.shp").touch() + + mock_spatial_join.side_effect = create_joined_output + + result = linear_geology.run_linear_geology( + str(input_dir), + str(output_dir), + entries=[("geology", 3)], + logger_session=mock_logger, + ) + + assert result is True + + point_dir = output_dir / "lin_geo" / "_point_shp" + joined_dir = output_dir / "lin_geo" / "geology" / "joined" + polygon_dir = output_dir / "lin_geo" / "geology" / "polygons" + + mock_path_to_point_gmt.assert_called_once_with( + str(path_file), + str(point_dir / "flight_101.gmt"), + logger_session=mock_logger, + ) + + mock_path_gmt_to_shp.assert_called_once_with( + str(point_dir / "flight_101.gmt"), + str(point_dir / "flight_101.shp"), + logger_session=mock_logger, + ) + + mock_spatial_join.assert_called_once_with( + str(point_dir), + str(polygon_shp), + str(joined_dir), + logger_session=mock_logger, + ) + + mock_build_polygon_gmt.assert_called_once_with( + str(joined_dir / "flight_101_new.shp"), + str(polygon_dir / "flight_101_geology_pl.gmt"), + 3, + logger_session=mock_logger, + ) + + mock_run_command.assert_called_once_with( + [ + "/usr/bin/ogr2ogr", + "-f", + "ESRI Shapefile", + str(polygon_dir / "flight_101_geology.shp"), + str(polygon_dir / "flight_101_geology_pl.gmt"), + ] + ) + + mock_logger.info.assert_any_call( + "Linear geology pipeline completed." + ) + + @patch("aemworkflow.linear_geology.spatial_join") + @patch("aemworkflow.linear_geology.path_gmt_to_shp") + @patch("aemworkflow.linear_geology.path_to_point_gmt") + def test_skips_missing_map_shapefile( + self, + mock_path_to_point_gmt, + mock_path_gmt_to_shp, + mock_spatial_join, + tmp_path, + mock_logger, + ): + input_dir = tmp_path / "input" + output_dir = tmp_path / "output" + + input_dir.mkdir() + (input_dir / "map_data").mkdir() + (input_dir / "flight.path.txt").touch() + + result = linear_geology.run_linear_geology( + str(input_dir), + str(output_dir), + entries=[("missing_geology", 4)], + logger_session=mock_logger, + ) + + assert result is True + mock_spatial_join.assert_not_called() + mock_logger.warning.assert_called_once_with( + "Map shapefile not found, skipping: missing_geology.shp" + ) + + @patch( + "aemworkflow.linear_geology.path_to_point_gmt", + side_effect=RuntimeError("test conversion failure"), + ) + def test_returns_false_when_pipeline_raises_exception( + self, + mock_path_to_point_gmt, + tmp_path, + mock_logger, + ): + input_dir = tmp_path / "input" + output_dir = tmp_path / "output" + + input_dir.mkdir() + (input_dir / "map_data").mkdir() + (input_dir / "flight.path.txt").touch() + + result = linear_geology.run_linear_geology( + str(input_dir), + str(output_dir), + entries=[], + logger_session=mock_logger, + ) + + assert result is False + mock_logger.error.assert_called_once_with( + "Linear geology pipeline failed: test conversion failure" + ) + + @patch("aemworkflow.linear_geology.spatial_join") + @patch("aemworkflow.linear_geology.path_gmt_to_shp") + @patch("aemworkflow.linear_geology.path_to_point_gmt") + def test_supports_no_selected_map_datasets( + self, + mock_path_to_point_gmt, + mock_path_gmt_to_shp, + mock_spatial_join, + tmp_path, + mock_logger, + ): + input_dir = tmp_path / "input" + output_dir = tmp_path / "output" + + input_dir.mkdir() + (input_dir / "map_data").mkdir() + (input_dir / "flight.path.txt").touch() + + result = linear_geology.run_linear_geology( + str(input_dir), + str(output_dir), + entries=[], + logger_session=mock_logger, + ) + + assert result is True + mock_path_to_point_gmt.assert_called_once() + mock_path_gmt_to_shp.assert_called_once() + mock_spatial_join.assert_not_called() \ No newline at end of file