Spaces:
Sleeping
Sleeping
Download src/modules/bath.py from Sierpinksi-Project/NGF_on_Fractale: direct link, hf CLI and curl.
- Browser
- Download file 4.05 kB
-
https://huggingface.co/spaces/Sierpinksi-Project/NGF_on_Fractale/resolve/main/src/modules/bath.py
- Command line
-
hf download hf://spaces/Sierpinksi-Project/NGF_on_Fractale/src/modules/bath.py
-
curl -L -o bath.py https://huggingface.co/spaces/Sierpinksi-Project/NGF_on_Fractale/resolve/main/src/modules/bath.py
4.05 kB
| 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)} | |