Files
nav-carte/utils/connaissances/graphe.ts
T

170 lines
7.0 KiB
TypeScript

/**
* graphe — B19b M4. La géométrie de `GrapheConnaissances`, sortie du `.vue` (DESIGN-SYSTEM
* §Vue fiches : la logique pure vit dans `utils/`) et testée par
* `scripts/test-connaissances.mjs`. Fonctions pures, mêmes signatures qu'en B19 ; aucune
* connaissance de la couche, de la vue fiches ni du DOM : B9 réécrit les reprend telles quelles.
*
* - `disposer` : force simple à graine fixe, positions dans un repère sans unité, centré,
* d'étendue 1 (aucune position en données) ;
* - `disposerEnCache` : la même, mémorisée par signature du graphe (une fois par processus) ;
* - `voisinage` : identifiants à `pas` liens au plus d'un nœud (graphe local d'Obsidian) ;
* - `boite` : boîte englobante d'un ensemble de points, une seule écriture pour le dessin et la caméra ;
* - `amorcer` (B9) : pose au cache une disposition calculée ailleurs, sous la même signature.
*/
/** Un nœud : `kind` dit sa forme (principal si dans `kindsPrincipaux`, sinon secondaire). */
export interface NoeudGraphe { id: string; libelle: string; kind: string; poids?: number }
export interface LienGraphe { de: string; vers: string; type: string; provenance: string }
export type Pas = 1 | 2 | 'tout'
export type Pt = { x: number; y: number }
export interface Boite { x0: number; x1: number; y0: number; y1: number }
/** Boîte englobante ; vide = bornes infinies (`Number.isFinite(b.x0)` est faux). */
export function boite(points: Iterable<Pt>): Boite {
let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity
for (const p of points) { x0 = Math.min(x0, p.x); x1 = Math.max(x1, p.x); y0 = Math.min(y0, p.y); y1 = Math.max(y1, p.y) }
return { x0, x1, y0, y1 }
}
/** PRNG à graine fixe (mulberry32) : même graphe, même dessin, au serveur comme au navigateur. */
function alea(graine: number) {
let a = graine >>> 0
return () => {
a = (a + 0x6d2b79f5) >>> 0
let t = a
t = Math.imul(t ^ (t >>> 15), t | 1)
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
/**
* Force simple (Fruchterman-Reingold), graine fixe, nombre de pas fixe : positions dans un
* repère sans unité, centré, d'étendue 1. Fonction pure de (nœuds, liens, principaux).
*/
export function disposer(noeuds: NoeudGraphe[], liens: LienGraphe[], principaux: Set<string>): Map<string, Pt> {
const n = noeuds.length
const pos = new Map<string, Pt>()
if (!n) return pos
const rnd = alea(0x9e3779b9)
const index = new Map(noeuds.map((x, i) => [x.id, i]))
const aretes = liens
.map((l) => [index.get(l.de), index.get(l.vers)] as const)
.filter((a): a is readonly [number, number] => a[0] != null && a[1] != null && a[0] !== a[1])
const voisins: number[][] = noeuds.map(() => [])
for (const [a, b] of aretes) { voisins[a].push(b); voisins[b].push(a) }
// Départ : les principaux en cercle, chaque secondaire au barycentre de ses voisins principaux.
const prin = noeuds.map((x, i) => (principaux.has(x.kind) ? i : -1)).filter((i) => i >= 0)
const X = new Float64Array(n)
const Y = new Float64Array(n)
prin.forEach((i, k) => {
const t = (2 * Math.PI * k) / Math.max(prin.length, 1)
X[i] = 0.4 * Math.cos(t)
Y[i] = 0.4 * Math.sin(t)
})
noeuds.forEach((x, i) => {
if (principaux.has(x.kind)) return
const v = voisins[i].filter((j) => principaux.has(noeuds[j].kind))
if (v.length) {
X[i] = (v.reduce((s, j) => s + X[j], 0) / v.length) * 1.35 + (rnd() - 0.5) * 0.08
Y[i] = (v.reduce((s, j) => s + Y[j], 0) / v.length) * 1.35 + (rnd() - 0.5) * 0.08
} else {
X[i] = (rnd() - 0.5) * 0.9
Y[i] = (rnd() - 0.5) * 0.9
}
})
const k = 0.9 * Math.sqrt(1 / n)
const ITER = 350
const dx = new Float64Array(n)
const dy = new Float64Array(n)
for (let it = 0; it < ITER; it++) {
const temp = 0.08 * (1 - it / ITER) + 0.002
dx.fill(0)
dy.fill(0)
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
let ex = X[i] - X[j]
let ey = Y[i] - Y[j]
let d = Math.hypot(ex, ey)
if (d < 1e-4) { ex = (rnd() - 0.5) * 1e-3; ey = (rnd() - 0.5) * 1e-3; d = Math.hypot(ex, ey) }
const f = (k * k) / d
dx[i] += (ex / d) * f; dy[i] += (ey / d) * f
dx[j] -= (ex / d) * f; dy[j] -= (ey / d) * f
}
}
for (const [a, b] of aretes) {
const ex = X[a] - X[b]
const ey = Y[a] - Y[b]
const d = Math.max(Math.hypot(ex, ey), 1e-4)
const f = (d * d) / k
dx[a] -= (ex / d) * f; dy[a] -= (ey / d) * f
dx[b] += (ex / d) * f; dy[b] += (ey / d) * f
}
for (let i = 0; i < n; i++) {
dx[i] -= X[i] * 0.9 * k * 4
dy[i] -= Y[i] * 0.9 * k * 4
const d = Math.hypot(dx[i], dy[i])
if (d > 0) {
const m = Math.min(d, temp)
X[i] += (dx[i] / d) * m
Y[i] += (dy[i] / d) * m
}
}
}
// Centré, étendue 1 (le plus grand côté de la boîte englobante)
const { x0, x1, y0, y1 } = boite(Array.from(X, (x, i) => ({ x, y: Y[i] })))
const e = Math.max(x1 - x0, y1 - y0) || 1
noeuds.forEach((x, i) => pos.set(x.id, { x: (X[i] - (x0 + x1) / 2) / e, y: (Y[i] - (y0 + y1) / 2) / e }))
return pos
}
/** Cache par signature du graphe : au serveur, une fois par processus, pas une fois par requête. */
const CACHE = new Map<string, Map<string, Pt>>()
const signature = (noeuds: NoeudGraphe[], liens: LienGraphe[], principaux: Set<string>) =>
JSON.stringify([noeuds.map((x) => [x.id, x.kind]), liens.map((l) => [l.de, l.vers]), [...principaux]])
function garder(sig: string, p: Map<string, Pt>) {
if (CACHE.size > 24) CACHE.delete(CACHE.keys().next().value as string)
CACHE.set(sig, p)
}
export function disposerEnCache(noeuds: NoeudGraphe[], liens: LienGraphe[], principaux: Set<string>): Map<string, Pt> {
const sig = signature(noeuds, liens, principaux)
let p = CACHE.get(sig)
if (!p) {
p = disposer(noeuds, liens, principaux)
garder(sig, p)
}
return p
}
/**
* Lot B9 : une disposition déjà calculée (l'arborescence de la bibliothèque, radiale, en O(n)) entre
* au cache sous la signature du graphe ; `disposerEnCache` la rend sans calculer de force. Mêmes
* nœuds, liens et kinds principaux que ceux que recevra le composant, dans le même ordre.
*/
export function amorcer(noeuds: NoeudGraphe[], liens: LienGraphe[], principaux: Set<string>, p: Map<string, Pt>): void {
garder(signature(noeuds, liens, principaux), p)
}
/** Identifiants à `pas` liens au plus de `id` (le nœud compris) ; `tout` = tous. */
export function voisinage(liens: LienGraphe[], id: string, pas: Pas): Set<string> | null {
if (pas === 'tout') return null
const adj = new Map<string, string[]>()
for (const l of liens) {
if (!adj.has(l.de)) adj.set(l.de, [])
if (!adj.has(l.vers)) adj.set(l.vers, [])
adj.get(l.de)!.push(l.vers)
adj.get(l.vers)!.push(l.de)
}
const vus = new Set([id])
let front = [id]
for (let p = 0; p < pas; p++) {
const suite: string[] = []
for (const x of front) for (const y of adj.get(x) ?? []) if (!vus.has(y)) { vus.add(y); suite.push(y) }
front = suite
}
return vus
}