fling-layout 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fling/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ from .graphs import make_graph, edge_array, count_crossings, nonadjacent_pairs, bfs_rows
2
+ from .nets import Gabor
3
+ from .estimators import Fling, FlingStress, neulay
4
+ from .vis import FlingVis
5
+ from .conditional import FlingBlend, CondField
fling/baselines.py ADDED
@@ -0,0 +1,492 @@
1
+ import time
2
+
3
+ import networkx as nx
4
+ import numpy as np
5
+ import s_gd2
6
+ import torch
7
+ from fa2_modified import ForceAtlas2
8
+ from scipy.spatial import cKDTree
9
+ from sklearn.manifold import TSNE
10
+
11
+ torch.set_num_threads(8)
12
+
13
+
14
+ def all_pairs_D(graph):
15
+ idx = {node: i for i, node in enumerate(graph.nodes())}
16
+ n_nodes = len(idx)
17
+ dist = np.zeros((n_nodes, n_nodes), np.float32)
18
+
19
+ for src, dist_map in nx.all_pairs_shortest_path_length(graph):
20
+ for dst, length in dist_map.items():
21
+ dist[idx[src], idx[dst]] = length
22
+
23
+ return dist
24
+
25
+
26
+ def farthest_pivots(graph, n_pivots, among=None, seed=0):
27
+ rng = np.random.default_rng(seed)
28
+ nodes = list(graph.nodes())
29
+ idx = {node: i for i, node in enumerate(nodes)}
30
+ n_nodes = len(nodes)
31
+ pool = [idx[node] for node in (among if among is not None else nodes)]
32
+ pivots = [pool[int(rng.choice(len(pool)))]]
33
+ cols = []
34
+
35
+ for _ in range(n_pivots):
36
+ dist_map = nx.single_source_shortest_path_length(graph, nodes[pivots[-1]])
37
+ col = np.full(n_nodes, n_nodes, np.float32)
38
+
39
+ for dst, length in dist_map.items():
40
+ col[idx[dst]] = length
41
+
42
+ cols.append(col)
43
+ cand = np.min(np.stack(cols), 0).copy()
44
+ cand[pivots] = -1
45
+
46
+ if among is not None:
47
+ mask = np.ones(n_nodes, bool)
48
+ mask[pool] = False
49
+ cand[mask] = -1
50
+
51
+ far = int(np.argmax(cand))
52
+
53
+ if far in pivots:
54
+ break
55
+
56
+ pivots.append(far)
57
+
58
+ return np.array(pivots[: len(cols)]), np.stack(cols, 1)
59
+
60
+
61
+ def full_sns(pos, D):
62
+ n_nodes = len(pos)
63
+ iu = np.triu_indices(n_nodes, 1)
64
+ dist = D[iu].astype(np.float64)
65
+ edist = np.linalg.norm(pos[iu[0]] - pos[iu[1]], axis=1)
66
+ mask = dist > 0
67
+ dist, edist = dist[mask], edist[mask]
68
+ scale = (edist / dist).sum() / ((edist / dist) ** 2).sum()
69
+
70
+ return float(np.mean((scale * edist / dist - 1) ** 2))
71
+
72
+
73
+ def adj_recall(pos, nbrs, subset=None):
74
+ tree = cKDTree(pos)
75
+ hits = total = 0
76
+ node_ids = range(len(nbrs)) if subset is None else subset
77
+
78
+ for nid in node_ids:
79
+ deg = len(nbrs[nid])
80
+
81
+ if deg == 0:
82
+ continue
83
+
84
+ idx = tree.query(pos[nid], deg + 1)[1][1:]
85
+ hits += len(set(int(cand) for cand in idx) & nbrs[nid])
86
+ total += deg
87
+
88
+ return hits / max(total, 1)
89
+
90
+
91
+ def label_purity(pos, labels, n_nbrs=10):
92
+ tree = cKDTree(pos)
93
+ n_nodes = len(pos)
94
+ n_nbrs = min(n_nbrs, n_nodes - 1)
95
+ same = 0
96
+ idx = tree.query(pos, n_nbrs + 1)[1][:, 1:]
97
+
98
+ for nid in range(n_nodes):
99
+ same += np.mean(labels[idx[nid]] == labels[nid])
100
+
101
+ return same / n_nodes
102
+
103
+
104
+ def fa2(graph, iters=400):
105
+ layout = ForceAtlas2(verbose=False).forceatlas2_networkx_layout(
106
+ graph, pos=None, iterations=iters
107
+ )
108
+
109
+ return np.array([layout[node] for node in graph.nodes()], float)
110
+
111
+
112
+ def sgd_stress(graph, seed=0):
113
+ idx = {node: i for i, node in enumerate(graph.nodes())}
114
+ edges = np.array([[idx[src], idx[dst]] for src, dst in graph.edges()])
115
+ src = edges[:, 0].astype(np.int32)
116
+ dst = edges[:, 1].astype(np.int32)
117
+
118
+ try:
119
+ return np.asarray(s_gd2.layout(src, dst, random_seed=seed), float)
120
+ except TypeError:
121
+ return np.asarray(s_gd2.layout(src, dst), float)
122
+
123
+
124
+ def tsnet(D, seed=0, perplexity=30):
125
+ perp = max(5, min(perplexity, (len(D) - 1) // 3))
126
+
127
+ return TSNE(
128
+ metric="precomputed", init="random", perplexity=perp, random_state=seed
129
+ ).fit_transform(D.astype(np.float64))
130
+
131
+
132
+ def tsnet_star(D, seed=0, perplexity=40):
133
+ perp = max(5, min(perplexity, (len(D) - 1) // 3))
134
+ init = _mds2(D)
135
+ init = (init - init.mean(0)) / (init.std(0) + 1e-9) * 1e-4
136
+
137
+ return TSNE(
138
+ metric="precomputed",
139
+ init=init.astype(np.float64),
140
+ perplexity=perp,
141
+ random_state=seed,
142
+ ).fit_transform(D.astype(np.float64))
143
+
144
+
145
+ def _mds2(D):
146
+ dist_sq = D.astype(float) ** 2
147
+ gram = -0.5 * (
148
+ dist_sq
149
+ - dist_sq.mean(0, keepdims=True)
150
+ - dist_sq.mean(1, keepdims=True)
151
+ + dist_sq.mean()
152
+ )
153
+ uvec, sval, _ = np.linalg.svd(gram, full_matrices=False)
154
+
155
+ return uvec[:, :2] * np.sqrt(
156
+ np.maximum(sval[:2], 0.0)
157
+ ) # classical scaling: U @ sqrt(Lambda)
158
+
159
+
160
+ def _pmds_embed(cols, dim):
161
+ dist_sq = cols.astype(float) ** 2
162
+ gram = -0.5 * (
163
+ dist_sq
164
+ - dist_sq.mean(0, keepdims=True)
165
+ - dist_sq.mean(1, keepdims=True)
166
+ + dist_sq.mean()
167
+ )
168
+ uvec, sval, _ = np.linalg.svd(gram, full_matrices=False)
169
+ n_comp = min(dim, uvec.shape[1])
170
+ emb = uvec[:, :n_comp] * sval[:n_comp]
171
+
172
+ return (emb - emb.mean(0)) / (emb.std(0) + 1e-9)
173
+
174
+
175
+ class _MLP(torch.nn.Module):
176
+ def __init__(self, dim_in, dim_out=2):
177
+ super().__init__()
178
+ self.net = torch.nn.Sequential(
179
+ torch.nn.Linear(dim_in, 256),
180
+ torch.nn.LeakyReLU(),
181
+ torch.nn.Linear(256, 512),
182
+ torch.nn.LeakyReLU(),
183
+ torch.nn.Linear(512, 256),
184
+ torch.nn.LeakyReLU(),
185
+ torch.nn.Linear(256, dim_out),
186
+ )
187
+
188
+ def forward(self, feat):
189
+ return self.net(feat)
190
+
191
+
192
+ def _train_mlp(feat, target, rows, epochs, batch, lr, seed):
193
+ torch.manual_seed(seed)
194
+ net = _MLP(feat.shape[1])
195
+ opt = torch.optim.Adam(net.parameters(), lr=lr)
196
+ rows = np.asarray(rows)
197
+ inputs = feat[torch.as_tensor(rows, dtype=torch.long)]
198
+ targets = torch.as_tensor(target, dtype=torch.float32)
199
+ n_rows = len(rows)
200
+ rng = np.random.default_rng(seed)
201
+
202
+ for _ in range(epochs):
203
+ perm = rng.permutation(n_rows)
204
+
205
+ for start in range(0, n_rows, batch):
206
+ idx = perm[start : start + batch]
207
+ loss = ((net(inputs[idx]) - targets[idx]) ** 2).mean()
208
+ opt.zero_grad()
209
+ loss.backward()
210
+ opt.step()
211
+
212
+ return net
213
+
214
+
215
+ class NNPNet:
216
+ def __init__(
217
+ self,
218
+ n_components=2,
219
+ emb=50,
220
+ pmds_pivots=250,
221
+ perp=40,
222
+ epochs=40,
223
+ batch=64,
224
+ lr=1e-3,
225
+ seed=0,
226
+ ):
227
+ self.n_components = n_components
228
+ self.emb = emb
229
+ self.pmds_pivots = pmds_pivots
230
+ self.perp = perp
231
+ self.epochs = epochs
232
+ self.batch = batch
233
+ self.lr = lr
234
+ self.seed = seed
235
+
236
+ def fit(self, graph, train_nodes=None):
237
+ nodes = list(graph.nodes())
238
+ idx = {node: i for i, node in enumerate(nodes)}
239
+
240
+ train = np.array(
241
+ [idx[node] for node in (nodes if train_nodes is None else train_nodes)]
242
+ )
243
+
244
+ _, cols = farthest_pivots(
245
+ graph, min(self.pmds_pivots, len(train) - 1), among=train, seed=self.seed
246
+ )
247
+
248
+ feat = torch.tensor(
249
+ _pmds_embed(cols, self.emb), dtype=torch.float32
250
+ ) # PivotMDS input, all nodes
251
+
252
+ dist_tr = all_pairs_D(graph)[
253
+ np.ix_(train, train)
254
+ ] # tsNET* target on the train nodes
255
+
256
+ target = tsnet_star(dist_tr, self.seed, self.perp)
257
+ target = (target - target.mean(0)) / (target.std(0) + 1e-9)
258
+ t_start = time.perf_counter()
259
+
260
+ self.net_ = _train_mlp(
261
+ feat, target, train, self.epochs, self.batch, self.lr, self.seed
262
+ )
263
+ self.fit_time_ = time.perf_counter() - t_start
264
+ self.nodes_ = nodes
265
+
266
+ self.edges_ = (
267
+ np.array(
268
+ [[idx[src], idx[dst]] for src, dst in graph.edges()], dtype=np.int64
269
+ )
270
+ if graph.number_of_edges()
271
+ else np.empty((0, 2), np.int64)
272
+ )
273
+
274
+ with torch.no_grad():
275
+ self.embedding_ = self.net_(feat).cpu().numpy().astype(np.float64)
276
+
277
+ return self
278
+
279
+ def fit_transform(self, graph, train_nodes=None):
280
+ return self.fit(graph, train_nodes).embedding_
281
+
282
+
283
+ # Simonetto, Archambault, Auber and Bourqui, "ImPrEd: An Improved Force-Directed Algorithm that
284
+ # Prevents Nodes Crossing Edges", Computer Graphics Forum 30(3):1071-1080, 2011 (EuroVis),
285
+ # refining PrEd (Bertault, GD 2000). Structure follows the reference implementation accompanying
286
+ # Pupyrev's 2026 evaluation (github.com/spupyrev/planar-vibe, MIT).
287
+ def _seg_point_dist(px, py, ax, ay, bx, by):
288
+ # distance from each point to each segment, and the closest point on it: (N,1)x(1,E)->(N,E)
289
+ vx, vy = bx - ax, by - ay
290
+ wx, wy = px - ax, py - ay
291
+ vv = vx * vx + vy * vy
292
+
293
+ t = np.where(vv > 1e-12, (wx * vx + wy * vy) / np.maximum(vv, 1e-12), 0.0)
294
+ t = np.clip(t, 0.0, 1.0)
295
+
296
+ cx, cy = ax + t * vx, ay + t * vy
297
+
298
+ return np.hypot(px - cx, py - cy), cx, cy
299
+
300
+
301
+ def _ray_seg_t(px, py, dx, dy, ax, ay, bx, by):
302
+ # distance along ray (p, d) to segment (a, b). Returns inf if it does not hit. Broadcasts.
303
+ ex, ey = bx - ax, by - ay
304
+ den = dx * ey - dy * ex
305
+ ok = np.abs(den) > 1e-12
306
+ den = np.where(ok, den, 1.0)
307
+
308
+ qx, qy = ax - px, ay - py
309
+
310
+ t = (qx * ey - qy * ex) / den # along the ray
311
+ u = (qx * dy - qy * dx) / den # along the segment
312
+
313
+ hit = ok & (t > 1e-9) & (u >= 0.0) & (u <= 1.0)
314
+
315
+ return np.where(hit, t, np.inf)
316
+
317
+
318
+ def _crossed(pos0, pos1, edges, tol=0.01):
319
+ # (node, edge) pairs where the node moved through the edge: side flips, foot stays inside
320
+ def sides(p):
321
+ a, b = p[edges[:, 0]], p[edges[:, 1]]
322
+ v = (b - a)[None, :, :]
323
+ w = p[:, None, :] - a[None, :, :]
324
+ cr = v[..., 0] * w[..., 1] - v[..., 1] * w[..., 0]
325
+ vv = (v**2).sum(-1)
326
+ t = np.where(vv > 1e-12, (w * v).sum(-1) / np.maximum(vv, 1e-12), -1.0)
327
+
328
+ return np.sign(cr), (t > 0.0) & (t < 1.0)
329
+
330
+ s0, in0 = sides(pos0)
331
+ s1, in1 = sides(pos1)
332
+
333
+ inc = np.zeros((len(pos0), len(edges)), bool)
334
+ inc[edges[:, 0], np.arange(len(edges))] = True
335
+ inc[edges[:, 1], np.arange(len(edges))] = True
336
+
337
+ return (s0 != s1) & in0 & in1 & ~inc & (s0 != 0)
338
+
339
+
340
+ def impred(
341
+ pos,
342
+ edges,
343
+ iters=100,
344
+ n_sectors=8,
345
+ gamma=None,
346
+ seed=0,
347
+ w_edge=1.0,
348
+ w_node=1.0,
349
+ w_nodeedge=1.0,
350
+ cool=None,
351
+ chunk=256,
352
+ damp=0.5,
353
+ verbose=False,
354
+ ):
355
+ # `pos` is the drawing to refine (n, 2), `edges` an (E, 2) index array. `gamma` is the
356
+ # node-edge interaction radius, defaulting to the median edge length.
357
+ pos = np.array(pos, float, copy=True)
358
+ edges = np.asarray(edges, int)
359
+ n, E = len(pos), len(edges)
360
+
361
+ seg = np.linalg.norm(pos[edges[:, 0]] - pos[edges[:, 1]], axis=1)
362
+ scale = float(np.median(seg[seg > 0])) if np.any(seg > 0) else 1.0
363
+ gamma = scale if gamma is None else gamma
364
+ step_max = 0.5 * scale
365
+
366
+ inc = np.zeros((n, E), bool)
367
+ inc[edges[:, 0], np.arange(E)] = True
368
+ inc[edges[:, 1], np.arange(E)] = True
369
+
370
+ sec_ang = (np.arange(n_sectors) + 0.5) * (2 * np.pi / n_sectors) - np.pi
371
+ sec_dx, sec_dy = np.cos(sec_ang), np.sin(sec_ang)
372
+ sector_w = 2.0 * np.pi / n_sectors
373
+
374
+ # cooling is tied to the iteration count, not a fixed per-step factor
375
+ cool = (0.1 ** (1.0 / max(iters, 1))) if cool is None else cool
376
+ temp = 1.0
377
+
378
+ for _it in range(iters):
379
+ prev = pos.copy()
380
+ disp = np.zeros_like(pos)
381
+
382
+ # (1) edge attraction toward the rest length
383
+ d = pos[edges[:, 1]] - pos[edges[:, 0]]
384
+ L = np.linalg.norm(d, axis=1, keepdims=True)
385
+ u = d / np.maximum(L, 1e-12)
386
+ f = w_edge * (L - scale) / scale * u
387
+
388
+ np.add.at(disp, edges[:, 0], f)
389
+ np.add.at(disp, edges[:, 1], -f)
390
+
391
+ # (2) node-node repulsion, only within gamma
392
+ for i, j in cKDTree(pos).query_pairs(gamma, output_type="ndarray"):
393
+ dv = pos[i] - pos[j]
394
+ dist = max(float(np.hypot(*dv)), 1e-9)
395
+ g = w_node * (gamma - dist) / dist * dv
396
+
397
+ disp[i] += g
398
+ disp[j] -= g
399
+
400
+ # (3) node-edge repulsion, and (4) the per-sector movement limits
401
+ limit = np.full((n, n_sectors), step_max)
402
+
403
+ for lo in range(0, n, chunk):
404
+ hi = min(lo + chunk, n)
405
+ px, py = pos[lo:hi, 0][:, None], pos[lo:hi, 1][:, None]
406
+ ax, ay = pos[edges[:, 0], 0][None, :], pos[edges[:, 0], 1][None, :]
407
+ bx, by = pos[edges[:, 1], 0][None, :], pos[edges[:, 1], 1][None, :]
408
+ dist, cx, cy = _seg_point_dist(px, py, ax, ay, bx, by)
409
+ dist = np.where(inc[lo:hi], np.inf, dist)
410
+
411
+ near = (dist < gamma) & np.isfinite(dist)
412
+ if near.any():
413
+ ni, ei = np.nonzero(near)
414
+ dv = np.stack([px[ni, 0] - cx[ni, ei], py[ni, 0] - cy[ni, ei]], 1)
415
+ dd = np.maximum(np.linalg.norm(dv, axis=1, keepdims=True), 1e-9)
416
+ g = w_nodeedge * ((gamma - dd) ** 2) / (gamma * dd) * dv
417
+ np.add.at(disp, ni + lo, g)
418
+ np.add.at(disp, edges[ei, 0], -0.5 * g)
419
+ np.add.at(disp, edges[ei, 1], -0.5 * g)
420
+
421
+ reach = (dist < 3.0 * step_max) & np.isfinite(
422
+ dist
423
+ ) # farther edges are unreachable
424
+
425
+ if reach.any():
426
+ ni, ei = np.nonzero(reach)
427
+
428
+ for s in range(n_sectors):
429
+ t = _ray_seg_t(
430
+ pos[ni + lo, 0],
431
+ pos[ni + lo, 1],
432
+ sec_dx[s],
433
+ sec_dy[s],
434
+ pos[edges[ei, 0], 0],
435
+ pos[edges[ei, 0], 1],
436
+ pos[edges[ei, 1], 0],
437
+ pos[edges[ei, 1], 1],
438
+ )
439
+
440
+ np.minimum.at(limit, (ni + lo, np.full(len(ni), s)), t)
441
+
442
+ limit = np.maximum(limit - 1e-4, 0.0)
443
+
444
+ # (5) move, clamped to the limit of the sector the displacement points into
445
+ mag = np.linalg.norm(disp, axis=1)
446
+
447
+ if not (mag > 1e-12).any():
448
+ break
449
+
450
+ dsec = np.floor((np.arctan2(disp[:, 1], disp[:, 0]) + np.pi) / sector_w).astype(
451
+ int
452
+ )
453
+
454
+ cap = np.minimum(limit[np.arange(n), dsec % n_sectors], step_max) * temp
455
+
456
+ pos += (
457
+ disp
458
+ * np.where(mag > 1e-12, np.minimum(1.0, cap / np.maximum(mag, 1e-12)), 0.0)[
459
+ :, None
460
+ ]
461
+ )
462
+
463
+ # (6) the guarantee: revert any node that went through an edge, and damp it
464
+ bad = _crossed(prev, pos, edges)
465
+ n_bad, full = int(bad.any() and len(np.unique(np.nonzero(bad)[0]))), False
466
+
467
+ if bad.any():
468
+ for _ in range(6):
469
+ vi, ei = np.nonzero(bad)
470
+ revert = np.unique(np.concatenate([vi, edges[ei, 0], edges[ei, 1]]))
471
+ pos[revert] = prev[revert]
472
+ bad = _crossed(prev, pos, edges)
473
+
474
+ if not bad.any():
475
+ break
476
+
477
+ if bad.any():
478
+ pos = prev
479
+ full = True
480
+ temp *= damp
481
+
482
+ if verbose:
483
+ print(
484
+ f" it{_it:>4} step={np.linalg.norm(pos - prev, axis=1).mean():.5f} "
485
+ f"cap_med={np.median(cap):.4f} force_med={np.median(mag):.4f} "
486
+ f"offenders={n_bad} full_rollback={full} temp={temp:.4f}",
487
+ flush=True,
488
+ )
489
+
490
+ temp *= cool
491
+
492
+ return pos