Coverage for app / documents / visuals / network.py: 98%

242 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""A ```graph fence: a network of nodes and edges, 2D or 3D. 

2 

3Laid out exactly as fe-core lays it out (``RichMarkdown.tsx`` 

4``NetworkGraphContent``), so a graph has the same shape in the chat and the 

5PDF: nodes with coordinates are scaled into the frame (y flipped for ``geo``); 

6otherwise a seeded start (``_seeded_rand``, a 32-bit LCG, seed 42) and 300 

7steps of the same force simulation, operation for operation, so the floats 

8come out the same. Drawn in fe-core's 600 × 360 view, scaled to the page: 

9halos, labels under each node, edges with their labels, arrowheads when 

10directed; a 3D graph from fe-core's starting rotation. 

11""" 

12 

13from __future__ import annotations 

14 

15import math 

16from dataclasses import dataclass, field 

17 

18from reportlab.graphics.shapes import Circle, Drawing, Polygon 

19from reportlab.lib.colors import Color 

20 

21from .colors import parse_color 

22from .fence import VisualError, number, read_object, text 

23from .primitives import label, rule 

24from .registry import Layout, Visual, register_visual 

25from .theme import EDGE, FAINT, LABEL, PALETTE, Theme, WHITE 

26 

27#: fe-core's view box. 

28VIEW_WIDTH, VIEW_HEIGHT = 600, 360 

29#: The most nodes a force layout is run for (about 1.5 s); a graph with its 

30#: own coordinates may have more. 

31FORCE_LAYOUT_MAX_NODES = 200 

32MAX_NODES = 2_000 

33MAX_EDGES = 4_000 

34_ITERATIONS = 300 

35_ROTATION = (0.35, 0.4) 

36 

37 

38@dataclass 

39class SimNode: 

40 id: str 

41 label: str 

42 nx: float 

43 ny: float 

44 nz: float 

45 fixed: bool 

46 color: str | None = None 

47 size: float | None = None 

48 vx: float = field(default=0.0) 

49 vy: float = field(default=0.0) 

50 vz: float = field(default=0.0) 

51 

52 

53@dataclass(frozen=True) 

54class Edge: 

55 source: str 

56 target: str 

57 label: str 

58 weight: float | None 

59 color: str | None 

60 

61 

62@dataclass(frozen=True) 

63class GraphSpec: 

64 title: str | None 

65 three_d: bool 

66 directed: bool 

67 flip_y: bool 

68 nodes: list[dict] 

69 edges: list[Edge] 

70 has_positions: bool 

71 

72 

73def seeded_rand(seed: int): 

74 """fe-core's ``_seededRand``: ``s = imul(s, 1664525) + 1013904223``, 

75 32 bits, read as an unsigned fraction.""" 

76 state = seed & 0xFFFFFFFF 

77 

78 def next_value() -> float: 

79 nonlocal state 

80 state = (state * 1664525 + 1013904223) & 0xFFFFFFFF 

81 return state / 0x100000000 

82 

83 return next_value 

84 

85 

86def node_color(node_id: str) -> str: 

87 """fe-core's ``_graphNodeColor``: the id hashed over its UTF-16 code 

88 units with 32-bit wraparound, into the palette.""" 

89 h = 0 

90 data = node_id.encode("utf-16-le") 

91 for i in range(0, len(data), 2): 

92 h = (h * 31 + int.from_bytes(data[i : i + 2], "little")) & 0xFFFFFFFF 

93 signed = h - 0x100000000 if h & 0x80000000 else h 

94 return PALETTE[abs(signed) % len(PALETTE)] 

95 

96 

97def build_sim_nodes(nodes: list[dict], three_d: bool, flip_y: bool) -> list[SimNode]: 

98 rng = seeded_rand(42) 

99 if any( 

100 number(n.get("x")) is not None and number(n.get("y")) is not None for n in nodes 

101 ): 

102 xs = [v for n in nodes if (v := number(n.get("x"))) is not None] 

103 ys = [v for n in nodes if (v := number(n.get("y"))) is not None] 

104 zs = [v for n in nodes if (v := number(n.get("z"))) is not None] 

105 min_x, max_x, min_y, max_y = min(xs), max(xs), min(ys), max(ys) 

106 min_z, max_z = (min(zs), max(zs)) if zs else (0.0, 1.0) 

107 rx, ry, rz = max_x - min_x or 1, max_y - min_y or 1, max_z - min_z or 1 

108 out = [] 

109 for n in nodes: 

110 x, y, z = number(n.get("x")), number(n.get("y")), number(n.get("z")) 

111 nx = 0.08 + ((x - min_x) / rx) * 0.84 if x is not None else 0.5 

112 raw_y = 0.08 + ((y - min_y) / ry) * 0.84 if y is not None else 0.5 

113 ny = 1.0 - raw_y if flip_y else raw_y 

114 nz = 0.08 + ((z - min_z) / rz) * 0.84 if three_d and z is not None else 0.5 

115 out.append(_sim(n, nx, ny, nz, fixed=True)) 

116 return out 

117 out = [] 

118 for n in nodes: 

119 nx = 0.1 + rng() * 0.8 

120 ny = 0.1 + rng() * 0.8 

121 nz = 0.1 + rng() * 0.8 if three_d else 0.5 

122 out.append(_sim(n, nx, ny, nz, fixed=False)) 

123 return out 

124 

125 

126def _sim(n: dict, nx: float, ny: float, nz: float, *, fixed: bool) -> SimNode: 

127 node_id = text(n.get("id")) 

128 return SimNode( 

129 node_id, 

130 text(n.get("label")) or node_id, 

131 nx, 

132 ny, 

133 nz, 

134 fixed, 

135 n.get("color") if isinstance(n.get("color"), str) else None, 

136 number(n.get("size")), 

137 ) 

138 

139 

140def _spring_length(weight: float | None) -> float: 

141 # ``e.weight ? min(0.45, w / (w + 10) * 0.5 + 0.1) : 0.2``; a weight that 

142 # makes it no number (-10) is the default, where JavaScript would break. 

143 if not weight: 

144 return 0.2 

145 try: 

146 length = min(0.45, weight / (weight + 10) * 0.5 + 0.1) 

147 except ZeroDivisionError: 

148 return 0.2 

149 return length if math.isfinite(length) else 0.2 

150 

151 

152def run_force_simulation( 

153 nodes: list[SimNode], edges: list[Edge], three_d: bool 

154) -> None: 

155 """fe-core's ``_runForceSimulation``, step for step.""" 

156 if all(n.fixed for n in nodes): 

157 return 

158 by_id = {n.id: n for n in nodes} 

159 for iteration in range(_ITERATIONS): 

160 cool = 1 - iteration / _ITERATIONS 

161 for i in range(len(nodes)): 

162 for j in range(i + 1, len(nodes)): 

163 a, b = nodes[i], nodes[j] 

164 dx, dy = b.nx - a.nx, b.ny - a.ny 

165 dz = b.nz - a.nz if three_d else 0 

166 d2 = dx * dx + dy * dy + dz * dz + 1e-4 

167 f = 4e-3 / d2 

168 d = math.sqrt(d2) 

169 fx, fy = dx / d * f, dy / d * f 

170 fz = dz / d * f if three_d else 0 

171 if not a.fixed: 

172 a.vx -= fx 

173 a.vy -= fy 

174 a.vz -= fz 

175 if not b.fixed: 

176 b.vx += fx 

177 b.vy += fy 

178 b.vz += fz 

179 for e in edges: 

180 a, b = by_id.get(e.source), by_id.get(e.target) 

181 if a is None or b is None: 

182 continue 

183 dx, dy = b.nx - a.nx, b.ny - a.ny 

184 dz = b.nz - a.nz if three_d else 0 

185 d = math.sqrt(dx * dx + dy * dy + dz * dz) or 1e-3 

186 stretch = (d - _spring_length(e.weight)) * 0.05 

187 fx, fy = dx / d * stretch, dy / d * stretch 

188 fz = dz / d * stretch if three_d else 0 

189 if not a.fixed: 

190 a.vx += fx 

191 a.vy += fy 

192 a.vz += fz 

193 if not b.fixed: 

194 b.vx -= fx 

195 b.vy -= fy 

196 b.vz -= fz 

197 for n in nodes: 

198 if n.fixed: 

199 continue 

200 n.vx += (0.5 - n.nx) * 0.012 

201 n.vy += (0.5 - n.ny) * 0.012 

202 if three_d: 

203 n.vz += (0.5 - n.nz) * 0.012 

204 for n in nodes: 

205 if n.fixed: 

206 continue 

207 n.vx *= 0.85 

208 n.vy *= 0.85 

209 n.vz *= 0.85 

210 n.nx = max(0.04, min(0.96, n.nx + n.vx * cool)) 

211 n.ny = max(0.04, min(0.96, n.ny + n.vy * cool)) 

212 if three_d: 

213 n.nz = max(0.04, min(0.96, n.nz + n.vz * cool)) 

214 

215 

216def positions( 

217 nodes: list[SimNode], three_d: bool 

218) -> dict[str, tuple[float, float, float]]: 

219 """Each node's place in the 600 × 360 view (y down, as SVG), and its depth.""" 

220 out: dict[str, tuple[float, float, float]] = {} 

221 rx, ry = _ROTATION 

222 cos_y, sin_y, cos_x, sin_x = math.cos(ry), math.sin(ry), math.cos(rx), math.sin(rx) 

223 for n in nodes: 

224 if not three_d: 

225 out[n.id] = (n.nx * VIEW_WIDTH, n.ny * VIEW_HEIGHT, 0.0) 

226 continue 

227 x1 = (n.nx - 0.5) * cos_y - (n.nz - 0.5) * sin_y 

228 z1 = (n.nx - 0.5) * sin_y + (n.nz - 0.5) * cos_y 

229 y2 = (n.ny - 0.5) * cos_x - z1 * sin_x 

230 z2 = (n.ny - 0.5) * sin_x + z1 * cos_x 

231 p = 2.5 / (2.5 + z2) 

232 out[n.id] = ((x1 * p + 0.5) * VIEW_WIDTH, (y2 * p + 0.5) * VIEW_HEIGHT, z2) 

233 return out 

234 

235 

236@register_visual 

237class NetworkVisual(Visual): 

238 kind = "graph" 

239 noun = "Graph" 

240 

241 def read(self, source: str) -> GraphSpec: 

242 spec = read_object(source) 

243 raw_nodes = spec.get("nodes") 

244 nodes = [ 

245 n 

246 for n in (raw_nodes if isinstance(raw_nodes, list) else []) 

247 if isinstance(n, dict) and text(n.get("id")) 

248 ] 

249 if not nodes: 

250 raise VisualError("it has no nodes") 

251 if len(nodes) > MAX_NODES: 

252 raise VisualError(f"it has more than {MAX_NODES:,} nodes") 

253 raw_edges = spec.get("edges") if isinstance(spec.get("edges"), list) else [] 

254 edges = [ 

255 Edge( 

256 text(e.get("source")), 

257 text(e.get("target")), 

258 text(e.get("label")), 

259 number(e.get("weight")), 

260 e.get("color") if isinstance(e.get("color"), str) else None, 

261 ) 

262 for e in raw_edges 

263 if isinstance(e, dict) 

264 ] 

265 if len(edges) > MAX_EDGES: 

266 raise VisualError(f"it has more than {MAX_EDGES:,} edges") 

267 has_positions = any( 

268 number(n.get("x")) is not None and number(n.get("y")) is not None 

269 for n in nodes 

270 ) 

271 if not has_positions and len(nodes) > FORCE_LAYOUT_MAX_NODES: 

272 raise VisualError( 

273 f"it has more than {FORCE_LAYOUT_MAX_NODES} nodes to lay out" 

274 ) 

275 title = spec.get("title") 

276 return GraphSpec( 

277 text(title) or None if isinstance(title, str) else None, 

278 spec.get("type") == "3d", 

279 spec.get("directed") is True, 

280 spec.get("geo") is True or spec.get("flipY") is True, 

281 nodes, 

282 edges, 

283 has_positions, 

284 ) 

285 

286 def title(self, spec: GraphSpec) -> str | None: 

287 return spec.title 

288 

289 def cost(self, spec: GraphSpec) -> int: 

290 return 0 if spec.has_positions else len(spec.nodes) ** 2 

291 

292 def layout( 

293 self, spec: GraphSpec, width: float, max_height: float, theme: Theme 

294 ) -> Layout: 

295 sim = build_sim_nodes(spec.nodes, spec.three_d, spec.flip_y) 

296 run_force_simulation(sim, spec.edges, spec.three_d) 

297 where = positions(sim, spec.three_d) 

298 scale = min(width / VIEW_WIDTH, max_height / VIEW_HEIGHT) 

299 height = VIEW_HEIGHT * scale 

300 

301 def at(x: float, y: float) -> tuple[float, float]: 

302 # SVG's y runs down; a drawing's runs up. Each point is turned, 

303 # never the group, or the labels would print upside down. 

304 return x * scale, (VIEW_HEIGHT - y) * scale 

305 

306 by_id = {n.id: n for n in sim} 

307 drawing = Drawing(VIEW_WIDTH * scale, height) 

308 for e in spec.edges: 

309 source, target = where.get(e.source), where.get(e.target) 

310 if source is None or target is None: 

311 continue 

312 x2, y2 = target[0], target[1] 

313 if spec.directed: 

314 dx, dy = target[0] - source[0], target[1] - source[1] 

315 dist = math.sqrt(dx * dx + dy * dy) or 1 

316 node = by_id.get(e.target) 

317 shorten = (node.size if node and node.size is not None else 7) + 5 

318 x2, y2 = ( 

319 target[0] - dx / dist * shorten, 

320 target[1] - dy / dist * shorten, 

321 ) 

322 color = parse_color(e.color, EDGE) 

323 (ax, ay), (bx, by) = at(source[0], source[1]), at(x2, y2) 

324 drawing.add(rule(ax, ay, bx, by, color, 1.5 * scale, opacity=0.65)) 

325 if spec.directed: 

326 drawing.add(_arrowhead(ax, ay, bx, by, 1.5 * scale, EDGE)) 

327 if e.label: 

328 mx, my = at( 

329 (source[0] + target[0]) / 2, (source[1] + target[1]) / 2 - 5 

330 ) 

331 drawing.add( 

332 label(mx, my, e.label, theme.regular, 9 * scale, FAINT, "middle") 

333 ) 

334 ordered = sorted(sim, key=lambda n: where[n.id][2]) if spec.three_d else sim 

335 for n in ordered: 

336 x, y, depth = where[n.id] 

337 color = parse_color(n.color, parse_color(node_color(n.id), EDGE)) 

338 base = n.size if n.size is not None else 7 

339 r = base * max(0.5, 0.75 + depth * 0.5) if spec.three_d else base 

340 cx, cy = at(x, y) 

341 drawing.add( 

342 Circle( 

343 cx, 

344 cy, 

345 (r + 3) * scale, 

346 fillColor=color, 

347 fillOpacity=0.12, 

348 strokeColor=None, 

349 ) 

350 ) 

351 drawing.add( 

352 Circle( 

353 cx, 

354 cy, 

355 r * scale, 

356 fillColor=color, 

357 strokeColor=WHITE, 

358 strokeWidth=1.5 * scale, 

359 ) 

360 ) 

361 lx, ly = at(x, y + r + 12) 

362 drawing.add( 

363 label(lx, ly, n.label, theme.regular, 9 * scale, LABEL, "middle") 

364 ) 

365 return Layout(drawing, VIEW_WIDTH * scale, height) 

366 

367 

368def _arrowhead( 

369 x0: float, y0: float, x1: float, y1: float, stroke: float, color: Color 

370) -> Polygon: 

371 """fe-core's marker (``M0,0 L6,2 L0,4``, in stroke widths, its point one 

372 unit past the line's end).""" 

373 dx, dy = x1 - x0, y1 - y0 

374 length = math.hypot(dx, dy) or 1 

375 ux, uy = dx / length, dy / length 

376 tip_x, tip_y = x1 + ux * stroke, y1 + uy * stroke 

377 back_x, back_y = tip_x - ux * 6 * stroke, tip_y - uy * 6 * stroke 

378 half = 2 * stroke 

379 return Polygon( 

380 [ 

381 tip_x, 

382 tip_y, 

383 back_x - uy * half, 

384 back_y + ux * half, 

385 back_x + uy * half, 

386 back_y - ux * half, 

387 ], 

388 fillColor=color, 

389 strokeColor=None, 

390 )