File size: 7,202 Bytes
d742243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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