Spaces:
Runtime error
Runtime error
Download src/streamlit_app.py from Sierpinksi-Project/Sierpinksi-IDEAL: direct link, hf CLI and curl.
- Browser
- Download file 18.2 kB
-
https://huggingface.co/spaces/Sierpinksi-Project/Sierpinksi-IDEAL/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/Sierpinksi-Project/Sierpinksi-IDEAL/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/Sierpinksi-Project/Sierpinksi-IDEAL/resolve/main/src/streamlit_app.py
18.2 kB
| from __future__ import annotations | |
| import io | |
| import math | |
| import json | |
| from dataclasses import dataclass, field | |
| from typing import Dict, List, Tuple, Set, Literal | |
| import numpy as np | |
| import streamlit as st | |
| import plotly.graph_objects as go | |
| from scipy.sparse import coo_matrix, csr_matrix, save_npz | |
| GraphType = Literal["SG", "ST"] | |
| class Vertex: | |
| vid: int | |
| barycentric: Tuple[int, ...] | |
| coords: Tuple[float, float, float] | |
| level_min: int | |
| level_max: int | |
| class IdealGraph: | |
| graph_type: GraphType | |
| level_max: int | |
| vertices: Dict[int, Vertex] = field(default_factory=dict) | |
| edges: Set[Tuple[int, int]] = field(default_factory=set) | |
| vertex_measure: Dict[int, float] = field(default_factory=dict) | |
| addresses: Dict[int, List[Tuple[str, int]]] = field(default_factory=dict) | |
| def as_basic_dict(self) -> dict: | |
| return { | |
| "graph_type": self.graph_type, | |
| "level_max": self.level_max, | |
| "vertex_count": len(self.vertices), | |
| "edge_count": len(self.edges), | |
| } | |
| def _base_points(graph_type: GraphType): | |
| if graph_type == "SG": | |
| p0 = (0.0, 0.0, 0.0) | |
| p1 = (1.0, 0.0, 0.0) | |
| p2 = (0.5, math.sqrt(3.0) / 2.0, 0.0) | |
| return [p0, p1, p2] | |
| elif graph_type == "ST": | |
| p0 = (0.0, 0.0, 0.0) | |
| p1 = (1.0, 0.0, 0.0) | |
| p2 = (0.5, math.sqrt(3.0) / 2.0, 0.0) | |
| p3 = (0.5, math.sqrt(3.0) / 6.0, math.sqrt(6.0) / 3.0) | |
| return [p0, p1, p2, p3] | |
| else: | |
| raise ValueError(f"Unsupported graph_type: {graph_type}") | |
| def _base_edges(graph_type: GraphType): | |
| if graph_type == "SG": | |
| return [(0, 1), (1, 2), (2, 0)] | |
| elif graph_type == "ST": | |
| idx = [0, 1, 2, 3] | |
| edges = [] | |
| for i in range(len(idx)): | |
| for j in range(i + 1, len(idx)): | |
| edges.append((idx[i], idx[j])) | |
| return edges | |
| else: | |
| raise ValueError(f"Unsupported graph_type: {graph_type}") | |
| def _initial_barycentric(graph_type: GraphType): | |
| dim = 3 if graph_type == "SG" else 4 | |
| base = [] | |
| for i in range(dim): | |
| vec = [0] * dim | |
| vec[i] = 1 | |
| base.append(tuple(vec)) | |
| return base | |
| def _apply_contraction_barycentric(n: Tuple[int, ...], symbol_index: int) -> Tuple[int, ...]: | |
| s = sum(n) | |
| return tuple(nk + (s if idx == symbol_index else 0) for idx, nk in enumerate(n)) | |
| def _barycentric_to_coords( | |
| bary: Tuple[int, ...], | |
| base_points, | |
| ) -> Tuple[float, float, float]: | |
| total = float(sum(bary)) | |
| if total <= 0.0: | |
| raise ValueError("Barycentric vector has non-positive total.") | |
| x = y = z = 0.0 | |
| for weight, p in zip(bary, base_points): | |
| w = weight / total | |
| x += w * p[0] | |
| y += w * p[1] | |
| z += w * p[2] | |
| return (x, y, z) | |
| def generate_ideal_graph(graph_type: GraphType, level_max: int) -> IdealGraph: | |
| if level_max < 0: | |
| raise ValueError("level_max must be >= 0") | |
| base_pts = _base_points(graph_type) | |
| base_bary = _initial_barycentric(graph_type) | |
| vertex_by_key: Dict[Tuple[int, ...], int] = {} | |
| vertices: Dict[int, Vertex] = {} | |
| addresses: Dict[int, List[Tuple[str, int]]] = {} | |
| vertex_measure: Dict[int, float] = {} | |
| edges: Set[Tuple[int, int]] = set() | |
| next_vid = 0 | |
| def register_vertex( | |
| bary: Tuple[int, ...], | |
| level: int, | |
| word: str, | |
| base_index: int, | |
| ) -> int: | |
| nonlocal next_vid | |
| key = bary | |
| if key in vertex_by_key: | |
| vid = vertex_by_key[key] | |
| v = vertices[vid] | |
| if level < v.level_min: | |
| v.level_min = level | |
| if level > v.level_max: | |
| v.level_max = level | |
| else: | |
| vid = next_vid | |
| next_vid += 1 | |
| coords = _barycentric_to_coords(bary, base_pts) | |
| vertex = Vertex( | |
| vid=vid, | |
| barycentric=bary, | |
| coords=coords, | |
| level_min=level, | |
| level_max=level, | |
| ) | |
| vertices[vid] = vertex | |
| vertex_by_key[key] = vid | |
| vertex_measure[vid] = 1.0 | |
| addr_list = addresses.setdefault(vid, []) | |
| addr_list.append((word, base_index)) | |
| return vid | |
| alphabet_size = 3 if graph_type == "SG" else 4 | |
| symbols = list(range(alphabet_size)) | |
| def traverse(word: List[int], bary_list: List[Tuple[int, ...]], level: int): | |
| word_str = "".join(str(s) for s in word) | |
| vids_for_base = [] | |
| for base_index, bary in enumerate(bary_list): | |
| vid = register_vertex(bary, level, word_str, base_index) | |
| vids_for_base.append(vid) | |
| for i, j in _base_edges(graph_type): | |
| vi = vids_for_base[i] | |
| vj = vids_for_base[j] | |
| if vi == vj: | |
| continue | |
| edge = (vi, vj) if vi < vj else (vj, vi) | |
| edges.add(edge) | |
| if level >= level_max: | |
| return | |
| for s in symbols: | |
| next_bary_list = [ | |
| _apply_contraction_barycentric(bary, s) for bary in bary_list | |
| ] | |
| traverse(word + [s], next_bary_list, level + 1) | |
| traverse([], base_bary, level=0) | |
| return IdealGraph( | |
| graph_type=graph_type, | |
| level_max=level_max, | |
| vertices=vertices, | |
| edges=edges, | |
| vertex_measure=vertex_measure, | |
| addresses=addresses, | |
| ) | |
| def build_adjacency_matrix(graph: IdealGraph) -> csr_matrix: | |
| n = len(graph.vertices) | |
| if n == 0: | |
| return csr_matrix((0, 0)) | |
| rows = [] | |
| cols = [] | |
| data = [] | |
| for i, j in sorted(graph.edges): | |
| rows.append(i) | |
| cols.append(j) | |
| data.append(1.0) | |
| rows.append(j) | |
| cols.append(i) | |
| data.append(1.0) | |
| coo = coo_matrix((data, (rows, cols)), shape=(n, n)) | |
| return coo.tocsr() | |
| def build_laplacian_matrix(graph: IdealGraph) -> csr_matrix: | |
| A = build_adjacency_matrix(graph) | |
| degrees = np.array(A.sum(axis=1)).ravel() | |
| n = A.shape[0] | |
| D = coo_matrix((degrees, (np.arange(n), np.arange(n))), shape=(n, n)).tocsr() | |
| L = D - A | |
| return L | |
| def export_ideal_graph_artifact(graph: IdealGraph, buffer, matrix_format: str = "sparse_csr") -> None: | |
| """ | |
| Exportiert ein IDEAL-Graph-Artefakt in ein Zip-ähnliches Buffer-Objekt. | |
| matrix_format: | |
| - "sparse_csr": SciPy-CSR-Matrizen als .npz (komprimiert) | |
| - "dense_npy": dichte Matrizen als .npy | |
| """ | |
| import csv | |
| import zipfile | |
| A = build_adjacency_matrix(graph) | |
| L = build_laplacian_matrix(graph) | |
| # Pfade für Operatoren je nach Format | |
| if matrix_format == "sparse_csr": | |
| adjacency_path = "operators/adjacency_csr.npz" | |
| laplacian_path = "operators/laplacian_csr.npz" | |
| elif matrix_format == "dense_npy": | |
| adjacency_path = "operators/adjacency_dense.npy" | |
| laplacian_path = "operators/laplacian_dense.npy" | |
| else: | |
| raise ValueError(f"Unknown matrix_format: {matrix_format!r}") | |
| # Level-Statistik und Blockstruktur | |
| max_level = graph.level_max | |
| level_vertices: Dict[int, List[int]] = {L: [] for L in range(max_level + 1)} | |
| for vid, v in graph.vertices.items(): | |
| Lvl = v.level_min | |
| if 0 <= Lvl <= max_level: | |
| level_vertices[Lvl].append(vid) | |
| level_edges_count: Dict[int, int] = {L: 0 for L in range(max_level + 1)} | |
| edges_respect_levels = True | |
| for (i, j) in graph.edges: | |
| li = graph.vertices[i].level_min | |
| lj = graph.vertices[j].level_min | |
| if li == lj and 0 <= li <= max_level: | |
| level_edges_count[li] += 1 | |
| else: | |
| edges_respect_levels = False | |
| levels_meta = {} | |
| for Lvl in range(max_level + 1): | |
| levels_meta[str(Lvl)] = { | |
| "vertex_count": len(level_vertices[Lvl]), | |
| "edge_count": level_edges_count[Lvl], | |
| "vertex_ids_path": f"levels/level_{Lvl}_vertices.json", | |
| } | |
| with zipfile.ZipFile(buffer, mode="w", compression=zipfile.ZIP_DEFLATED) as zf: | |
| # Manifest mit expliziter Schema-/Level-Semantik | |
| manifest = { | |
| "schema_version": "1.1.0", | |
| "type": "IDEAL_GRAPH", | |
| "substrate": graph.graph_type, | |
| "level_max": graph.level_max, | |
| "vertex_count": len(graph.vertices), | |
| "edge_count": len(graph.edges), | |
| "matrix_format": matrix_format, | |
| "level_semantics": ( | |
| "multi_level_bundle: each level L forms a block with " | |
| "vertices satisfying level_min == L and edges whose endpoints " | |
| "both lie in that vertex set" | |
| ), | |
| "levels": levels_meta, | |
| "block_structure": { | |
| "edges_respect_levels": edges_respect_levels, | |
| }, | |
| "ideal_conductance": { | |
| "type": "uniform", | |
| "value": 1.0, | |
| "comment": "all IDEAL edges carry unit conductance in the unweighted Dirichlet energy", | |
| }, | |
| "edge_indexing": ( | |
| "edges.csv row order is the canonical edge index order; " | |
| "use this for per-edge quantities c_e, etc." | |
| ), | |
| "paths": { | |
| "vertices": "vertices.csv", | |
| "edges": "edges.csv", | |
| "vertex_measure": "vertex_measure.csv", | |
| "addresses": "addresses.json", | |
| "adjacency": adjacency_path, | |
| "laplacian": laplacian_path, | |
| }, | |
| "definition_notes": ( | |
| "Vertices are given by barycentric integer coordinates relative to " | |
| "the regular simplex, following the IDEAL-Graph definition on SG/ST. " | |
| "The Laplacian corresponds to the unweighted graph energy " | |
| "E_L(f) = sum_{edges} (f(i)-f(j))^2 = f^T L f. " | |
| "The global graph is a multi-level bundle over levels L=0..level_max; " | |
| "subgraphs per level should be constructed via level_min==L." | |
| ), | |
| } | |
| zf.writestr("manifest.json", json.dumps(manifest, indent=2)) | |
| # Level-Vertexlisten (pro Level eine Datei) | |
| for Lvl in range(max_level + 1): | |
| verts_ids = sorted(level_vertices[Lvl]) | |
| level_file = f"levels/level_{Lvl}_vertices.json" | |
| zf.writestr(level_file, json.dumps(verts_ids)) | |
| # Vertices | |
| vertex_csv = io.StringIO() | |
| writer = csv.writer(vertex_csv) | |
| writer.writerow( | |
| [ | |
| "id", | |
| "x", | |
| "y", | |
| "z", | |
| "level_min", | |
| "level_max", | |
| "barycentric", | |
| ] | |
| ) | |
| for vid, v in sorted(graph.vertices.items()): | |
| writer.writerow( | |
| [ | |
| vid, | |
| f"{v.coords[0]:.16g}", | |
| f"{v.coords[1]:.16g}", | |
| f"{v.coords[2]:.16g}", | |
| v.level_min, | |
| v.level_max, | |
| ";".join(str(x) for x in v.barycentric), | |
| ] | |
| ) | |
| zf.writestr("vertices.csv", vertex_csv.getvalue()) | |
| # Edges (kanonische Reihenfolge) | |
| edges_csv = io.StringIO() | |
| writer = csv.writer(edges_csv) | |
| writer.writerow(["source", "target"]) | |
| for i, j in sorted(graph.edges): | |
| writer.writerow([i, j]) | |
| zf.writestr("edges.csv", edges_csv.getvalue()) | |
| # Vertexmaß | |
| mu_csv = io.StringIO() | |
| writer = csv.writer(mu_csv) | |
| writer.writerow(["id", "mu"]) | |
| for vid in sorted(graph.vertices.keys()): | |
| writer.writerow([vid, graph.vertex_measure.get(vid, 1.0)]) | |
| zf.writestr("vertex_measure.csv", mu_csv.getvalue()) | |
| # Adressen | |
| addr_serializable = { | |
| str(vid): [(word, int(base_idx)) for (word, base_idx) in addr_list] | |
| for vid, addr_list in graph.addresses.items() | |
| } | |
| zf.writestr("addresses.json", json.dumps(addr_serializable, indent=2)) | |
| # Matrizen | |
| if matrix_format == "sparse_csr": | |
| adj_buf = io.BytesIO() | |
| save_npz(adj_buf, A) | |
| zf.writestr(adjacency_path, adj_buf.getvalue()) | |
| lap_buf = io.BytesIO() | |
| save_npz(lap_buf, L) | |
| zf.writestr(laplacian_path, lap_buf.getvalue()) | |
| else: # dense_npy | |
| adj_buf = io.BytesIO() | |
| np.save(adj_buf, A.toarray()) | |
| zf.writestr(adjacency_path, adj_buf.getvalue()) | |
| lap_buf = io.BytesIO() | |
| np.save(lap_buf, L.toarray()) | |
| zf.writestr(laplacian_path, lap_buf.getvalue()) | |
| def _make_3d_figure(graph: IdealGraph) -> go.Figure: | |
| xs = [] | |
| ys = [] | |
| zs = [] | |
| for vid, v in sorted(graph.vertices.items()): | |
| xs.append(v.coords[0]) | |
| ys.append(v.coords[1]) | |
| zs.append(v.coords[2]) | |
| edge_x = [] | |
| edge_y = [] | |
| edge_z = [] | |
| for i, j in sorted(graph.edges): | |
| vi = graph.vertices[i] | |
| vj = graph.vertices[j] | |
| edge_x.extend([vi.coords[0], vj.coords[0], None]) | |
| edge_y.extend([vi.coords[1], vj.coords[1], None]) | |
| edge_z.extend([vi.coords[2], vj.coords[2], None]) | |
| fig = go.Figure() | |
| fig.add_trace( | |
| go.Scatter3d( | |
| x=edge_x, | |
| y=edge_y, | |
| z=edge_z, | |
| mode="lines", | |
| line=dict(width=1), | |
| hoverinfo="none", | |
| ) | |
| ) | |
| fig.add_trace( | |
| go.Scatter3d( | |
| x=xs, | |
| y=ys, | |
| z=zs, | |
| mode="markers", | |
| marker=dict(size=4), | |
| hoverinfo="text", | |
| text=[f"vid={vid}" for vid in sorted(graph.vertices.keys())], | |
| ) | |
| ) | |
| fig.update_layout( | |
| scene=dict( | |
| xaxis=dict(showgrid=False, zeroline=False, visible=False), | |
| yaxis=dict(showgrid=False, zeroline=False, visible=False), | |
| zaxis=dict(showgrid=False, zeroline=False, visible=False), | |
| aspectmode="data", | |
| ), | |
| margin=dict(l=0, r=0, b=0, t=30), | |
| ) | |
| return fig | |
| def main(): | |
| st.set_page_config( | |
| page_title="IDEAL-Graph Generator (SG/ST)", | |
| layout="wide", | |
| ) | |
| st.title("IDEAL-Graph Generator für Sierpinski-Gasket (SG) und Sierpinski-Tetraeder (ST)") | |
| st.markdown( | |
| """ | |
| Diese App generiert **IDEAL-Graphen** auf dem Sierpinski-Gasket (SG) | |
| bzw. Sierpinski-Tetraeder (ST) gemäß der formalen Definition: | |
| - p.c.f.-Fraktale mit IFS \(F_i(x) = \tfrac12(x - q_i) + q_i\), | |
| - diskrete Approximanten \(V_L, E_L\) über alle Level \(L \leq L_\text{max}\), | |
| - baryzentrische Kodierung und Adressbaum \((w, i)\), | |
| - ungewichtete Dirichlet-Energie \(E_L(f) = \sum_{\{x,y\} \in E_L} (f(x)-f(y))^2\). | |
| Das Ergebnis kann als **Artefakt-Zip** exportiert und in anderen | |
| Apps weiterverwendet werden. | |
| """ | |
| ) | |
| with st.sidebar: | |
| st.header("Parameter") | |
| graph_type_label = st.selectbox( | |
| "Fraktaltyp", | |
| options=[ | |
| "Sierpinski-Gasket (SG)", | |
| "Sierpinski-Tetraeder (ST)", | |
| ], | |
| ) | |
| if graph_type_label.startswith("Sierpinski-Gasket"): | |
| graph_type = "SG" | |
| else: | |
| graph_type = "ST" | |
| max_allowed_level = 8 if graph_type == "SG" else 7 | |
| default_level = 5 if graph_type == "SG" else 4 | |
| level_max = st.slider( | |
| "Approximations-Level L", | |
| min_value=0, | |
| max_value=max_allowed_level, | |
| value=default_level, | |
| ) | |
| matrix_format_label = st.selectbox( | |
| "Matrix-Exportformat", | |
| options=[ | |
| "Sparse CSR (.npz, komprimiert)", | |
| "Dicht (voll) (.npy)", | |
| ], | |
| index=0, | |
| ) | |
| if "Sparse CSR" in matrix_format_label: | |
| matrix_format = "sparse_csr" | |
| else: | |
| matrix_format = "dense_npy" | |
| st.caption( | |
| "Hinweis: Höhere Level führen zu stark wachsender Vertexanzahl. " | |
| "Für große Graphen ist das Sparse-Format deutlich speichereffizienter." | |
| ) | |
| generate_button = st.button("IDEAL-Graph generieren", type="primary") | |
| if not generate_button: | |
| st.info("Wähle Parameter in der Seitenleiste und klicke auf **IDEAL-Graph generieren**.") | |
| return | |
| with st.spinner("Generiere IDEAL-Graph..."): | |
| graph = generate_ideal_graph(graph_type, level_max) | |
| st.success("IDEAL-Graph erzeugt.") | |
| col_left, col_right = st.columns([2, 1]) | |
| with col_left: | |
| st.subheader("3D-Vorschau") | |
| fig = _make_3d_figure(graph) | |
| st.plotly_chart(fig, use_container_width=True) | |
| with col_right: | |
| st.subheader("Basis-Informationen") | |
| st.json(graph.as_basic_dict()) | |
| buf = io.BytesIO() | |
| export_ideal_graph_artifact(graph, buf, matrix_format=matrix_format) | |
| buf.seek(0) | |
| st.download_button( | |
| label="Artefakt (.zip) herunterladen", | |
| data=buf, | |
| file_name=f"ideal_graph_{graph.graph_type}_L{graph.level_max}.zip", | |
| mime="application/zip", | |
| ) | |
| st.markdown( | |
| """ | |
| **Struktur des Artefakts:** | |
| - `manifest.json` – Metadaten zum IDEAL-Graph (inkl. `schema_version`, `matrix_format`, | |
| `level_semantics`, `levels`, `ideal_conductance`, `edge_indexing`) | |
| - `vertices.csv` – Knoten mit Koordinaten, Levels und baryzentrischen Integer-Vektoren | |
| - `edges.csv` – Kantenliste (ungerichtet, Reihenfolge = kanonischer Edge-Index) | |
| - `vertex_measure.csv` – Vertex-Maß (hier: Zählmaß) | |
| - `addresses.json` – Adressen \((w, i)\) je Vertex | |
| - `levels/level_L_vertices.json` – Vertex-IDs für jedes Level L=0..L_max | |
| - Matrizen (abhängig vom Format): | |
| - Sparse: `operators/adjacency_csr.npz`, `operators/laplacian_csr.npz` | |
| - Dicht: `operators/adjacency_dense.npy`, `operators/laplacian_dense.npy` | |
| """ | |
| ) | |
| if __name__ == "__main__": | |
| main() | |