feat(quantum-alignment): Qiskit suite + Layer 101 browser-native sibling#22
feat(quantum-alignment): Qiskit suite + Layer 101 browser-native sibling#22slavazeph-coder wants to merge 3 commits into
Conversation
Adds quantum_alignment/ with a single-file Qiskit harness that runs three experiments (H-RZ-H interference sweep, mid-circuit measurement vs HH, deepening identity X-X chains) across three execution modes (ideal Aer, noisy Aer from a synthetic fake backend, and real IBM hardware via qiskit-ibm-runtime when IBM_QUANTUM_TOKEN is set). Outputs CSV, two matplotlib plots, and a plain-English report. README documents safe token handling and explicitly frames the suite as a test of quantum phase coherence/interference/noise -- not literal multiverse theory.
…e Qiskit suite Completes the in-browser side of the quantum-alignment work that landed in 6325d38 (which shipped only the Python/Qiskit harness under quantum_alignment/). The original task asked for "browser-native first, no backend, simulate locally in JavaScript" — that part wasn't built. This adds: - src/utils/quantumCoherence.js: complex/H/X/Z/RZ helpers, three experiments (phase / observation / decoherence) shaped to mirror the Qiskit circuits in quantum_alignment/quantum_alignment_tests.py, simple dephasing + bit-flip noise, coherenceScore, and mapQuantumToBrainState (PFC↑ coherence · AMY↑ noise · THL↑ routing · HPC↑ survival · BG↑ dominance · CBL↑ correction · CTX↑ complexity). - src/components/QuantumCoherencePanel.jsx: theta / shots / noise / depth / observe-midway controls, scientific ↔ metaphor mode toggle, P(0)/P(1) bars, coherence score 0–100, plain-English explanation, circuit-row visualization. Cross-links the Qiskit suite as the hardware-grade offline path. - App.jsx: wired with onApplyToBrain that nudges the 7 region levels. - layerCatalog: registered as L101 with new "experimental" group. - Tests: 18 cases via node:test (theta=0/π, observation, decoherence, noise/depth scaling, brain mapping). `npm run test:quantum`. - Docs: README section explicitly disclaims literal multiverse / consciousness / Planck / spiritual claims; cross-references the Qiskit suite for hardware runs. No vendor API keys in the frontend — IBM tokens stay in the Python suite (IBM_QUANTUM_TOKEN at runtime). npm install + npm run build pass. https://claude.ai/code/session_01VYArf8MTS6QdhmswtqNPox
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8cb1b5e49c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| state[0], | ||
| complex(state[1].re, state[1].im * k), |
There was a problem hiding this comment.
Model dephasing on both coherence components
This dephasing step only damps state[1].im, so states with purely real coherence are unaffected even at high noise. In runPhaseExperiment, the common θ=0 branch reaches [1/√2, 1/√2] before dephasing, making this function a no-op and preventing the expected interference damping toward 50/50. That yields systematically wrong phase/noise behavior for part of the sweep.
Useful? React with 👍 / 👎.
| let state = [complex(1, 0), complex(0, 0)]; | ||
| for (let i = 0; i < pairs; i += 1) { | ||
| state = applyX(state); |
There was a problem hiding this comment.
Add missing Hadamards in decoherence experiment
The function claims to mirror |0⟩ → H → (X X)^n → H → M, but it initializes |0⟩ and immediately enters the X X loop with no surrounding Hadamards. Without those H gates, the state stays in the computational basis, so the dephasing term cannot act on superposition and the experiment no longer matches the intended circuit semantics or the Qiskit sibling.
Useful? React with 👍 / 👎.
| const noisy = runDecoherenceExperiment({ xxPairs: 6, shots: SHOTS, noise: 0.7 }); | ||
| assert.ok( | ||
| noisy.distribution[0] < ideal.distribution[0], |
There was a problem hiding this comment.
Make decoherence noise test deterministic
This assertion compares a single noisy run against ideal even though runDecoherenceExperiment is stochastic (Math.random), so it intermittently fails when noisy and ideal both return P(0)=1. I reproduced this failure by rerunning the test several times. Averaging multiple trials or controlling randomness is needed to avoid CI flakiness.
Useful? React with 👍 / 👎.
Completes the quantum cluster on top of L101. All three layers are browser-native, no backend, no vendor API keys. Layer 102 — Bell Pair Lab - bellPair.js: 2-qubit state (4 amplitudes), H/X/RY/RZ-on-qubit, CNOT, joint distribution + sampling, signed correlationStrength. - runBellPairExperiment: |00⟩ → H ⊗ I → CNOT(0,1) → optional RY(θ) on qubit 0 → joint measurement. Depolarizing noise mixes the pure distribution with uniform [0.25 × 4] by weight `noise`. - mapBellToBrainState: HPC↑ correlation, PFC↑ |correlation|, CTX↑ shots, AMY↑ noise, THL↑ rotation, BG↑ dominance, CBL↑ noise·(1-|corr|). - BellPairPanel: RY-θ slider, noise slider, shots picker, joint bars for |00⟩|01⟩|10⟩|11⟩, signed correlation strength card, ASCII circuit diagram, Scientific ↔ Metaphor mode, Apply-to-brain. - 12 tests covering Hadamard / CNOT / Bell construction / rotation breakdown / noise damping / brain mapping bounds. Layer 103 — Quantum Sweep - quantumSweep.js: runSweep(kind: 'phase' | 'noise' | 'depth'), CSV serialization with the same column shape as quantum_alignment/results/results.csv, sweepSummary stats. - QuantumSweepPanel: kind picker, steps / shots / fixed-noise / fixed-θ / max-depth controls, inline SVG line chart of P(0) / P(1) vs the ideal curve, "Download CSV" button. - 9 tests covering sweep correctness, CSV escaping, summary math. Layer 104 — Quantum Glossary - QuantumGlossaryPanel: searchable reference card (23 terms across states / gates / processes / noise / metrics) with plain-language, math, and metaphor columns side-by-side. Complements the Metaphor toggle in L101 and L102. L101 noise model - Replaced random per-gate bit-flips with a single depolarizing-style distribution mix (matches L102 / L103). This makes runs deterministic in expectation, fixes a flaky decoherence test, and aligns with the "noise = mix toward uniform" reading the panel and glossary teach. Wiring - App.jsx: 3 new ErrorBoundary blocks, L102 wired with onApplyToBrain. - layerCatalog.js: L102 / L103 / L104 registered under the experimental group. - README.md: file-map rows for 102/103/104; Quantum Coherence Lab section gains a "cluster siblings" subsection summarizing all three. - package.json: test:quantum runs all three test files. 39/39 tests pass (`npm run test:quantum`). `npm run build` ✓ — index bundle 648 → 676 KB (+27 KB / +7 KB gzipped) for three new layers. https://claude.ai/code/session_01VYArf8MTS6QdhmswtqNPox
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3121c1a720
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| depth: Math.max(1, depth + 1), | ||
| observedMidway: observeMidway, |
There was a problem hiding this comment.
Exclude depth penalty when midway observation is active
When observeMidway is enabled, the panel runs runObservationExperiment (which ignores depth), but this score calculation still applies depth + 1, so users can lower coherence just by moving the depth slider without changing the executed circuit. That makes the reported coherence inconsistent with the actual experiment and can show severe false degradation after toggling observation on with a previously high depth.
Useful? React with 👍 / 👎.
| // depth-driven decoherence growth. | ||
| const ideal = [1, 0]; | ||
| const perPair = Math.max(0, Math.min(1, noise)); | ||
| const effective = pairs === 0 ? perPair : 1 - Math.pow(1 - perPair, pairs); |
There was a problem hiding this comment.
Make zero-depth noise lower than one X·X pair
This formula makes xxPairs=0 and xxPairs=1 produce the same effective noise (perPair) whenever noise is nonzero, so adding the first X·X pair has no impact on the decoherence curve. That flattens the early depth sweep and conflicts with the documented per-pair compounding model, where each additional pair should increase degradation.
Useful? React with 👍 / 👎.
Roll the homepage repositioning across the in-product app, build the Brand Risk Scorecard layer, and replace the homepage gallery placeholders with real scan illustrations. brainsnn-r3f-app - index.html title + og + twitter meta now lead with "affective- intelligence engine" and the four-outcome positioning sentence. - OnboardingWalkthrough STEPS rewritten — step 1 leads with the positioning sentence, the Cognitive Firewall is framed as "the engine," the new Brand Risk Scorecard gets its own step, and the ordering puts the engine before the visualization layer. - MilestonePanel intro paragraph updated to the new framing. - Layer 106 (Brand Risk Scorecard) added to layerCatalog and mounted in App.jsx behind an ErrorBoundary, after the Milestone panel. L106 — Brand Risk Scorecard - src/utils/brandRisk.js: splitItems / scoreItem / computeBrandRisk / brandBriefMarkdown. Pure functions, no side effects. Aggregates Cognitive Firewall (L4) + Propaganda Templates (L39) + Ad Transparency archetypes (L48) into a single 0–100 score with a 4-tier classification (Clean / Watch / At risk / Critical). - src/components/BrandRiskPanel.jsx: brand input + items textarea + load-sample helper, headline score card, dominant archetypes, most-fired templates, top 5 worst items, copy-brief-as-Markdown. - Score formula: 60% mean pressure + 25% peak pressure + 15% high- risk archetype share. High-risk archetypes: abusive-domestic, phishing, conspiracy-hook, political-attack, cult-recruitment. - Number 106 picked to avoid colliding with the open L101 PRs (#22, #24, #25 — see PR #27 description for the suggested resolution). ui/brainsnn-site gallery - public/scan-fear-cascade.svg, scan-certainty-theater.svg, and scan-affective-trajectory.svg — three hand-rolled SVG cards that match the new gallery copy. 4-dim score bars, brain proxy with the appropriate region glowing, evidence chips. - GALLERY_ITEMS now carries an `image` field; App.jsx reads it with the demo-placeholder.svg as a fallback. Builds - npm run build --prefix ui/brainsnn-site — 624 modules, 8.03s, clean. - npm run build --prefix brainsnn-r3f-app — 912 modules, 6.19s, clean. https://claude.ai/code/session_brainsnn-ui-build-28ebr
Summary
This PR now ships both halves of the quantum-alignment work:
Half 1 — Offline Qiskit suite (
quantum_alignment/)A self-contained Qiskit harness that probes the physical meaning of "alignment" in quantum computing — phase coherence, observation collapse, and decoherence — across three execution modes.
|0⟩ → H → RZ(θ) → H → Measureswept over θ ∈ {0, π/8, π/4, π/2, 3π/4, π}. Compared against the closed-form idealp(0) = cos²(θ/2).H · HvsH · Measure · H · Measure. Mid-circuit measurement collapses the superposition and pushes final readout to ~50/50. Gracefully degrades on backends that do not support mid-circuit measurement.|0⟩ → H → (X X)ⁿ → H → Measurewith n ∈ {0, 1, 2, 4, 8, 16, 32, 64}. EachX Xis logical identity, so any drift away fromp(0) = 1is purely noise.Three modes:
--mode ideal—AerSimulator(no token, no network)--mode noisy—AerSimulator.from_backend(GenericBackendV2(...))(no token; uses qiskit core's fake backend)--mode real— real IBM hardware viaqiskit-ibm-runtimeSamplerV2. Lazy-imported. ReadsIBM_QUANTUM_TOKENfrom env only — never logged, never written to disk.Outputs:
results.csv,phase_alignment_plot.png,noise_depth_plot.png,report.md.Half 2 — Browser-native BrainSNN layer (Layer 101 — Quantum Coherence Lab)
The original task asked for "browser-native first, no backend, simulate locally in JavaScript" — that part wasn't built in the first commit. This commit adds it:
brainsnn-r3f-app/src/utils/quantumCoherence.js— complex helpers (complex/addComplex/mulComplex/abs2/normalizeState), gates (applyH/applyX/applyZ/applyRZ), measurement (measureDistribution/sampleShots), three experiments shaped to mirror the Qiskit circuits (runPhaseExperiment/runObservationExperiment/runDecoherenceExperiment), simple dephasing + bit-flip noise,coherenceScore, andmapQuantumToBrainState.brainsnn-r3f-app/src/components/QuantumCoherencePanel.jsx— θ slider (0 → π), shots picker (256 / 1024 / 4096), noise slider, X·X depth slider, observe-midway toggle, Scientific / Metaphor mode toggle, P(0) / P(1) bars, coherence score 0–100, plain-English explanation, and anH → RZ(θ) → H → Mcircuit visualization.App.jsx; registered inlayerCatalog.jsas L101 with a newexperimentalgroup.node:testrunner —npm run test:quantum. No new dev deps.Both halves explicitly disclaim literal multiverse theory, consciousness collapse, Planck foam, and spiritual-portal claims. Those are framing metaphors only.
Test plan
Qiskit suite:
pip install -r quantum_alignment/requirements.txtresolves cleanlypython quantum_alignment_tests.py --mode ideal --shots 4096writes all 4 artifactspython quantum_alignment_tests.py --mode noisy --shots 4096shows expected fringes / 50-50 collapse / depth driftIBM_QUANTUM_TOKENrequired for ideal/noisy; token only read from envBrainSNN layer:
npm installsucceedsnpm run buildsucceeds (Vite, ~9s)npm run test:quantum— 18/18 passinghttps://claude.ai/code/session_01VYArf8MTS6QdhmswtqNPox
Generated by Claude Code