SPB Git

Repository Public

viz.js 36.3 KB 290 lines javascript

1/*2 * SP CLIP scene kit — bibliothèque de VISUALISATION scientifique et financière (chargée après kit3.js, s'appuie sur SKN pour les calculs).3 * Principe : la scène ne dessine jamais un chiffre « à la main ». Les valeurs viennent de SKN (calcul validé par des tests), d'un calcul Python4 * en bac à sable (SK.data) ou des faits vérifiés du script ; les graduations et valeurs posées par cette bibliothèque portent `data-computed`5 * (elles échappent au contrôle « chiffre absent des faits », mais la scène doit alors afficher SK.provenance(...)).6 *7 *  SK.viz.plot(o)      repère cartésien : P.fn, P.series, P.points, P.bars, P.path, P.vline, P.hline, P.marker, P.field, P.sx, P.sy8 *  SK.viz.heatmap(o)   matrice colorée (attention, corrélations)            SK.viz.tokens(o) / SK.viz.arcs(o)   jetons et liens d'attention9 *  SK.viz.network(o)   réseau de neurones en couches, impulsions            SK.viz.flow(o)   schéma d'architecture (boîtes, flux, paquets)10 *  SK.viz.candles(o)   chandeliers                                           SK.viz.orderbook(o)   carnet d'ordres en profondeur11 *  SK.viz.surface(o)   surface 3D z = f(x, y) projetée (canvas), caméra en orbite12 * Tous acceptent `parent` (sélecteur ou élément SVG ; défaut : le premier svg.sk-art ou calque data-depth="0") et des instants "@repère".13 */14(function () {15  "use strict";16  var SK = window.SK; if (!SK || !SK.T) return;17  var U = SK.U, T = SK.T, el = SK.el, anim = SK.anim, NS = "http://www.w3.org/2000/svg";18  var q = function (s) { return typeof s === "string" ? document.querySelector(s) : s; };19  var parentOf = function (o) { return q(o && o.parent) || document.querySelector('svg[data-depth="0"]') || document.querySelector("svg.sk-art") || document.querySelector(".scene svg:not(.sk-decor)"); };20  var txt = function (g, x, y, s, o) {21    o = o || {};22    var t = el("text", { x: x, y: y, "text-anchor": o.anchor || "middle", "dominant-baseline": o.base || "central", "font-size": o.size || 2.7 * U, "font-weight": o.weight || 500, text: s }, g);23    t.style.fill = o.color || "var(--soft)"; if (o.computed !== false) t.setAttribute("data-computed", ""); if (o.mono) t.style.fontFamily = "var(--mono)";24    return t;25  };26  var fade = function (e, at, dur) { if (at != null) anim(e, [{ opacity: 0 }, { opacity: 1 }], { at: at, dur: dur == null ? 0.5 : dur }); return e; };27  var fmt = function (v, dec) { var s = Math.abs(v).toFixed(dec == null ? (Math.abs(v) >= 100 ? 0 : Math.abs(v) >= 10 ? 1 : 2) : dec).replace(".", ","); return (v < 0 ? "−" : "") + s.replace(/\B(?=(\d{3})+(?!\d))/g, " "); };28  var niceTicks = function (lo, hi, n) { var span = hi - lo, step = Math.pow(10, Math.floor(Math.log10(span / n))), err = span / n / step; step *= err >= 7.5 ? 10 : err >= 3.5 ? 5 : err >= 1.5 ? 2 : 1; var out = [], v = Math.ceil(lo / step - 1e-9) * step; for (; v <= hi + 1e-9; v += step) out.push(Math.round(v / step) * step); return out; };29  function mixColor(a, b, u) {30    var pa = SK.color(a).match(/[\d.]+/g).map(Number), pb = SK.color(b).match(/[\d.]+/g).map(Number), aa = pa[3] == null ? 1 : pa[3], ab = pb[3] == null ? 1 : pb[3];31    return "rgba(" + [0, 1, 2].map(function (i) { return Math.round(pa[i] + (pb[i] - pa[i]) * u); }).join(",") + "," + (aa + (ab - aa) * u).toFixed(3) + ")";32  }3334  /* ════════ repère cartésien ════════ */35  /**36   * var P = SK.viz.plot({ x, y, w, h, xRange: [0, 10], yRange: [0, 1], axes: true, grid: true, ticks: 5 | { x: [...], y: [...] } | false,37   *   xLabel, yLabel, at: "@axes", decimals, xFormat: v => "…", yFormat })38   * (x, y) = coin haut gauche de la zone de tracé, en pixels. Sans `ticks`, aucun chiffre n'est écrit (graphique qualitatif).39   */40  function plot(o) {41    var g = el("g", { "class": "sk-plot" }, parentOf(o)), xr = o.xRange, yr = o.yRange, at = o.at == null ? null : T(o.at);42    var sx = function (v) { return o.x + (v - xr[0]) / (xr[1] - xr[0]) * o.w; }, sy = function (v) { return o.y + o.h - (v - yr[0]) / (yr[1] - yr[0]) * o.h; };43    var tk = o.ticks === false || o.ticks == null ? null : typeof o.ticks === "number" ? { x: niceTicks(xr[0], xr[1], o.ticks), y: niceTicks(yr[0], yr[1], o.ticks) } : o.ticks;44    var trim = function (v) { return o.decimals != null ? fmt(v, o.decimals) : fmt(v, 4).replace(/,?0+$/, ""); };45    var fx = o.xFormat || trim, fy = o.yFormat || trim;46    var back = el("g", {}, g);47    if (o.grid !== false && tk) {48      (tk.y || []).forEach(function (v) { el("path", { d: "M" + o.x + " " + sy(v) + " H" + (o.x + o.w), stroke: "var(--t-line)", "stroke-width": 0.12 * U, opacity: 0.35, fill: "none" }, back); });49      (tk.x || []).forEach(function (v) { el("path", { d: "M" + sx(v) + " " + o.y + " V" + (o.y + o.h), stroke: "var(--t-line)", "stroke-width": 0.12 * U, opacity: 0.2, fill: "none" }, back); });50    }51    if (o.axes !== false) {52      var y0 = yr[0] <= 0 && yr[1] >= 0 ? sy(0) : o.y + o.h, x0 = xr[0] <= 0 && xr[1] >= 0 && o.yAxisAtZero ? sx(0) : o.x;53      var ax = el("path", { d: "M" + x0 + " " + o.y + " V" + (o.y + o.h) + " M" + o.x + " " + y0 + " H" + (o.x + o.w), stroke: "var(--soft)", "stroke-width": 0.28 * U, "stroke-linecap": "round", fill: "none", opacity: 0.85 }, back);54      if (at != null) SK.draw(ax, { at: at, dur: 0.9 });55    }56    if (tk) {57      (tk.x || []).forEach(function (v) { fade(txt(back, sx(v), o.y + o.h + 3 * U, fx(v), { mono: true }), at == null ? null : at + 0.4); });58      (tk.y || []).forEach(function (v) { fade(txt(back, o.x - 1.6 * U, sy(v), fy(v), { anchor: "end", mono: true }), at == null ? null : at + 0.4); });59    }60    if (o.xLabel) fade(txt(back, o.x + o.w / 2, o.y + o.h + (tk ? 7 : 3.6) * U, o.xLabel, { computed: false, size: 2.9 * U, color: "var(--muted)" }), at == null ? null : at + 0.5);61    if (o.yLabel) { var yl = txt(back, o.x - (tk ? 9 : 3) * U, o.y + o.h / 2, o.yLabel, { computed: false, size: 2.9 * U, color: "var(--muted)" }); yl.setAttribute("transform", "rotate(-90 " + (o.x - (tk ? 9 : 3) * U) + " " + (o.y + o.h / 2) + ")"); fade(yl, at == null ? null : at + 0.5); }62    if (at != null) fade(back.querySelectorAll("path:not(:last-of-type)").length ? back : back, null);63    var pathOf = function (pts) { return pts.map(function (p, i) { return (i ? "L" : "M") + sx(p[0]).toFixed(1) + " " + sy(p[1]).toFixed(1); }).join(" "); };64    var P = {65      g: g, sx: sx, sy: sy, x: o.x, y: o.y, w: o.w, h: o.h,66      /** Courbe d'une fonction : P.fn(x => Math.sin(x), { color, width, at, dur, samples, area, dashed, dot }) */67      fn: function (f, c) { c = c || {}; var n = c.samples || 160, pts = []; for (var i = 0; i <= n; i++) { var xv = xr[0] + (xr[1] - xr[0]) * i / n, yv = f(xv); if (isFinite(yv)) pts.push([xv, Math.max(yr[0] - (yr[1] - yr[0]), Math.min(yr[1] + (yr[1] - yr[0]), yv))]); } return P.path(pts, c); },68      /** Série de points reliés : P.series(xs, ys, { … }) */69      series: function (xs, ys, c) { return P.path(xs.map(function (xv, i) { return [xv, ys[i]]; }), c); },70      /** Tracé par points [[x, y], …] en coordonnées de données ; options : color, width, at, dur, area, dashed, dot (point qui suit le tracé), ease */71      path: function (pts, c) {72        c = c || {};73        var d = pathOf(pts), col = c.color || "var(--gold)", w = c.width || 0.6 * U, t = c.at == null ? null : T(c.at), dur = c.dur == null ? 1.6 : c.dur, grp = el("g", {}, g);74        if (o.clip !== false) { var id = "skc" + Math.floor(Math.random() * 1e9), cp = el("clipPath", { id: id }, grp); el("rect", { x: o.x, y: o.y - U, width: o.w, height: o.h + 2 * U }, cp); grp.setAttribute("clip-path", "url(#" + id + ")"); }75        if (c.area) { var a = el("path", { d: d + " L" + sx(pts[pts.length - 1][0]) + " " + sy(Math.max(yr[0], 0)) + " L" + sx(pts[0][0]) + " " + sy(Math.max(yr[0], 0)) + " Z", fill: col, opacity: c.areaOpacity || 0.16 }, grp); if (t != null) anim(a, [{ clipPath: "inset(0 100% 0 0)" }, { clipPath: "inset(0 0 0 0)" }], { at: t, dur: dur, ease: c.ease || "inout" }); }76        var p = el("path", { d: d, fill: "none", stroke: col, "stroke-width": w, "stroke-linecap": "round", "stroke-linejoin": "round" }, grp);77        if (c.dashed) { p.setAttribute("stroke-dasharray", w * 2 + " " + w * 2.2); if (t != null) anim(p, [{ clipPath: "inset(-50% 100% -50% 0)" }, { clipPath: "inset(-50% 0 -50% 0)" }], { at: t, dur: dur, ease: c.ease || "inout" }); }78        else if (t != null) SK.draw(p, { at: t, dur: dur, ease: c.ease || "inout" });79        if (c.dot && t != null) {80          var dot = el("circle", { r: w * 1.9, fill: col, stroke: "var(--bg)", "stroke-width": w * 0.5 }, g), L = p.getTotalLength(), e = SK.E[c.ease] || SK.E.inout;81          SK.onFrame(function (tt) { var u = e(SK.clamp01((tt - t) / dur)), pt = p.getPointAtLength(u * L); dot.setAttribute("cx", pt.x); dot.setAttribute("cy", pt.y); dot.style.opacity = tt < t ? 0 : 1; });82        }83        return p;84      },85      /** Nuage de points : P.points([[x, y], …] ou [{ x, y, color, r, label }], { color, r, at, stagger }) */86      points: function (pts, c) {87        c = c || {}; var t = c.at == null ? null : T(c.at), grp = el("g", {}, g);88        pts.forEach(function (p, i) { var xv = p.x == null ? p[0] : p.x, yv = p.y == null ? p[1] : p.y, ci = el("circle", { cx: sx(xv), cy: sy(yv), r: p.r || c.r || 0.7 * U, fill: p.color || c.color || "var(--p)", opacity: c.opacity || 0.92 }, grp); if (t != null) SK.enter(ci, "pop", { at: t + i * (c.stagger == null ? Math.min(0.03, 1.2 / pts.length) : c.stagger), dur: 0.45 }); if (p.label) txt(grp, sx(xv), sy(yv) - 2.4 * U, p.label, { computed: false, color: "var(--text)" }); });89        return grp;90      },91      /** Histogramme / barres : P.bars(edges (n+1) ou centres (n), heights, { color, at, stagger, gap }) */92      bars: function (xs, hs, c) {93        c = c || {}; var t = c.at == null ? null : T(c.at), grp = el("g", {}, g), n = hs.length, edges = xs.length === n + 1 ? xs : null, bw = edges ? null : (xs[1] - xs[0]);94        hs.forEach(function (hv, i) { var a = edges ? edges[i] : xs[i] - bw / 2, b = edges ? edges[i + 1] : xs[i] + bw / 2, gp = (c.gap == null ? 0.12 : c.gap) * (sx(b) - sx(a)), r = el("rect", { x: sx(a) + gp / 2, y: sy(Math.max(hv, 0)), width: Math.max(1, sx(b) - sx(a) - gp), height: Math.abs(sy(hv) - sy(0)), rx: 0.3 * U, fill: c.color || "var(--p)", opacity: c.opacity || 0.85, "data-origin": "bottom" }, grp); if (t != null) SK.enter(r, "grow-y", { at: t + i * (c.stagger == null ? 0.02 : c.stagger), dur: 0.6 }); });95        return grp;96      },97      vline: function (xv, c) { c = c || {}; var p = el("path", { d: "M" + sx(xv) + " " + (o.y + o.h) + " V" + o.y, stroke: c.color || "var(--gold)", "stroke-width": c.width || 0.3 * U, "stroke-dasharray": c.solid ? "" : U + " " + U, fill: "none" }, g); if (c.at != null) SK.draw(p, { at: T(c.at), dur: 0.6 }); if (c.label) fade(txt(g, sx(xv), o.y - 2 * U, c.label, { computed: !!c.computed, color: c.color || "var(--gold)", size: 3 * U, weight: 600 }), c.at == null ? null : T(c.at) + 0.3); return p; },98      hline: function (yv, c) { c = c || {}; var p = el("path", { d: "M" + o.x + " " + sy(yv) + " H" + (o.x + o.w), stroke: c.color || "var(--gold)", "stroke-width": c.width || 0.3 * U, "stroke-dasharray": c.solid ? "" : U + " " + U, fill: "none" }, g); if (c.at != null) SK.draw(p, { at: T(c.at), dur: 0.6 }); if (c.label) fade(txt(g, o.x + o.w - U, sy(yv) - 2 * U, c.label, { computed: !!c.computed, anchor: "end", color: c.color || "var(--gold)", size: 3 * U, weight: 600 }), c.at == null ? null : T(c.at) + 0.3); return p; },99      /** Point repère avec halo et étiquette : P.marker(x, y, { label, color, at, pulse }) */100      marker: function (xv, yv, c) { c = c || {}; var m = el("g", { transform: "translate(" + sx(xv) + " " + sy(yv) + ")" }, g), col = c.color || "var(--gold)"; var halo = el("circle", { r: 2.2 * U, fill: col, opacity: 0.25 }, m); el("circle", { r: 0.9 * U, fill: col, stroke: "var(--bg)", "stroke-width": 0.25 * U }, m); if (c.pulse !== false) SK.loop(halo, "pulse", { dur: 1.1, amp: 0.5 }); if (c.label) txt(m, 0, -3.6 * U, c.label, { computed: !!c.computed, color: "var(--text)", size: 3 * U, weight: 600 }); if (c.at != null) SK.enter(m, "pop", { at: T(c.at) }); return m; },101      /** Champ de vecteurs (résultat de SKN.vectorField) : P.field(F, { color, at, scale }) */102      field: function (F, c) { c = c || {}; var t = c.at == null ? null : T(c.at), grp = el("g", {}, g), cell = Math.min(o.w / F.xs.length, o.h / F.ys.length) * (c.scale || 0.8); F.points.forEach(function (p, i) { if (!p.mag) return; var L = cell * (0.35 + 0.65 * p.mag / F.maxMag), a = Math.atan2(-p.v, p.u), x1 = sx(p.x), y1 = sy(p.y), x2 = x1 + Math.cos(a) * L, y2 = y1 + Math.sin(a) * L, h = Math.max(0.5 * U, L * 0.28); var ar = el("path", { d: "M" + x1 + " " + y1 + " L" + x2 + " " + y2 + " M" + (x2 - Math.cos(a - 0.5) * h) + " " + (y2 - Math.sin(a - 0.5) * h) + " L" + x2 + " " + y2 + " L" + (x2 - Math.cos(a + 0.5) * h) + " " + (y2 - Math.sin(a + 0.5) * h), stroke: c.color || mixColor("var(--s)", "var(--gold)", p.mag / F.maxMag), "stroke-width": 0.22 * U, "stroke-linecap": "round", fill: "none", opacity: 0.85 }, grp); if (t != null) anim(ar, [{ opacity: 0 }, { opacity: 0.85 }], { at: t + (i % F.xs.length + Math.floor(i / F.xs.length)) * 0.025, dur: 0.4 }); }); return grp; }103    };104    return P;105  }106107  /* ════════ matrice colorée ════════ */108  /**109   * SK.viz.heatmap({ x, y, w, h, matrix, rows: ["Le", …], cols: […], at, stagger: .02, low: "var(--t-surface)", high: "var(--gold)", values: false, gap })110   * → { g, cell(i, j) → <rect>, focusRow(i, { at }), focusCell(i, j, { at }) }. Les cellules s'allument en diagonale.111   */112  function heatmap(o) {113    var g = el("g", { "class": "sk-heat" }, parentOf(o)), M = o.matrix, n = M.length, m = M[0].length, gap = o.gap == null ? 0.4 * U : o.gap, cw = (o.w - gap * (m - 1)) / m, ch = (o.h - gap * (n - 1)) / n, at = o.at == null ? null : T(o.at), cells = [], max = o.max || Math.max.apply(null, M.map(function (r) { return Math.max.apply(null, r); })) || 1, lo = o.low || "rgba(255,255,255,.06)", hi = o.high || "var(--gold)";114    M.forEach(function (row, i) {115      cells.push([]);116      row.forEach(function (v, j) {117        var x = o.x + j * (cw + gap), y = o.y + i * (ch + gap), r = el("rect", { x: x, y: y, width: cw, height: ch, rx: Math.min(cw, ch) * 0.16, fill: mixColor(SK.color(lo), SK.color(hi), Math.pow(v / max, 0.8)) }, g);118        if (at != null) anim(SK.el ? r : r, [{ opacity: 0, scale: 0.6 }, { opacity: 1, scale: 1 }], { at: at + (i + j) * (o.stagger == null ? 0.035 : o.stagger), dur: 0.45, ease: "back" });119        r.style.transformBox = "fill-box"; r.style.transformOrigin = "center";120        if (o.values) fade(txt(g, x + cw / 2, y + ch / 2, fmt(v, o.decimals == null ? 2 : o.decimals), { size: Math.min(ch * 0.36, cw * 0.3), color: v / max > 0.55 ? "#1a1408" : "var(--text)", mono: true }), at == null ? null : at + (i + j) * 0.035 + 0.2);121        cells[i].push(r);122      });123      if (o.rows) fade(txt(g, o.x - 1.4 * U, o.y + i * (ch + gap) + ch / 2, o.rows[i], { anchor: "end", computed: false, size: Math.min(3.2 * U, ch * 0.5), color: "var(--text)" }), at);124    });125    if (o.cols) o.cols.forEach(function (c, j) { fade(txt(g, o.x + j * (cw + gap) + cw / 2, o.y - 2.2 * U, c, { computed: false, size: Math.min(3.2 * U, cw * 0.34), color: "var(--text)" }), at); });126    var dim = function (keep, t) { cells.forEach(function (row, i) { row.forEach(function (r, j) { if (!keep(i, j)) anim(r, [{ opacity: 0.22 }], { at: t, dur: 0.5, fill: "forwards" }); }); }); };127    return { g: g, cell: function (i, j) { return cells[i][j]; }, cw: cw, ch: ch,128      focusRow: function (i, c) { dim(function (a) { return a === i; }, T((c || {}).at)); },129      focusCell: function (i, j, c) { var t = T((c || {}).at); dim(function (a, b) { return a === i && b === j; }, t); var r = cells[i][j]; var ring = el("rect", { x: r.getAttribute("x") - 0.3 * U, y: r.getAttribute("y") - 0.3 * U, width: cw + 0.6 * U, height: ch + 0.6 * U, rx: Math.min(cw, ch) * 0.2, fill: "none", stroke: "var(--text)", "stroke-width": 0.35 * U }, g); SK.draw(ring, { at: t, dur: 0.5 }); } };130  }131132  /* ════════ jetons et liens d'attention ════════ */133  /** SK.viz.tokens({ x, y, tokens: ["Le", "chat"], at, stagger, size, gap, color }) → { g, items: [{ el, cx, cy, w, h }], highlight(i, { at, color }) } ; (x, y) = centre de la rangée. */134  function tokens(o) {135    var g = el("g", { "class": "sk-tokens" }, parentOf(o)), size = o.size || 3.6 * U, pad = size * 0.7, h = size * 2, gap = o.gap == null ? size * 0.45 : o.gap, at = o.at == null ? null : T(o.at), items = [], total = 0;136    var ws = o.tokens.map(function (s) { var t = el("text", { "font-size": size, "font-weight": 600, text: s }, g), w = t.getComputedTextLength() + 2 * pad; t.remove(); return w; });137    total = ws.reduce(function (a, b) { return a + b; }, 0) + gap * (ws.length - 1);138    var x = o.x - total / 2;139    o.tokens.forEach(function (s, i) {140      var cx = x + ws[i] / 2, it = el("g", { transform: "translate(" + cx + " " + o.y + ")" }, g);141      var r = el("rect", { x: -ws[i] / 2, y: -h / 2, width: ws[i], height: h, rx: h * 0.28, fill: o.color || "var(--t-surface)", stroke: "var(--t-line)", "stroke-width": 0.22 * U }, it);142      var t = el("text", { "text-anchor": "middle", "dominant-baseline": "central", "font-size": size, "font-weight": 600, text: s }, it); t.style.fill = "var(--text)";143      if (at != null) SK.enter(it, o.fx || "pop", { at: at + i * (o.stagger == null ? 0.1 : o.stagger) });144      items.push({ el: it, rect: r, text: t, cx: cx, cy: o.y, w: ws[i], h: h }); x += ws[i] + gap;145    });146    return { g: g, items: items, width: total, highlight: function (i, c) { c = c || {}; anim(items[i].rect, [{ fill: c.color || "var(--gold)", stroke: c.color || "var(--gold)" }], { at: T(c.at), dur: 0.4, fill: "forwards" }); anim(items[i].text, [{ fill: "#1a1408" }], { at: T(c.at), dur: 0.4, fill: "forwards" }); } };147  }148  /** SK.viz.arcs({ tokens: T (résultat de SK.viz.tokens), from: 3, weights: [..] (ligne de SKN.attention().weights), at, color, above: true }) : arcs d'épaisseur proportionnelle au poids. */149  function arcs(o) {150    var g = el("g", { "class": "sk-arcs" }, o.tokens.g), it = o.tokens.items, a = it[o.from], at = T(o.at), max = Math.max.apply(null, o.weights) || 1, sign = o.above === false ? 1 : -1;151    o.tokens.g.insertBefore(g, o.tokens.g.firstChild);152    o.weights.forEach(function (w, j) {153      if (j === o.from || w / max < 0.04) return;154      var b = it[j], y0 = a.cy + sign * a.h / 2, lift = Math.min(26 * U, Math.abs(b.cx - a.cx) * 0.42 + 4 * U);155      var p = el("path", { d: "M" + a.cx + " " + y0 + " C" + a.cx + " " + (y0 + sign * lift) + " " + b.cx + " " + (y0 + sign * lift) + " " + b.cx + " " + y0, fill: "none", stroke: o.color || "var(--gold)", "stroke-width": Math.max(0.18 * U, 1.3 * U * w / max), "stroke-linecap": "round", opacity: 0.25 + 0.75 * w / max }, g);156      SK.draw(p, { at: at + j * 0.06, dur: 0.7 });157    });158    return g;159  }160161  /* ════════ réseau de neurones ════════ */162  /**163   * SK.viz.network({ x, y, w, h, layers: [3, 5, 5, 2], at, stagger, r, labels: ["Entrée", …], pulses: { at, every: .5, count: 6, color }, weights: fn(l, i, j) → −1..1 })164   * → { g, node(l, i) → <circle>, activate(l, values 0..1, { at }) }. Les impulsions parcourent les liens de couche en couche (propagation avant).165   */166  function network(o) {167    var g = el("g", { "class": "sk-net" }, parentOf(o)), L = o.layers, at = o.at == null ? null : T(o.at), nodes = [], edges = el("g", {}, g), r = o.r || Math.min(2.4 * U, o.h / (Math.max.apply(null, L) * 2.8)), rnd = SK.rand(o.seed || 5);168    L.forEach(function (n, l) { nodes.push([]); for (var i = 0; i < n; i++) nodes[l].push({ x: o.x + (L.length === 1 ? o.w / 2 : o.w * l / (L.length - 1)), y: o.y + o.h / 2 + (i - (n - 1) / 2) * Math.min(o.h / Math.max(1, n - 1 || 1), r * 3.4) }); });169    var links = [];170    for (var l = 0; l < L.length - 1; l++) nodes[l].forEach(function (a, i) { nodes[l + 1].forEach(function (b, j) { var w = o.weights ? o.weights(l, i, j) : rnd() * 2 - 1, p = el("path", { d: "M" + a.x + " " + a.y + " L" + b.x + " " + b.y, stroke: w >= 0 ? "var(--p)" : "var(--s)", "stroke-width": 0.1 * U + Math.abs(w) * 0.32 * U, opacity: 0.16 + Math.abs(w) * 0.34, fill: "none" }, edges); if (at != null) SK.draw(p, { at: at + l * (o.stagger == null ? 0.35 : o.stagger) + 0.15, dur: 0.6 }); links.push({ l: l, a: a, b: b, w: w }); }); });171    nodes.forEach(function (layer, l) {172      layer.forEach(function (n, i) { n.el = el("circle", { cx: n.x, cy: n.y, r: r, fill: "var(--t-ink)", stroke: l === 0 ? "var(--p)" : l === L.length - 1 ? "var(--gold)" : "var(--soft)", "stroke-width": 0.32 * U }, g); n.core = el("circle", { cx: n.x, cy: n.y, r: r * 0.62, fill: l === L.length - 1 ? "var(--gold)" : "var(--p-hi)", opacity: 0 }, g); if (at != null) SK.enter(n.el, "pop", { at: at + l * (o.stagger == null ? 0.35 : o.stagger) + i * 0.04 }); });173      if (o.labels && o.labels[l]) fade(txt(g, layer[0].x, o.y + o.h + 3.4 * U, o.labels[l], { computed: false, size: 2.9 * U, color: "var(--muted)" }), at == null ? null : at + l * 0.35);174    });175    if (o.pulses) {176      var pc = o.pulses, t0 = T(pc.at), every = pc.every || 0.55, count = pc.count || 5, hop = pc.hop || 0.5, cv = SK.canvas({ layer: "mid" }), col = SK.color(pc.color || "var(--gold)"), world = g.closest("[data-depth]") || g.ownerSVGElement;177      cv.draw(function (ctx, t) {178        var m = (world.getScreenCTM ? g.getScreenCTM() : null); if (!m) return;179        ctx.fillStyle = col; ctx.globalCompositeOperation = "lighter";180        for (var k = 0; k < count; k++) { var lt = t - t0 - k * every; if (lt < 0) continue; var layer = Math.floor(lt / hop), u = SK.E.inout((lt - layer * hop) / hop); if (layer >= L.length - 1) continue; for (var e = 0; e < links.length; e++) { var ln = links[e]; if (ln.l !== layer || Math.abs(ln.w) < 0.35) continue; var x = ln.a.x + (ln.b.x - ln.a.x) * u, y = ln.a.y + (ln.b.y - ln.a.y) * u, X = m.a * x + m.c * y + m.e, Y = m.b * x + m.d * y + m.f; ctx.globalAlpha = 0.25 + 0.6 * Math.abs(ln.w); ctx.beginPath(); ctx.arc(X, Y, 0.42 * U * m.a, 0, 6.2832); ctx.fill(); } }181      });182      for (var k2 = 0; k2 < count; k2++) for (var l2 = 1; l2 < L.length; l2++) nodes[l2].forEach(function (n) { anim(n.core, [{ opacity: 0 }, { opacity: 0.95 }, { opacity: 0.25 }], { at: t0 + k2 * every + l2 * hop - 0.08, dur: 0.5, fill: "forwards" }); });183    }184    return { g: g, nodes: nodes, node: function (l, i) { return nodes[l][i].el; },185      activate: function (l, vals, c) { var t = T((c || {}).at); nodes[l].forEach(function (n, i) { anim(n.core, [{ opacity: Math.max(0.05, vals[i] == null ? 0 : vals[i]) }], { at: t + i * 0.04, dur: 0.4, fill: "forwards" }); }); } };186  }187188  /* ════════ schéma d'architecture ════════ */189  /**190   * SK.viz.flow({ nodes: [{ id, x, y, w, h, label, sub, color, icon: "#s-database", at }], edges: [{ from, to, at, label, dashed, bend, packets: 3 }], at })191   * (x, y) = centre de chaque boîte. Les paquets (petits points) circulent le long des liens à partir de leur `at` : flux de données, messages, jetons.192   * → { g, node(id) → <g>, pulse(id, { at }) }193   */194  function flow(o) {195    var g = el("g", { "class": "sk-flow" }, parentOf(o)), eg = el("g", {}, g), by = {}, base = o.at == null ? 0 : T(o.at);196    o.nodes.forEach(function (n, i) {197      var w = n.w || 26 * U, h = n.h || 12 * U, t = n.at == null ? base + i * 0.18 : T(n.at), it = el("g", { transform: "translate(" + n.x + " " + n.y + ")" }, g), col = n.color || "var(--p)";198      el("rect", { x: -w / 2, y: -h / 2 + 0.6 * U, width: w, height: h, rx: 1.8 * U, fill: "#000", opacity: 0.25 }, it);199      el("rect", { x: -w / 2, y: -h / 2, width: w, height: h, rx: 1.8 * U, fill: "var(--t-ink)", stroke: col, "stroke-width": 0.32 * U }, it);200      el("rect", { x: -w / 2, y: -h / 2, width: 0.9 * U, height: h, rx: 0.45 * U, fill: col }, it);201      var tx = n.icon ? -w / 2 + h * 0.95 : 0;202      if (n.icon) { var us = el("use", { href: n.icon, x: -w / 2 + h * 0.18, y: -h * 0.32, width: h * 0.64, height: h * 0.64 }, it); us.style.setProperty("--a", SK.color(col)); }203      var lab = el("text", { x: tx, y: n.sub ? -1.3 * U : 0, "text-anchor": n.icon ? "start" : "middle", "dominant-baseline": "central", "font-size": n.size || 3.2 * U, "font-weight": 600, text: n.label }, it); lab.style.fill = "var(--text)";204      if (n.sub) { var sb = el("text", { x: tx, y: 2.2 * U, "text-anchor": n.icon ? "start" : "middle", "dominant-baseline": "central", "font-size": 2.6 * U, text: n.sub }, it); sb.style.fill = "var(--muted)"; }205      SK.enter(it, "pop", { at: t, dur: 0.55 });206      if (n.beat) it.setAttribute("data-beat", n.beat);207      by[n.id] = { n: n, el: it, w: w, h: h, t: t };208    });209    var cv = null, packets = [];210    (o.edges || []).forEach(function (e, i) {211      var a = by[e.from], b = by[e.to]; if (!a || !b) { console.warn("SK.viz.flow : lien vers un nœud inconnu " + e.from + " → " + e.to); return; }212      var dx = b.n.x - a.n.x, dy = b.n.y - a.n.y, horiz = Math.abs(dx) * a.h >= Math.abs(dy) * a.w, x1 = a.n.x + (horiz ? Math.sign(dx) * a.w / 2 : 0), y1 = a.n.y + (horiz ? 0 : Math.sign(dy) * a.h / 2), x2 = b.n.x - (horiz ? Math.sign(dx) * (b.w / 2 + 1.4 * U) : 0), y2 = b.n.y - (horiz ? 0 : Math.sign(dy) * (b.h / 2 + 1.4 * U));213      var t = e.at == null ? Math.max(a.t, b.t) + 0.3 : T(e.at), bend = e.bend == null ? 0 : e.bend, mx = (x1 + x2) / 2 - (y2 - y1) * bend, my = (y1 + y2) / 2 + (x2 - x1) * bend;214      var d = horiz && !bend ? "M" + x1 + " " + y1 + " C" + (x1 + x2) / 2 + " " + y1 + " " + (x1 + x2) / 2 + " " + y2 + " " + x2 + " " + y2 : !horiz && !bend ? "M" + x1 + " " + y1 + " C" + x1 + " " + (y1 + y2) / 2 + " " + x2 + " " + (y1 + y2) / 2 + " " + x2 + " " + y2 : "M" + x1 + " " + y1 + " Q" + mx + " " + my + " " + x2 + " " + y2;215      var col = e.color || "var(--soft)", p = el("path", { d: d, fill: "none", stroke: col, "stroke-width": 0.3 * U, "stroke-linecap": "round", opacity: 0.8 }, eg), L = p.getTotalLength(), end = p.getPointAtLength(L), pre = p.getPointAtLength(L - 2), ang = Math.atan2(end.y - pre.y, end.x - pre.x) * 180 / Math.PI;216      if (e.dashed) p.setAttribute("stroke-dasharray", 0.9 * U + " " + 0.9 * U);217      if (e.dashed) fade(p, t, 0.6); else SK.draw(p, { at: t, dur: 0.6 });218      var hd = el("path", { d: "M0 0 L" + -1.6 * U + " " + -0.9 * U + " L" + -1.6 * U + " " + 0.9 * U + " Z", fill: col, transform: "translate(" + end.x + " " + end.y + ") rotate(" + ang + ")" }, eg); fade(hd, t + 0.45, 0.25);219      if (e.label) { var mid = p.getPointAtLength(L / 2); fade(txt(eg, mid.x, mid.y - 2 * U, e.label, { computed: false, size: 2.6 * U, color: "var(--muted)" }), t + 0.3); }220      if (e.packets) packets.push({ p: p, L: L, t: t + 0.5, n: e.packets, every: e.every || 0.35, dur: e.travel || 0.9, col: SK.color(e.packetColor || "var(--gold)"), loop: !!e.loop, idx: i });221    });222    if (packets.length) {223      cv = SK.canvas({ layer: "mid" });224      cv.draw(function (ctx, t) {225        var m = g.getScreenCTM(); if (!m) return; ctx.globalCompositeOperation = "lighter";226        packets.forEach(function (k) { for (var j = 0; j < k.n; j++) { var lt = t - k.t - j * k.every; if (k.loop && lt > 0) lt = lt % (k.n * k.every + k.dur); if (lt < 0 || lt > k.dur) continue; var u = SK.E.inout(lt / k.dur), pt = k.p.getPointAtLength(u * k.L), X = m.a * pt.x + m.c * pt.y + m.e, Y = m.b * pt.x + m.d * pt.y + m.f; ctx.fillStyle = k.col; ctx.globalAlpha = Math.min(1, Math.min(u, 1 - u) * 8 + 0.2); ctx.beginPath(); ctx.arc(X, Y, 0.62 * U * m.a, 0, 6.2832); ctx.fill(); ctx.globalAlpha *= 0.3; ctx.beginPath(); ctx.arc(X, Y, 1.5 * U * m.a, 0, 6.2832); ctx.fill(); } });227      });228    }229    return { g: g, node: function (id) { return by[id] && by[id].el; }, pulse: function (id, c) { var b = by[id]; if (!b) return; anim(b.el.querySelectorAll("rect")[1], [{ strokeWidth: 0.32 * U + "px" }, { strokeWidth: 0.9 * U + "px", offset: 0.4 }, { strokeWidth: 0.32 * U + "px" }], { at: T((c || {}).at), dur: 0.8 }); } };230  }231232  /* ════════ finance ════════ */233  /** SK.viz.candles({ x, y, w, h, bars: SKN.ohlcFromPath(...), at, dur, up: "var(--green)", down: "var(--coral)", yRange }) → { g, sy } — les chandeliers apparaissent dans l'ordre du temps. */234  function candles(o) {235    var g = el("g", { "class": "sk-candles" }, parentOf(o)), B = o.bars, n = B.length, lo = o.yRange ? o.yRange[0] : Math.min.apply(null, B.map(function (b) { return b.low; })), hi = o.yRange ? o.yRange[1] : Math.max.apply(null, B.map(function (b) { return b.high; })), pad = o.yRange ? 0 : (hi - lo) * 0.06, sy = function (v) { return o.y + o.h - (v - lo + pad) / (hi - lo + 2 * pad) * o.h; }, slot = o.w / n, bw = Math.max(2, slot * 0.62), at = o.at == null ? null : T(o.at), dur = o.dur == null ? 2 : o.dur;236    B.forEach(function (b, i) { var up = b.close >= b.open, col = up ? (o.up || "var(--green)") : (o.down || "var(--coral)"), cx = o.x + slot * (i + 0.5), it = el("g", {}, g); el("path", { d: "M" + cx + " " + sy(b.high) + " V" + sy(b.low), stroke: col, "stroke-width": Math.max(1.5, bw * 0.14), "stroke-linecap": "round" }, it); el("rect", { x: cx - bw / 2, y: sy(Math.max(b.open, b.close)), width: bw, height: Math.max(2, Math.abs(sy(b.open) - sy(b.close))), rx: Math.min(bw * 0.18, 0.4 * U), fill: col }, it); if (at != null) anim(it, [{ opacity: 0, translate: "0 " + 1.5 * U + "px" }, { opacity: 1, translate: "0 0" }], { at: at + dur * i / n, dur: 0.35 }); });237    return { g: g, sy: sy, slot: slot };238  }239  /**240   * SK.viz.orderbook({ x, y, w, h, book: SKN.orderBook(...), at, levels, bid: "var(--green)", ask: "var(--coral)", prices: true })241   * Carnet horizontal : achats à gauche du prix médian, ventes à droite, profondeur cumulée en escalier. → { g, consume(side, fills, { at }) } pour montrer un ordre au marché qui « mange » les niveaux.242   */243  function orderbook(o) {244    var g = el("g", { "class": "sk-book" }, parentOf(o)), bk = o.book, n = Math.min(o.levels || bk.bids.length, bk.bids.length), at = o.at == null ? null : T(o.at), half = o.w / 2, gapc = 0.8 * U, slot = (half - gapc) / n, maxQ = Math.max.apply(null, bk.bids.slice(0, n).concat(bk.asks.slice(0, n)).map(function (l) { return l.qty; })), rects = { buy: [], sell: [] };245    var side = function (levels, dir, col, key) { levels.slice(0, n).forEach(function (l, i) { var bh = o.h * 0.86 * l.qty / maxQ, x = o.x + half + dir * (gapc + slot * i) + (dir < 0 ? -slot * 0.9 : 0), r = el("rect", { x: x, y: o.y + o.h - bh, width: slot * 0.9, height: bh, rx: 0.4 * U, fill: col, opacity: 0.9 - i * 0.04, "data-origin": "bottom" }, g); if (at != null) SK.enter(r, "grow-y", { at: at + i * 0.06, dur: 0.6 }); rects[key].push(r); if (o.prices !== false && (i === 0 || i === n - 1)) fade(txt(g, x + slot * 0.45, o.y + o.h + 2.6 * U, fmt(l.price, o.decimals == null ? 2 : o.decimals), { size: 2.3 * U, mono: true }), at == null ? null : at + 0.3 + i * 0.06); }); };246    side(bk.bids, -1, o.bid || "var(--green)", "sell"); side(bk.asks, 1, o.ask || "var(--coral)", "buy");247    var mid = el("path", { d: "M" + (o.x + half) + " " + o.y + " V" + (o.y + o.h), stroke: "var(--text)", "stroke-width": 0.2 * U, "stroke-dasharray": 0.8 * U + " " + 0.8 * U, opacity: 0.7 }, g); fade(mid, at);248    return { g: g, consume: function (sd, fills, c) { var t = T((c || {}).at); fills.forEach(function (f, i) { var r = rects[sd][i]; if (!r) return; var lv = (sd === "buy" ? bk.asks : bk.bids)[i], part = f.qty / lv.qty; anim(r, [{ fill: SK.color("var(--gold)") }, { fill: SK.color("var(--gold)"), opacity: part >= 0.999 ? 0.12 : 0.5 }], { at: t + i * 0.28, dur: 0.5, fill: "forwards" }); }); } };249  }250251  /* ════════ surface 3D projetée (canvas 2D) ════════ */252  /**253   * SK.viz.surface({ x, y, w, h, grid: SKN.surface(...) ou { xs, ys, z } (ex. volSurface : xs = strikes, ys = maturities, z = iv), at, dur: 1.2 (la surface « pousse »),254   *   low: "var(--s)", high: "var(--gold)", wire: true, zScale: 1, keys: [{ at, yaw (deg), pitch (deg), zoom }], path: [[x, y], …] + pathAt/pathDur (trajet posé sur la surface, ex. descente de gradient) })255   * (x, y) = centre de la projection à l'écran ; w = largeur approximative occupée. Rendu par facettes triées (peintre), ombrage par la pente.256   */257  function surface(o) {258    var G = o.grid, xs = G.xs, ys = G.ys, Z = G.z, nx = xs.length, ny = ys.length, zMin = G.zMin == null ? Math.min.apply(null, Z.map(function (r) { return Math.min.apply(null, r); })) : G.zMin, zMax = G.zMax == null ? Math.max.apply(null, Z.map(function (r) { return Math.max.apply(null, r); })) : G.zMax, zs = (zMax - zMin) || 1;259    var cv = SK.canvas({ layer: o.layer || "mid" }), at = o.at == null ? 0 : T(o.at), grow = o.dur == null ? 1.2 : o.dur, zScale = o.zScale == null ? 1 : o.zScale;260    var cam = SK.track((o.keys || [{ at: 0, yaw: -35, pitch: 28, zoom: 1 }]).map(function (k, i) { var v = {}; ["yaw", "pitch", "zoom"].forEach(function (p) { if (k[p] != null) v[p] = k[p]; }); if (i === 0) v = { yaw: v.yaw == null ? -35 : v.yaw, pitch: v.pitch == null ? 28 : v.pitch, zoom: v.zoom == null ? 1 : v.zoom }; return { at: k.at, ease: k.ease || "cine", v: v }; }), "surface");261    var lo = SK.color(o.low || "var(--s)").match(/[\d.]+/g).map(Number), hi = SK.color(o.high || "var(--gold)").match(/[\d.]+/g).map(Number);262    var nrm = function (i, j) { return [(xs[i] - xs[0]) / (xs[nx - 1] - xs[0]) * 2 - 1, (ys[j] - ys[0]) / (ys[ny - 1] - ys[0]) * 2 - 1, ((Z[j][i] - zMin) / zs - 0.5) * 1.1 * zScale]; };263    var pathPts = o.path ? o.path.map(function (p) { var fx = (p[0] - xs[0]) / (xs[nx - 1] - xs[0]), fy = (p[1] - ys[0]) / (ys[ny - 1] - ys[0]), i = Math.min(nx - 2, Math.max(0, Math.floor(fx * (nx - 1)))), j = Math.min(ny - 2, Math.max(0, Math.floor(fy * (ny - 1)))), u = fx * (nx - 1) - i, v = fy * (ny - 1) - j, z = Z[j][i] * (1 - u) * (1 - v) + Z[j][i + 1] * u * (1 - v) + Z[j + 1][i] * (1 - u) * v + Z[j + 1][i + 1] * u * v; return [fx * 2 - 1, fy * 2 - 1, ((z - zMin) / zs - 0.5) * 1.1 * zScale]; }) : null;264    cv.draw(function (ctx, t) {265      if (t < at) return;266      var c = cam(t), g = SK.E.out(SK.clamp01((t - at) / grow)), yaw = c.yaw * Math.PI / 180, pit = c.pitch * Math.PI / 180, S = o.w * 0.36 * c.zoom, cy = Math.cos(yaw), sy = Math.sin(yaw), cp = Math.cos(pit), spn = Math.sin(pit), dist = 4.2;267      var pr = function (p) { var x = p[0] * cy - p[1] * sy, y = p[0] * sy + p[1] * cy, z = p[2] * g, d = y * cp + z * spn, up = -y * spn + z * cp, f = dist / (dist + d); return [o.x + x * S * f, o.y - up * S * f, d]; };268      var P = [], i, j; for (j = 0; j < ny; j++) { P.push([]); for (i = 0; i < nx; i++) P[j].push(pr(nrm(i, j))); }269      var faces = []; for (j = 0; j < ny - 1; j++) for (i = 0; i < nx - 1; i++) faces.push([i, j, (P[j][i][2] + P[j + 1][i + 1][2] + P[j][i + 1][2] + P[j + 1][i][2]) / 4]);270      faces.sort(function (a, b) { return b[2] - a[2]; });271      ctx.lineJoin = "round"; ctx.globalAlpha = Math.min(1, (t - at) / 0.4);272      for (var k = 0; k < faces.length; k++) {273        i = faces[k][0]; j = faces[k][1];274        var a = P[j][i], b = P[j][i + 1], cc = P[j + 1][i + 1], d = P[j + 1][i], zv = ((Z[j][i] + Z[j][i + 1] + Z[j + 1][i + 1] + Z[j + 1][i]) / 4 - zMin) / zs, sl = (Z[j][i + 1] - Z[j][i] + Z[j + 1][i + 1] - Z[j + 1][i]) / zs * (nx - 1) * 0.08, sh = Math.max(0.62, Math.min(1.22, 0.95 + sl * 0.5));275        ctx.fillStyle = "rgb(" + [0, 1, 2].map(function (q2) { return Math.round(Math.min(255, (lo[q2] + (hi[q2] - lo[q2]) * zv) * sh)); }).join(",") + ")";276        ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.lineTo(cc[0], cc[1]); ctx.lineTo(d[0], d[1]); ctx.closePath(); ctx.fill();277        if (o.wire !== false) { ctx.strokeStyle = "rgba(255,255,255,.14)"; ctx.lineWidth = 1; ctx.stroke(); } else { ctx.strokeStyle = ctx.fillStyle; ctx.lineWidth = 0.6; ctx.stroke(); }278      }279      if (pathPts) {280        var pa = T(o.pathAt == null ? at + grow : o.pathAt), u = SK.E.inout(SK.clamp01((t - pa) / (o.pathDur || 3))), upto = u * (pathPts.length - 1);281        if (t >= pa) { ctx.globalAlpha = 1; ctx.strokeStyle = SK.color(o.pathColor || "var(--text)"); ctx.lineWidth = 0.5 * U; ctx.lineCap = "round"; ctx.beginPath(); var last = null; for (var m = 0; m <= Math.floor(upto); m++) { var q3 = pr([pathPts[m][0], pathPts[m][1], pathPts[m][2] + 0.03]); if (m) ctx.lineTo(q3[0], q3[1]); else ctx.moveTo(q3[0], q3[1]); last = q3; } ctx.stroke(); if (last) { ctx.fillStyle = SK.color(o.pathColor || "var(--text)"); ctx.beginPath(); ctx.arc(last[0], last[1], 1.1 * U, 0, 6.2832); ctx.fill(); } }282      }283    });284    return { camera: cam };285  }286287  SK.viz = { plot: plot, heatmap: heatmap, tokens: tokens, arcs: arcs, network: network, flow: flow, candles: candles, orderbook: orderbook, surface: surface, mix: mixColor, fmt: fmt };288  void NS;289})();290
Files main
Menu

Theme