File size: 15,686 Bytes
f956d64
 
 
4288025
 
 
 
f956d64
4288025
f956d64
4288025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ceee520
4288025
 
 
 
 
 
f956d64
 
94e47b0
79cd0aa
f956d64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4288025
 
 
f956d64
 
 
 
 
 
 
 
 
4288025
f956d64
 
 
 
 
 
 
 
 
 
 
 
4288025
 
 
 
 
 
 
 
 
e52951c
 
 
 
 
 
 
 
 
 
 
4288025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324791f
4288025
 
 
 
324791f
 
 
 
 
 
 
4288025
 
 
 
 
 
 
 
324791f
4288025
324791f
4288025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e52951c
 
 
 
 
 
 
4288025
e52951c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4288025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324791f
 
 
 
 
 
 
f956d64
 
 
324791f
 
 
 
 
f956d64
 
 
 
4288025
 
 
 
 
f956d64
79cd0aa
 
f956d64
 
 
 
 
 
 
 
 
 
 
 
4288025
 
f956d64
 
 
4288025
f956d64
4288025
f956d64
 
 
4288025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f956d64
4288025
 
 
f956d64
 
4288025
 
 
 
 
 
64aa288
 
 
 
4288025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64aa288
 
4288025
 
 
 
 
 
 
 
 
f956d64
 
79cd0aa
 
 
 
f956d64
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Uniform transformation signature — the same visual vocabulary for
// what ANY step did to the circuit, whether it's QuCAD pruning,
// CompVQC folding, a transpile, or a user plugin. The executor
// captures before/after structural snapshots centrally; this module
// renders them as a designed GLYPH (the "delta strip") rather than
// text chips, so that a composition of steps can be read as a row of
// small multiples and compared at a glance.
//
// ── Delta-strip design rationale (cited in the paper) ──────────────
//
// 1. FIXED CHANNEL ORDER. The strip always shows the same four
//    channels in the same order, top-to-bottom: D(epth), G(ates),
//    P(arams), Q(ubits). Position — not a label — identifies the
//    channel, which is what makes the glyph learnable: after seeing
//    two or three strips the reader stops decoding and starts
//    pattern-matching ("top-heavy strip = depth optimizer"). The
//    cost-like channels (D, G, P — the things optimizers try to
//    shrink) sit together at the top; the width channel (Q) anchors
//    the bottom. We use horizontal bars stacked vertically, mirrored
//    around a CENTER VERTICAL zero axis, because at tile scale
//    (14px tall) four 2px-high rows still give each bar ~20px of
//    horizontal run to encode magnitude — the transposed variant
//    (vertical bars) would compress magnitude into ±6px, below
//    useful resolution.
//
// 2. RELATIVE-CHANGE NORMALIZATION. Bar length encodes
//    delta / before, capped at ±100%. Absolute deltas are
//    incomparable across circuits (−6 depth is dramatic on a depth-12
//    circuit, noise on depth-600); normalizing by the BEFORE value
//    makes "halved the depth" the same visual size on any circuit,
//    which is the invariant a comparison table needs. The cap keeps
//    growth (e.g. transpile blow-ups) from destroying the scale; the
//    printed numbers carry exactness where it matters. A channel
//    that appears from zero (before=0, delta>0, e.g. parameters
//    introduced by an ansatz) renders at full scale.
//
// 3. DIVERGING ENCODING WITH GOAL-ANCHORED COLOR. Bars extend LEFT
//    of the axis for decreases (ok/green — every optimizer in this
//    catalog aims to shrink cost channels) and RIGHT for increases
//    (warn/amber). Qubit-count changes are neutral (accent/blue in
//    either direction): at these scales width is a property, not a
//    cost, and pruning a qubit is not automatically "good". Sign is
//    thus double-encoded (side + hue) and survives both colorblind
//    viewing and grayscale print.
//
// 4. CONSTANT SILHOUETTE. Zero-change channels render as a faint
//    tick on the axis instead of disappearing. Every strip therefore
//    has the same 4-row frame; glyph recognition (and step-aligned
//    comparison across runs) depends on that constant frame — a
//    missing row would re-introduce per-glyph decoding.
//
// All fills use currentColor driven by the theme token classes
// (text-ok / text-warn / text-accent / text-mute), so the glyph
// re-colors under both themes (dark / light) for free.
//
// Two densities:
//   size="tile"  — 46×14, no labels (tooltip carries numbers); for
//                  canvas nodes and comparison-table cells;
//   size="card"  — 180×56, with channel letters + printed deltas;
//                  for the results pane.

import type { StepResult } from "../lib/api";
import CircuitDiff from "./CircuitDiff";
import { useApp } from "../lib/store";

export interface TransformationPayload {
  before: {
    num_qubits: number;
    depth: number;
    size: number;
    num_parameters: number;
    ops: Record<string, number>;
  } | null;
  after: TransformationPayload["before"];
  delta: {
    num_qubits: number;
    depth: number;
    size: number;
    num_parameters: number;
  };
  ops_delta: Record<string, number>;
  changed: boolean;
}

export function transformationOf(
  step: StepResult | undefined | null,
): TransformationPayload | null {
  const t = step?.transformation;
  if (!t || typeof t !== "object") return null;
  return t as unknown as TransformationPayload;
}

// Fixed strip order (design point 1). This array is the single
// source of truth: glyph rows, tooltip lines and the numeric grid
// all iterate it, so every surface presents channels identically.
const CHANNELS: Array<{
  key: keyof TransformationPayload["delta"];
  short: string;
  label: string;
  neutral?: boolean;
}> = [
  { key: "depth", short: "D", label: "depth" },
  { key: "size", short: "G", label: "gates" },
  { key: "num_parameters", short: "P", label: "params" },
  { key: "num_qubits", short: "Q", label: "qubits", neutral: true },
];

function deltaTone(v: number, neutral?: boolean): string {
  if (v === 0) return "text-mute";
  if (neutral) return "text-accent";
  return v < 0 ? "text-ok" : "text-warn";
}

function fmtDelta(v: number): string {
  return v > 0 ? `+${v}` : `${v}`;
}

/** Relative change, capped at ±1 (design point 2). before<=0 with a
 *  nonzero delta means the channel appeared from nothing — render at
 *  full scale in the delta's direction. */
function relChange(before: number | undefined, delta: number): number {
  if (delta === 0) return 0;
  if (!before || before <= 0) return delta > 0 ? 1 : -1;
  return Math.max(-1, Math.min(1, delta / before));
}

/** True when the capped encoding is saturated: |Δ/before| ≥ 100% (or
 *  the channel appeared from nothing). A saturated bar is rendered at
 *  the cap, so without a marker a 100% change and a 400% change look
 *  identical — the glyph must disclose "≥ cap", not pretend "= cap"
 *  (audit fix: silent saturation is a lie of omission). */
function isSaturated(before: number | undefined, delta: number): boolean {
  if (delta === 0) return false;
  if (!before || before <= 0) return true;
  return Math.abs(delta / before) >= 1;
}

function sigTooltip(t: TransformationPayload): string {
  return `Circuit transformation (Δ / before):\n${CHANNELS.map((c) => {
    const b = t.before ? t.before[c.key] : 0;
    return `${c.label}: ${fmtDelta(t.delta[c.key])} (was ${b})`;
  }).join("\n")}`;
}

// Per-density geometry. Tile numbers are tuned so the strip stays
// legible at 100% zoom on a canvas node: 2px bars with 1px gaps read
// as distinct rows down to ~12px total height.
const GEOM = {
  tile: {
    w: 46,
    h: 14,
    barH: 2,
    gap: 1,
    padY: 1.5,
    cx: 23,
    half: 20,
    minBar: 2, // a real change is never mistaken for a zero tick
    tickW: 1,
    labels: false,
  },
  card: {
    w: 180,
    h: 56,
    barH: 5,
    gap: 9,
    padY: 4.5,
    cx: 94,
    half: 44,
    minBar: 3,
    tickW: 1.5,
    labels: true,
  },
} as const;

/** The delta-strip glyph itself, rendering a raw transformation
 *  payload. Exported so the canvas tile, the results card and the
 *  comparison table all draw the exact same encoding. */
export function SignatureGlyph({
  t,
  size = "tile",
  className = "",
  stretch = false,
}: {
  t: TransformationPayload;
  size?: "tile" | "card";
  className?: string;
  /** Fill the parent's width (preserveAspectRatio="none"). Only the
   *  horizontal axis stretches, and every bar scales by the same
   *  factor around the centered zero axis — the relative-magnitude
   *  encoding is invariant under this transform, so a stretched
   *  strip stays comparable with an unstretched one. Used on canvas
   *  node faces where the glyph anchors the full tile width. */
  stretch?: boolean;
}) {
  const g = GEOM[size];
  const aria = `delta-strip: ${CHANNELS.map(
    (c) => `${c.label} ${fmtDelta(t.delta[c.key])}`,
  ).join(", ")}`;
  return (
    <svg
      viewBox={`0 0 ${g.w} ${g.h}`}
      width={stretch ? "100%" : g.w}
      height={g.h}
      preserveAspectRatio={stretch ? "none" : "xMidYMid meet"}
      className={`delta-strip ${className}`}
      role="img"
      aria-label={aria}
    >
      {/* zero axis — part of the constant frame (design point 4) */}
      <line
        x1={g.cx}
        y1={0.5}
        x2={g.cx}
        y2={g.h - 0.5}
        stroke="currentColor"
        strokeWidth={1}
        className="text-mute"
        opacity={0.45}
      />
      {CHANNELS.map((c, i) => {
        const y = g.padY + i * (g.barH + g.gap);
        const cy = y + g.barH / 2;
        const d = t.delta[c.key];
        const rel = relChange(t.before ? t.before[c.key] : 0, d);
        const tone = deltaTone(d, c.neutral);
        let bar;
        if (d === 0) {
          // faint tick: keeps the 4-row silhouette constant
          bar = (
            <rect
              x={g.cx - g.tickW / 2}
              y={y}
              width={g.tickW}
              height={g.barH}
              fill="currentColor"
              className="text-mute"
              opacity={0.35}
            />
          );
        } else {
          const len = Math.max(g.minBar, Math.abs(rel) * g.half);
          const saturated = isSaturated(t.before ? t.before[c.key] : 0, d);
          // Outward arrowhead at the bar tip when the ±100% cap is
          // hit: the bar cannot grow past the cap, so the notch says
          // "at least this much" instead of silently reading as
          // exactly 100%.
          const aw = size === "card" ? 3.5 : 2;
          const tipX = rel < 0 ? g.cx - len : g.cx + len;
          bar = (
            <>
              <rect
                x={rel < 0 ? g.cx - len : g.cx}
                y={y}
                width={len}
                height={g.barH}
                rx={size === "card" ? 1 : 0.5}
                fill="currentColor"
                className={tone}
                opacity={0.9}
              />
              {saturated && (
                <path
                  d={
                    rel < 0
                      ? `M ${tipX} ${y - 1} L ${tipX - aw} ${y + g.barH / 2} L ${tipX} ${y + g.barH + 1} Z`
                      : `M ${tipX} ${y - 1} L ${tipX + aw} ${y + g.barH / 2} L ${tipX} ${y + g.barH + 1} Z`
                  }
                  fill="currentColor"
                  className={tone}
                  opacity={0.9}
                />
              )}
            </>
          );
        }
        return (
          <g key={c.key}>
            {bar}
            {g.labels && (
              <>
                <text
                  x={8}
                  y={cy + 3}
                  fontSize={8}
                  fill="currentColor"
                  className="text-mute font-mono"
                >
                  {c.short}
                </text>
                <text
                  x={g.w - 4}
                  y={cy + 3}
                  fontSize={8}
                  textAnchor="end"
                  fill="currentColor"
                  className={`${tone} font-mono`}
                >
                  {d === 0 ? "·" : fmtDelta(d)}
                </text>
              </>
            )}
          </g>
        );
      })}
    </svg>
  );
}

/** Compact canvas-tile form. Renders nothing for pass-through steps
 *  — an unchanged circuit needs no ink on the canvas (the constant-
 *  silhouette rule applies WITHIN a strip; whether to show a strip
 *  at all is the node's call, and canvas real estate is scarce). */
export function SignatureTile({
  step,
  stretch = false,
}: {
  step: StepResult;
  stretch?: boolean;
}) {
  const t = transformationOf(step);
  if (!t || !t.changed) return null;
  return (
    <div
      className={`mt-1 leading-none ${stretch ? "w-full" : ""}`}
      title={sigTooltip(t)}
    >
      <SignatureGlyph t={t} size="tile" stretch={stretch} />
    </div>
  );
}

/** Full results-card form: card-size glyph beside the before → after
 *  numeric grid (the glyph gives shape, the numbers give exactness),
 *  then a per-op diverging bar list. Pass-through steps get an
 *  explicit one-liner so the reader can tell "read the circuit, left
 *  it alone" from "no circuit in scope at all" (renders nothing). */
export function SignatureCard({ step }: { step: StepResult }) {
  // Scenario F5: gate diffs on QuCAD cards boot expanded.
  const gateDiffDefaultOpen = useApp((s) => s.gateDiffDefaultOpen);
  const t = transformationOf(step);
  if (!t) return null;
  if (!t.changed) {
    return (
      <div className="text-[10px] text-mute mt-1">
        Circuit pass-through — this step read the circuit but did not
        modify it.
      </div>
    );
  }
  const b = t.before;
  const a = t.after;
  // Per-op detail, sorted by |delta| so the biggest structural edit
  // leads; same diverging left/right + ok/warn encoding as the strip.
  const opEntries = Object.entries(t.ops_delta).sort(
    (x, y) => Math.abs(y[1]) - Math.abs(x[1]),
  );
  const opMax = Math.max(1, ...opEntries.map(([, d]) => Math.abs(d)));
  return (
    <div className="panel-alt p-2 mt-1 space-y-2">
      <div className="text-[10px] uppercase tracking-wider text-mute">
        circuit transformation
      </div>
      <div className="flex flex-wrap items-start gap-x-4 gap-y-2">
        <SignatureGlyph t={t} size="card" className="shrink-0" />
        <div className="grid grid-cols-2 gap-x-4 gap-y-1 flex-1 min-w-[140px]">
          {CHANNELS.map((c) => {
            const d = t.delta[c.key];
            return (
              <div key={c.key} className="text-[10px]">
                <div className="text-mute">{c.label}</div>
                <div className="font-mono">
                  {b ? b[c.key] : 0}
                  <span className="text-mute"> → </span>
                  {a ? a[c.key] : 0}
                  {d !== 0 && (
                    <span className={`ml-1 ${deltaTone(d, c.neutral)}`}>
                      {fmtDelta(d)}
                    </span>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
      {opEntries.length > 0 && (
        <div className="space-y-0.5">
          {opEntries.map(([op, d]) => {
            // bar width as % of the half-track, normalized by the
            // largest |op delta| in THIS step (op counts are only
            // comparable within a step, unlike the channel strip)
            const pct = (Math.abs(d) / opMax) * 50;
            // Width floor BEFORE the side offset (audit S3): floors
            // applied at render time pushed a tiny negative bar across
            // the centerline onto the positive side.
            const wPct = Math.max(pct, 2);
            return (
              <div
                key={op}
                className="flex items-center gap-1.5 text-[9px] font-mono leading-none"
                title={`${op}: ${fmtDelta(d)} gates`}
              >
                <span className="w-14 shrink-0 truncate text-right text-mute">
                  {op}
                </span>
                <div className="relative h-2 w-24 shrink-0">
                  <div className="absolute inset-y-0 left-1/2 w-px bg-mute/40" />
                  <div
                    className={`absolute top-0.5 bottom-0.5 rounded-sm ${
                      d < 0 ? "bg-ok/80" : "bg-warn/80"
                    }`}
                    style={{
                      left: d < 0 ? `${50 - wPct}%` : "50%",
                      width: `${wPct}%`,
                    }}
                  />
                </div>
                <span className={d < 0 ? "text-ok" : "text-warn"}>
                  {fmtDelta(d)}
                </span>
              </div>
            );
          })}
        </div>
      )}
      <CircuitDiff
        t={t}
        defaultOpen={gateDiffDefaultOpen && step.node_type === "qucad"}
      />
    </div>
  );
}