Spaces:
Sleeping
Sleeping
Download src/modules/real_dynamics.py from Sierpinksi-Project/NGF_on_Fractale: direct link, hf CLI and curl.
- Browser
- Download file 8.62 kB
-
https://huggingface.co/spaces/Sierpinksi-Project/NGF_on_Fractale/resolve/main/src/modules/real_dynamics.py
- Command line
-
hf download hf://spaces/Sierpinksi-Project/NGF_on_Fractale/src/modules/real_dynamics.py
-
curl -L -o real_dynamics.py https://huggingface.co/spaces/Sierpinksi-Project/NGF_on_Fractale/resolve/main/src/modules/real_dynamics.py
8.62 kB
| from __future__ import annotations | |
| from typing import Dict, Iterable, List, Sequence, Tuple | |
| import networkx as nx | |
| import numpy as np | |
| import scipy.sparse as sp | |
| import scipy.sparse.linalg as spla | |
| def solve_harmonic_extension( | |
| G: nx.Graph, | |
| boundary_values: Dict[int, float], | |
| ) -> Dict[int, float]: | |
| """ | |
| Löse das diskrete Laplace-Problem mit Dirichlet-Randbedingungen. | |
| Δ f = 0 im Inneren, f = f_bath auf dem Rand. | |
| """ | |
| boundary_nodes = set(boundary_values.keys()) | |
| all_nodes = list(G.nodes) | |
| interior_nodes = [n for n in all_nodes if n not in boundary_nodes] | |
| idx_map_int = {n: i for i, n in enumerate(interior_nodes)} | |
| idx_map_bnd = {n: i for i, n in enumerate(boundary_nodes)} | |
| ni = len(interior_nodes) | |
| nb = len(boundary_nodes) | |
| if ni == 0: | |
| return dict(boundary_values) | |
| rows = [] | |
| cols = [] | |
| data = [] | |
| b = np.zeros(ni, dtype=float) | |
| for n in interior_nodes: | |
| i = idx_map_int[n] | |
| neighbors = list(G.neighbors(n)) | |
| deg = len(neighbors) | |
| rows.append(i) | |
| cols.append(i) | |
| data.append(deg) | |
| for m in neighbors: | |
| if m in boundary_nodes: | |
| b[i] += boundary_values[m] | |
| else: | |
| j = idx_map_int[m] | |
| rows.append(i) | |
| cols.append(j) | |
| data.append(-1.0) | |
| A = sp.csr_matrix((data, (rows, cols)), shape=(ni, ni)) | |
| f_int = spla.spsolve(A, b) | |
| f: Dict[int, float] = {} | |
| for n, val in boundary_values.items(): | |
| f[n] = float(val) | |
| for n in interior_nodes: | |
| f[n] = float(f_int[idx_map_int[n]]) | |
| return f | |
| def compute_edge_energies( | |
| G: nx.Graph, | |
| f: Dict[int, float], | |
| base_conductance: float = 1.0, | |
| ) -> Dict[Tuple[int, int], float]: | |
| """ | |
| Berechne diskrete Kantenergien E_{xy} = 1/2 * c * (f_x - f_y)^2. | |
| """ | |
| energies: Dict[Tuple[int, int], float] = {} | |
| for u, v in G.edges: | |
| df = f[u] - f[v] | |
| E = 0.5 * base_conductance * df * df | |
| key = (u, v) if u <= v else (v, u) | |
| energies[key] = float(E) | |
| G.edges[u, v]["energy"] = float(E) | |
| return energies | |
| def copy_graph_with_weights(G: nx.Graph) -> nx.Graph: | |
| H = nx.Graph() | |
| for n, data in G.nodes(data=True): | |
| H.add_node(n, **data) | |
| for u, v, data in G.edges(data=True): | |
| w = data.get("weight", 1.0) | |
| H.add_edge(u, v, weight=float(w)) | |
| return H | |
| def update_internal_edge_weights( | |
| G: nx.Graph, | |
| edge_energies: Dict[Tuple[int, int], float], | |
| boundary_nodes: Sequence[int], | |
| alpha: float, | |
| beta: float, | |
| ) -> nx.Graph: | |
| """ | |
| Aktualisiere die Kantengewichte im Inneren anhand einer nichtlinearen Funktion der Energie. | |
| c' = c * (1 + alpha * tanh(beta * (E / <E_int> - 1))) | |
| """ | |
| boundary_nodes = set(boundary_nodes) | |
| internal_energies: List[float] = [] | |
| for (u, v), E in edge_energies.items(): | |
| if u not in boundary_nodes or v not in boundary_nodes: | |
| internal_energies.append(E) | |
| if not internal_energies: | |
| mean_E = 1.0 | |
| else: | |
| mean_E = float(np.mean(internal_energies)) | |
| if mean_E <= 0: | |
| mean_E = 1.0 | |
| for (u, v), E in edge_energies.items(): | |
| if u in boundary_nodes and v in boundary_nodes: | |
| # äußere Kanten: Gewicht unverändert lassen | |
| continue | |
| c_old = G.edges[u, v].get("weight", 1.0) | |
| x = E / mean_E | |
| factor = 1.0 + alpha * np.tanh(beta * (x - 1.0)) | |
| c_new = float(c_old * factor) | |
| G.edges[u, v]["weight"] = c_new | |
| return G | |
| def distort_geometry( | |
| G: nx.Graph, | |
| pos_ideal: Dict[int, np.ndarray], | |
| f_potential: Dict[int, float], | |
| boundary_nodes: Sequence[int], | |
| edge_energies: Dict[Tuple[int, int], float], | |
| gamma_mode: str = "A", | |
| eta: float | None = None, | |
| ) -> Tuple[Dict[int, np.ndarray], float]: | |
| """ | |
| Verzerrt die Geometrie der inneren Knoten entlang des Gradienten von f. | |
| gamma_mode = "A": Energie-Normalisierung | |
| γ = sqrt( E_tot / sum_x ||grad f(x)||^2 ), | |
| wobei E_tot über innere Kanten (ohne Randknoten) summiert wird. | |
| gamma_mode = "B": Längenskalen-Normalisierung | |
| γ wird so gewählt, dass die RMS-Verschiebung der inneren Knoten | |
| δr_rms = η * ℓ_edge beträgt, mit ℓ_edge = Median der Kantenlängen | |
| der inneren Kanten in der IDEAL-Geometrie. | |
| gamma_mode = "C": DtN-/Randfluss-Normalisierung | |
| Zunächst wird aus f_potential ein diskreter Randfluss j_b an den | |
| Randknoten b via | |
| j_b = sum_{m Nachbar von b} w_{b m} * (f(b) - f(m)) | |
| bestimmt (w_{b m} = Kantengewicht, falls vorhanden, sonst 1). | |
| Dann | |
| γ = sqrt( sum_b j_b^2 / sum_x ||grad f(x)||^2 ). | |
| Dieser Modus koppelt die Geometrieverzerrung an die Stärke der | |
| Randflüsse (Dirichlet-to-Neumann-artige Größe) für die aktuell | |
| verwendeten Randwerte f_potential. | |
| Randknoten bleiben geometrisch fix. | |
| """ | |
| boundary_set = set(boundary_nodes) | |
| # Gradient an inneren Knoten bestimmen | |
| gradients: Dict[int, np.ndarray] = {} | |
| G2 = 0.0 | |
| pos_real: Dict[int, np.ndarray] = {} | |
| for nid, p in pos_ideal.items(): | |
| pos_real[nid] = np.asarray(p, dtype=float).copy() | |
| for n in G.nodes: | |
| if n in boundary_set: | |
| continue | |
| p0 = np.asarray(pos_ideal[n], dtype=float) | |
| f0 = float(f_potential[n]) | |
| grad = np.zeros_like(p0) | |
| for m in G.neighbors(n): | |
| pm = np.asarray(pos_ideal[m], dtype=float) | |
| fm = float(f_potential[m]) | |
| df = fm - f0 | |
| dp = pm - p0 | |
| norm = np.linalg.norm(dp) | |
| if norm > 0.0: | |
| # diskreter Richtungsgradient entlang der Kante (n,m) | |
| grad += (df / norm) * (dp / norm) | |
| gradients[n] = grad | |
| G2 += float(np.dot(grad, grad)) | |
| # Falls keine inneren Gradienten vorhanden sind | |
| if not gradients or G2 <= 0.0: | |
| gamma = 0.0 | |
| else: | |
| gamma = 0.0 | |
| if gamma_mode == "A": | |
| # Modus A: Energie-Normalisierung über innere Kanten | |
| E_tot = 0.0 | |
| for (u, v), E in edge_energies.items(): | |
| if u in boundary_set or v in boundary_set: | |
| continue | |
| E_tot += float(E) | |
| if E_tot > 0.0: | |
| gamma = float(np.sqrt(E_tot / G2)) | |
| elif gamma_mode == "B": | |
| # Modus B: Längenskalen-Normalisierung über innere Kanten | |
| lengths: List[float] = [] | |
| for u, v in G.edges: | |
| if u in boundary_set or v in boundary_set: | |
| continue | |
| ru = np.asarray(pos_ideal[u], dtype=float) | |
| rv = np.asarray(pos_ideal[v], dtype=float) | |
| lengths.append(float(np.linalg.norm(rv - ru))) | |
| if lengths: | |
| ell_edge = float(np.median(lengths)) | |
| n_int = len(gradients) | |
| G_rms = float(np.sqrt(G2 / float(n_int))) | |
| if G_rms > 0.0: | |
| eta_eff = 1.0 if eta is None else float(eta) | |
| gamma = float(eta_eff * ell_edge / G_rms) | |
| elif gamma_mode == "C": | |
| # Modus C: DtN-/Randfluss-Normalisierung | |
| # Diskreter Randfluss j_b via gewichteter Differenz der Potentiale | |
| J2 = 0.0 | |
| for b in boundary_nodes: | |
| fb = float(f_potential[b]) | |
| j_b = 0.0 | |
| for m in G.neighbors(b): | |
| fm = float(f_potential[m]) | |
| # Kantengewicht falls vorhanden, sonst 1.0 | |
| w = 1.0 | |
| edge_data = G.get_edge_data(b, m, default=None) | |
| if edge_data is not None: | |
| # übliche Felder: "weight" oder "conductance" | |
| if "conductance" in edge_data: | |
| w = float(edge_data["conductance"]) | |
| elif "weight" in edge_data: | |
| w = float(edge_data["weight"]) | |
| j_b += w * (fb - fm) | |
| J2 += float(j_b * j_b) | |
| if J2 > 0.0: | |
| gamma = float(np.sqrt(J2 / G2)) | |
| # unbekannter Modus -> gamma bleibt 0.0 | |
| # REAL-Positionen anwenden (nur innere Knoten verschieben) | |
| for n, grad in gradients.items(): | |
| p0 = np.asarray(pos_ideal[n], dtype=float) | |
| pos_real[n] = p0 + gamma * grad | |
| # Positionen in Graph-Attribut schreiben | |
| for nid, p in pos_real.items(): | |
| G.nodes[nid]["pos_real"] = np.asarray(p, dtype=float) | |
| return pos_real, gamma | |