-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmulti_agent_runner.py
More file actions
3227 lines (2837 loc) · 133 KB
/
Copy pathmulti_agent_runner.py
File metadata and controls
3227 lines (2837 loc) · 133 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import ast
import base64
import csv
import datetime
import io
import json
import os
import re
import shutil
import subprocess
import numpy as np
from openai import OpenAI
from copy import deepcopy
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, Optional, List, Tuple
from runner import DEFAULT_CONFIG, deep_update, load_config, run_workflow, resolve_execution_mode
from geo_modeling_workflow import build_geology_model
from existing_results import load_existing_geology_result
from evidence_bundle import build_evidence_bundle, save_evidence_bundle
# =============================================================================
# 0. File helpers
# =============================================================================
def _resolve_geology_context_path(context_path: Path) -> Path:
"""
Resolve the geology context path with lightweight fallbacks.
Primary use-case: config points to *.txt but only *.pdf exists.
"""
candidates: List[Path] = [context_path]
suffix = context_path.suffix.lower()
if suffix:
for ext in (".txt", ".pdf"):
if ext != suffix:
candidates.append(context_path.with_suffix(ext))
else:
candidates.extend([context_path.with_suffix(".txt"), context_path.with_suffix(".pdf")])
if not context_path.is_absolute():
fallback_dir = Path("Geology report")
candidates.extend([fallback_dir / c.name for c in candidates])
seen = set()
unique_candidates: List[Path] = []
for c in candidates:
key = str(c)
if key not in seen:
seen.add(key)
unique_candidates.append(c)
for candidate in unique_candidates:
if candidate.exists():
if candidate != context_path:
print(f"[INFO] Geology context fallback: {context_path} -> {candidate}")
return candidate
tried = ", ".join(str(p) for p in unique_candidates)
raise FileNotFoundError(
f"Geology context file not found: {context_path}. Tried: {tried}"
)
def read_geology_context(context_path: Path) -> str:
resolved_path = _resolve_geology_context_path(context_path)
suffix = resolved_path.suffix.lower()
if suffix == ".pdf":
return _read_pdf_text(resolved_path)
return resolved_path.read_text(encoding="utf-8")
def _stage_report_figures(report_path: Path, output_dir: Path) -> List[Path]:
"""Copy Markdown-referenced result figures beside a report before export."""
report_text = report_path.read_text(encoding="utf-8")
report_dir = report_path.parent
staged: List[Path] = []
references = re.findall(r"!\[[^\]]*\]\(([^)]+)\)", report_text)
for reference in references:
if "://" in reference or reference.startswith("data:"):
continue
relative_path = Path(reference.replace("\\", "/"))
destination = report_dir / relative_path
if destination.is_file():
continue
candidates = [output_dir / relative_path]
candidates.extend(
path for path in output_dir.rglob(relative_path.name)
if report_dir not in path.parents
)
source = next((path for path in candidates if path.is_file()), None)
if source is None:
print(f"[WARN] Report figure not found; leaving reference unchanged: {reference}")
continue
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
staged.append(destination)
return staged
def _prepare_report_figure_inventory(
fig_paths: Dict[str, Any],
report_dir: Path,
) -> Tuple[Dict[str, Any], set[str]]:
"""Copy existing figures into the report folder and return allowed Markdown paths."""
figure_dir = report_dir / "figures"
figure_dir.mkdir(parents=True, exist_ok=True)
source_to_reference: Dict[str, str] = {}
used_names: Dict[str, str] = {}
def stage(raw_path: Any) -> str:
if not raw_path:
return ""
source = Path(str(raw_path)).expanduser().resolve()
if not source.is_file():
return ""
source_key = str(source)
if source_key in source_to_reference:
return source_to_reference[source_key]
candidate = source.name
existing_source = used_names.get(candidate)
if existing_source is not None and existing_source != source_key:
candidate = f"{source.stem}_{len(used_names) + 1}{source.suffix}"
destination = figure_dir / candidate
shutil.copy2(source, destination)
reference = f"figures/{candidate}"
used_names[candidate] = source_key
source_to_reference[source_key] = reference
return reference
inventory: Dict[str, Any] = {}
for key, value in fig_paths.items():
if isinstance(value, list):
inventory[key] = [reference for item in value if (reference := stage(item))]
else:
inventory[key] = stage(value)
return inventory, set(source_to_reference.values())
def _sanitize_report_image_references(
report_text: str,
report_dir: Path,
allowed_references: set[str],
) -> Tuple[str, List[str]]:
"""Remove Markdown images that are absent or outside the supplied figure inventory."""
removed: List[str] = []
pattern = re.compile(r"!\[[^\]]*\]\(([^)]+)\)")
def replace(match: re.Match[str]) -> str:
reference = match.group(1).strip().replace("\\", "/")
local_path = report_dir / Path(reference)
if reference in allowed_references and local_path.is_file():
return match.group(0)
removed.append(reference)
return ""
sanitized = pattern.sub(replace, report_text)
sanitized = re.sub(r"\n{3,}", "\n\n", sanitized).strip() + "\n"
return sanitized, removed
def _sanitize_report_windows_paths(report_text: str) -> str:
"""Protect bare Windows paths from being interpreted as LaTeX commands.
LLM reports occasionally print provenance paths such as ``D:\\project\\run``
as plain Markdown. Pandoc passes the backslashes through in a way that can
make XeLaTeX treat sequences such as ``\\Iowa`` as undefined commands.
Inline-code formatting preserves the provenance text and makes PDF export
deterministic.
"""
path_at_line_end = re.compile(
r"(?<!`)\b[A-Za-z]:\\[^`\r\n]*?(?=(?: {2,})?$)",
flags=re.MULTILINE,
)
return path_at_line_end.sub(lambda match: f"`{match.group(0).rstrip()}`", report_text)
def _append_standard_report_figures(report_text: str, fig_paths: Dict[str, Any]) -> str:
"""Append a fixed common figure set so cross-LLM reports remain comparable."""
candidates: List[Tuple[str, str]] = []
def add(title: str, reference: Any) -> None:
if isinstance(reference, str) and reference:
candidates.append((title, reference))
add("Density-susceptibility classification", fig_paths.get("scatter_rho_kappa"))
add("Archived pseudo-geological model", fig_paths.get("geo_3d"))
geo_figures = fig_paths.get("geo_geo_id_pngs", [])
if isinstance(geo_figures, list):
for target_id in (4, 5):
match = next(
(path for path in geo_figures if Path(str(path)).stem == f"geo_id_{target_id}"),
"",
)
add(f"Target Geo {target_id}", match)
sections = fig_paths.get("combo_section_list", [])
if isinstance(sections, list) and sections:
add("Representative central XZ section", sections[len(sections) // 2])
existing = {
match.group(1).strip().replace("\\", "/")
for match in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", report_text)
}
blocks = [
f"### {title}\n\n"
for title, reference in candidates
if reference not in existing
]
if not blocks:
return report_text
return report_text.rstrip() + "\n\n## Selected Supporting Figures\n\n" + "\n\n".join(blocks) + "\n"
def export_markdown_report_pdf(report_path: Path, output_dir: Path) -> Optional[Path]:
"""Export an existing Markdown report to PDF without rerunning the workflow."""
report_path = report_path.resolve()
output_dir = output_dir.resolve()
_stage_report_figures(report_path, output_dir)
pdf_path = report_path.with_suffix(".pdf")
pandoc_workdir = report_path.parent
command_base = ["pandoc", report_path.name, "-o", pdf_path.name]
env = os.environ.copy()
extra_paths: List[Path] = []
if os.name == "nt":
extra_paths.extend(
[
Path.home() / "AppData" / "Local" / "Programs" / "MiKTeX" / "miktex" / "bin" / "x64",
Path.home() / "AppData" / "Local" / "Programs" / "MiKTeX" / "miktex" / "bin",
Path("C:/Program Files/Pandoc"),
]
)
winget_root = Path.home() / "AppData" / "Local" / "Microsoft" / "WinGet" / "Packages"
if winget_root.exists():
extra_paths.extend(path.parent for path in winget_root.glob("JohnMacFarlane.Pandoc_*/*/pandoc.exe"))
existing_path = env.get("PATH", "")
prepend = [str(path) for path in extra_paths if path.exists()]
if prepend:
env["PATH"] = os.pathsep.join(prepend + [existing_path])
if not shutil.which("pandoc", path=env.get("PATH")):
print(f"[WARN] Pandoc was not found; Markdown report retained at: {report_path}")
return None
engines = ("xelatex", "pdflatex", "lualatex", "tectonic", "wkhtmltopdf", "weasyprint")
available_engines = [engine for engine in engines if shutil.which(engine, path=env.get("PATH"))]
if not available_engines:
print("[WARN] No supported PDF engine found; Markdown report retained at: " f"{report_path}")
return None
errors: List[str] = []
for engine in available_engines:
font_args: List[str] = []
if engine == "xelatex" and os.name == "nt":
fonts_dir = Path("C:/Windows/Fonts")
if fonts_dir.exists() and any(fonts_dir.glob("times*.tt*")) and any(fonts_dir.glob("cambria*.tt*")):
font_args = ["-V", "mainfont=Times New Roman", "-V", "mathfont=Cambria Math"]
try:
result = subprocess.run(
[*command_base, "--pdf-engine", engine, *font_args],
check=True,
cwd=pandoc_workdir,
env=env,
text=True,
capture_output=True,
)
warning_text = (result.stderr or "").strip()
if warning_text:
print(f"Pandoc warnings ({engine}): {warning_text}")
print(f"PDF report saved to: {pdf_path} (engine: {engine})")
return pdf_path
except subprocess.CalledProcessError as exc:
detail = (exc.stderr or "").strip().replace("\n", " ")
errors.append(f"{engine} (exit {exc.returncode})" + (f": {detail[:400]}" if detail else ""))
print("[WARN] PDF generation failed with all available engines. " + " | ".join(errors))
return None
def _read_pdf_text(path: Path) -> str:
errors: List[str] = []
def _join_pages(pages: List[str]) -> str:
cleaned = [p.strip() for p in pages if p and p.strip()]
return "\n\n".join(cleaned).strip()
# 1) pypdf (preferred)
try:
from pypdf import PdfReader
reader = PdfReader(str(path))
pages = [(page.extract_text() or "") for page in reader.pages]
text = _join_pages(pages)
if text:
return text
except Exception as exc:
errors.append(f"pypdf: {exc}")
# 2) PyPDF2 (older)
try:
from PyPDF2 import PdfReader as PdfReader2
reader = PdfReader2(str(path))
pages = [(page.extract_text() or "") for page in reader.pages]
text = _join_pages(pages)
if text:
return text
except Exception as exc:
errors.append(f"PyPDF2: {exc}")
# 3) pdfplumber
try:
import pdfplumber
with pdfplumber.open(str(path)) as pdf:
pages = [(page.extract_text() or "") for page in pdf.pages]
text = _join_pages(pages)
if text:
return text
except Exception as exc:
errors.append(f"pdfplumber: {exc}")
# 4) External tools (pdftotext / mutool)
for cmd in (
["pdftotext", "-layout", str(path), "-"],
["pdftotext", str(path), "-"],
["mutool", "draw", "-F", "text", str(path)],
):
try:
proc = subprocess.run(cmd, check=True, capture_output=True, text=True)
text = (proc.stdout or "").strip()
if text:
return text
except FileNotFoundError:
continue
except subprocess.CalledProcessError as exc:
errors.append(f"{cmd[0]}: {exc}")
# 5) pandoc (if available)
try:
proc = subprocess.run(
["pandoc", str(path), "-t", "plain"],
check=True,
capture_output=True,
text=True,
)
text = (proc.stdout or "").strip()
if text:
return text
except FileNotFoundError:
pass
except subprocess.CalledProcessError as exc:
errors.append(f"pandoc: {exc}")
msg = (
"Unable to extract text from PDF. "
"Install 'pypdf' (recommended) or ensure 'pdftotext' is on PATH."
)
if errors:
msg += f" Tried: {', '.join(errors)}"
raise RuntimeError(msg)
def _safe_float(value: Any, default: float = 0.0) -> float:
try:
out = float(value)
except Exception:
return default
if not np.isfinite(out):
return default
return out
def _format_float(value: float) -> str:
return f"{_safe_float(value):.6g}"
def _resolve_geo_output_path(cfg: Dict[str, Any], geo_cfg: Dict[str, Any], key: str, default_suffix: str) -> Path:
cfg_path = geo_cfg.get(key)
if cfg_path:
p = Path(cfg_path)
else:
proj_dir = Path(cfg["project"]["input_dir"])
p = proj_dir / f"{cfg['project']['name']}_{default_suffix}"
p.parent.mkdir(parents=True, exist_ok=True)
return p
def _first_existing_path(candidates: List[Path]) -> Optional[Path]:
seen: set[str] = set()
for c in candidates:
key = str(c)
if key in seen:
continue
seen.add(key)
if c.exists():
return c
return None
def _normalize_geo_input_paths(cfg: Dict[str, Any], geo_cfg: Dict[str, Any]) -> Dict[str, Any]:
"""
Resolve geology input file paths with project-local priority.
This prevents cross-project leakage (e.g., Iowa run reading Hannah files).
"""
project_name = str(cfg.get("project", {}).get("name", "")).strip()
project_dir = Path(str(cfg.get("project", {}).get("input_dir", ".")).strip() or ".")
def _resolve_one(key: str, preferred_names: List[str], extra_candidates: Optional[List[Path]] = None) -> None:
raw_val = geo_cfg.get(key)
raw_path = Path(raw_val) if raw_val else None
candidates: List[Path] = []
# 1) Always prefer current project folder first.
for name in preferred_names:
candidates.append(project_dir / name)
# 2) Then try user/LLM-provided path variants.
if raw_path is not None:
if raw_path.is_absolute():
candidates.append(raw_path)
else:
candidates.append(project_dir / raw_path)
candidates.append(project_dir / raw_path.name)
candidates.append(raw_path)
candidates.append(Path(raw_path.name))
# 3) Workspace-level conventional names (fallback).
for name in preferred_names:
candidates.append(Path(name))
# 4) Extra custom fallbacks (e.g., Geology report dir).
if extra_candidates:
candidates.extend(extra_candidates)
resolved = _first_existing_path(candidates)
if resolved is not None:
prev = str(raw_path) if raw_path is not None else "(unset)"
if raw_path is None or Path(str(raw_path)) != resolved:
print(f"[INFO] {key} resolved for project '{project_name}': {prev} -> {resolved}")
geo_cfg[key] = str(resolved)
elif raw_path is None and preferred_names:
# Keep a deterministic project-local default even if file does not exist yet.
geo_cfg[key] = str(project_dir / preferred_names[0])
_resolve_one(
"unit_defs_csv",
preferred_names=[f"{project_name}_unit_defs.csv", "unit_defs.csv"],
)
_resolve_one(
"unit_groups_csv",
preferred_names=[f"{project_name}_unit_groups.csv", "unit_groups.csv"],
)
_resolve_one(
"context_path",
preferred_names=[
f"{project_name}_geology_context.txt",
f"{project_name}_geology_context.pdf",
"geology_context.txt",
"geology_context.pdf",
],
extra_candidates=[
Path("Geology report") / f"{project_name}_geology_context.txt",
Path("Geology report") / f"{project_name}_geology_context.pdf",
],
)
return geo_cfg
def _read_unit_defs_rows(path: Path) -> List[Dict[str, Any]]:
rows: List[Dict[str, Any]] = []
if not path.exists():
return rows
with path.open("r", encoding="utf-8-sig", newline="") as f:
reader = csv.DictReader(f)
for r in reader:
if not r:
continue
try:
unit_id = int(float(r.get("unit_id", "")))
except Exception:
continue
rows.append(
{
"unit_id": unit_id,
"name": str(r.get("name", "")).strip() or f"Unit {unit_id}",
"dens_min": _safe_float(r.get("dens_min"), 0.0),
"dens_max": _safe_float(r.get("dens_max"), 0.0),
"susc_min": _safe_float(r.get("susc_min"), 0.0),
"susc_max": _safe_float(r.get("susc_max"), 0.0),
}
)
rows.sort(key=lambda x: int(x["unit_id"]))
return rows
def _unit_defs_rows_to_csv(rows: List[Dict[str, Any]]) -> str:
out = io.StringIO()
writer = csv.writer(out, lineterminator="\n")
writer.writerow(["unit_id", "name", "dens_min", "dens_max", "susc_min", "susc_max"])
for row in sorted(rows, key=lambda x: int(x["unit_id"])):
uid = int(row["unit_id"])
writer.writerow(
[
uid,
str(row.get("name", "")).strip() or f"Unit {uid}",
_format_float(_safe_float(row.get("dens_min"), 0.0)),
_format_float(_safe_float(row.get("dens_max"), 0.0)),
_format_float(_safe_float(row.get("susc_min"), 0.0)),
_format_float(_safe_float(row.get("susc_max"), 0.0)),
]
)
txt = out.getvalue()
return txt if txt.endswith("\n") else (txt + "\n")
def _unit_stats_from_unit_rows(unit_rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
stats: List[Dict[str, Any]] = []
for row in sorted(unit_rows, key=lambda x: int(x["unit_id"])):
dens_min = _safe_float(row.get("dens_min"), 0.0)
dens_max = _safe_float(row.get("dens_max"), 0.0)
susc_min = _safe_float(row.get("susc_min"), 0.0)
susc_max = _safe_float(row.get("susc_max"), 0.0)
stats.append(
{
"unit_id": int(row["unit_id"]),
"name": str(row.get("name", "")).strip() or f"Unit {int(row['unit_id'])}",
"voxel_count": 0,
"voxel_fraction": 0.0,
"dens_mean": 0.5 * (dens_min + dens_max),
"dens_p10": dens_min,
"dens_p90": dens_max,
"susc_mean": 0.5 * (susc_min + susc_max),
"susc_p10": susc_min,
"susc_p90": susc_max,
"depth_index_mean": 0.5,
}
)
return stats
def _zscore(x: np.ndarray) -> np.ndarray:
x = np.asarray(x, dtype=float)
if x.size == 0:
return x
m = float(np.mean(x))
s = float(np.std(x))
if s < 1e-9:
return np.zeros_like(x, dtype=float)
return (x - m) / s
def _target_scores(unit_stats: List[Dict[str, Any]]) -> np.ndarray:
if not unit_stats:
return np.array([], dtype=float)
dens = np.array([_safe_float(s.get("dens_mean"), 0.0) for s in unit_stats], dtype=float)
susc = np.array([_safe_float(s.get("susc_mean"), 0.0) for s in unit_stats], dtype=float)
depth = np.array([_safe_float(s.get("depth_index_mean"), 0.5) for s in unit_stats], dtype=float)
# Heuristic target tendency:
# lower density + higher |susceptibility| + relatively shallow depth.
return _zscore(-dens) + _zscore(np.abs(susc)) + 0.5 * _zscore(-depth)
def _build_fallback_unit_groups_csv(unit_stats: List[Dict[str, Any]], target_name: str = "") -> str:
unit_stats_sorted = sorted(unit_stats, key=lambda x: int(x["unit_id"]))
unit_ids = [int(s["unit_id"]) for s in unit_stats_sorted]
n_units = len(unit_ids)
if n_units == 0:
return "unit_id,geo_id,geo_name\n"
# Fixed target range: 3~5 groups (bounded by number of units).
if n_units >= 9:
n_groups = 5
elif n_units >= 6:
n_groups = 4
else:
n_groups = min(3, n_units)
n_groups = max(1, min(n_groups, n_units))
feats = np.array(
[
[
_safe_float(s.get("dens_mean"), 0.0),
_safe_float(s.get("susc_mean"), 0.0),
_safe_float(s.get("depth_index_mean"), 0.5),
]
for s in unit_stats_sorted
],
dtype=float,
)
feats = (feats - feats.mean(axis=0)) / np.where(feats.std(axis=0) < 1e-9, 1.0, feats.std(axis=0))
labels: np.ndarray
try:
from sklearn.cluster import KMeans
km = KMeans(n_clusters=n_groups, n_init=10, random_state=42)
labels = km.fit_predict(feats)
except Exception:
# Deterministic fallback: split by density ranking.
order = np.argsort(feats[:, 0])
labels = np.zeros(n_units, dtype=int)
for i, idx in enumerate(order):
labels[idx] = int(i * n_groups / max(1, n_units))
labels[idx] = min(labels[idx], n_groups - 1)
cluster_ids = sorted(np.unique(labels).tolist())
cluster_order = sorted(cluster_ids, key=lambda c: float(np.mean(feats[labels == c, 0])))
cluster_to_geo = {cid: i + 1 for i, cid in enumerate(cluster_order)}
scores = _target_scores(unit_stats_sorted)
primary_idx = int(np.argmax(scores)) if scores.size else 0
primary_geo = cluster_to_geo.get(int(labels[primary_idx]), 1)
target_label = target_name.strip() or "Inferred mineral system"
geo_name_by_geo: Dict[int, str] = {}
for geo_id in sorted(set(cluster_to_geo.values())):
if geo_id == primary_geo:
geo_name_by_geo[geo_id] = f"Primary target: {target_label}"
else:
geo_name_by_geo[geo_id] = f"Geo group {geo_id}"
out = io.StringIO()
writer = csv.writer(out, lineterminator="\n")
writer.writerow(["unit_id", "geo_id", "geo_name"])
for uid, lab in zip(unit_ids, labels, strict=False):
gid = cluster_to_geo[int(lab)]
writer.writerow([uid, gid, geo_name_by_geo.get(gid, f"Geo group {gid}")])
txt = out.getvalue()
return txt if txt.endswith("\n") else (txt + "\n")
def _normalize_unit_groups_csv(
csv_text: str,
unit_stats: List[Dict[str, Any]],
target_name: str = "",
) -> str:
unit_stats_sorted = sorted(unit_stats, key=lambda x: int(x["unit_id"]))
unit_ids = [int(s["unit_id"]) for s in unit_stats_sorted]
if not unit_ids:
return "unit_id,geo_id,geo_name\n"
if not csv_text or not csv_text.strip():
return _build_fallback_unit_groups_csv(unit_stats_sorted, target_name=target_name)
by_unit: Dict[int, Tuple[int, str]] = {}
geo_name_first: Dict[int, str] = {}
try:
reader = csv.DictReader(io.StringIO(csv_text.strip()))
for r in reader:
if not r:
continue
try:
uid = int(float(r.get("unit_id", "")))
gid = int(float(r.get("geo_id", "")))
except Exception:
continue
if uid not in unit_ids or gid <= 0:
continue
gname = str(r.get("geo_name", "")).strip()
if uid not in by_unit:
by_unit[uid] = (gid, gname)
if gname and gid not in geo_name_first:
geo_name_first[gid] = gname
except Exception:
return _build_fallback_unit_groups_csv(unit_stats_sorted, target_name=target_name)
if not by_unit:
return _build_fallback_unit_groups_csv(unit_stats_sorted, target_name=target_name)
# Fill missing units into an existing geo group first.
default_gid = next(iter(by_unit.values()))[0]
for uid in unit_ids:
if uid not in by_unit:
by_unit[uid] = (default_gid, "")
old_geo_ids = sorted({gid for gid, _ in by_unit.values()})
if not (3 <= len(old_geo_ids) <= 5):
return _build_fallback_unit_groups_csv(unit_stats_sorted, target_name=target_name)
# Ensure there is a primary target group.
has_primary = any("primary target" in (name or "").lower() for name in geo_name_first.values())
if not has_primary:
scores = _target_scores(unit_stats_sorted)
primary_uid = unit_ids[int(np.argmax(scores))] if scores.size else unit_ids[0]
primary_gid = by_unit[primary_uid][0]
target_label = target_name.strip() or "Inferred mineral system"
geo_name_first[primary_gid] = f"Primary target: {target_label}"
# Re-index geo ids to contiguous 1..N.
old_to_new = {old: i + 1 for i, old in enumerate(old_geo_ids)}
new_geo_name: Dict[int, str] = {}
for old, new in old_to_new.items():
new_geo_name[new] = geo_name_first.get(old, f"Geo group {new}")
out = io.StringIO()
writer = csv.writer(out, lineterminator="\n")
writer.writerow(["unit_id", "geo_id", "geo_name"])
for uid in sorted(unit_ids):
old_gid = by_unit[uid][0]
new_gid = old_to_new[old_gid]
writer.writerow([uid, new_gid, new_geo_name[new_gid]])
txt = out.getvalue()
return txt if txt.endswith("\n") else (txt + "\n")
def _normalize_unit_name_map(raw_name_map: Any, unit_ids: List[int]) -> Dict[int, str]:
name_map: Dict[int, str] = {}
if isinstance(raw_name_map, dict):
for k, v in raw_name_map.items():
try:
uid = int(k)
except Exception:
continue
if uid in unit_ids:
name = str(v).strip()
if name:
name_map[uid] = name
for uid in unit_ids:
name_map.setdefault(uid, f"Unit {uid}")
return name_map
def _apply_unit_name_map(unit_rows: List[Dict[str, Any]], name_map: Dict[int, str]) -> List[Dict[str, Any]]:
out: List[Dict[str, Any]] = []
for row in sorted(unit_rows, key=lambda x: int(x["unit_id"])):
uid = int(row["unit_id"])
row_new = dict(row)
row_new["name"] = str(name_map.get(uid, row.get("name", f"Unit {uid}"))).strip() or f"Unit {uid}"
out.append(row_new)
return out
def _cluster_units_from_inversion_gmm(
inversion_result: Dict[str, Any],
unit_id_npy_path: Path,
k_min: int = 6,
k_max: int = 10,
random_state: int = 42,
max_fit_samples: int = 200000,
) -> Dict[str, Any]:
try:
from sklearn.mixture import GaussianMixture
except Exception as exc:
raise RuntimeError(
"scikit-learn is required for GMM+BIC clustering. "
"Please install it (e.g., `uv pip install scikit-learn`)."
) from exc
paths = inversion_result.get("paths", {})
dens_path = Path(paths.get("density_core_npy") or paths.get("dens_core_npy") or "")
susc_path = Path(paths.get("susceptibility_core_npy") or paths.get("susc_core_npy") or "")
if not dens_path.exists() or not susc_path.exists():
raise FileNotFoundError(
f"Missing inversion core models for clustering: density={dens_path}, susceptibility={susc_path}"
)
dens = np.load(dens_path)
susc = np.load(susc_path)
if dens.shape != susc.shape:
raise ValueError(f"density and susceptibility shape mismatch: {dens.shape} vs {susc.shape}")
if dens.ndim != 3:
raise ValueError(f"Expected 3D core models, got shape: {dens.shape}")
nx, ny, nz = dens.shape
dens_flat = dens.ravel()
susc_flat = susc.ravel()
z_index = np.broadcast_to(np.arange(nz, dtype=np.float32).reshape(1, 1, nz), dens.shape).ravel()
z_norm = z_index / max(1.0, float(nz - 1))
# Signed log compresses susceptibility while preserving polarity.
susc_feat = np.sign(susc_flat) * np.log10(1.0 + np.abs(susc_flat))
feats = np.column_stack([dens_flat, susc_feat, z_norm]).astype(np.float64)
valid_mask = np.isfinite(feats).all(axis=1)
if int(np.sum(valid_mask)) < 2:
raise RuntimeError("Not enough valid voxels for clustering.")
feats_valid = feats[valid_mask]
med = np.median(feats_valid, axis=0)
mad = np.median(np.abs(feats_valid - med), axis=0)
scale = 1.4826 * mad
std = np.std(feats_valid, axis=0)
scale = np.where(scale > 1e-9, scale, np.where(std > 1e-9, std, 1.0))
feats_valid_std = (feats_valid - med) / scale
n_valid = feats_valid_std.shape[0]
rng = np.random.default_rng(random_state)
if n_valid > max_fit_samples:
fit_idx = rng.choice(n_valid, size=max_fit_samples, replace=False)
feats_fit = feats_valid_std[fit_idx]
else:
feats_fit = feats_valid_std
k_lower = k_min if n_valid >= k_min else 2
k_upper = min(k_max, max(2, n_valid - 1))
if k_upper < k_lower:
k_lower = max(2, min(k_upper, k_min))
if k_upper < 2:
raise RuntimeError("Insufficient valid samples for GMM.")
best_model: Optional[Any] = None
best_bic = float("inf")
bic_scores: Dict[int, float] = {}
for k in range(k_lower, k_upper + 1):
model = GaussianMixture(
n_components=k,
covariance_type="full",
reg_covar=1e-6,
n_init=2,
random_state=random_state,
max_iter=300,
)
model.fit(feats_fit)
bic = float(model.bic(feats_fit))
bic_scores[k] = bic
if bic < best_bic:
best_bic = bic
best_model = model
if best_model is None:
raise RuntimeError("GMM fitting failed: no valid model selected.")
labels_valid = np.empty(n_valid, dtype=np.int16)
chunk = 250000
for i0 in range(0, n_valid, chunk):
i1 = min(i0 + chunk, n_valid)
labels_valid[i0:i1] = best_model.predict(feats_valid_std[i0:i1]).astype(np.int16)
dens_valid = dens_flat[valid_mask]
susc_valid = susc_flat[valid_mask]
z_valid = z_norm[valid_mask]
cluster_ids = sorted(np.unique(labels_valid).tolist())
cluster_means: Dict[int, Tuple[float, float]] = {}
for cid in cluster_ids:
m = labels_valid == cid
cluster_means[cid] = (
float(np.mean(dens_valid[m])) if np.any(m) else 0.0,
float(np.mean(susc_valid[m])) if np.any(m) else 0.0,
)
cid_sorted = sorted(cluster_ids, key=lambda c: cluster_means[c])
cid_to_uid = {cid: i + 1 for i, cid in enumerate(cid_sorted)}
unit_valid = np.array([cid_to_uid[int(c)] for c in labels_valid], dtype=np.int16)
unit_flat = np.zeros_like(dens_flat, dtype=np.int16)
unit_flat[valid_mask] = unit_valid
unit_id_3d = unit_flat.reshape((nx, ny, nz))
unit_id_npy_path.parent.mkdir(parents=True, exist_ok=True)
np.save(unit_id_npy_path, unit_id_3d.astype(np.int16))
unit_rows: List[Dict[str, Any]] = []
unit_stats: List[Dict[str, Any]] = []
total = float(np.sum(valid_mask))
for uid in sorted(set(cid_to_uid.values())):
mask_u = unit_flat == uid
count = int(np.sum(mask_u))
if count == 0:
continue
dvals = dens_flat[mask_u]
svals = susc_flat[mask_u]
zvals = z_norm[mask_u]
dens_min = float(np.percentile(dvals, 1.0))
dens_max = float(np.percentile(dvals, 99.0))
susc_min = float(np.percentile(svals, 1.0))
susc_max = float(np.percentile(svals, 99.0))
if dens_max <= dens_min:
dens_max = dens_min + 1e-6
if susc_max <= susc_min:
susc_max = susc_min + 1e-6
unit_rows.append(
{
"unit_id": uid,
"name": f"GMM Unit {uid}",
"dens_min": dens_min,
"dens_max": dens_max,
"susc_min": susc_min,
"susc_max": susc_max,
}
)
unit_stats.append(
{
"unit_id": uid,
"name": f"GMM Unit {uid}",
"voxel_count": count,
"voxel_fraction": count / total if total > 0 else 0.0,
"dens_mean": float(np.mean(dvals)),
"dens_p10": float(np.percentile(dvals, 10.0)),
"dens_p90": float(np.percentile(dvals, 90.0)),
"susc_mean": float(np.mean(svals)),
"susc_p10": float(np.percentile(svals, 10.0)),
"susc_p90": float(np.percentile(svals, 90.0)),
"depth_index_mean": float(np.mean(zvals)),
}
)
unit_rows.sort(key=lambda x: int(x["unit_id"]))
unit_stats.sort(key=lambda x: int(x["unit_id"]))
return {
"unit_rows": unit_rows,
"unit_stats": unit_stats,
"unit_id_npy": str(unit_id_npy_path),
"best_k": int(best_model.n_components),
"bic_scores": bic_scores,
}
def unit_stats_from_unit_id(
inversion_result: Dict[str, Any],
unit_id_npy: str | Path,
) -> List[Dict[str, Any]]:
"""Compute reusable physical-property statistics for fixed unit labels."""
paths = inversion_result.get("paths", {})
density = inversion_result.get("dens_core_3d")
susceptibility = inversion_result.get("susc_core_3d")
if density is None:
density_path = paths.get("density_core_npy") or paths.get("dens_core_npy")
density = np.load(density_path)
if susceptibility is None:
susceptibility_path = paths.get("susceptibility_core_npy") or paths.get("susc_core_npy")
susceptibility = np.load(susceptibility_path)
labels = np.load(Path(unit_id_npy))
if labels.shape != density.shape or labels.shape != susceptibility.shape:
raise ValueError(
"Fixed unit labels must have the same shape as inversion arrays: "
f"labels={labels.shape}, density={density.shape}, susceptibility={susceptibility.shape}"
)
valid = (labels > 0) & np.isfinite(density) & np.isfinite(susceptibility)
z_index = np.broadcast_to(
np.arange(labels.shape[2], dtype=float).reshape(1, 1, labels.shape[2]), labels.shape
)
total = float(np.sum(valid))
stats: List[Dict[str, Any]] = []
for uid in sorted(int(v) for v in np.unique(labels) if int(v) > 0):
mask = valid & (labels == uid)
if not np.any(mask):
continue
dvals = density[mask]
svals = susceptibility[mask]
zvals = z_index[mask]
stats.append(
{
"unit_id": uid,
"name": f"Unit {uid}",
"voxel_count": int(np.sum(mask)),
"voxel_fraction": float(np.sum(mask)) / total if total else 0.0,
"dens_mean": float(np.mean(dvals)),
"dens_p10": float(np.percentile(dvals, 10)),
"dens_p90": float(np.percentile(dvals, 90)),
"susc_mean": float(np.mean(svals)),
"susc_p10": float(np.percentile(svals, 10)),
"susc_p90": float(np.percentile(svals, 90)),
"depth_index_mean": float(np.mean(zvals) / max(1.0, labels.shape[2] - 1)),
}
)
return stats
def _unit_rows_from_stats(unit_stats: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
rows: List[Dict[str, Any]] = []
for stats in unit_stats:
rows.append(
{
"unit_id": int(stats["unit_id"]),
"name": str(stats.get("name", f"Unit {stats['unit_id']}")),
"dens_min": float(stats.get("dens_p10", stats.get("dens_mean", 0.0))),
"dens_max": float(stats.get("dens_p90", stats.get("dens_mean", 0.0)) + 1e-6),
"susc_min": float(stats.get("susc_p10", stats.get("susc_mean", 0.0))),
"susc_max": float(stats.get("susc_p90", stats.get("susc_mean", 0.0)) + 1e-6),
}
)
return rows
def _write_gmm_artifacts(output_dir: Path, cluster_out: Dict[str, Any]) -> Dict[str, str]:
"""Persist deterministic GMM artifacts below an interpretation directory."""
geo_dir = output_dir / "geology_models"
geo_dir.mkdir(parents=True, exist_ok=True)
unit_id_path = Path(cluster_out["unit_id_npy"])
if unit_id_path.parent.resolve() != geo_dir.resolve():
target = geo_dir / "unit_id_gmm.npy"
shutil.copy2(unit_id_path, target)
unit_id_path = target
defs_path = geo_dir / "unit_defs_gmm.csv"
stats_path = geo_dir / "unit_stats.json"