File size: 4,049 Bytes
5543795
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from typing import Dict, Iterable, List, Sequence, Tuple

import networkx as nx
import numpy as np

# Cache für Rand-Rand-Distanzen je (cache_key)
_BOUNDARY_DIST_CACHE: Dict[object, Tuple[np.ndarray, List[int]]] = {}


def _bfs_distances_limited(
    G: nx.Graph,
    source: int,
    cutoff: int,
) -> Dict[int, int]:
    """Kürzere Hülle um einen Startknoten, nur bis cutoff."""
    return dict(nx.single_source_shortest_path_length(G, source, cutoff=cutoff))


def _compute_boundary_distance_matrix(
    G: nx.Graph,
    boundary_nodes: Sequence[int],
) -> Tuple[np.ndarray, List[int]]:
    """
    Vollständige Distanzmatrix D[i, j] der kürzesten Pfadlängen zwischen Randknoten.

    Diese wird ggf. im Cache abgelegt und kann dann für verschiedene Korrelationslängen
    wiederverwendet werden.
    """
    bnodes = list(boundary_nodes)
    n = len(bnodes)
    if n == 0:
        raise ValueError("boundary_nodes darf nicht leer sein.")

    D = np.full((n, n), np.inf, dtype=float)
    for i, src in enumerate(bnodes):
        dists = nx.single_source_shortest_path_length(G, src)
        for j, tgt in enumerate(bnodes):
            if tgt in dists:
                D[i, j] = float(dists[tgt])
    return D, bnodes


def compute_boundary_correlation(
    G: nx.Graph,
    boundary_nodes: Sequence[int],
    correlation_length: float,
    max_factor: float = 4.0,
    cache_key: object | None = None,
) -> Tuple[np.ndarray, List[int]]:
    """
    Berechne eine Kovarianzmatrix C für das Bad an den Randknoten.

    Varianten:
    - Mit cache_key != None:
        * Es wird eine vollständige Distanzmatrix D[i,j] zwischen Randknoten
          für diesen cache_key berechnet (falls noch nicht vorhanden) und
          im Speicher behalten.
        * Für gegebene Korrelationslänge werden nur Einträge mit Distanz
          d <= R = max_factor * correlation_length berücksichtigt.
    - Ohne cache_key:
        * Es wird wie zuvor für jeden Randknoten eine BFS mit Radius R ausgeführt.

    In beiden Fällen wird die Diagonale leicht aufgeblasen, um die
    positive Definitheit numerisch zu stabilisieren.
    """
    bnodes = list(boundary_nodes)
    n = len(bnodes)
    if n == 0:
        raise ValueError("boundary_nodes darf nicht leer sein.")

    R = max(1, int(max_factor * correlation_length))
    C = np.zeros((n, n), dtype=float)

    if cache_key is not None:
        cached = _BOUNDARY_DIST_CACHE.get(cache_key)
        if cached is None:
            D, order = _compute_boundary_distance_matrix(G, bnodes)
            _BOUNDARY_DIST_CACHE[cache_key] = (D, order)
        else:
            D, order = cached
            # Sicherheitscheck: gleiche Ordnung / gleiche Randknotenanzahl
            if len(order) != n or any(a != b for a, b in zip(order, bnodes)):
                D, order = _compute_boundary_distance_matrix(G, bnodes)
                _BOUNDARY_DIST_CACHE[cache_key] = (D, order)

        # D ist in derselben Reihenfolge wie bnodes
        mask = D <= float(R)
        # Vermeide exp(-inf / xi): mask schließt inf aus
        C[mask] = np.exp(-D[mask] / float(correlation_length))
    else:
        # Distanzmatrizen nur lokal (ursprüngliches Verhalten)
        for i, src in enumerate(bnodes):
            dists = _bfs_distances_limited(G, src, cutoff=R)
            for j, tgt in enumerate(bnodes):
                if tgt not in dists:
                    continue
                d = dists[tgt]
                C[i, j] = np.exp(-d / correlation_length)

    # Diagonale stabilisieren
    C += 1e-6 * np.eye(n, dtype=float)
    return C, bnodes


def sample_bath_values(C: np.ndarray, boundary_order: Sequence[int], seed: int = 0) -> Dict[int, float]:
    """
    Ziehe eine Realisierung des Bads an den Randknoten mit Kovarianzmatrix C.
    """
    rng = np.random.default_rng(seed)
    n = C.shape[0]
    mean = np.zeros(n, dtype=float)
    values = rng.multivariate_normal(mean, C)

    return {nid: float(val) for nid, val in zip(boundary_order, values)}