from __future__ import annotations import json from pathlib import Path from typing import Any, Dict, Optional import numpy as np import scipy.sparse as sp import yaml from models import BoundaryInfo, GraphGeometry, IdealGraph, CStarAlgebraSpec, SubstratePackage from io_utils import compute_checksums_for_run_dir def load_substrate(run_dir: Path, verify_checksums: bool = False) -> SubstratePackage: """ Lade ein SubstratePackage aus einem von der App erzeugten Output-Verzeichnis. Erwartet wird die durch die App erzeugte Struktur: run_dir/ manifest.json graph/... algebra/... docs/... Rückgabe: SubstratePackage mit rekonstruiertem Graph, C*-Algebra und Metadaten. """ run_dir = Path(run_dir).expanduser().resolve() manifest_path = run_dir / "manifest.json" if not manifest_path.exists(): raise FileNotFoundError(f"manifest.json nicht gefunden in {run_dir}") with manifest_path.open("r", encoding="utf-8") as f: manifest = json.load(f) # Optional: Checksums aus dem Manifest gegen die tatsächlichen Dateien prüfen if verify_checksums: expected = manifest.get("checksums") or {} if expected: actual = compute_checksums_for_run_dir(run_dir) # Wir prüfen nur die im Manifest aufgeführten Dateien; zusätzliche Dateien sind erlaubt. for rel_path, expected_hash in expected.items(): if rel_path not in actual: raise FileNotFoundError( f"Artefaktdatei {rel_path!r} fehlt in {run_dir}, obwohl sie im Manifest referenziert wird." ) if actual[rel_path] != expected_hash: raise ValueError( f"Checksum-Fehler für {rel_path!r}: erwartet {expected_hash}, erhalten {actual[rel_path]}." ) substrate_meta: Dict[str, Any] = manifest.get("substrate_metadata", {}) graph: Optional[IdealGraph] = None cstar: Optional[CStarAlgebraSpec] = None # Graph laden, falls vorhanden graph_info = manifest.get("graph") graph_dir = run_dir / "graph" if graph_info is not None and graph_dir.exists(): adj_path = graph_dir / "adjacency_csr.npz" coords_path = graph_dir / "coords.npy" adjacency = sp.load_npz(adj_path) if adj_path.exists() else sp.csr_matrix((0, 0), dtype=float) coords = np.load(coords_path) if coords_path.exists() else None # Randinformationen über boundary_mask_*.npy rekonstruieren boundary_infos = [] for b in graph_info.get("boundary_infos", []): kind = b.get("kind", "outer") desc = b.get("description", "") mask_path = graph_dir / f"boundary_mask_{kind}.npy" if not mask_path.exists(): continue mask = np.load(mask_path) node_ids = np.where(mask)[0].astype(np.int64) boundary_infos.append(BoundaryInfo(node_ids=node_ids, kind=kind, description=desc)) geometry = GraphGeometry(coords=coords, metric=graph_info.get("metadata", {}).get("metric", "euclidean")) graph = IdealGraph( adjacency=adjacency, boundary_infos=boundary_infos, geometry=geometry, metadata=graph_info.get("metadata", {}), ) # C*-Algebra laden, falls vorhanden cstar_info = manifest.get("cstar") algebra_dir = run_dir / "algebra" if cstar_info is not None and algebra_dir.exists(): gens_path = algebra_dir / "cstar_generators.yaml" rels_path = algebra_dir / "cstar_relations.yaml" meta_path = algebra_dir / "cstar_metadata.json" generators = yaml.safe_load(gens_path.read_text(encoding="utf-8")) if gens_path.exists() else [] relations = yaml.safe_load(rels_path.read_text(encoding="utf-8")) if rels_path.exists() else [] cmeta = json.loads(meta_path.read_text(encoding="utf-8")) if meta_path.exists() else {} cstar = CStarAlgebraSpec( generators=generators, relations=relations, representation=None, metadata=cmeta, ) # Zusätzliche Strukturen rekonstruieren (z.B. Dirichlet-Form) additional_structures: Dict[str, Any] = {} if graph is not None: dirichlet_path = graph_dir / "dirichlet_form_csr.npz" if dirichlet_path.exists(): try: additional_structures["dirichlet_form"] = sp.load_npz(dirichlet_path) except Exception: pass # Operator-Matrizen rekonstruieren (falls vorhanden) op_dir = run_dir / "algebra" / "operator_matrices" if op_dir.exists(): operators: Dict[str, Any] = {} index_path = op_dir / "index.json" if index_path.exists(): try: idx_data = json.loads(index_path.read_text(encoding="utf-8")) for entry in idx_data.get("operators", []): name = entry.get("name") fname = entry.get("filename") if not name or not fname: continue op_path = op_dir / fname if not op_path.exists(): continue if fname.endswith(".npz"): try: mat = sp.load_npz(op_path) except Exception: continue elif fname.endswith(".npy"): try: mat = np.load(op_path) except Exception: continue else: continue operators[str(name)] = mat except Exception: operators = {} # Fallback: falls kein Index vorhanden oder leer ist, alle *.npz laden if not operators: for op_path in op_dir.glob("*.npz"): try: mat = sp.load_npz(op_path) except Exception: continue operators[op_path.stem] = mat if operators: additional_structures["operator_matrices"] = operators # Falls eine C*-Algebra vorhanden ist, lege eine einfache Repräsentation an if cstar is not None: if cstar.representation is None or not isinstance(cstar.representation, dict): cstar.representation = {} rep_ops = cstar.representation.get("operators") if not isinstance(rep_ops, dict): rep_ops = {} rep_ops.update(operators) cstar.representation["operators"] = rep_ops if additional_structures: pkg = SubstratePackage( graph=graph, cstar=cstar, additional_structures=additional_structures, metadata=substrate_meta, ) else: pkg = SubstratePackage( graph=graph, cstar=cstar, metadata=substrate_meta, ) return pkg