From 60f50c8860325db4dc0d7fe2d7b8e9cb6dbbef05 Mon Sep 17 00:00:00 2001 From: Tehreem Hassan Date: Mon, 12 Oct 2026 12:10:39 +1100 Subject: [PATCH 1/6] linear geology implemented --- aemworkflow/linear_geology.py | 293 ++++++++++++++++++++++++++++++++++ 1 file changed, 293 insertions(+) create mode 100644 aemworkflow/linear_geology.py diff --git a/aemworkflow/linear_geology.py b/aemworkflow/linear_geology.py new file mode 100644 index 0000000..971b952 --- /dev/null +++ b/aemworkflow/linear_geology.py @@ -0,0 +1,293 @@ +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 parse_folder_lst(folder_lst_path: str) -> List[Tuple[str, int]]: + """ + Parse folder.lst returning a list of (shapefile_stem, column_index) tuples. + Each row format: {stem} {directory} {column_index} + The directory is ignored — map shapefiles are located by stem in map_data_dir. + """ + entries = [] + with open(folder_lst_path, 'r') as f: + for line in f: + line = line.strip() + if not line: + continue + parts = line.split() + if len(parts) >= 3: + stem = parts[0] + col = int(parts[2]) + entries.append((stem, col)) + return entries + + +def path_to_point_gmt(path_file: str, output_gmt: str, crs_in: int, crs_out: int = 4283, + logger_session=logger) -> None: + """ + Translate all_pts_i_gmt.awk: convert a .path.txt file into a GMT point file. + Each row in the path file becomes a point feature with linenum and flib attributes. + Columns used: col1=linenum, col2=flib, col5=x(easting), col6=y(northing). + """ + 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(f"# @Je{crs_in}\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) < 6: + continue + linenum = parts[0] + flib = parts[1] + x = parts[4] + y = parts[5] + out.write(">\n") + out.write(f"# @D{linenum}|{flib}\n") + out.write(f"{x} {y}\n") + + logger_session.info(f"GMT point file written: {Path(output_gmt).name}") + + +def path_gmt_to_shp(gmt_file: str, shp_file: str, crs_in: int, crs_out: int, + logger_session=logger) -> None: + """Convert a GMT point file to a shapefile, reprojecting from crs_in to crs_out.""" + cmd = [ + get_ogr_path(), + "-f", "ESRI Shapefile", + "-s_srs", f"EPSG:{crs_in}", + "-t_srs", f"EPSG:{crs_out}", + shp_file, + gmt_file, + ] + run_command(cmd) + 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 the polygon shapefile, 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 os.listdir(point_shp_dir): + if not filename.endswith(".shp"): + continue + path = os.path.join(point_shp_dir, filename) + points = gpd.read_file(path) + 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: read the joined point shapefile (converted + to GMT), group consecutive points by column_index value, and write 5-point + rectangular polygons (height=20 image units) to a GMT polygon file. + + The joined shapefile is first converted to GMT format by the caller, then this + function reads that GMT directly. + """ + logger_session.info(f"Building polygon GMT from: {Path(joined_shp).name}, column index: {column_index}") + + # Convert joined shapefile to intermediate GMT so we can read @D metadata + stem = Path(joined_shp).stem + work_dir = str(Path(joined_shp).parent) + path_surfgeo_gmt = os.path.join(work_dir, f"{stem}_path_SurfGeo.gmt") + + cmd = [get_ogr_path(), "-f", "GMT", path_surfgeo_gmt, joined_shp] + run_command(cmd) + + # Parse the GMT and build polygons + 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("|") + # column_index is 1-based as in the AWK (clm variable) + 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.""" + parent = Path(input_directory) + for child in parent.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, crs: str, + logger_session=logger) -> bool: + """ + Run the full linear geology pipeline for all map datasets. + + Expected input_directory structure: + *.path.txt — flight line geometry files + map_data/ (or Map_data/) — polygon shapefiles; optionally folder.lst + + If folder.lst is present it controls which shapefiles are processed and which + column index to use per dataset. If absent, all *.shp files in map_data/ are + processed using the default column index (6). + + Output goes to output_directory/lin_geo/{map_stem}/ per dataset. + Returns True on success, False on any failure. + """ + DEFAULT_COLUMN = 6 + + try: + crs_in = int(crs) + 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 + + folder_lst = os.path.join(map_data_dir, "folder.lst") + + if Path(folder_lst).is_file(): + entries = parse_folder_lst(folder_lst) + if not entries: + logger_session.error("folder.lst is empty or could not be parsed.") + return False + logger_session.info(f"Using folder.lst: {len(entries)} dataset(s) defined.") + else: + shp_files = sorted(Path(map_data_dir).glob("*.shp")) + if not shp_files: + logger_session.error("No shapefiles found in map_data directory.") + return False + entries = [(s.stem, DEFAULT_COLUMN) for s in shp_files] + logger_session.warning( + f"folder.lst not found — processing {len(entries)} shapefile(s) with default column {DEFAULT_COLUMN}." + ) + + 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, crs_in, logger_session=logger_session) + path_gmt_to_shp(gmt_out, shp_out, crs_in, 4283, logger_session=logger_session) + + # Stage 2 + 3: per 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: {polygon_shp}") + continue + + logger_session.info(f"Processing map dataset: {map_stem}") + + 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) + + # Stage 2: spatial join + spatial_join(point_shp_dir, polygon_shp, joined_dir, logger_session=logger_session) + + # Stage 3: build polygon GMT + SHP per joined file + 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) + + cmd = [get_ogr_path(), "-f", "ESRI Shapefile", poly_shp, poly_gmt] + run_command(cmd) + 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 From 259330550cf9f7e8bea1f4dc0dd7cd1e4d7ceac0 Mon Sep 17 00:00:00 2001 From: Tehreem Hassan Date: Mon, 12 Oct 2026 14:33:04 +1100 Subject: [PATCH 2/6] Use path file lon/lat coordinates instead of CRS reprojection --- aemworkflow/linear_geology.py | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/aemworkflow/linear_geology.py b/aemworkflow/linear_geology.py index 971b952..7f070ce 100644 --- a/aemworkflow/linear_geology.py +++ b/aemworkflow/linear_geology.py @@ -28,18 +28,18 @@ def parse_folder_lst(folder_lst_path: str) -> List[Tuple[str, int]]: return entries -def path_to_point_gmt(path_file: str, output_gmt: str, crs_in: int, crs_out: int = 4283, - logger_session=logger) -> None: +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. - Each row in the path file becomes a point feature with linenum and flib attributes. - Columns used: col1=linenum, col2=flib, col5=x(easting), col6=y(northing). + 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(f"# @Je{crs_in}\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") @@ -47,27 +47,24 @@ def path_to_point_gmt(path_file: str, output_gmt: str, crs_in: int, crs_out: int with open(path_file, 'r') as f: for line in f: parts = line.strip().split() - if len(parts) < 6: + if len(parts) < 8: continue linenum = parts[0] flib = parts[1] - x = parts[4] - y = parts[5] + lon = parts[6] + lat = parts[7] out.write(">\n") out.write(f"# @D{linenum}|{flib}\n") - out.write(f"{x} {y}\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, crs_in: int, crs_out: int, - logger_session=logger) -> None: - """Convert a GMT point file to a shapefile, reprojecting from crs_in to crs_out.""" +def path_gmt_to_shp(gmt_file: str, shp_file: str, logger_session=logger) -> None: + """Convert a GMT point file (EPSG:4283) to a shapefile with no reprojection.""" cmd = [ get_ogr_path(), "-f", "ESRI Shapefile", - "-s_srs", f"EPSG:{crs_in}", - "-t_srs", f"EPSG:{crs_out}", shp_file, gmt_file, ] @@ -194,7 +191,7 @@ def find_map_data_dir(input_directory: str) -> str: return "" -def run_linear_geology(input_directory: str, output_directory: str, crs: str, +def run_linear_geology(input_directory: str, output_directory: str, logger_session=logger) -> bool: """ Run the full linear geology pipeline for all map datasets. @@ -213,7 +210,6 @@ def run_linear_geology(input_directory: str, output_directory: str, crs: str, DEFAULT_COLUMN = 6 try: - crs_in = int(crs) map_data_dir = find_map_data_dir(input_directory) if not map_data_dir: @@ -253,8 +249,8 @@ def run_linear_geology(input_directory: str, output_directory: str, crs: str, 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, crs_in, logger_session=logger_session) - path_gmt_to_shp(gmt_out, shp_out, crs_in, 4283, logger_session=logger_session) + 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 map dataset for map_stem, col_idx in entries: From c0dba01a1794930b5b7be93b08cf403a71729bce Mon Sep 17 00:00:00 2001 From: Tehreem Hassan Date: Tue, 13 Oct 2026 11:38:31 +1100 Subject: [PATCH 3/6] Use map data from map_data folder --- aemworkflow/linear_geology.py | 121 ++++++++-------------------------- 1 file changed, 27 insertions(+), 94 deletions(-) diff --git a/aemworkflow/linear_geology.py b/aemworkflow/linear_geology.py index 7f070ce..0e5b0a2 100644 --- a/aemworkflow/linear_geology.py +++ b/aemworkflow/linear_geology.py @@ -1,6 +1,6 @@ import os from pathlib import Path -from typing import List, Tuple +from typing import Dict, List, Tuple import geopandas as gpd from loguru import logger @@ -8,24 +8,9 @@ from aemworkflow.utilities import get_ogr_path, run_command -def parse_folder_lst(folder_lst_path: str) -> List[Tuple[str, int]]: - """ - Parse folder.lst returning a list of (shapefile_stem, column_index) tuples. - Each row format: {stem} {directory} {column_index} - The directory is ignored — map shapefiles are located by stem in map_data_dir. - """ - entries = [] - with open(folder_lst_path, 'r') as f: - for line in f: - line = line.strip() - if not line: - continue - parts = line.split() - if len(parts) >= 3: - stem = parts[0] - col = int(parts[2]) - entries.append((stem, col)) - return entries +def get_map_data_defaults(map_data_dir: str) -> Dict[str, int]: + """Return {stem: 1} for every .shp in map_data_dir.""" + return {shp.stem: 1 for shp in sorted(Path(map_data_dir).glob("*.shp"))} def path_to_point_gmt(path_file: str, output_gmt: str, logger_session=logger) -> None: @@ -61,14 +46,8 @@ def path_to_point_gmt(path_file: str, output_gmt: str, logger_session=logger) -> def path_gmt_to_shp(gmt_file: str, shp_file: str, logger_session=logger) -> None: - """Convert a GMT point file (EPSG:4283) to a shapefile with no reprojection.""" - cmd = [ - get_ogr_path(), - "-f", "ESRI Shapefile", - shp_file, - gmt_file, - ] - run_command(cmd) + """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}") @@ -76,7 +55,7 @@ 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 the polygon shapefile, writing *_new.shp to output_dir. + 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) @@ -85,8 +64,7 @@ def spatial_join(point_shp_dir: str, polygon_shp: str, output_dir: str, for filename in os.listdir(point_shp_dir): if not filename.endswith(".shp"): continue - path = os.path.join(point_shp_dir, filename) - points = gpd.read_file(path) + 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" @@ -97,26 +75,16 @@ def spatial_join(point_shp_dir: str, polygon_shp: str, output_dir: str, def build_polygon_gmt(joined_shp: str, output_gmt: str, column_index: int, logger_session=logger) -> None: """ - Translate lin_geology_5p_clm.awk: read the joined point shapefile (converted - to GMT), group consecutive points by column_index value, and write 5-point - rectangular polygons (height=20 image units) to a GMT polygon file. - - The joined shapefile is first converted to GMT format by the caller, then this - function reads that GMT directly. + 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 from: {Path(joined_shp).name}, column index: {column_index}") + logger_session.info(f"Building polygon GMT: {Path(joined_shp).name}, col={column_index}") - # Convert joined shapefile to intermediate GMT so we can read @D metadata stem = Path(joined_shp).stem - work_dir = str(Path(joined_shp).parent) - path_surfgeo_gmt = os.path.join(work_dir, f"{stem}_path_SurfGeo.gmt") - - cmd = [get_ogr_path(), "-f", "GMT", path_surfgeo_gmt, joined_shp] - run_command(cmd) + 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]) - # Parse the GMT and build polygons - h1 = "" - h2 = "" + h1 = h2 = "" first = True current_key = None x_pts: list = [] @@ -135,19 +103,15 @@ def _write_polygon(x_list: list) -> None: 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("|") - # column_index is 1-based as in the AWK (clm variable) key = fields[column_index - 1] if len(fields) >= column_index else None if not header_written: @@ -184,56 +148,29 @@ def _write_polygon(x_list: list) -> None: def find_map_data_dir(input_directory: str) -> str: """Return the map_data subfolder path, case-insensitive. Empty string if not found.""" - parent = Path(input_directory) - for child in parent.iterdir(): + 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 for all map datasets. - - Expected input_directory structure: - *.path.txt — flight line geometry files - map_data/ (or Map_data/) — polygon shapefiles; optionally folder.lst + Run the full linear geology pipeline. - If folder.lst is present it controls which shapefiles are processed and which - column index to use per dataset. If absent, all *.shp files in map_data/ are - processed using the default column index (6). - - Output goes to output_directory/lin_geo/{map_stem}/ per dataset. - Returns True on success, False on any failure. + 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 """ - DEFAULT_COLUMN = 6 - 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 - folder_lst = os.path.join(map_data_dir, "folder.lst") - - if Path(folder_lst).is_file(): - entries = parse_folder_lst(folder_lst) - if not entries: - logger_session.error("folder.lst is empty or could not be parsed.") - return False - logger_session.info(f"Using folder.lst: {len(entries)} dataset(s) defined.") - else: - shp_files = sorted(Path(map_data_dir).glob("*.shp")) - if not shp_files: - logger_session.error("No shapefiles found in map_data directory.") - return False - entries = [(s.stem, DEFAULT_COLUMN) for s in shp_files] - logger_session.warning( - f"folder.lst not found — processing {len(entries)} shapefile(s) with default column {DEFAULT_COLUMN}." - ) - path_files = sorted(Path(input_directory).glob("*.path.txt")) if not path_files: logger_session.error("No .path.txt files found in input directory.") @@ -252,33 +189,29 @@ def run_linear_geology(input_directory: str, output_directory: str, 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 map dataset + # 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: {polygon_shp}") + logger_session.warning(f"Map shapefile not found, skipping: {map_stem}.shp") continue - logger_session.info(f"Processing map dataset: {map_stem}") + 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) - # Stage 2: spatial join spatial_join(point_shp_dir, polygon_shp, joined_dir, logger_session=logger_session) - # Stage 3: build polygon GMT + SHP per joined file 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) - - cmd = [get_ogr_path(), "-f", "ESRI Shapefile", poly_shp, poly_gmt] - run_command(cmd) + 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.") From c548401588c43c949e03d208a42605e57f35e08e Mon Sep 17 00:00:00 2001 From: Tehreem Hassan Date: Tue, 13 Oct 2026 13:09:49 +1100 Subject: [PATCH 4/6] Linear geology cli version implemented --- CHANGELOG.md | 5 +- README.rst | 22 ++ aemworkflow/aemworkflow.py | 15 + aemworkflow/linear_geology.py | 11 +- pyproject.toml | 2 +- tests/test_linear_geology.py | 599 ++++++++++++++++++++++++++++++++++ 6 files changed, 646 insertions(+), 8 deletions(-) create mode 100644 tests/test_linear_geology.py 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..e7e727c 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 index 0e5b0a2..40c91cc 100644 --- a/aemworkflow/linear_geology.py +++ b/aemworkflow/linear_geology.py @@ -1,6 +1,6 @@ import os from pathlib import Path -from typing import Dict, List, Tuple +from typing import List, Tuple import geopandas as gpd from loguru import logger @@ -8,11 +8,6 @@ from aemworkflow.utilities import get_ogr_path, run_command -def get_map_data_defaults(map_data_dir: str) -> Dict[str, int]: - """Return {stem: 1} for every .shp in map_data_dir.""" - return {shp.stem: 1 for shp in sorted(Path(map_data_dir).glob("*.shp"))} - - 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. @@ -220,3 +215,7 @@ def run_linear_geology(input_directory: str, output_directory: str, 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_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 From 6779a48a622d1304b33ba41af42e566ce6b596e1 Mon Sep 17 00:00:00 2001 From: Tehreem Hassan Date: Tue, 13 Oct 2026 13:14:55 +1100 Subject: [PATCH 5/6] readme updated --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index e7e727c..55d7dbf 100644 --- a/README.rst +++ b/README.rst @@ -288,7 +288,7 @@ Argument Required Default Options 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 -============================ ============== =============== ================================================ ============================================== +============================= ============== =============== ================================================ ============================================= From cad662572154f23c39694f54c0d8086f87c2969f Mon Sep 17 00:00:00 2001 From: Tehreem Hassan Date: Tue, 13 Oct 2026 13:59:57 +1100 Subject: [PATCH 6/6] unit tests fixed --- aemworkflow/linear_geology.py | 2 +- tests/test_interpretation.py | 61 +++++++++++++++++++++++++++-------- 2 files changed, 49 insertions(+), 14 deletions(-) diff --git a/aemworkflow/linear_geology.py b/aemworkflow/linear_geology.py index 40c91cc..6b9d21f 100644 --- a/aemworkflow/linear_geology.py +++ b/aemworkflow/linear_geology.py @@ -56,7 +56,7 @@ def spatial_join(point_shp_dir: str, polygon_shp: str, output_dir: str, polygons = gpd.read_file(polygon_shp) logger_session.info(f"Loaded polygon shapefile: {Path(polygon_shp).name} ({len(polygons)} features)") - for filename in os.listdir(point_shp_dir): + 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)) 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