antaris commited on
Commit
be423b3
·
verified ·
1 Parent(s): 8fb471a

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +235 -1318
src/streamlit_app.py CHANGED
@@ -1,1344 +1,261 @@
1
- # app.py
2
- # IDEAL → REAL (verifiziert & ressourcenschonend)
3
- # Changelog (diese Version):
4
- # - Heatmaps: kontraststark (divergent, zentriert, robustes Clipping), Modus-Auswahl (real/imag/abs/abslog/phase),
5
- # Legende links, Colorbar rechts.
6
- # - Heat-Kernel-Heatmaps (IDEAL & REAL) mit intrinsischer Diffusionszeit (aus Spektrum),
7
- # bei großen n automatisches Subsampling (ressourcenschonend).
8
- # - Intrinsische Massen m_ID, m_REAL aus Hamiltonian-Geometrie: m := ⟨deg⟩ (keine freien Parameter),
9
- # H := L + m·I, überall genutzt (LvN & GKSL).
10
- # - Sierpiński Carpet: zellenbasiert (symmetrisch).
11
- # - H-Tree (2D): Zentrum explizit gesplittet (zusammenhängend) → kein singularer Grounded-Laplacian.
12
- # - Koch: robustes Mapping, Diamond: robuste Segment→Graph-Map.
13
- # - Harmonische Einbettung: korrekte Rand-Checks.
14
- # - Eigenwerte: robuster „safe_small_eigs“ (SA → Shift-Invert-Reg → LOBPCG-Fallback) gegen ARPACK-NoConvergence.
15
- # - Plot-Graphen/Heatmaps: Colorbars rechts, Legende links, saubere Abstände.
16
- # - Erklärungen: Aufklappbare Abschnitte (Expander) an allen zentralen Stellen.
17
 
18
- import os, io, json, math, time, zipfile, hashlib
19
- from datetime import datetime
20
- import warnings
 
21
  import numpy as np
22
- import scipy.sparse as sps
23
- import scipy.sparse.linalg as spla
24
- from scipy.sparse import csc_matrix
25
- from scipy.sparse import SparseEfficiencyWarning
26
- import networkx as nx
27
  import plotly.graph_objects as go
28
- import plotly.express as px
29
  import streamlit as st
 
30
 
31
- # -------------------------------------------
32
- # Konfiguration (leise, schnell, robust)
33
- # -------------------------------------------
34
- warnings.filterwarnings("ignore", category=SparseEfficiencyWarning)
35
- np.set_printoptions(precision=4, suppress=True)
36
-
37
- def mk_out(run_id):
38
- outdir = os.path.join("out", run_id)
39
- os.makedirs(outdir, exist_ok=True)
40
- return outdir
41
-
42
- def save_json(path, obj):
43
- with open(path, "w", encoding="utf-8") as f:
44
- json.dump(obj, f, ensure_ascii=False, indent=2)
45
-
46
- def save_csv(path, header, rows):
47
- with open(path, "w", encoding="utf-8") as f:
48
- f.write(",".join(header) + "\n")
49
- for r in rows:
50
- f.write(",".join(map(str, r)) + "\n")
51
-
52
- def zip_dir(src_dir, zip_path):
53
- with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
54
- base = os.path.basename(src_dir)
55
- for root, _, files in os.walk(src_dir):
56
- for name in files:
57
- full = os.path.join(root, name)
58
- rel = os.path.relpath(full, src_dir)
59
- zf.write(full, arcname=os.path.join(base, rel))
60
- return zip_path
61
-
62
- # -------------------------------------------
63
- # Numerik-Utilities
64
- # -------------------------------------------
65
- def to_csc(M):
66
- return M.tocsc() if sps.issparse(M) and not isinstance(M, csc_matrix) else M
67
 
68
- def as_dense(B):
69
- return B.toarray() if sps.issparse(B) else np.asarray(B)
70
 
71
- def safe_logdet_spd(M):
72
- M = 0.5*(M + M.T)
73
- n = M.shape[0]
74
- eps = 1e-12 * (np.trace(M)/max(1, n))
75
- sign, logdet = np.linalg.slogdet(M + eps*np.eye(n))
76
- if sign <= 0:
77
- w = np.linalg.eigvalsh(M + eps*np.eye(n))
78
- w = np.clip(w, 1e-18, None)
79
- logdet = float(np.sum(np.log(w)))
80
- return float(logdet)
81
 
82
- def safe_small_eigs_vals(L_csr, want_k, dense_cutoff=700):
83
- """
84
- Liefert kleinste Eigenwerte robust:
85
- - für kleine n: dichte EVD
86
- - sonst: eigsh('SA'); Fallback: Shift-Invert (σ≈0, +εI), Fallback2: LOBPCG
87
- """
88
- n = L_csr.shape[0]
89
- k = int(min(max(2, want_k), max(1, n-2)))
90
- if n <= dense_cutoff:
91
- w = np.linalg.eigvalsh(L_csr.toarray())
92
- return np.real(np.sort(w))
93
- try:
94
- w = spla.eigsh(L_csr, k=k, which="SA", return_eigenvectors=False,
95
- maxiter=40000, tol=1e-8)
96
- return np.real(np.sort(w))
97
- except Exception:
98
- eps = 1e-8 * (np.mean(L_csr.diagonal()) if L_csr.nnz else 1.0)
 
 
99
  try:
100
- w = spla.eigsh(to_csc(L_csr) + eps*sps.eye(n, format='csc'),
101
- k=k, which="LM", sigma=0.0,
102
- return_eigenvectors=False, maxiter=40000, tol=1e-8)
103
- return np.real(np.sort(w - eps))
104
  except Exception:
105
- X = np.random.randn(n, k)
106
- w, _ = spla.lobpcg(to_csc(L_csr) + eps*sps.eye(n, format='csc'),
107
- X, tol=1e-6, maxiter=1000, largest=False)
108
- return np.real(np.sort(w - eps))
109
-
110
- # -------------------------------------------
111
- # Mikrostruktur-Bausteine (deterministisch)
112
- # Jede Funktion liefert: coords (N×d), edges ([(i,j),...]), boundary ([...])
113
- # -------------------------------------------
114
- SQRT3 = math.sqrt(3.0)
115
- SQRT_2_3 = math.sqrt(2.0/3.0)
116
-
117
- def _merge_nodes_by_pos(pts, eps=1e-10):
118
- arr = np.array(pts, dtype=float)
119
- rounder = (np.round(arr/eps)*eps)
120
- unique, inv = np.unique(rounder.round(12), axis=0, return_inverse=True)
121
- return unique, inv
122
-
123
- # --- Sierpinski Gasket (2D) ---
124
- def build_sierpinski_gasket(level=3):
125
- A = np.array([0.0, 0.0])
126
- B = np.array([1.0, 0.0])
127
- C = np.array([0.5, SQRT3/2.0])
128
- V0 = np.stack([A,B,C], axis=0)
129
- words = [()]
130
- for _ in range(level):
131
- words = [w+(i,) for w in words for i in range(3)]
132
- all_tri = []
133
- for w in words:
134
- tri = V0.copy()
135
- for i in w:
136
- tri = (tri + V0[i])/2.0
137
- all_tri.append(tri)
138
- pts = np.vstack(all_tri)
139
- pts_u, _ = _merge_nodes_by_pos(pts)
140
- edges = []
141
- for tri in all_tri:
142
- ids = []
143
- for k in range(3):
144
- key = np.round(tri[k], 10)
145
- j = np.argmin(np.linalg.norm(pts_u - key, axis=1))
146
- ids.append(j)
147
- for a,b in [(0,1),(1,2),(2,0)]:
148
- i,j = ids[a], ids[b]
149
- if i!=j: edges.append(tuple(sorted((i,j))))
150
- edges = sorted(set(edges))
151
- center = pts_u.mean(axis=0)
152
- d = np.linalg.norm(pts_u - center, axis=1)
153
- boundary = np.array(sorted(np.argsort(d)[-3:]), dtype=int)
154
- return pts_u, edges, boundary
155
-
156
- # --- Sierpinski Tetraeder (3D) ---
157
- def build_sierpinski_tetra(level=2):
158
- A = np.array([0.0, 0.0, 0.0])
159
- B = np.array([1.0, 0.0, 0.0])
160
- C = np.array([0.5, SQRT3/2.0, 0.0])
161
- D = np.array([0.5, SQRT3/6.0, SQRT_2_3])
162
- V0 = np.stack([A,B,C,D], axis=0)
163
- words = [()]
164
- for _ in range(level):
165
- words = [w+(i,) for w in words for i in range(4)]
166
- all_tet = []
167
- for w in words:
168
- tet = V0.copy()
169
- for i in w:
170
- tet = (tet + V0[i])/2.0
171
- all_tet.append(tet)
172
- pts = np.vstack(all_tet)
173
- pts_u,_ = _merge_nodes_by_pos(pts)
174
- edges = []
175
- for tet in all_tet:
176
- ids = []
177
- for k in range(4):
178
- key = np.round(tet[k], 10)
179
- j = np.argmin(np.linalg.norm(pts_u - key, axis=1))
180
- ids.append(j)
181
- for a,b in [(0,1),(1,2),(2,0),(0,3),(1,3),(2,3)]:
182
- i,j = ids[a], ids[b]
183
- if i!=j: edges.append(tuple(sorted((i,j))))
184
- edges = sorted(set(edges))
185
- center = pts_u.mean(axis=0)
186
- d = np.linalg.norm(pts_u - center, axis=1)
187
- boundary = np.array(sorted(np.argsort(d)[-4:]), dtype=int)
188
- return pts_u, edges, boundary
189
-
190
- # --- Sierpinski Carpet (2D) – zellenbasiert, symmetrisch ---
191
- def build_sierpinski_carpet(level=2):
192
- n = 3**level
193
- keep = np.ones((n, n), dtype=bool)
194
-
195
- def is_removed(i, j):
196
- while i > 0 or j > 0:
197
- if (i % 3 == 1) and (j % 3 == 1):
198
- return True
199
- i //= 3; j //= 3
200
- return False
201
-
202
- for i in range(n):
203
- for j in range(n):
204
- if is_removed(i, j):
205
- keep[i, j] = False
206
-
207
- coords, index = [], {}
208
- for i in range(n):
209
- for j in range(n):
210
- if keep[i, j]:
211
- idx = len(coords)
212
- index[(i, j)] = idx
213
- coords.append([(i+0.5)/n, (j+0.5)/n])
214
- coords = np.array(coords, float)
215
-
216
- edges = []
217
- for i in range(n):
218
- for j in range(n):
219
- if not keep[i, j]:
220
- continue
221
- u = index[(i, j)]
222
- if i+1 < n and keep[i+1, j]:
223
- v = index[(i+1, j)]; edges.append((min(u,v), max(u,v)))
224
- if j+1 < n and keep[i, j+1]:
225
- v = index[(i, j+1)]; edges.append((min(u,v), max(u,v)))
226
- edges = sorted(set(edges))
227
-
228
- boundary = [index[(i,j)] for i in range(n) for j in range(n)
229
- if keep[i,j] and (i in (0,n-1) or j in (0,n-1))]
230
- return coords, edges, np.array(sorted(set(boundary)), dtype=int)
231
-
232
- # --- Vicsek (2D) ---
233
- def build_vicsek(level=2):
234
- scale = 3**level
235
- pts = []
236
- def keep_cell(i,j,L):
237
- while L>0:
238
- if (i%3, j%3) not in [(1,1),(1,0),(0,1),(1,2),(2,1)]:
239
- return False
240
- i//=3; j//=3; L-=1
241
- return True
242
- for i in range(scale):
243
- for j in range(scale):
244
- if keep_cell(i,j,level):
245
- pts.append(((i+0.5)/scale, (j+0.5)/scale))
246
- coords = np.array(pts, float)
247
- from scipy.spatial import cKDTree
248
- kd = cKDTree(coords)
249
- edges = []
250
- for u,p in enumerate(coords):
251
- for v in kd.query_ball_point(p, r=1.01/scale):
252
- if u<v:
253
- if np.isclose(np.sum(np.abs(coords[u]-coords[v]))*scale, 1.0, atol=1e-6):
254
- edges.append((u,v))
255
- edges = sorted(set(edges))
256
- corners = np.array([[0,0],[1,0],[1,1],[0,1]], float)
257
- boundary = set()
258
- for c in corners:
259
- v = int(np.argmin(np.linalg.norm(coords - c, axis=1)))
260
- boundary.add(v)
261
- boundary = np.array(sorted(boundary), dtype=int)
262
- return coords, edges, boundary
263
-
264
- # --- T-Fraktal (2D) ---
265
- def build_t_fractal(level=4):
266
- nodes = [np.array([-0.5,0.0]), np.array([0.5,0.0])]
267
- segs = [(nodes[0], nodes[1])]
268
- for _ in range(level):
269
- new = []
270
- for a, b in segs:
271
- mid = 0.5*(a+b)
272
- L = np.linalg.norm(b-a)
273
- if L == 0: continue
274
- ortho = np.array([0.0, L/2.0])
275
- new += [(a, mid), (mid, b), (mid, mid+ortho)]
276
- segs = new
277
- index, coords, edges = {}, [], []
278
- def gid(p):
279
- k = tuple(np.round(p, 12))
280
- if k in index: return index[k]
281
- idx = len(coords); index[k] = idx; coords.append(np.array(p, float)); return idx
282
- for a,b in segs:
283
- i,j = gid(a), gid(b)
284
- if i!=j: edges.append((min(i,j), max(i,j)))
285
- coords = np.array(coords, float)
286
- edges = sorted(set(edges))
287
- mn, mx = coords.min(0), coords.max(0)
288
- span = np.maximum(mx-mn, 1e-12)
289
- coords = (coords - mn)/span
290
- deg = np.zeros(len(coords), int)
291
- for i,j in edges:
292
- deg[i]+=1; deg[j]+=1
293
- boundary = np.array([i for i,d in enumerate(deg) if d==1], dtype=int)
294
- return coords, edges, boundary
295
-
296
- # --- H-Tree (2D) – robust & verbunden (Zentrum explizit) ---
297
- def build_h_tree(level=4):
298
- index, coords, edges = {}, [], []
299
-
300
- def gid(p):
301
- k = tuple(np.round(p, 12))
302
- if k in index: return index[k]
303
- idx = len(coords); index[k] = idx; coords.append(np.array(p, float)); return idx
304
-
305
- def seg(a, b):
306
- i, j = gid(a), gid(b)
307
- if i != j: edges.append((min(i, j), max(i, j)))
308
-
309
- def rec(x, y, L, d):
310
- x0, x1 = x - L/2.0, x + L/2.0
311
- y0, y1 = y - L/2.0, y + L/2.0
312
- seg((x0, y), (x, y)) # split
313
- seg((x, y), (x1, y)) # split
314
- seg((x0, y0), (x0, y1))
315
- seg((x1, y0), (x1, y1))
316
- if d > 0:
317
- L2 = L/np.sqrt(2.0)
318
- rec(x0, y0, L2, d-1); rec(x0, y1, L2, d-1)
319
- rec(x1, y0, L2, d-1); rec(x1, y1, L2, d-1)
320
-
321
- rec(0.5, 0.5, 0.8, level)
322
- coords = np.array(coords, float)
323
- edges = sorted(set(edges))
324
- deg = np.zeros(len(coords), int)
325
- for i, j in edges: deg[i] += 1; deg[j] += 1
326
- boundary = np.array([i for i, d in enumerate(deg) if d <= 2], dtype=int)
327
- return coords, edges, boundary
328
-
329
- # --- Koch-Schneeflocke (2D) ---
330
- def build_koch_snowflake(level=2):
331
- p0 = np.array([0.0, 0.0]); p1 = np.array([1.0, 0.0]); p2 = np.array([0.5, SQRT3/2.0])
332
- poly = [p0, p1, p2]
333
- def koch_step(pts):
334
- out = []
335
- R = np.array([[0.5, -SQRT3/2.0], [SQRT3/2.0, 0.5]]) # +60°
336
- for a, b in zip(pts, pts[1:] + pts[:1]):
337
- v = b - a
338
- a1 = a + v/3.0
339
- a2 = a + 2.0*v/3.0
340
- peak = a1 + R @ (v/3.0)
341
- out += [a, a1, peak, a2]
342
- return out
343
- for _ in range(level):
344
- poly = koch_step(poly)
345
- index, coords, edges = {}, [], []
346
- def gid(p):
347
- k = tuple(np.round(p, 12))
348
- if k in index: return index[k]
349
- idx = len(coords); index[k] = idx; coords.append(np.array(p, float)); return idx
350
- for a, b in zip(poly, poly[1:] + poly[:1]):
351
- i, j = gid(a), gid(b)
352
- if i != j: edges.append((min(i, j), max(i, j)))
353
- coords = np.array(coords, float)
354
- edges = sorted(set(edges))
355
- boundary = np.array(sorted({gid(p0), gid(p1), gid(p2)}), dtype=int)
356
- return coords, edges, boundary
357
-
358
- # --- Apollonisches Netz (2D) ---
359
- def build_apollonian(level=2):
360
- coords = [np.array([0.0,0.0]), np.array([1.0,0.0]), np.array([0.5,SQRT3/2.0])]
361
- edges = {(0,1),(1,2),(0,2)}
362
- faces = {(0,1,2)}
363
- for _ in range(level):
364
- new_faces = set()
365
- for (a,b,c) in list(faces):
366
- p = (coords[a]+coords[b]+coords[c])/3.0
367
- idx = len(coords); coords.append(p)
368
- for u,v in [(a,b),(b,c),(c,a)]:
369
- edges.add(tuple(sorted((idx,u))))
370
- edges.add(tuple(sorted((idx,v))))
371
- new_faces.update({tuple(sorted((a,b,idx))),
372
- tuple(sorted((b,c,idx))),
373
- tuple(sorted((c,a,idx)))})
374
- faces = new_faces
375
- coords = np.array(coords, float)
376
- edges = sorted(set([tuple(sorted(e)) for e in edges]))
377
- boundary = np.array([0,1,2], dtype=int)
378
- return coords, edges, boundary
379
-
380
- # --- Pseudofraktales skalenfreies Netz ---
381
- def build_pseudofractal(level=3):
382
- coords = [np.array([0.0,0.0]), np.array([1.0,0.0]), np.array([0.5,SQRT3/2.0])]
383
- edges = {(0,1),(1,2),(0,2)}
384
- def offset(a,b):
385
- v = b-a
386
- if np.linalg.norm(v)<1e-12: return np.zeros(2)
387
- R = np.array([[0, -1],[1,0]])
388
- return (R@v) * 0.03
389
- for _ in range(level):
390
- old_edges = list(edges)
391
- for (i,j) in old_edges:
392
- k = len(coords)
393
- p = 0.5*(coords[i]+coords[j]) + offset(coords[i],coords[j])
394
- coords.append(p)
395
- edges.add(tuple(sorted((i,k))))
396
- edges.add(tuple(sorted((j,k))))
397
- coords = np.array(coords, float)
398
- edges = sorted(set([tuple(sorted(e)) for e in edges]))
399
- boundary = np.array([0,1,2], dtype=int)
400
- return coords, edges, boundary
401
-
402
- # --- Diamond-Fraktal (2D) ---
403
- def build_diamond(level=3):
404
- segs = [(np.array([0.0, 0.0]), np.array([1.0, 0.0]))]
405
- for _ in range(level):
406
- new = []
407
- for a, b in segs:
408
- mid = 0.5*(a+b)
409
- v = b - a; L = np.linalg.norm(v)
410
- if L == 0: continue
411
- u = v/L; ortho = np.array([-u[1], u[0]]) * (L * 0.25)
412
- p, q = mid + ortho, mid - ortho
413
- new += [(a, p), (p, b), (a, q), (q, b)]
414
- segs = new
415
- index, coords, edges = {}, [], []
416
- def gid(p):
417
- k = tuple(np.round(p, 12))
418
- if k in index: return index[k]
419
- idx = len(coords); index[k] = idx; coords.append(np.array(p, float)); return idx
420
- for a, b in segs:
421
- i, j = gid(a), gid(b)
422
- if i != j: edges.append((min(i, j), max(i, j)))
423
- coords = np.array(coords, float)
424
- edges = sorted(set(edges))
425
- mn, mx = coords[:, 0].min(), coords[:, 0].max()
426
- B = [int(np.argmin((coords[:,0]-mn)**2)), int(np.argmin((coords[:,0]-mx)**2))]
427
- return coords, edges, np.array(sorted(set(B)), dtype=int)
428
-
429
- # --- Square/Cube Patch & Menger (3D) ---
430
- def build_square_patch(n=10):
431
- xs, ys = np.meshgrid(np.linspace(0,1,n), np.linspace(0,1,n))
432
- coords = np.stack([xs.ravel(), ys.ravel()], axis=1)
433
- def idx(i,j): return i*n+j
434
- edges = []
435
- for i in range(n):
436
- for j in range(n):
437
- if i+1<n: edges.append((idx(i,j), idx(i+1,j)))
438
- if j+1<n: edges.append((idx(i,j), idx(i,j+1)))
439
- edges = sorted(set([tuple(sorted(e)) for e in edges]))
440
- boundary = []
441
- for i in range(n):
442
- boundary += [idx(i,0), idx(i,n-1)]
443
- for j in range(1,n-1):
444
- boundary += [idx(0,j), idx(n-1,j)]
445
- boundary = np.array(sorted(set(boundary)), dtype=int)
446
- return coords, edges, boundary
447
-
448
- def build_cube_patch(n=5):
449
- xs, ys, zs = np.meshgrid(np.linspace(0,1,n), np.linspace(0,1,n), np.linspace(0,1,n))
450
- coords = np.stack([xs.ravel(), ys.ravel(), zs.ravel()], axis=1)
451
- def idx(i,j,k): return (i*n + j)*n + k
452
- edges = []
453
- for i in range(n):
454
- for j in range(n):
455
- for k in range(n):
456
- if i+1<n: edges.append((idx(i,j,k), idx(i+1,j,k)))
457
- if j+1<n: edges.append((idx(i,j,k), idx(i,j+1,k)))
458
- if k+1<n: edges.append((idx(i,j,k), idx(i,j,k+1)))
459
- edges = sorted(set([tuple(sorted(e)) for e in edges]))
460
- boundary = []
461
- for i in range(n):
462
- for j in range(n):
463
- for k in range(n):
464
- if i in (0,n-1) or j in (0,n-1) or k in (0,n-1):
465
- boundary.append(idx(i,j,k))
466
- boundary = np.array(sorted(set(boundary)), dtype=int)
467
- return coords, edges, boundary
468
-
469
- def build_menger(level=1):
470
- keep = []
471
- n = 3**level
472
- for i in range(n):
473
- for j in range(n):
474
- for k in range(n):
475
- flags = sum([(i%3==1),(j%3==1),(k%3==1)])
476
- if flags <= 1:
477
- keep.append((i,j,k))
478
- coords = np.array([[(i+0.5)/n,(j+0.5)/n,(k+0.5)/n] for (i,j,k) in keep], float)
479
- idx = {p:t for t,p in enumerate(keep)}
480
- edges = []
481
- for (i,j,k) in keep:
482
- u = idx[(i,j,k)]
483
- for di,dj,dk in [(1,0,0),(0,1,0),(0,0,1)]:
484
- q = (i+di, j+dj, k+dk)
485
- if q in idx:
486
- v = idx[q]
487
- edges.append((min(u,v), max(u,v)))
488
- edges = sorted(set(edges))
489
- boundary = []
490
- for (i,j,k) in keep:
491
- if i in (0,n-1) or j in (0,n-1) or k in (0,n-1):
492
- boundary.append(idx[(i,j,k)])
493
- boundary = np.array(sorted(set(boundary)), dtype=int)
494
- return coords, edges, boundary
495
-
496
- # -------------------------------------------
497
- # Laplace / Dirichlet / Widerstände / Masse
498
- # -------------------------------------------
499
- def edges_to_sparse(n, edges, weights=None):
500
- if weights is None:
501
- weights = np.ones(len(edges), dtype=float)
502
- I = []; J = []; V = []
503
- for (w,(i,j)) in zip(weights, edges):
504
- I += [i,j]; J += [j,i]; V += [w,w]
505
- A = sps.csr_matrix((V,(I,J)), shape=(n,n))
506
- d = np.asarray(A.sum(axis=1)).ravel()
507
- L = sps.diags(d) - A
508
- return A, L
509
-
510
- def build_laplacian(n, edges, wdict=None):
511
- if wdict is None:
512
- weights = np.ones(len(edges), dtype=float)
513
- else:
514
- weights = np.array([wdict[(i,j) if i<j else (j,i)] for (i,j) in edges], float)
515
- return edges_to_sparse(n, edges, weights=weights)[1]
516
-
517
- def intrinsic_mass_from_L(L_csr):
518
- # m := durchschnittlicher Knotengrad = trace(L)/n (vollständig intrinsisch)
519
- n = L_csr.shape[0]
520
- deg = np.asarray(L_csr.diagonal()).ravel()
521
- return float(deg.mean()) if n>0 else 0.0
522
-
523
- # DtN
524
- def dtn_map_sparse(L_csr, B):
525
- B = np.asarray(B, dtype=int).ravel()
526
- B = np.unique(B)
527
- n = L_csr.shape[0]
528
- I = np.setdiff1d(np.arange(n), B)
529
- if I.size == 0:
530
- return L_csr[np.ix_(B,B)].toarray()
531
- LBB = L_csr[np.ix_(B,B)].toarray()
532
- LIB = to_csc(L_csr[np.ix_(I,B)])
533
- LII = to_csc(L_csr[np.ix_(I,I)])
534
- LU = spla.splu(LII)
535
- X = LU.solve(LIB.toarray())
536
- return LBB - LIB.T.toarray() @ X
537
-
538
- def dtn_error_sparse(L_id_csr, L_real_csr, B):
539
- Lam_id = dtn_map_sparse(L_id_csr, B)
540
- Lam_real = dtn_map_sparse(L_real_csr, B)
541
- num = np.linalg.norm(Lam_real - Lam_id, "fro")
542
- den = max(1.0, np.linalg.norm(Lam_id, "fro"))
543
- return float(num/den)
544
-
545
- def calibrate_s_star_sparse(L_id_csr, edges, w_base, B, grid=np.linspace(0.4, 3.0, 18)):
546
- n = L_id_csr.shape[0]
547
- best_err, best_s, best_w = float("inf"), 1.0, None
548
- for s in grid:
549
- w = {}
550
- for (i,j) in edges:
551
- key = (i,j) if i<j else (j,i)
552
- if (i in B and j in B):
553
- w[key] = 1.0
554
- else:
555
- w[key] = s*w_base[key]
556
- Ls = build_laplacian(n, edges, w)
557
- err = dtn_error_sparse(L_id_csr, Ls, B)
558
- if err < best_err:
559
- best_err, best_s, best_w = err, s, w
560
- return best_s, best_w, best_err
561
-
562
- # Effektivwiderstand (geerdete LU)
563
- def grounded_factorization(L_csr, ground=0):
564
- n = L_csr.shape[0]
565
- idx = [k for k in range(n) if k != ground]
566
- A = to_csc(L_csr[np.ix_(idx, idx)])
567
- try:
568
- LU = spla.splu(A)
569
- except RuntimeError:
570
- eps = 1e-9
571
- LU = spla.splu(A + eps*sps.eye(A.shape[0], format='csc'))
572
- return idx, LU
573
-
574
- def eff_resistance_pair(L_csr, LU, keep_idx, i, j, ground=0):
575
- if i == j: return 0.0
576
- m = {orig: k for k, orig in enumerate(keep_idx)}
577
- ei = np.zeros(len(keep_idx)); ej = np.zeros(len(keep_idx))
578
- if i != ground and i in m: ei[m[i]] = 1.0
579
- if j != ground and j in m: ej[m[j]] = 1.0
580
- b = ei - ej
581
- x = LU.solve(b)
582
- vi = 0.0 if i==ground else x[m[i]]
583
- vj = 0.0 if j==ground else x[m[j]]
584
- return float(abs(vi - vj))
585
-
586
- # Tiefe vom Rand (für Renorm)
587
- def level_by_depth_from_boundary(n, edges, boundary):
588
- G = nx.Graph()
589
- G.add_nodes_from(range(n))
590
- G.add_edges_from(edges)
591
- depths = np.full(n, np.inf)
592
- from collections import deque
593
- dq = deque()
594
- for b in boundary:
595
- depths[b] = 0
596
- dq.append(b)
597
- while dq:
598
- u = dq.popleft()
599
- for v in G[u]:
600
- if depths[v] > depths[u] + 1:
601
- depths[v] = depths[u] + 1
602
- dq.append(v)
603
- depths[np.isinf(depths)] = depths[~np.isinf(depths)].max() + 1
604
- e_levels = np.array([min(depths[i],depths[j]) for (i,j) in edges], dtype=float)
605
- return depths, e_levels
606
-
607
- # --- Multiplikatoren ---
608
- def energy_driven_multipliers(L, edges, boundary):
609
- n = L.shape[0]
610
- B = list(boundary)
611
- if len(B) <= 1:
612
- return np.ones(len(edges), dtype=float)
613
- pairs = [(B[k], B[(k+1)%len(B)]) for k in range(len(B))]
614
- accum = np.zeros(len(edges), dtype=float)
615
- for (a,b) in pairs:
616
- fixed = np.array([a,b], dtype=int)
617
- free = np.array(sorted(set(range(n)) - set(fixed)), dtype=int)
618
- Lff = to_csc(L[np.ix_(free,free)])
619
- Lfc = L[np.ix_(free,fixed)]
620
- u_fixed = np.array([1.0, 0.0])
621
- if free.size>0:
622
- lu = spla.splu(Lff)
623
- rhs = - as_dense(Lfc) @ u_fixed
624
- u_free = lu.solve(rhs)
625
- else:
626
- u_free = np.array([])
627
- u = np.zeros(n); u[fixed]=u_fixed; u[free]=u_free
628
- for idx,(i,j) in enumerate(edges):
629
- du = u[i]-u[j]
630
- accum[idx] += du*du
631
- bmask = np.array([(i in boundary) and (j in boundary) for i,j in edges], dtype=bool)
632
- bmean = accum[bmask].mean() if np.any(bmask) else accum.mean() if accum.mean()>0 else 1.0
633
- accum = accum / max(bmean, 1e-12)
634
- mult = np.clip(1.0 + accum, 1.0, 50.0)
635
- return mult
636
-
637
- def real_weights_deepening(L_id_csr, edges, boundary, level_hint=2.0):
638
- alpha = level_hint
639
- n = L_id_csr.shape[0]
640
- B = set(boundary)
641
- keep, LU = grounded_factorization(L_id_csr, ground=0)
642
- depths, e_levels = level_by_depth_from_boundary(n, edges, boundary)
643
- w = {}
644
- for t,(i,j) in enumerate(edges):
645
- key = (i,j) if i<j else (j,i)
646
- if (i in B and j in B):
647
- w[key] = 1.0
648
- continue
649
- Rij = max(eff_resistance_pair(L_id_csr, LU, keep, i, j, 0), 1e-12)
650
- ell = e_levels[t]
651
- w[key] = (alpha**ell) * (1.0/Rij)
652
- return w
653
-
654
- def real_weights_kron(L_id_csr, edges, boundary):
655
- L_id = L_id_csr.toarray()
656
- B = set(boundary)
657
- w = {}
658
- n = L_id.shape[0]
659
- I = list(sorted(set(range(n))-B))
660
- if I:
661
- LBB = L_id[np.ix_(list(B), list(B))]
662
- LBI = L_id[np.ix_(list(B), I)]
663
- LIB = L_id[np.ix_(I, list(B))]
664
- LII = L_id[np.ix_(I, I)]
665
- LII_p = np.linalg.pinv(LII)
666
- _ = LBB - LBI @ LII_p @ LIB
667
- Lp_full = np.linalg.pinv(L_id)
668
- d_full = np.diag(Lp_full)
669
- for (i,j) in edges:
670
- key = (i,j) if i<j else (j,i)
671
- if (i in B and j in B):
672
- w[key] = 1.0
673
- else:
674
- Rij = max(float(d_full[i] + d_full[j] - 2.0*Lp_full[i,j]), 1e-12)
675
- w[key] = 1.0 / Rij
676
- else:
677
- for (i,j) in edges:
678
- key = (i,j) if i<j else (j,i)
679
- w[key] = 1.0
680
- return w
681
-
682
- # -------------------------------------------
683
- # Einbettung & Projektion (ST-Hülle)
684
- # -------------------------------------------
685
- def harmonic_embed_with_fixed_boundary(L_real_csr, X_boundary_from_ideal, B):
686
- n = L_real_csr.shape[0]
687
- d = X_boundary_from_ideal.shape[1]
688
- X = np.zeros((n, d), float)
689
- B = np.asarray(B, dtype=int).ravel()
690
- if B.size == 0:
691
- return X
692
- B = np.unique(B)
693
- I = np.setdiff1d(np.arange(n), B)
694
- X[B, :] = X_boundary_from_ideal[B, :]
695
- if I.size == 0:
696
- return X
697
- LII = to_csc(L_real_csr[np.ix_(I, I)])
698
- LIB = to_csc(L_real_csr[np.ix_(I, B)])
699
- LU = spla.splu(LII)
700
- RHS = - LIB @ X[B, :]
701
- X[I, :] = LU.solve(RHS)
702
- return X
703
-
704
- def project_points_into_tetra(X, verts_idx, verts_pos):
705
- A,B,C,D = verts_pos
706
- T = np.column_stack((A-D, B-D, C-D))
707
- Tinv = np.linalg.pinv(T)
708
- Xp = X.copy()
709
- for i in range(len(X)):
710
- if i in verts_idx: continue
711
- w = Tinv @ (X[i]-D)
712
- a,b,c = w; d = 1.0 - (a+b+c)
713
- w4 = np.clip(np.array([a,b,c,d]), 0.0, 1.0); s = w4.sum()
714
- w4 = w4/s if s>1e-15 else np.array([0,0,0,1.0])
715
- Xp[i] = w4[0]*A + w4[1]*B + w4[2]*C + w4[3]*D
716
- return Xp
717
-
718
- # -------------------------------------------
719
- # Dynamik & Heat-Kernel
720
- # -------------------------------------------
721
- def herm_expm(H, t):
722
- w, U = np.linalg.eigh(H)
723
- phase = np.exp(-1j * w * t)
724
- return (U * phase) @ U.conj().T
725
-
726
- def lv_n_density(H, rho0, t):
727
- U = herm_expm(H, t)
728
- return U @ rho0 @ U.conj().T
729
-
730
- def pick_initial_state(n, kind="delta@center"):
731
- rho0 = np.zeros((n,n), dtype=complex)
732
- if kind.startswith("delta"):
733
- idx = n//2
734
- rho0[idx, idx] = 1.0
735
- elif kind == "maximally_mixed":
736
- rho0 = np.eye(n, dtype=complex) / n
737
- else:
738
- rho0[0,0] = 1.0
739
- return rho0
740
 
741
- def derive_gksl_ops_from_structure(L_real):
742
- n = L_real.shape[0]
743
- deg = np.asarray(L_real.diagonal()).ravel()
744
- gamma = deg/deg.max() if deg.max() > 0 else np.ones(n)
745
- Lops = []
746
- for i in range(n):
747
- if gamma[i] > 1e-12:
748
- Li = np.zeros((n,n), dtype=complex); Li[i,i] = math.sqrt(gamma[i])
749
- Lops.append(Li)
750
- return Lops
751
 
752
- def gksl_step(H, rho, Lops):
753
- drho = -1j * (H @ rho - rho @ H)
754
- for L in Lops:
755
- LdL = L.conj().T @ L
756
- drho += L @ rho @ L.conj().T - 0.5 * (LdL @ rho + rho @ LdL)
757
- return drho
758
 
759
- def simulate_gksl(H, rho0, Lops, T, steps=200):
760
- dt = T/steps
761
- rho = rho0.copy()
762
- for _ in range(steps):
763
- k1 = gksl_step(H, rho, Lops)
764
- k2 = gksl_step(H, rho + 0.5*dt*k1, Lops)
765
- k3 = gksl_step(H, rho + 0.5*dt*k2, Lops)
766
- k4 = gksl_step(H, rho + dt*k3, Lops)
767
- rho = rho + (dt/6.0)*(k1 + 2*k2 + 2*k3 + k4)
768
- rho = 0.5*(rho + rho.conj().T)
769
- tr = np.trace(rho)
770
- if abs(tr) > 0:
771
- rho /= tr
772
- return rho
773
 
774
- def heat_kernel_matrix_for_plot(L_csr, tau, cap=450):
775
- """
776
- Liefert Heat-Kernel exp(-tau L).
777
- - Für n<=cap: volle Matrix (dicht) für Heatmap.
778
- - Für n>cap: Subsampling gleicher Abstände (cap×cap-Block).
779
- """
780
- n = L_csr.shape[0]
781
- if n <= cap:
782
- K = spla.expm(-tau * to_csc(L_csr)).toarray()
783
- return K, np.arange(n, dtype=int)
784
- m = cap
785
- idx = np.linspace(0, n-1, m, dtype=int)
786
- K = spla.expm(-tau * to_csc(L_csr[np.ix_(idx, idx)])).toarray()
787
- return K, idx
788
 
789
- # -------------------------------------------
790
- # Plots & Heatmaps
791
- # -------------------------------------------
792
- def plot_graph(coords, edges, title, node_vals=None, dim=None, show_edges=True, height=520):
793
- dim = coords.shape[1] if dim is None else dim
794
- E_x = []; E_y = []; E_z = []
795
- for (i,j) in edges:
796
- p = coords[i]; q = coords[j]
797
- E_x += [p[0], q[0], None]
798
- E_y += [p[1], q[1], None]
799
- if dim==3:
800
- E_z += [p[2], q[2], None]
801
- if dim==2:
802
- fig = go.Figure()
803
- if show_edges:
804
- fig.add_trace(go.Scatter(
805
- x=E_x, y=E_y, mode="lines", line=dict(width=1),
806
- name="edges", hoverinfo="skip", showlegend=True
807
- ))
808
- marker=dict(size=6)
809
- if node_vals is not None:
810
- marker.update(dict(
811
- color=node_vals, showscale=True,
812
- colorbar=dict(x=1.02, y=0.5, len=0.9, thickness=12, outlinewidth=0)
813
- ))
814
- fig.add_trace(go.Scatter(
815
- x=coords[:,0], y=coords[:,1], mode="markers",
816
- marker=marker, name="nodes", showlegend=True
817
- ))
818
- fig.update_layout(
819
- title=title, height=height, margin=dict(l=80,r=90,t=50,b=10),
820
- legend=dict(x=0.0, y=1.0, xanchor="left", yanchor="top")
821
- )
822
- return fig
823
  else:
824
- fig = go.Figure()
825
- if show_edges:
826
- fig.add_trace(go.Scatter3d(
827
- x=E_x, y=E_y, z=E_z, mode="lines",
828
- line=dict(width=1), name="edges", hoverinfo="skip", showlegend=True
829
- ))
830
- marker=dict(size=2)
831
- if node_vals is not None:
832
- marker.update(dict(
833
- color=node_vals, showscale=True,
834
- colorbar=dict(x=1.02, y=0.5, len=0.9, thickness=12, outlinewidth=0)
835
- ))
836
- fig.add_trace(go.Scatter3d(
837
- x=coords[:,0], y=coords[:,1], z=coords[:,2],
838
- mode="markers", marker=marker, name="nodes", showlegend=True
839
- ))
840
- fig.update_layout(
841
- title=title, height=height, margin=dict(l=80,r=90,t=50,b=10),
842
- legend=dict(x=0.0, y=1.0, xanchor="left", yanchor="top")
843
- )
844
- return fig
845
 
846
- def heatmap_density(rho, title, mode="real", clip_q=0.995, height=460):
847
- """
848
- Hübsche & robuste Heatmap:
849
- mode in {"real", "imag", "abs", "abslog", "phase"}
850
- - real/imag: divergend, zmid=0, robustes symm. Clipping
851
- - abs: linear
852
- - abslog: log10(|rho|+1e-12)
853
- - phase: Winkel [-pi, pi]
854
- Legende links, Colorbar rechts.
855
- """
856
- M = None; cmap = "Viridis"; zmid = None
857
- if mode == "real":
858
- M = np.real(rho); cmap = "RdBu"; zmid = 0.0
859
- vmax = np.quantile(np.abs(M), clip_q)
860
- zmin, zmax = -vmax, vmax
861
- elif mode == "imag":
862
- M = np.imag(rho); cmap = "PuOr"; zmid = 0.0
863
- vmax = np.quantile(np.abs(M), clip_q)
864
- zmin, zmax = -vmax, vmax
865
- elif mode == "abs":
866
- M = np.abs(rho)
867
- zmin, zmax = float(np.quantile(M, 0.0)), float(np.quantile(M, clip_q))
868
- elif mode == "abslog":
869
- M = np.log10(np.abs(rho) + 1e-12)
870
- zmin, zmax = float(np.quantile(M, 0.01)), float(np.quantile(M, 0.99))
871
- else: # phase
872
- M = np.angle(rho); cmap = "Twilight"; zmid = 0.0
873
- zmin, zmax = -np.pi, np.pi
874
 
875
- fig = px.imshow(M, origin="lower", color_continuous_scale=cmap,
876
- zmin=zmin, zmax=zmax, title=title)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
877
  fig.update_layout(
878
- height=height,
879
- margin=dict(l=80, r=90, t=50, b=10),
880
- legend=dict(x=0.0, y=1.0, xanchor="left", yanchor="top")
 
 
881
  )
882
- fig.update_layout(coloraxis_colorbar=dict(
883
- x=1.02, xanchor="left", y=0.5, yanchor="middle",
884
- len=0.9, thickness=12, outlinewidth=0
885
- ))
886
  return fig
887
 
888
- # -------------------------------------------
889
- # UI
890
- # -------------------------------------------
891
- st.set_page_config(page_title="IDEAL→REAL (Verified, Efficient)", layout="wide")
892
- st.title("Ableitung IDEAL → REAL")
893
 
894
- with st.sidebar:
895
- st.header("IDEAL-Mikrostruktur (deterministisch)")
896
- graph_kind = st.selectbox("Struktur", [
897
- "Sierpinski Gasket (2D)",
898
- "Sierpinski Tetrahedron (3D)",
899
- "Sierpinski Carpet (2D)",
900
- "Vicsek Cross (2D)",
901
- "T-Fractal (2D)",
902
- "H-Tree (2D)",
903
- "Koch Snowflake (2D)",
904
- "Apollonian Network (2D)",
905
- "Pseudofractal SF (Dorogovtsev–Mendes) (2D)",
906
- "Diamond Fractal (2D)",
907
- "Square Patch (2D)",
908
- "Cube Patch (3D)",
909
- "Menger Sponge (3D)"
910
- ])
911
-
912
- st.header("Approximations-Level")
913
- if graph_kind in ["Sierpinski Gasket (2D)"]:
914
- level = st.slider("Level", 1, 5, 2)
915
- elif graph_kind in ["Sierpinski Tetrahedron (3D)"]:
916
- level = st.slider("Level", 1, 4, 2)
917
- elif graph_kind in ["Sierpinski Carpet (2D)"]:
918
- level = st.slider("Level", 1, 4, 2)
919
- elif graph_kind in ["Vicsek Cross (2D)"]:
920
- level = st.slider("Level", 1, 4, 2)
921
- elif graph_kind in ["T-Fractal (2D)"]:
922
- level = st.slider("Level", 1, 4, 2)
923
- elif graph_kind in ["H-Tree (2D)"]:
924
- level = st.slider("Level", 1, 4, 2)
925
- elif graph_kind in ["Koch Snowflake (2D)"]:
926
- level = st.slider("Level", 0, 4, 2)
927
- elif graph_kind in ["Apollonian Network (2D)"]:
928
- level = st.slider("Generationen", 0, 4, 2)
929
- elif graph_kind in ["Pseudofractal SF (Dorogovtsev–Mendes) (2D)"]:
930
- level = st.slider("Generationen", 0, 4, 2)
931
- elif graph_kind in ["Diamond Fractal (2D)"]:
932
- level = st.slider("Level", 1, 4, 2)
933
- elif graph_kind in ["Square Patch (2D)"]:
934
- side = st.slider("n×n", 6, 20, 10)
935
- elif graph_kind in ["Cube Patch (3D)"]:
936
- side = st.slider("n×n×n", 3, 9, 3)
937
- elif graph_kind in ["Menger Sponge (3D)"]:
938
- level = st.slider("Level", 1, 3, 2)
939
-
940
- st.header("REAL-Ableitung (Methoden)")
941
- method = st.selectbox("Selbstwechselwirkung", [
942
- "R_eff-Deepening",
943
- "Kron-Reduktion (DtN-match)",
944
- "Energie-Renorm (Level-basiert)"
945
- ])
946
- do_calib = st.checkbox("DtN-Kalibrierung s* anwenden", value=True)
947
-
948
- st.header("Dynamik & Export")
949
- dyn_time = st.selectbox("IDEAL Zeit T (LvN)", [
950
- "T = 2π / median(λ_nonzero)",
951
- "T = π / max(λ_nonzero)",
952
- "T = 1"
953
- ])
954
- hm_mode = st.selectbox("Dichte-Heatmap zeigt …",
955
- ["real", "imag", "abs", "abslog", "phase"], index=0)
956
- do_gksl = st.checkbox("Markov-Pockets (REAL) → GKSL zeigen", value=True)
957
- gksl_steps = st.slider("GKSL steps", 50, 800, 300, step=50)
958
-
959
- st.header("Ressourcen")
960
- show_edges = st.checkbox("Kanten anzeigen", value=True)
961
- save_html = st.checkbox("Plots als HTML speichern", value=True)
962
-
963
- st.markdown("—")
964
-
965
- with st.expander("Was bedeuten IDEAL, REAL, Dirichlet-Form, Selbstwechselwirkung, GKSL?"):
966
- st.markdown(
967
- """
968
- - **IDEAL**: Ausgangsgraph mit wohldefinierter Dirichlet-Form (kombinatorischer Laplace-Operator).
969
- - **REAL**: Aus IDEAL abgeleitete effektive Geometrie (Gewichte/Renormierung), Rand bleibt fest.
970
- - **Dirichlet-Form**: \( \mathcal{E}(u)=\frac12 \sum_{(i,j)} w_{ij}(u_i-u_j)^2 \). Daraus \(L=D-A\).
971
- - **Selbstwechselwirkung**: Ableitung der Innengewichte aus Geometrie (R_eff, Kron/DtN, Energie-Renorm).
972
- - **Intrinsische Masse**: \(m:=\langle \deg\rangle = \mathrm{trace}(L)/n\). Hamiltonian \(H=L+mI\).
973
- - **LvN**: \( \dot\rho = -i[H,\rho]\) (geschlossene Dynamik auf IDEAL/REAL).
974
- - **GKSL**: Emergente Markov-Regionen (REAL-Cluster) mit Dissipation \( \dot\rho = -i[H,\rho] + \sum_k \mathcal{D}_{L_k}(\rho)\).
975
- - **Heat-Kernel**: \(K(\tau)=e^{-\tau L}\) (Diffusion). Heatmap zeigt Kopplungsintensitäten zwischen Knoten für intrinsische \(\tau\).
976
- """)
977
-
978
- # --- IDEAL aufbauen ---
979
- with st.spinner("Baue IDEAL-Graph..."):
980
- if graph_kind == "Sierpinski Gasket (2D)":
981
- coords, edges, boundary = build_sierpinski_gasket(level)
982
- elif graph_kind == "Sierpinski Tetrahedron (3D)":
983
- coords, edges, boundary = build_sierpinski_tetra(level)
984
- elif graph_kind == "Sierpinski Carpet (2D)":
985
- coords, edges, boundary = build_sierpinski_carpet(level)
986
- elif graph_kind == "Vicsek Cross (2D)":
987
- coords, edges, boundary = build_vicsek(level)
988
- elif graph_kind == "T-Fractal (2D)":
989
- coords, edges, boundary = build_t_fractal(level)
990
- elif graph_kind == "H-Tree (2D)":
991
- coords, edges, boundary = build_h_tree(level)
992
- elif graph_kind == "Koch Snowflake (2D)":
993
- coords, edges, boundary = build_koch_snowflake(level)
994
- elif graph_kind == "Apollonian Network (2D)":
995
- coords, edges, boundary = build_apollonian(level)
996
- elif graph_kind == "Pseudofractal SF (Dorogovtsev–Mendes) (2D)":
997
- coords, edges, boundary = build_pseudofractal(level)
998
- elif graph_kind == "Diamond Fractal (2D)":
999
- coords, edges, boundary = build_diamond(level)
1000
- elif graph_kind == "Square Patch (2D)":
1001
- coords, edges, boundary = build_square_patch(side)
1002
- elif graph_kind == "Cube Patch (3D)":
1003
- coords, edges, boundary = build_cube_patch(side)
1004
- else: # Menger
1005
- coords, edges, boundary = build_menger(level)
1006
-
1007
- n = len(coords); dim = coords.shape[1]
1008
- A_id, L_id = edges_to_sparse(n, edges, weights=None)
1009
-
1010
- colA, colB = st.columns(2)
1011
- with colA:
1012
- st.subheader("IDEAL – Geometrie & Boundary")
1013
- depths_id, _ = level_by_depth_from_boundary(n, edges, boundary)
1014
- fig_id = plot_graph(coords, edges, "IDEAL", dim=dim, show_edges=show_edges, node_vals=depths_id)
1015
- if dim==2:
1016
- fig_id.add_trace(go.Scatter(
1017
- x=coords[boundary,0], y=coords[boundary,1], mode="markers",
1018
- marker=dict(size=10, symbol="x", line=dict(width=2)),
1019
- name="Boundary", showlegend=True
1020
- ))
1021
- else:
1022
- fig_id.add_trace(go.Scatter3d(
1023
- x=coords[boundary,0], y=coords[boundary,1], z=coords[boundary,2],
1024
- mode="markers",
1025
- marker=dict(size=4, symbol="x", line=dict(width=2)),
1026
- name="Boundary", showlegend=True
1027
- ))
1028
- st.plotly_chart(fig_id, use_container_width=True)
1029
-
1030
- with colB:
1031
- st.subheader("IDEAL – Spektrum & DtN")
1032
- w_id = safe_small_eigs_vals(L_id, want_k=min(max(6, min(n-2, 50)), n-2))
1033
- w_id = np.real(np.sort(w_id)); w_nonzero = w_id[w_id>1e-12]
1034
- fig_w = px.scatter(x=np.arange(len(w_nonzero)), y=w_nonzero, labels=dict(x="index", y="eigenvalue"),
1035
- title="Eigenwerte (nicht-null)")
1036
- fig_w.update_layout(margin=dict(l=60,r=40,t=50,b=10), legend=dict(x=0.0, y=1.0, xanchor="left", yanchor="top"))
1037
- st.plotly_chart(fig_w, use_container_width=True)
1038
- DtN_id = dtn_map_sparse(L_id, boundary)
1039
- st.caption(f"DtN(ID): shape={DtN_id.shape}, cond≈{np.linalg.cond(DtN_id):.3e}")
1040
-
1041
-
1042
-
1043
- # --- REAL herleiten ---
1044
- with st.spinner("Leite REAL aus IDEAL ab..."):
1045
- if method == "R_eff-Deepening":
1046
- w_base = real_weights_deepening(L_id, edges, boundary, level_hint=2.0)
1047
- elif method == "Kron-Reduktion (DtN-match)":
1048
- w_base = real_weights_kron(L_id, edges, boundary)
1049
- else:
1050
- depths, e_levels = level_by_depth_from_boundary(n, edges, boundary)
1051
- w_base = {}
1052
- for t,(i,j) in enumerate(edges):
1053
- key = (i,j) if i<j else (j,i)
1054
- w_base[key] = 1.0 + e_levels[t]/max(1.0,e_levels.max())
1055
-
1056
- if do_calib:
1057
- s_star, w_real, dtn_err = calibrate_s_star_sparse(L_id, edges, w_base, boundary)
1058
- else:
1059
- w_real, s_star, dtn_err = w_base, 1.0, float("nan")
1060
-
1061
- L_real = build_laplacian(n, edges, w_real)
1062
- # Harmonische Einbettung mit fixiertem Rand (Tutte)
1063
- X_real = harmonic_embed_with_fixed_boundary(L_real, coords, boundary)
1064
- # ST: halte innere Punkte in der Tetraederhülle
1065
- if graph_kind == "Sierpinski Tetrahedron (3D)":
1066
- X_real = project_points_into_tetra(X_real, boundary, coords[boundary])
1067
-
1068
- colC, colD = st.columns(2)
1069
- with colC:
1070
- st.subheader("REAL – Geometrie (Rand fix)")
1071
- depths, _ = level_by_depth_from_boundary(n, edges, boundary)
1072
- fig_real = plot_graph(X_real, edges, f"REAL ({method}, s*={s_star:.3g}, DtN-err≈{dtn_err:.2e})",
1073
- dim=dim, show_edges=show_edges, node_vals=depths)
1074
- if dim==2:
1075
- fig_real.add_trace(go.Scatter(
1076
- x=X_real[boundary,0], y=X_real[boundary,1], mode="markers",
1077
- marker=dict(size=10, symbol="x", line=dict(width=2)), name="Boundary", showlegend=True
1078
- ))
1079
- else:
1080
- fig_real.add_trace(go.Scatter3d(
1081
- x=X_real[boundary,0], y=X_real[boundary,1], z=X_real[boundary,2],
1082
- mode="markers", marker=dict(size=4, symbol="x", line=dict(width=2)),
1083
- name="Boundary", showlegend=True
1084
- ))
1085
- st.plotly_chart(fig_real, use_container_width=True)
1086
- b_err = float(np.max(np.linalg.norm(X_real[boundary] - coords[boundary], axis=1)))
1087
- st.info(f"Boundary-Abweichung (REAL vs. IDEAL): {b_err:.2e}")
1088
-
1089
- with colD:
1090
- st.subheader("REAL – Spektrum & DtN")
1091
- w_re = safe_small_eigs_vals(L_real, want_k=min(max(6, min(n-2, 50)), n-2))
1092
- w_re = np.real(np.sort(w_re)); w_nonzero_re = w_re[w_re>1e-12]
1093
- fig_wr = px.scatter(x=np.arange(len(w_nonzero_re)), y=w_nonzero_re, labels=dict(x="index", y="eigenvalue"),
1094
- title="Eigenwerte (nicht-null)")
1095
- fig_wr.update_layout(margin=dict(l=60,r=40,t=50,b=10), legend=dict(x=0.0, y=1.0, xanchor="left", yanchor="top"))
1096
- st.plotly_chart(fig_wr, use_container_width=True)
1097
- DtN_re = dtn_map_sparse(L_real, boundary)
1098
- st.caption(f"DtN(REAL): shape={DtN_re.shape}, cond≈{np.linalg.cond(DtN_re):.3e}")
1099
-
1100
- with st.expander("Wie werden REAL-Gewichte bestimmt?"):
1101
- st.markdown(r"""
1102
- **Ziel.** Aus dem IDEAL-Graphen wird durch rein geometrische Ableitung (ohne freie, „von außen“ gesetzte Parameter) ein **REAL**-Graph konstruiert, der bei **fixem Außenrand** dieselbe oder eine eng verwandte Randantwort (Dirichlet-zu-Neumann) zeigt. Drei komplementäre Verfahren stehen zur Auswahl:
1103
-
1104
- ---
1105
-
1106
- ### 1) R\_eff-Deepening (elektrische Metrik + Tiefenverstärkung)
1107
- Wir nutzen die **effektive Widerstandsmetrik** \(R_{ij}\) des IDEAL-Laplazians \(L\).
1108
- Für zwei Knoten \(i,j\) gilt
1109
- \[
1110
- R_{ij} \;=\; (L^{+})_{ii} + (L^{+})_{jj} - 2(L^{+})_{ij},
1111
- \]
1112
- wobei \(L^{+}\) das Moore–Penrose-Pseudoinverse von \(L\) ist.
1113
- Die REAL-Kantengewichte werden innen **größer** gewählt und sind umgekehrt proportional zum Widerstand, zusätzlich skaliert nach der **Randtiefe** \(\ell_{ij}\) der Kante:
1114
- \[
1115
- w_{ij}^{\mathrm{REAL}} \;\propto\; \frac{\alpha^{\ell_{ij}}}{R_{ij}},
1116
- \qquad \ell_{ij}=\min(\operatorname{dist}(i,B),\operatorname{dist}(j,B)).
1117
- \]
1118
- **Randkanten** (beide Endpunkte auf dem Außenrand \(B\)) bleiben **normiert**: \(w_{ij}=1\).
1119
- Damit werden parallele Pfade belohnt (Rayleigh-Monotonie), und „tiefere“ Schichten tragen stärker zur Innenkopplung bei.
1120
-
1121
- ---
1122
-
1123
- ### 2) Kron-Reduktion (DtN-Match via Schur-Komplement)
1124
- Wir partitionieren den IDEAL-Laplazian nach **Rand \(B\)** und **Innerem \(I\)**:
1125
- \[
1126
- L \;=\; \begin{bmatrix} L_{BB} & L_{BI}\\[2pt] L_{IB} & L_{II}\end{bmatrix}.
1127
- \]
1128
- Eliminieren des Inneren liefert die **Dirichlet-zu-Neumann-(DtN)-Karte** auf dem Rand:
1129
- \[
1130
- \Lambda_{\text{ID}} \;=\; L_{BB} \;-\; L_{BI}\,L_{II}^{-1} L_{IB}.
1131
- \]
1132
- Wir bestimmen die REAL-Gewichte \(w_{ij}\) (mit \(w_{ij}=1\) für Randkanten), so dass die DtN-Karte des REAL-Graphen \(\Lambda_{\text{REAL}}\) **möglichst nahe** an \(\Lambda_{\text{ID}}\) liegt (z. B. Minimierung von \(\|\Lambda_{\text{REAL}}-\Lambda_{\text{ID}}\|_F\)).
1133
- Das Schur-Komplement erhält zentrale **Randantwort-Eigenschaften** und ist der diskrete Standardweg, Innere zu „kondensieren“.
1134
-
1135
- ---
1136
-
1137
- ### 3) Energie-Renormierung (schalenweise, konservativ)
1138
- Aus der Dirichlet-Form
1139
- \[
1140
- \mathcal{E}(u)=\tfrac12\!\sum\_{(i,j)}\! w_{ij}\,\big(u_i-u_j\big)^2
1141
- \]
1142
- leiten wir **schalenweise** (nach Randtiefe) Multiplikatoren ab, die die **Energiedichte** Richtung Inneres anheben, ohne den Außenrand zu verändern. Das ist numerisch robust und **sparsam**, wenn z. B. eine exakte DtN-Gleichheit nicht gefordert ist, aber eine realistische Innenkopplung (mit wachsender Tiefe) gewünscht ist.
1143
-
1144
- ---
1145
-
1146
- ### Globale Kalibrierung \(s^\*\) (optional, aber parameterfrei)
1147
- Ein **einziger** globaler Faktor \(s^\*\) wird automatisch gewählt, um die **DtN-Abweichung** zu minimieren:
1148
- \[
1149
- s^\* \;=\; \arg\min\_{s>0}\ \big\|\Lambda\_{\text{REAL}}(s)-\Lambda\_{\text{ID}}\big\|\_F.
1150
- \]
1151
- Damit gibt es **keine** frei zu setzenden Hyperparameter – Auswahl nur zwischen Methodiken; der Rest folgt aus der IDEAL-Geometrie.
1152
-
1153
- ---
1154
-
1155
- **Randbedingungen & Positivität.**
1156
- - Außenrand bleibt **fix**, Rand-Rand-Kanten: \(w=1\).
1157
- - Innengewichte \(w_{ij}>0\) ⇒ REAL-Laplazian bleibt **symmetrisch, diagonal-dominant** (stabil).
1158
- - Die Verfahren sind **ressourcenschonend** (Schur-Komplement/DtN nur auf Randgröße, Widerstandsmetriken wiederverwendbar).
1159
-
1160
- **Praktische Hinweise.**
1161
- - R\_eff-Deepening betont Mehrpfad-Strukturen (»elektrische Nähe«).
1162
- - Kron/DtN priorisiert die **exakte Randantwort** (»Boundary Physics«).
1163
- - Energie-Renorm ist robust, wenn kleine Modelle/hohe Level gefragt sind.
1164
- """)
1165
-
1166
-
1167
- run = st.button("▶️ Start")
1168
-
1169
- if run:
1170
- run_id = datetime.utcnow().strftime("%Y%m%dT%H%M%S") + "_" + hashlib.md5(str(time.time()).encode()).hexdigest()[:6]
1171
- outdir = mk_out(run_id)
1172
-
1173
- # Intrinsische Massen & Hamiltonians
1174
- m_id = intrinsic_mass_from_L(L_id)
1175
- m_re = intrinsic_mass_from_L(L_real)
1176
- H_id_s = (L_id + m_id * sps.eye(n, format='csr')).toarray()
1177
- H_re_s = (L_real + m_re * sps.eye(n, format='csr')).toarray()
1178
-
1179
- with st.expander("Intrinsische Massen & Hamiltonians (ohne freie Parameter)"):
1180
- st.markdown(
1181
- f"""
1182
- - **m_ID** = ⟨deg⟩_IDEAL = {m_id:.6g}
1183
- - **m_REAL** = ⟨deg⟩_REAL = {m_re:.6g}
1184
- - **Hamiltonian**: \(H=L+m\,I\) (IDEAL und REAL getrennt konstruiert).
1185
- """)
1186
-
1187
- meta = dict(graph_kind=graph_kind, level=int(locals().get("level", -1)),
1188
- side=int(locals().get("side", -1)), method=method, n=n, dim=dim,
1189
- s_star=float(s_star), dtn_err=float(dtn_err),
1190
- m_id=m_id, m_re=m_re)
1191
-
1192
- np.savez_compressed(os.path.join(outdir, "graph_ideal.npz"),
1193
- coords=coords, edges=np.array(edges, dtype=int), boundary=boundary,
1194
- L=L_id.toarray() if sps.issparse(L_id) else np.array(L_id),
1195
- m=m_id, H=H_id_s)
1196
- np.savez_compressed(os.path.join(outdir, "graph_real.npz"),
1197
- coords=X_real, edges=np.array(edges, dtype=int), boundary=boundary,
1198
- L=L_real.toarray() if sps.issparse(L_real) else np.array(L_real),
1199
- weights=np.array([w_real[(i,j) if i<j else (j,i)] for (i,j) in edges]),
1200
- m=m_re, H=H_re_s)
1201
-
1202
- # Zeitskala für LvN
1203
- T = (2.0*math.pi / (np.median(w_nonzero) if len(w_nonzero)>0 else 1.0)
1204
- if dyn_time=="T = 2π / median(λ_nonzero)"
1205
- else (math.pi / (w_nonzero.max() if len(w_nonzero)>0 else 1.0)
1206
- if dyn_time=="T = π / max(λ_nonzero)" else 1.0))
1207
-
1208
- rho0 = pick_initial_state(n, "delta@center")
1209
- rho_id = lv_n_density(H_id_s, rho0, T)
1210
- rho_re = lv_n_density(H_re_s, rho0, T)
1211
-
1212
- st.subheader("Dichtematrizen (IDEAL/REAL, Heatmaps)")
1213
- with st.expander("Was sagen die Farben in ρ-Heatmaps aus?"):
1214
- st.markdown(
1215
- """
1216
- - **real/imag**: Divergente Skala um 0 – Rot/Orange = positiv, Blau/Violett = negativ, Weiß ≈ 0.
1217
- - **abs**: Stärke von Populationen/Kohärenzen \(|ρ_{ij}|\).
1218
- - **abslog**: \(\log_{10}(|ρ|+10^{-12})\) macht winzige Werte sichtbar.
1219
- - **phase**: Winkel \(\arg ρ_{ij}\in[-\pi,\pi]\).
1220
- """)
1221
-
1222
- colE, colF = st.columns(2)
1223
- with colE:
1224
- fig_hi = heatmap_density(rho_id, f"IDEAL ρ(T), T={T:.3g}", mode=hm_mode)
1225
- st.plotly_chart(fig_hi, use_container_width=True)
1226
- with colF:
1227
- fig_hr = heatmap_density(rho_re, f"REAL ρ(T), T={T:.3g}", mode=hm_mode)
1228
- st.plotly_chart(fig_hr, use_container_width=True)
1229
-
1230
- # Heat-Kernel (intrinsische τ aus Spektrum)
1231
- tau_id = 1.0 / (np.median(w_nonzero) if len(w_nonzero)>0 else 1.0)
1232
- tau_re = 1.0 / (np.median(w_nonzero_re) if len(w_nonzero_re)>0 else 1.0)
1233
- K_id, idx_id = heat_kernel_matrix_for_plot(L_id, tau_id)
1234
- K_re, idx_re = heat_kernel_matrix_for_plot(L_real, tau_re)
1235
-
1236
- st.subheader("Heat-Kernel-Heatmaps (IDEAL/REAL)")
1237
- with st.expander("Heat-Kernel & Farbe (IDEAL/REAL): Was sieht man?"):
1238
- st.markdown(
1239
- """
1240
- - **Heat-Kernel** \(K(\tau)=e^{-\tau L}\) misst, wie stark Wärme/Amplitude in Zeit \(\tau\) vom Knoten \(i\) nach \(j\) diffundiert.
1241
- - Wir wählen \(\tau = 1/\mathrm{median}(\{\lambda_k>0\})\) – eine intrinsische Skala der Geometrie (keine freien Parameter).
1242
- - In den Heatmaps zeigt **hell**/**hoch** starke Kopplung, **dunkel** schwache (Modus *abs*), bei *real/imag* divergente Skalen ± mit 0 als Weißpunkt.
1243
- - Bei sehr großen Netzen plotten wir automatisch einen **repräsentativen Subblock** (ressourcenschonend, Artefakte werden dokumentiert).
1244
- """)
1245
- colHK1, colHK2 = st.columns(2)
1246
- with colHK1:
1247
- st.caption(f"IDEAL: K(τ_ID)=exp(-τ_ID·L), τ_ID≈{tau_id:.3g} — gezeigt: Größe {K_id.shape[0]}×{K_id.shape[1]}")
1248
- st.plotly_chart(heatmap_density(K_id, "IDEAL Heat-Kernel |K|", mode="abs"), use_container_width=True)
1249
- with colHK2:
1250
- st.caption(f"REAL: K(τ_RE)=exp(-τ_RE·L), τ_RE≈{tau_re:.3g} — gezeigt: Größe {K_re.shape[0]}×{K_re.shape[1]}")
1251
- st.plotly_chart(heatmap_density(K_re, "REAL Heat-Kernel |K|", mode="abs"), use_container_width=True)
1252
-
1253
- if do_gksl:
1254
- st.subheader("Emergente GKSL in Markov-Clustern (REAL)")
1255
- with st.expander("Emergente GKSL in Markov-Clustern (REAL) – Erklärung"):
1256
- st.markdown(r"""
1257
- **Idee.** In **REAL** entstehen lokal **Markovsche Taschen (»Pockets«)**, wenn die Kopplung der Knoten untereinander
1258
- deutlich schneller ist als ihre Kopplung nach außen. In dieser **Zeitskalen-Trennung** lässt sich die geschlossene
1259
- LvN-Dynamik auf dem Pocket effektiv als **GKSL-Mastergleichung** beschreiben (Markovianität im
1260
- Schwachkopplungs-/Coarse-Graining-Sinn).
1261
-
1262
- **GKSL-Form.** Für die Dichtematrix \(\rho\) des Pocket-Subsystems gilt
1263
- \[
1264
- \dot\rho \;=\; -\,i[H,\rho]\;+\;\sum_k\!\Big(L_k\,\rho\,L_k^\dagger-\tfrac12\{L_k^\dagger L_k,\rho\}\Big),
1265
- \]
1266
- wobei \(H\) der (intrinsische) Hamiltonian des Pockets ist und \(\{L_k\}\) die **Lindblad-Operatoren** sind.
1267
- Diese Form garantiert **komplette Positivität** und **Spurerhaltung** der Dynamik (CPTP-Semigruppe).
1268
-
1269
- **Wie werden die Größen in dieser App gewählt?**
1270
- - *Pocketwahl:* Knoten mit kleinerem Grad/eingeschränkter Anbindung (langsamer »Leakage«) bilden eine Pocket-Region.
1271
- - *Hamiltonian:* \(H=L+m\,\mathbb{I}\) mit intrinsischer Masse \(m=\langle\deg\rangle\) (keine freien Parameter).
1272
- - *Lindblad-Operatoren:* Lokal-diagonale \(L_i=\sqrt{\gamma_i}\,|i\rangle\!\langle i|\) mit \(\gamma_i\propto\deg(i)\) (normiert).
1273
- Das modelliert **lokale Dephasierung/Relaxation** im Pocket – Kohärenzen dämpfen, Populationen relaxieren.
1274
- - *Integrationszeit \(T\):* an Spektrum des Laplace-Operators skaliert (intrinsische Zeitskala).
1275
- - *Numerik:* stabilisierte Runge–Kutta-Integration; nach jedem Schritt Hermitisierung und Normierung (\(\mathrm{tr}\,\rho=1\)).
1276
-
1277
- **Was zeigt die Heatmap »ρ\_GKSL(T)«?**
1278
- Die Heatmap visualisiert die Matrixelemente \(\rho_{ij}(T)\) des Pocket-Zustands:
1279
- - **Modus „real/imag“:** divergente Farbskala um 0 (Weiß ≈ 0, warme Farben \(>\!0\), kalte \(<\!0\)).
1280
- - **Modus „abs“:** \(|\rho_{ij}|\) = Stärke von Populationen/Kohärenzen (hell = groß, dunkel = klein).
1281
- - **Modus „abslog“:** \(\log_{10}(|\rho_{ij}|+10^{-12})\) hebt feine Strukturen hervor.
1282
- - **Modus „phase“:** \(\arg \rho_{ij}\in[-\pi,\pi]\) – Phase der Kohärenzen.
1283
-
1284
- **Interpretationstipps.**
1285
- - **Diagonaleinträge** \(\rho_{ii}\): Populationen im Pocket (Wahrscheinlichkeitsdichte an Knoten \(i\)).
1286
- - **Off-Diagonale** \(|\rho_{ij}|\): Quanteneffekte/Kohärenzen zwischen Knoten \(i,j\).
1287
- Starke Lindblad-Raten \(\gamma_i\) → **Dephasierung** → Off-Diagonale dämpfen, Heatmap wird diagonaldominant.
1288
- - **Vergleich IDEAL vs. REAL:**
1289
- REAL-Pockets zeigen oftmals **schnellere lokale Mischung** (größere Heat-Kernel-Konzentration) und
1290
- **stärkere Dämpfung** der Kohärenzen als IDEAL bei gleicher äußerer Randgeometrie.
1291
-
1292
- **Wann ist die GKSL-Approximation sinnvoll?**
1293
- - (i) **Schwachkopplung** des Pockets an seine Umgebung,
1294
- - (ii) **Zeitliche Grobkornung** \( \Delta t \) größer als die Bad-Korrelationszeit,
1295
- - (iii) **Nichtentartete**/aufgelöste internen Frequenzen (Rotating-Wave/Resonanz-Selektion).
1296
- Dann ist die Markov-Beschreibung in GKSL-Form **physikalisch konsistent** (CPTP) und numerisch stabil.
1297
 
1298
- **Was bedeuten die eingeblendeten Zahlen?**
1299
- - **\|Pocket\|**: Anzahl Knoten im betrachteten Markov-Cluster.
1300
- - **T**: Integrierte Zeit (app-weit definierte intrinsische Skala).
1301
- - **steps**: RK-Schritte für \(\rho(t)\).
1302
- - **#Lindblad**: Anzahl verwendeter \(L_k\) im Pocket (hier ein \(L_i\) pro Knoten mit Rate \(\gamma_i\)).
1303
 
1304
- **Hinweis zur Validierung.**
1305
- Im GKSL-Regime kontrahieren typische Abstandsmaße zwischen Zuständen monoton (Dynamik ist CPTP).
1306
- Heuristisch sichtbar: (a) keine negativen Populationsartefakte, (b) Off-Diagonale klingen stetig ab, (c) \(\mathrm{tr}\,\rho=1\).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1307
  """)
1308
-
1309
- deg = np.asarray(L_real.diagonal())
1310
- pocket = np.argsort(deg)[:min(40, n)]
1311
- Hp = H_re_s[np.ix_(pocket,pocket)]
1312
- rho0p = rho0[np.ix_(pocket,pocket)]
1313
- Lops = derive_gksl_ops_from_structure(L_real)
1314
- Lops_p = [L[np.ix_(pocket,pocket)] for L in Lops[:min(len(Lops), 6)]]
1315
- rho_gksl = simulate_gksl(Hp, rho0p, Lops_p, T, steps=gksl_steps)
1316
- fig_hp = heatmap_density(rho_gksl, f"REAL Pocket ρ_GKSL(T), |Pocket|={len(pocket)}", mode=hm_mode)
1317
- st.plotly_chart(fig_hp, use_container_width=True)
1318
-
1319
- # Export
1320
- if save_html:
1321
- def save_fig(fig, name):
1322
- path = os.path.join(outdir, name)
1323
- fig.write_html(path, include_plotlyjs="cdn")
1324
- return path
1325
- _ = [save_fig(f, n) for f,n in [
1326
- (fig_id, "plot_ideal_geom.html"),
1327
- (fig_real, "plot_real_geom.html"),
1328
- (fig_w, "plot_ideal_spectrum.html"),
1329
- (fig_wr, "plot_real_spectrum.html"),
1330
- (fig_hi, "heatmap_rho_ideal.html"),
1331
- (fig_hr, "heatmap_rho_real.html"),
1332
- ]]
1333
- # Heat-Kernel separat
1334
- save_fig(heatmap_density(K_id, "IDEAL Heat-Kernel |K|", mode="abs"), "heatkernel_ideal.html")
1335
- save_fig(heatmap_density(K_re, "REAL Heat-Kernel |K|", mode="abs"), "heatkernel_real.html")
1336
-
1337
- save_json(os.path.join(outdir, "meta.json"), meta)
1338
- rows = [[i,j,float(w_real[(i,j) if i<j else (j,i)])] for (i,j) in edges]
1339
- save_csv(os.path.join(outdir, "edge_weights_real.csv"), ["i","j","w"], rows)
1340
-
1341
- zip_path = zip_dir(outdir, os.path.join("out", f"{run_id}.zip"))
1342
- st.success(f"Fertig. Artefakte gespeichert: {outdir}")
1343
- st.download_button("📦 ZIP herunterladen", data=open(zip_path,"rb").read(),
1344
- file_name=f"{run_id}.zip", mime="application/zip")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
+ import json
3
+ from pathlib import Path
4
+ from typing import Dict, List, Tuple
5
+
6
  import numpy as np
7
+ import pandas as pd
 
 
 
 
8
  import plotly.graph_objects as go
 
9
  import streamlit as st
10
+ import networkx as nx
11
 
12
+ from ngf import NGFGenerator, EnergyDistribution
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ st.set_page_config(page_title="NGF Generator (Bianconi–Rahmede)", layout="wide")
 
15
 
16
+ # ---------- Sidebar: Controls ----------
17
+ st.sidebar.title("NGF Controls")
 
 
 
 
 
 
 
 
18
 
19
+ with st.sidebar:
20
+ st.markdown("**Network Geometry with Flavor (NGF)**")
21
+ d = st.number_input("Dimension d", min_value=1, max_value=3, value=2, step=1, help="Simplicial complex dimension.")
22
+ s = st.selectbox("Flavor s", options=[-1, 0, 1], index=1, help="s=-1 (CQNM/manifold), s=0, s=1 (explicit preferential attachment).")
23
+ beta = st.number_input("Inverse temperature β", min_value=0.0, value=0.1, step=0.1, help="β≥0 in the attachment weight exp(-β ε_α)(1+s n_α).")
24
+ total_nodes = st.slider("Total nodes N", min_value=50, max_value=3000, value=800, step=50)
25
+ seed = st.number_input("Random seed", min_value=0, value=42, step=1)
26
+ st.divider()
27
+ st.markdown("**Energy distribution g(ε)**")
28
+ dist_kind = st.selectbox("Kind", ["uniform_int", "poisson", "custom_list"], index=0)
29
+ if dist_kind == "uniform_int":
30
+ e_low = st.number_input("ε low (inclusive)", value=0, step=1)
31
+ e_high = st.number_input("ε high (exclusive)", value=10, step=1)
32
+ dist_params = {"low": int(e_low), "high": int(e_high)}
33
+ elif dist_kind == "poisson":
34
+ lam = st.number_input("λ (Poisson mean)", value=4.0, step=0.5)
35
+ dist_params = {"lam": float(lam)}
36
+ else:
37
+ vals = st.text_input("Custom integer values (comma-separated)", "0,1,2,3,5,8,13")
38
  try:
39
+ arr = [int(x.strip()) for x in vals.split(",") if x.strip()!=""]
 
 
 
40
  except Exception:
41
+ arr = [0,1,2,3]
42
+ dist_params = {"values": arr}
43
+
44
+ st.divider()
45
+ st.markdown("**Visualization options**")
46
+ show_triangles = st.checkbox("Show 2-faces (triangles) as mesh (if d≥2)", value=True)
47
+ show_boundary = st.checkbox("Highlight boundary (d-1)-faces", value=False)
48
+ size_by_degree = st.checkbox("Scale node size by 1-skeleton degree", value=True)
49
+
50
+ st.divider()
51
+ do_generate = st.button("Generate NGF", type="primary")
52
+
53
+
54
+ @st.cache_data(show_spinner=False)
55
+ def build_ngf(d, s, beta, total_nodes, dist_kind, dist_params, seed):
56
+ gen = NGFGenerator(
57
+ d=int(d),
58
+ s=int(s),
59
+ beta=float(beta),
60
+ energy_dist=EnergyDistribution(kind=dist_kind, params=dist_params, seed=seed),
61
+ seed=int(seed),
62
+ )
63
+ gen.run(total_nodes=int(total_nodes))
64
+ return gen
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
 
 
 
 
 
 
 
 
 
 
66
 
67
+ def graph_layout_3d(G: nx.Graph, seed: int = 42) -> Dict[int, Tuple[float, float, float]]:
68
+ pos = nx.spring_layout(G, dim=3, seed=seed, k=None, iterations=200)
69
+ return {int(k): tuple(map(float, v)) for k, v in pos.items()}
 
 
 
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
+ def plot_ngf_3d(gen: NGFGenerator, show_triangles: bool = True, show_boundary: bool = False, size_by_degree: bool = True):
73
+ G = gen.to_networkx()
74
+ pos = graph_layout_3d(G, seed=123)
 
 
 
 
 
 
 
 
 
 
 
75
 
76
+ # Node attributes
77
+ energies = np.array([gen.node_energy[i] for i in gen.nodes], dtype=float)
78
+ deg1 = gen.node_degrees_1skeleton()
79
+ degrees = np.array([deg1[i] for i in gen.nodes], dtype=float)
80
+ # Normalize sizes
81
+ if size_by_degree:
82
+ node_sizes = 5 + 4 * (degrees - degrees.min()) / (degrees.ptp() + 1e-9)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  else:
84
+ node_sizes = np.full_like(energies, 6.0)
85
+
86
+ # Node scatter
87
+ xs = [pos[i][0] for i in gen.nodes]
88
+ ys = [pos[i][1] for i in gen.nodes]
89
+ zs = [pos[i][2] for i in gen.nodes]
90
+
91
+ node_trace = go.Scatter3d(
92
+ x=xs, y=ys, z=zs,
93
+ mode="markers",
94
+ marker=dict(size=node_sizes, color=energies, showscale=True, colorbar=dict(title="ε"), opacity=0.9),
95
+ text=[f"node {i}<br>ε={gen.node_energy[i]}<br>deg={deg1[i]}" for i in gen.nodes],
96
+ hoverinfo="text",
97
+ name="nodes",
98
+ )
 
 
 
 
 
 
99
 
100
+ # Edge segments
101
+ ex, ey, ez = [], [], []
102
+ for u, v in gen.edges:
103
+ x0, y0, z0 = pos[u]
104
+ x1, y1, z1 = pos[v]
105
+ ex += [x0, x1, None]
106
+ ey += [y0, y1, None]
107
+ ez += [z0, z1, None]
108
+ edge_trace = go.Scatter3d(
109
+ x=ex, y=ey, z=ez,
110
+ mode="lines",
111
+ line=dict(width=1),
112
+ hoverinfo="none",
113
+ name="edges",
114
+ opacity=0.4,
115
+ )
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
+ data = [edge_trace, node_trace]
118
+
119
+ # Triangles (2-faces) via Mesh3d if requested and d≥2
120
+ if show_triangles and gen.d >= 2:
121
+ # Build triangle list
122
+ tris = [tuple(sorted(list(face))) for face in gen.face_counts[2].keys()] if 2 in gen.face_counts else []
123
+ # Map node id -> mesh index
124
+ idx_map = {nid: idx for idx, nid in enumerate(gen.nodes)}
125
+ # triangles may refer to nodes present (they should); filter if not
126
+ I, J, K = [], [], []
127
+ for (a, b, c) in tris:
128
+ if a in idx_map and b in idx_map and c in idx_map:
129
+ I.append(idx_map[a]); J.append(idx_map[b]); K.append(idx_map[c])
130
+ if I:
131
+ mesh = go.Mesh3d(
132
+ x=xs, y=ys, z=zs, i=I, j=J, k=K,
133
+ opacity=0.15, name="triangles",
134
+ hoverinfo="skip"
135
+ )
136
+ data.insert(0, mesh)
137
+
138
+ # Optionally highlight boundary (d-1)-faces as faint surfaces (approximate by drawing their edges thicker)
139
+ if show_boundary:
140
+ if gen.d >= 1:
141
+ bx, by, bz = [], [], []
142
+ boundary = gen.get_boundary_faces()
143
+ for face in boundary:
144
+ nodes = list(face)
145
+ # draw all pair edges of the (d-1)-face
146
+ for i in range(len(nodes)):
147
+ for j in range(i + 1, len(nodes)):
148
+ u, v = nodes[i], nodes[j]
149
+ x0, y0, z0 = pos[u]
150
+ x1, y1, z1 = pos[v]
151
+ bx += [x0, x1, None]
152
+ by += [y0, y1, None]
153
+ bz += [z0, z1, None]
154
+ if bx:
155
+ boundary_trace = go.Scatter3d(
156
+ x=bx, y=by, z=bz, mode="lines",
157
+ line=dict(width=4),
158
+ opacity=0.3, name="boundary (d-1)-faces", hoverinfo="skip"
159
+ )
160
+ data.append(boundary_trace)
161
+
162
+ fig = go.Figure(data=data)
163
  fig.update_layout(
164
+ scene=dict(xaxis=dict(visible=False), yaxis=dict(visible=False), zaxis=dict(visible=False)),
165
+ margin=dict(l=0, r=0, t=30, b=0),
166
+ legend=dict(orientation="h"),
167
+ height=700,
168
+ title=f"NGF d={gen.d}, s={gen.s}, β={gen.beta}, N={gen.N}, V={len(gen.simplexes_d)}"
169
  )
 
 
 
 
170
  return fig
171
 
 
 
 
 
 
172
 
173
+ def plot_histogram(hist: Dict[int, int], title: str, log_x: bool = True, log_y: bool = True):
174
+ xs = np.array(list(hist.keys()), dtype=float)
175
+ ys = np.array(list(hist.values()), dtype=float)
176
+ fig = go.Figure()
177
+ fig.add_bar(x=xs, y=ys)
178
+ fig.update_layout(title=title, xaxis_title="k", yaxis_title="count", height=360)
179
+ if log_x:
180
+ fig.update_xaxes(type="log")
181
+ if log_y:
182
+ fig.update_yaxes(type="log")
183
+ return fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
 
 
 
 
 
185
 
186
+ def plot_growth(gen: NGFGenerator):
187
+ t = np.arange(len(gen.area_history))
188
+ figA = go.Figure()
189
+ figA.add_scatter(x=t, y=np.array(gen.area_history), mode="lines")
190
+ figA.update_layout(title="Area A(t) (# boundary (d-1)-faces) vs steps", xaxis_title="t", yaxis_title="A", height=320)
191
+ figV = go.Figure()
192
+ figV.add_scatter(x=t, y=np.array(gen.volume_history), mode="lines")
193
+ figV.update_layout(title="Volume V(t) (# d-simplices) vs steps", xaxis_title="t", yaxis_title="V", height=320)
194
+ return figA, figV
195
+
196
+
197
+ st.title("Network Geometry with Flavor — NGF Generator & 3D Viewer")
198
+ st.caption("Implements the dynamics from Bianconi & Rahmede (2016). Visualizes the 1‑skeleton and (optionally) 2‑faces.")
199
+
200
+ if do_generate:
201
+ with st.spinner("Generating NGF..."):
202
+ gen = build_ngf(d, s, beta, total_nodes, dist_kind, dist_params, seed)
203
+
204
+ # Tabs
205
+ t1, t2, t3, t4 = st.tabs(["3D View", "Distributions", "Growth", "Export"])
206
+
207
+ with t1:
208
+ fig = plot_ngf_3d(gen, show_triangles=show_triangles, show_boundary=show_boundary, size_by_degree=size_by_degree)
209
+ st.plotly_chart(fig, use_container_width=True)
210
+
211
+ col1, col2, col3, col4 = st.columns(4)
212
+ with col1:
213
+ st.metric("N (nodes)", f"{gen.N}")
214
+ with col2:
215
+ st.metric("V (d-simplices)", f"{len(gen.simplexes_d)}")
216
+ with col3:
217
+ st.metric("Area A (boundary faces)", f"{sum(1 for f,n in gen.face_n.items() if n==0)}")
218
+ with col4:
219
+ st.metric("Edges (1-skeleton)", f"{len(gen.edges)}")
220
+
221
+ with t2:
222
+ # Node degree distribution (1-skeleton)
223
+ deg1 = gen.node_degrees_1skeleton()
224
+ hist_deg = {}
225
+ for k in deg1.values():
226
+ hist_deg[k] = hist_deg.get(k, 0) + 1
227
+ st.plotly_chart(plot_histogram(hist_deg, "1-skeleton degree distribution"), use_container_width=True)
228
+
229
+ # Generalized degree of (d-1)-faces
230
+ if gen.d >= 1:
231
+ hist_d1 = gen.generalized_degree_distribution(gen.d - 1)
232
+ st.plotly_chart(plot_histogram(hist_d1, f"Generalized degrees k₍{gen.d},{gen.d-1}₎ of (d-1)-faces"), use_container_width=True)
233
+
234
+ # Generalized degree of nodes (k_{d,0})
235
+ hist_nodes = gen.generalized_degree_distribution(0)
236
+ st.plotly_chart(plot_histogram(hist_nodes, f"Generalized degrees k₍{gen.d},0₎ of nodes"), use_container_width=True)
237
+
238
+ if gen.d >= 2:
239
+ hist_links = gen.generalized_degree_distribution(1)
240
+ st.plotly_chart(plot_histogram(hist_links, f"Generalized degrees k₍{gen.d},1₎ of links"), use_container_width=True)
241
+
242
+ with t3:
243
+ figA, figV = plot_growth(gen)
244
+ st.plotly_chart(figA, use_container_width=True)
245
+ st.plotly_chart(figV, use_container_width=True)
246
+
247
+ with t4:
248
+ data = gen.to_json()
249
+ st.json({"dimension": data["dimension"], "flavor": data["flavor"], "beta": data["beta"], "N": data["N"], "V": len(gen.simplexes_d)})
250
+ j = json.dumps(data).encode("utf-8")
251
+ st.download_button("Download NGF as JSON", j, file_name=f"ngf_d{gen.d}_s{gen.s}_N{gen.N}.json", mime="application/json")
252
+
253
+ else:
254
+ st.info("Wähle Parameter in der Seitenleiste und klicke **Generate NGF**.")
255
+ st.markdown("""
256
+ - **d**: Dimension der Simplizes (1: Kanten, 2: Dreiecke, 3: Tetraeder).
257
+ - **s**: Flavor: -1 (Manifold/CQNM), 0, 1 (bevorzugt hochgradige (d-1)-Flächen).
258
+ - **β**: Steuert den Einfluss der Energie-gewichteteten Auswahl der (d-1)-Flächen.
259
+ - **N**: Anzahl der Knoten (neuer Knoten pro Schritt).
260
  """)
261
+ st.caption("Hinweis: Triangles werden nur für d≥2 gerendert. Große N können die 3D-Layout-Berechnung verlangsamen.")