antaris commited on
Commit
a9514d1
·
verified ·
1 Parent(s): dfecac1

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +45 -34
src/streamlit_app.py CHANGED
@@ -19,9 +19,9 @@ st.sidebar.title("NGF Controls")
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(ε)**")
@@ -45,7 +45,7 @@ with st.sidebar:
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")
@@ -64,10 +64,9 @@ def build_ngf(d, s, beta, total_nodes, dist_kind, dist_params, seed):
64
  return gen
65
 
66
 
67
-
68
  def graph_layout_3d(G: nx.Graph, seed: int = 42) -> Dict[int, Tuple[float, float, float]]:
69
  """
70
- Try spring_layout in 3D (preferred; uses SciPy). If unavailable, fall back to SciPy-free random_layout.
71
  """
72
  try:
73
  import scipy # probe availability
@@ -81,17 +80,22 @@ def plot_ngf_3d(gen: NGFGenerator, show_triangles: bool = True, show_boundary: b
81
  G = gen.to_networkx()
82
  pos = graph_layout_3d(G, seed=123)
83
 
84
- # Node attributes
85
  energies = np.array([gen.node_energy[i] for i in gen.nodes], dtype=float)
86
  deg1 = gen.node_degrees_1skeleton()
87
  degrees = np.array([deg1[i] for i in gen.nodes], dtype=float)
88
- # Normalize sizes
 
89
  if size_by_degree:
90
- node_sizes = 5 + 4 * (degrees - degrees.min()) / (np.ptp(degrees) + 1e-9)
 
 
 
 
 
 
91
  else:
92
- node_sizes = np.full_like(energies, 6.0)
93
 
94
- # Node scatter
95
  xs = [pos[i][0] for i in gen.nodes]
96
  ys = [pos[i][1] for i in gen.nodes]
97
  zs = [pos[i][2] for i in gen.nodes]
@@ -99,13 +103,29 @@ def plot_ngf_3d(gen: NGFGenerator, show_triangles: bool = True, show_boundary: b
99
  node_trace = go.Scatter3d(
100
  x=xs, y=ys, z=zs,
101
  mode="markers",
102
- marker=dict(size=node_sizes, color=energies, showscale=True, colorbar=dict(title="ε"), opacity=0.9),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  text=[f"node {i}<br>ε={gen.node_energy[i]}<br>deg={deg1[i]}" for i in gen.nodes],
104
  hoverinfo="text",
105
  name="nodes",
106
  )
107
 
108
- # Edge segments
109
  ex, ey, ez = [], [], []
110
  for u, v in gen.edges:
111
  x0, y0, z0 = pos[u]
@@ -116,21 +136,17 @@ def plot_ngf_3d(gen: NGFGenerator, show_triangles: bool = True, show_boundary: b
116
  edge_trace = go.Scatter3d(
117
  x=ex, y=ey, z=ez,
118
  mode="lines",
119
- line=dict(width=1),
120
  hoverinfo="none",
121
  name="edges",
122
- opacity=0.4,
123
  )
124
 
125
  data = [edge_trace, node_trace]
126
 
127
- # Triangles (2-faces) via Mesh3d if requested and d≥2
128
  if show_triangles and gen.d >= 2:
129
- # Build triangle list
130
  tris = [tuple(sorted(list(face))) for face in gen.face_counts[2].keys()] if 2 in gen.face_counts else []
131
- # Map node id -> mesh index
132
  idx_map = {nid: idx for idx, nid in enumerate(gen.nodes)}
133
- # triangles may refer to nodes present (they should); filter if not
134
  I, J, K = [], [], []
135
  for (a, b, c) in tris:
136
  if a in idx_map and b in idx_map and c in idx_map:
@@ -138,19 +154,17 @@ def plot_ngf_3d(gen: NGFGenerator, show_triangles: bool = True, show_boundary: b
138
  if I:
139
  mesh = go.Mesh3d(
140
  x=xs, y=ys, z=zs, i=I, j=J, k=K,
141
- opacity=0.15, name="triangles",
142
  hoverinfo="skip"
143
  )
144
  data.insert(0, mesh)
145
 
146
- # Optionally highlight boundary (d-1)-faces as faint surfaces (approximate by drawing their edges thicker)
147
  if show_boundary:
148
  if gen.d >= 1:
149
  bx, by, bz = [], [], []
150
  boundary = gen.get_boundary_faces()
151
  for face in boundary:
152
  nodes = list(face)
153
- # draw all pair edges of the (d-1)-face
154
  for i in range(len(nodes)):
155
  for j in range(i + 1, len(nodes)):
156
  u, v = nodes[i], nodes[j]
@@ -162,7 +176,7 @@ def plot_ngf_3d(gen: NGFGenerator, show_triangles: bool = True, show_boundary: b
162
  if bx:
163
  boundary_trace = go.Scatter3d(
164
  x=bx, y=by, z=bz, mode="lines",
165
- line=dict(width=4),
166
  opacity=0.3, name="boundary (d-1)-faces", hoverinfo="skip"
167
  )
168
  data.append(boundary_trace)
@@ -173,7 +187,7 @@ def plot_ngf_3d(gen: NGFGenerator, show_triangles: bool = True, show_boundary: b
173
  margin=dict(l=0, r=0, t=30, b=0),
174
  legend=dict(orientation="h"),
175
  height=700,
176
- title=f"NGF d={gen.d}, s={gen.s}, β={gen.beta}, N={gen.N}, V={len(gen.simplexes_d)}"
177
  )
178
  return fig
179
 
@@ -203,13 +217,12 @@ def plot_growth(gen: NGFGenerator):
203
 
204
 
205
  st.title("Network Geometry with Flavor — NGF Generator & 3D Viewer")
206
- st.caption("Implements the dynamics from Bianconi & Rahmede (2016). Visualizes the 1‑skeleton and (optionally) 2‑faces.")
207
 
208
  if do_generate:
209
  with st.spinner("Generating NGF..."):
210
  gen = build_ngf(d, s, beta, total_nodes, dist_kind, dist_params, seed)
211
 
212
- # Tabs
213
  t1, t2, t3, t4 = st.tabs(["3D View", "Distributions", "Growth", "Export"])
214
 
215
  with t1:
@@ -227,19 +240,16 @@ if do_generate:
227
  st.metric("Edges (1-skeleton)", f"{len(gen.edges)}")
228
 
229
  with t2:
230
- # Node degree distribution (1-skeleton)
231
  deg1 = gen.node_degrees_1skeleton()
232
  hist_deg = {}
233
  for k in deg1.values():
234
  hist_deg[k] = hist_deg.get(k, 0) + 1
235
  st.plotly_chart(plot_histogram(hist_deg, "1-skeleton degree distribution"), use_container_width=True)
236
 
237
- # Generalized degree of (d-1)-faces
238
  if gen.d >= 1:
239
  hist_d1 = gen.generalized_degree_distribution(gen.d - 1)
240
  st.plotly_chart(plot_histogram(hist_d1, f"Generalized degrees k₍{gen.d},{gen.d-1}₎ of (d-1)-faces"), use_container_width=True)
241
 
242
- # Generalized degree of nodes (k_{d,0})
243
  hist_nodes = gen.generalized_degree_distribution(0)
244
  st.plotly_chart(plot_histogram(hist_nodes, f"Generalized degrees k₍{gen.d},0₎ of nodes"), use_container_width=True)
245
 
@@ -261,9 +271,10 @@ if do_generate:
261
  else:
262
  st.info("Wähle Parameter in der Seitenleiste und klicke **Generate NGF**.")
263
  st.markdown("""
264
- - **d**: Dimension der Simplizes (1: Kanten, 2: Dreiecke, 3: Tetraeder).
265
- - **s**: Flavor: -1 (Manifold/CQNM), 0, 1 (bevorzugt hochgradige (d-1)-Flächen).
266
- - **β**: Steuert den Einfluss der Energie-gewichteteten Auswahl der (d-1)-Flächen.
267
- - **N**: Anzahl der Knoten (neuer Knoten pro Schritt).
 
268
  """)
269
- st.caption("Hinweis: Triangles werden nur für d≥2 gerendert. Große N können die 3D-Layout-Berechnung verlangsamen.")
 
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 (preferential).")
23
+ beta = st.number_input("Inverse temperature β", min_value=0.0, value=0.1, step=0.1, help="β≥0 in exp(-β ε_α)(1+s n_α).")
24
+ total_nodes = st.slider("Total nodes N", min_value=50, max_value=3000, value=1000, 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(ε)**")
 
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 (Fig. 2 style)", value=True)
49
 
50
  st.divider()
51
  do_generate = st.button("Generate NGF", type="primary")
 
64
  return gen
65
 
66
 
 
67
  def graph_layout_3d(G: nx.Graph, seed: int = 42) -> Dict[int, Tuple[float, float, float]]:
68
  """
69
+ Preferred: spring_layout in 3D (requires SciPy). Fallback: random_layout (SciPy-free).
70
  """
71
  try:
72
  import scipy # probe availability
 
80
  G = gen.to_networkx()
81
  pos = graph_layout_3d(G, seed=123)
82
 
 
83
  energies = np.array([gen.node_energy[i] for i in gen.nodes], dtype=float)
84
  deg1 = gen.node_degrees_1skeleton()
85
  degrees = np.array([deg1[i] for i in gen.nodes], dtype=float)
86
+
87
+ # Fig.2 style: node size ∝ degree (with robust scaling)
88
  if size_by_degree:
89
+ deg_min = degrees.min()
90
+ deg_range = float(np.ptp(degrees))
91
+ size_min, size_max = 6.0, 22.0
92
+ if deg_range <= 1e-12:
93
+ node_sizes = np.full_like(energies, (size_min + size_max) * 0.5)
94
+ else:
95
+ node_sizes = size_min + (size_max - size_min) * (degrees - deg_min) / deg_range
96
  else:
97
+ node_sizes = np.full_like(energies, 10.0)
98
 
 
99
  xs = [pos[i][0] for i in gen.nodes]
100
  ys = [pos[i][1] for i in gen.nodes]
101
  zs = [pos[i][2] for i in gen.nodes]
 
103
  node_trace = go.Scatter3d(
104
  x=xs, y=ys, z=zs,
105
  mode="markers",
106
+ marker=dict(
107
+ size=node_sizes,
108
+ color=energies,
109
+ cmin=float(energies.min()),
110
+ cmax=float(energies.max()),
111
+ colorscale=[
112
+ [0.0, "#ff0000"], # red
113
+ [0.2, "#ff7f00"], # orange
114
+ [0.4, "#ffff00"], # yellow
115
+ [0.6, "#00ff00"], # green
116
+ [0.8, "#0000ff"], # blue
117
+ [1.0, "#8b00ff"], # violet
118
+ ],
119
+ showscale=True,
120
+ colorbar=dict(title="ε"),
121
+ opacity=0.9,
122
+ ),
123
  text=[f"node {i}<br>ε={gen.node_energy[i]}<br>deg={deg1[i]}" for i in gen.nodes],
124
  hoverinfo="text",
125
  name="nodes",
126
  )
127
 
128
+ # Edges: neutral gray
129
  ex, ey, ez = [], [], []
130
  for u, v in gen.edges:
131
  x0, y0, z0 = pos[u]
 
136
  edge_trace = go.Scatter3d(
137
  x=ex, y=ey, z=ez,
138
  mode="lines",
139
+ line=dict(width=1, color="rgba(120,120,120,0.5)"),
140
  hoverinfo="none",
141
  name="edges",
142
+ opacity=0.5,
143
  )
144
 
145
  data = [edge_trace, node_trace]
146
 
 
147
  if show_triangles and gen.d >= 2:
 
148
  tris = [tuple(sorted(list(face))) for face in gen.face_counts[2].keys()] if 2 in gen.face_counts else []
 
149
  idx_map = {nid: idx for idx, nid in enumerate(gen.nodes)}
 
150
  I, J, K = [], [], []
151
  for (a, b, c) in tris:
152
  if a in idx_map and b in idx_map and c in idx_map:
 
154
  if I:
155
  mesh = go.Mesh3d(
156
  x=xs, y=ys, z=zs, i=I, j=J, k=K,
157
+ opacity=0.12, name="triangles",
158
  hoverinfo="skip"
159
  )
160
  data.insert(0, mesh)
161
 
 
162
  if show_boundary:
163
  if gen.d >= 1:
164
  bx, by, bz = [], [], []
165
  boundary = gen.get_boundary_faces()
166
  for face in boundary:
167
  nodes = list(face)
 
168
  for i in range(len(nodes)):
169
  for j in range(i + 1, len(nodes)):
170
  u, v = nodes[i], nodes[j]
 
176
  if bx:
177
  boundary_trace = go.Scatter3d(
178
  x=bx, y=by, z=bz, mode="lines",
179
+ line=dict(width=4, color="rgba(50,50,50,0.35)"),
180
  opacity=0.3, name="boundary (d-1)-faces", hoverinfo="skip"
181
  )
182
  data.append(boundary_trace)
 
187
  margin=dict(l=0, r=0, t=30, b=0),
188
  legend=dict(orientation="h"),
189
  height=700,
190
+ title=f"NGF d={gen.d}, s={gen.s}, β={gen.beta}, N={gen.N}, V={len(gen.simplexes_d)} (Fig. 2 style)"
191
  )
192
  return fig
193
 
 
217
 
218
 
219
  st.title("Network Geometry with Flavor — NGF Generator & 3D Viewer")
220
+ st.caption("Implements the dynamics from Bianconi & Rahmede (2016). Visuals follow Fig. 2 style: node color ~ energy (red→violet), node size ~ degree; 2-faces optional.")
221
 
222
  if do_generate:
223
  with st.spinner("Generating NGF..."):
224
  gen = build_ngf(d, s, beta, total_nodes, dist_kind, dist_params, seed)
225
 
 
226
  t1, t2, t3, t4 = st.tabs(["3D View", "Distributions", "Growth", "Export"])
227
 
228
  with t1:
 
240
  st.metric("Edges (1-skeleton)", f"{len(gen.edges)}")
241
 
242
  with t2:
 
243
  deg1 = gen.node_degrees_1skeleton()
244
  hist_deg = {}
245
  for k in deg1.values():
246
  hist_deg[k] = hist_deg.get(k, 0) + 1
247
  st.plotly_chart(plot_histogram(hist_deg, "1-skeleton degree distribution"), use_container_width=True)
248
 
 
249
  if gen.d >= 1:
250
  hist_d1 = gen.generalized_degree_distribution(gen.d - 1)
251
  st.plotly_chart(plot_histogram(hist_d1, f"Generalized degrees k₍{gen.d},{gen.d-1}₎ of (d-1)-faces"), use_container_width=True)
252
 
 
253
  hist_nodes = gen.generalized_degree_distribution(0)
254
  st.plotly_chart(plot_histogram(hist_nodes, f"Generalized degrees k₍{gen.d},0₎ of nodes"), use_container_width=True)
255
 
 
271
  else:
272
  st.info("Wähle Parameter in der Seitenleiste und klicke **Generate NGF**.")
273
  st.markdown("""
274
+ - **Fig. 2 Style:** Knotenfarbe ~ Energie (rot→violett), Knotengröße ~ Grad.
275
+ - **d**: Dimension (1: Kanten, 2: Dreiecke, 3: Tetraeder).
276
+ - **s**: Flavor: −1 (CQNM/Manifold), 0, 1.
277
+ - **β**: Einfluss der Energie-gewichteten Auswahl der (d-1)-Flächen.
278
+ - **N**: Anzahl Knoten (Standard: 1000, wie in der Abbildung).
279
  """)
280
+ st.caption("Hinweis: Für sehr große N kann das 3D-Layout (spring/random) länger dauern; Dreiecks-Mesh optional deaktivieren.")