Spaces:
Runtime error
Runtime error
Download src/ngf.py from Sierpinksi-Project/Sierpinski-Project: direct link, hf CLI and curl.
- Browser
- Download file 6.63 kB
-
https://huggingface.co/spaces/Sierpinksi-Project/Sierpinski-Project/resolve/main/src/ngf.py
- Command line
-
hf download hf://spaces/Sierpinksi-Project/Sierpinski-Project/src/ngf.py
-
curl -L -o ngf.py https://huggingface.co/spaces/Sierpinksi-Project/Sierpinski-Project/resolve/main/src/ngf.py
6.63 kB
| import math | |
| import random | |
| from collections import defaultdict | |
| from itertools import combinations | |
| from typing import Dict, List, Tuple, Set, FrozenSet, Optional | |
| import numpy as np | |
| Face = FrozenSet[int] | |
| def all_faces(simplex: Tuple[int, ...], dim_face: int) -> List[Face]: | |
| k = dim_face + 1 | |
| if k <= 0: | |
| return [] | |
| return [frozenset(c) for c in combinations(simplex, k)] | |
| class EnergyDistribution: | |
| def __init__(self, kind: str = "uniform_int", params: Optional[dict] = None, seed: Optional[int] = None): | |
| self.kind = kind | |
| self.params = params or {} | |
| self.rng = random.Random(seed) | |
| def sample(self) -> int: | |
| if self.kind == "uniform_int": | |
| lo = int(self.params.get("low", 0)) | |
| hi = int(self.params.get("high", 10)) | |
| return self.rng.randrange(lo, hi) | |
| elif self.kind == "poisson": | |
| lam = float(self.params.get("lam", 4.0)) | |
| return int(np.random.poisson(lam)) | |
| elif self.kind == "custom_list": | |
| values = self.params.get("values", [0, 1, 2, 3, 4, 5]) | |
| return self.rng.choice(values) | |
| else: | |
| lo = int(self.params.get("low", 0)) | |
| hi = int(self.params.get("high", 10)) | |
| return self.rng.randrange(lo, hi) | |
| class NGFGenerator: | |
| def __init__( | |
| self, | |
| d: int = 2, | |
| s: int = 0, | |
| beta: float = 0.0, | |
| energy_dist: Optional[EnergyDistribution] = None, | |
| seed: Optional[int] = None, | |
| ): | |
| assert d >= 1 | |
| assert s in (-1, 0, 1) | |
| assert beta >= 0.0 | |
| self.d = int(d); self.s = int(s); self.beta = float(beta) | |
| self.energy_dist = energy_dist or EnergyDistribution("uniform_int", {"low": 0, "high": 10}, seed=seed) | |
| self.rng = random.Random(seed) | |
| np.random.seed(seed if seed is not None else None) | |
| self.N = 0 | |
| self.nodes: List[int] = [] | |
| self.node_energy: Dict[int, int] = {} | |
| self.simplexes_d: List[Tuple[int, ...]] = [] | |
| self.face_n: Dict[Face, int] = {} | |
| self.face_counts: Dict[int, Dict[Face, int]] = {delta: defaultdict(int) for delta in range(self.d)} | |
| self.edges: Set[Tuple[int, int]] = set() | |
| self.area_history: List[int] = [] | |
| self.volume_history: List[int] = [] | |
| self.steps = 0 | |
| def _add_node(self, energy: Optional[int] = None) -> int: | |
| i = self.N | |
| self.nodes.append(i) | |
| eps = energy if energy is not None else self.energy_dist.sample() | |
| self.node_energy[i] = int(eps) | |
| self.N += 1 | |
| return i | |
| def _face_energy(self, face: Face) -> int: | |
| return sum(self.node_energy[i] for i in face) | |
| def _update_area_volume(self): | |
| A = sum(1 for f, n in self.face_n.items() if n == 0) | |
| V = len(self.simplexes_d) | |
| self.area_history.append(A) | |
| self.volume_history.append(V) | |
| def _register_simplex(self, simplex: Tuple[int, ...]): | |
| simplex = tuple(sorted(simplex)) | |
| self.simplexes_d.append(simplex) | |
| for delta in range(self.d): | |
| for face in all_faces(simplex, delta): | |
| self.face_counts[delta][face] += 1 | |
| for face in all_faces(simplex, self.d - 1): | |
| if face not in self.face_n: | |
| self.face_n[face] = 0 | |
| else: | |
| self.face_n[face] += 1 | |
| if self.d >= 1: | |
| for e in all_faces(simplex, 1): | |
| u, v = sorted(tuple(e)) | |
| self.edges.add((u, v)) | |
| def initialize(self): | |
| if self.N > 0: | |
| return | |
| initial_nodes = [self._add_node() for _ in range(self.d + 1)] | |
| self._register_simplex(tuple(initial_nodes)) | |
| self.steps = 1 | |
| self._update_area_volume() | |
| def choose_face(self) -> Face: | |
| faces = list(self.face_n.keys()) | |
| weights = [] | |
| for f in faces: | |
| n = self.face_n[f] | |
| factor = 1.0 + self.s * n | |
| if self.s == -1 and n >= 1: | |
| factor = 0.0 | |
| if factor < 0: | |
| factor = 0.0 | |
| eps = self._face_energy(f) | |
| w = math.exp(-self.beta * eps) * factor | |
| weights.append(w) | |
| total_w = sum(weights) | |
| if total_w <= 0: | |
| boundary = [f for f in faces if self.face_n[f] == 0] | |
| if not boundary: | |
| boundary = faces | |
| return self.rng.choice(boundary) | |
| r = self.rng.random() * total_w | |
| acc = 0.0 | |
| for f, w in zip(faces, weights): | |
| acc += w | |
| if r <= acc: | |
| return f | |
| return faces[-1] | |
| def step(self): | |
| if self.N == 0: | |
| self.initialize() | |
| alpha = self.choose_face() | |
| i = self._add_node() | |
| new_simplex = tuple(sorted(tuple(alpha) + (i,))) | |
| self._register_simplex(new_simplex) | |
| self.steps += 1 | |
| self._update_area_volume() | |
| def run(self, total_nodes: int = 1000): | |
| self.initialize() | |
| while self.N < total_nodes: | |
| self.step() | |
| def get_boundary_faces(self) -> List[Face]: | |
| return [f for f, n in self.face_n.items() if n == 0] | |
| def node_degrees_1skeleton(self) -> Dict[int, int]: | |
| deg = {i: 0 for i in self.nodes} | |
| for u, v in self.edges: | |
| deg[u] += 1; deg[v] += 1 | |
| return deg | |
| def generalized_degree_distribution(self, delta: int) -> Dict[int, int]: | |
| hist = defaultdict(int) | |
| for _, k in self.face_counts[delta].items(): | |
| hist[k] += 1 | |
| return dict(sorted(hist.items())) | |
| def to_networkx(self): | |
| import networkx as nx | |
| G = nx.Graph() | |
| for i in self.nodes: | |
| G.add_node(i, energy=self.node_energy[i]) | |
| for u, v in self.edges: | |
| G.add_edge(u, v) | |
| return G | |
| def to_json(self) -> dict: | |
| data = { | |
| "dimension": self.d, | |
| "flavor": self.s, | |
| "beta": self.beta, | |
| "N": self.N, | |
| "nodes": [{"id": i, "energy": self.node_energy[i]} for i in self.nodes], | |
| "simplexes_d": [list(s) for s in self.simplexes_d], | |
| "edges": [list(e) for e in sorted(self.edges)], | |
| "area_history": self.area_history, | |
| "volume_history": self.volume_history, | |
| } | |
| face_hist = {} | |
| for delta in range(self.d): | |
| face_hist[str(delta)] = { | |
| "faces": [list(map(int, f)) for f in self.face_counts[delta].keys()], | |
| "k": list(map(int, self.face_counts[delta].values())), | |
| } | |
| data["face_counts"] = face_hist | |
| return data | |