-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2993 lines (2768 loc) · 121 KB
/
Copy pathscript.js
File metadata and controls
2993 lines (2768 loc) · 121 KB
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* =========================================================
QuantumLab Beginner — vanilla JS app logic
========================================================= */
(() => {
const MODULES = ['qubits','measurement','superposition','entanglement','circuits','algorithms','noise','qec'];
const STORAGE_KEY = 'quantumlab.progress.v1';
// ---------- Persistent state ----------
const defaultProgress = () => {
const s = {};
MODULES.forEach(m => s[m] = {done:false, score:0});
s.challenge = {done:false, score:0};
return s;
};
let progress = load();
function load(){
try{
const raw = localStorage.getItem(STORAGE_KEY);
if(!raw) return defaultProgress();
return Object.assign(defaultProgress(), JSON.parse(raw));
}catch{ return defaultProgress(); }
}
function save(){ localStorage.setItem(STORAGE_KEY, JSON.stringify(progress)); }
// ---------- Toast ----------
const toast = msg => {
const t = document.getElementById('toast');
t.textContent = msg;
t.classList.add('show');
clearTimeout(toast._t);
toast._t = setTimeout(() => t.classList.remove('show'), 2400);
};
// ---------- Glossary data ----------
const GLOSSARY = {
bit:'A classical unit of information. Either 0 or 1.',
qubit:'A quantum bit. Can be |0⟩, |1⟩, or a superposition of both.',
superposition:'A combination of multiple quantum states at the same time.',
entanglement:'A link between qubits where measuring one tells you about the other.',
measurement:'The act of reading a qubit, which forces it to choose 0 or 1.',
gate:'An operation that changes the state of one or more qubits.',
bloch:'A sphere used to picture the state of a single qubit.',
hadamard:'The H gate. Turns |0⟩ into a 50/50 superposition.',
cnot:'A 2-qubit gate that flips the target if the control is 1. Creates entanglement.',
noise:'Unwanted disturbances that can flip or smear qubit states.',
pulse:'A precisely shaped energy burst used to apply a gate.',
};
const FAQ = [
{q:'Do I need math to start?', a:'No! This whole tour avoids equations. We use sliders, bars, and pictures.'},
{q:'Is a qubit just a fancy bit?', a:'No — a qubit can be 0, 1, or both at once. That extra freedom is where quantum power comes from.'},
{q:'Can I build a real quantum computer at home?', a:'Not realistically — but you can run real circuits on cloud quantum hardware (e.g. IBM Quantum, IonQ).'},
{q:'Why is noise such a big deal?', a:'Quantum information is delicate. Tiny disturbances scramble it, so engineers spend huge effort isolating qubits.'},
{q:'What is a "gate"?', a:'A gate is a tiny operation, like a rotation, that changes a qubit. Stack gates to make a circuit.'},
{q:'Where do I go after this?', a:'Try IBM Quantum Composer, Microsoft Quantum Katas, or Q-CTRL Black Opal for deeper hands-on practice.'},
];
// ---------- Quiz data ----------
const QUIZ_DATA = {
qubits:[
{q:'How many states can one qubit hold *before* it is measured?',
choices:['Only 0','Only 1','A blend of 0 and 1','Always exactly 2 simultaneously'],
answer:2,
explain:'A qubit can be in a superposition — a blend of |0⟩ and |1⟩ — until measurement.'},
{q:'A classical bit is most like which state of a qubit?',
choices:['Superposition','|0⟩ or |1⟩ (a definite state)','An entangled qubit','A measured qubit only'],
answer:1,
explain:'A bit is always in a definite 0 or 1, similar to a qubit in a clean |0⟩ or |1⟩.'},
{q:'What does the Bloch arrow pointing straight up represent?',
choices:['|1⟩','|0⟩','Equal superposition','An error'],
answer:1,
explain:'By convention, the +z (up) pole is |0⟩ and the −z (down) pole is |1⟩.'},
],
superposition:[
{q:'If P(0) = 70%, what is P(1)?',
choices:['70%','30%','0%','100%'],
answer:1,
explain:'Probabilities for a single qubit must add to 100%, so P(1) = 100 − 70 = 30.'},
{q:'A 50/50 superposition means…',
choices:['You always get 0','You always get 1','Each measurement is fair-coin random','Both 0 and 1 at once after measuring'],
answer:2,
explain:'You see 0 or 1 randomly, with equal chance, every time you measure.'},
{q:'Which gate creates a balanced superposition from |0⟩?',
choices:['X','H','CNOT','Measure'],
answer:1,
explain:'The Hadamard (H) gate turns |0⟩ into an equal superposition of |0⟩ and |1⟩.'},
],
entanglement:[
{q:'Two entangled qubits in a Bell state always measure…',
choices:['Independent random results','Correlated results','Both 0','Both 1'],
answer:1,
explain:'In the Bell |Φ+⟩ state, both measurements give the same outcome — they are correlated.'},
{q:'Entanglement requires the qubits to be…',
choices:['Touching each other','Linked through prior interaction','Always at room temperature','Made of the same atom'],
answer:1,
explain:'They must have interacted in a way that ties their fates together; afterwards distance does not matter.'},
{q:'What is a CNOT gate good for?',
choices:['Resetting a qubit','Adding noise','Creating entanglement','Measuring a qubit'],
answer:2,
explain:'CNOT (controlled-NOT) is the standard gate for entangling two qubits.'},
],
measurement:[
{q:'After measurement, a superposed qubit becomes…',
choices:['Still superposed','Definitely 0 or definitely 1','An entangled state','Erased'],
answer:1,
explain:'Measurement collapses the qubit to a single classical outcome.'},
{q:'Repeated measurements with P(1)=70% give…',
choices:['Always 1','Always 0','About 70% ones over many trials','Exactly 7 ones, never more'],
answer:2,
explain:'Probabilities show up as long-run frequencies — about 70% of many shots will be 1.'},
{q:'Why not just measure all the time?',
choices:['It is too slow','It destroys the superposition we want to use','It costs energy','It is illegal'],
answer:1,
explain:'Measurement collapses the rich quantum state, losing the parallelism that powers algorithms.'},
],
circuits:[
{q:'In a circuit, gates are applied…',
choices:['All at once randomly','In a defined sequence over time','Only once per qubit','In secret'],
answer:1,
explain:'A circuit is read left-to-right; each gate acts in order.'},
{q:'Which gate flips |0⟩ to |1⟩?',
choices:['H','X','CNOT','Measure'],
answer:1,
explain:'X is the bit-flip (NOT) gate.'},
{q:'Where is the measurement usually placed?',
choices:['At the very start','At the very end','Both ends','It does not matter'],
answer:1,
explain:'You typically run all gates first, then measure to read the answer.'},
],
noise:[
{q:'Higher noise usually means…',
choices:['More accurate results','Less accurate results','Faster computation','No effect'],
answer:1,
explain:'Noise corrupts qubit states, smearing the measurement statistics away from the ideal.'},
{q:'A noisy bit-flip has roughly which effect?',
choices:['Adds a random colour','Flips 0↔1 with some probability','Doubles the qubit','Creates a new qubit'],
answer:1,
explain:'A bit-flip channel turns 0 into 1 (or vice-versa) at random with some probability.'},
{q:'How do we fight noise in real machines?',
choices:['Ignore it','Better isolation, calibration, and error correction','Use more electricity','Run the circuit louder'],
answer:1,
explain:'Engineers cool, shield, calibrate, and add error correction to protect qubits.'},
],
qec:[
{q:'The 3-qubit bit-flip code can correct how many flips per code block?',
choices:['0','1','2','3'],
answer:1,
explain:'A majority vote handles up to 1 flip out of 3. Two or three flips overwhelm it.'},
{q:'Above what physical-error rate does the 3-qubit code stop helping?',
choices:['10%','25%','50%','99%'],
answer:2,
explain:'At p = 50% the coded and bare error rates are equal. Above 50%, redundancy makes things worse — that is the code\'s break-even point.'},
{q:'The main idea of quantum error correction is to…',
choices:['Make perfect qubits','Encode 1 logical qubit into many physical qubits and detect/fix errors','Run every circuit twice','Replace qubits with classical bits'],
answer:1,
explain:'QEC spreads logical information across redundant physical qubits and uses syndrome measurements to detect and fix errors without disturbing the encoded state.'},
],
algorithms:[
{q:'A quantum coin flip uses which gate before measuring?',
choices:['X','H','CNOT','None'],
answer:1,
explain:'H makes a 50/50 superposition; measuring it produces a fair random bit.'},
{q:'Grover’s algorithm offers what kind of speed-up?',
choices:['No speed-up','Linear (×2)','Quadratic (√N)','Exponential'],
answer:2,
explain:'Grover finds the marked item in roughly √N steps versus N classically.'},
{q:'Deutsch–Jozsa decides constant vs balanced in how many quantum queries?',
choices:['1','log N','N/2','N'],
answer:0,
explain:'It needs only 1 quantum query for an answer that classically may require N/2 + 1.'},
],
};
const FINAL_QUIZ = [
{q:'Which of these is unique to quantum, not classical, computing?',
choices:['Bits','Wires','Superposition + entanglement','Loops'],
answer:2,
explain:'Superposition and entanglement together give quantum its edge.'},
{q:'You apply H to |0⟩ and measure. What do you see over many shots?',
choices:['Always 0','Always 1','≈50% 0, 50% 1','A new qubit'],
answer:2,
explain:'H creates a fair superposition.'},
{q:'Two qubits in a Bell state show which measurement pattern?',
choices:['Independent','Always equal (or always opposite)','Always 00','Always 11'],
answer:1,
explain:'They are perfectly correlated.'},
{q:'Increasing noise from 0% to 50% generally…',
choices:['Sharpens results','Flattens results toward random','Boosts speed','Removes gates'],
answer:1,
explain:'High noise pushes outcomes toward 50/50 randomness.'},
{q:'Why do quantum engineers care so much about pulse calibration?',
choices:['It looks cool','To get accurate gates','To save battery','To shorten wires'],
answer:1,
explain:'Mis-tuned pulses → wrong rotation angle → wrong gate → wrong answer.'},
];
// ---------- Hash router ----------
const sections = document.querySelectorAll('.module');
const navLinks = document.querySelectorAll('.nav-list a');
function showSection(id){
sections.forEach(s => s.classList.toggle('active', s.id === id));
navLinks.forEach(a => a.classList.toggle('active', a.getAttribute('href') === '#' + id));
document.getElementById('sidebar').classList.remove('open');
window.scrollTo({top:0, behavior:'smooth'});
}
window.addEventListener('hashchange', () => showSection((location.hash||'#qubits').slice(1)));
// ---------- Sidebar mobile toggle ----------
document.getElementById('menu-toggle').onclick = () =>
document.getElementById('sidebar').classList.toggle('open');
// ---------- Reset ----------
document.getElementById('reset-btn').onclick = () => {
if(!confirm('Reset all progress?')) return;
localStorage.removeItem(STORAGE_KEY);
progress = defaultProgress();
save();
toast('Progress reset.');
setTimeout(()=>location.reload(), 600);
};
// ---------- Render: progress, badges, scores ----------
function render(){
const done = MODULES.filter(m => progress[m].done).length;
document.getElementById('progress-text').textContent = `${done} / ${MODULES.length}`;
document.getElementById('progress-fill').style.width = (done/MODULES.length*100) + '%';
navLinks.forEach(a => {
const m = a.dataset.mod;
if(m && progress[m].done) a.classList.add('done');
else a.classList.remove('done');
});
// badges
const icons = {qubits:'⚛',superposition:'🌊',entanglement:'🔗',measurement:'📏',
circuits:'🔲',noise:'📡',qec:'🛡',algorithms:'🧮'};
const badgesEl = document.getElementById('badges');
badgesEl.innerHTML = '';
MODULES.forEach(m => {
const b = document.createElement('div');
b.className = 'badge' + (progress[m].done ? ' earned' : '');
b.title = m + (progress[m].done ? ' — completed' : ' — locked');
b.textContent = icons[m];
badgesEl.appendChild(b);
});
const totalScore = MODULES.reduce((s,m) => s + (progress[m].score||0), 0) + (progress.challenge.score||0);
document.getElementById('total-score').textContent = totalScore;
// challenge nav lock
document.getElementById('nav-challenge').classList.toggle('locked', done < 6);
}
// ---------- Glossary panels ----------
function renderGlossary(){
const list = document.getElementById('glossary-list');
const quick = document.getElementById('quick-glossary');
list.innerHTML = '';
quick.innerHTML = '';
Object.entries(GLOSSARY).forEach(([k,v]) => {
const cap = k[0].toUpperCase() + k.slice(1);
const item = document.createElement('div');
item.className = 'g-item';
item.innerHTML = `<b>${cap}</b><br><span class="muted">${v}</span>`;
list.appendChild(item);
const small = document.createElement('div');
small.innerHTML = `<b>${cap}</b> — ${v}`;
quick.appendChild(small);
});
// attach tooltips to .term spans
document.querySelectorAll('.term').forEach(t => {
const k = t.dataset.term;
if(GLOSSARY[k]) t.dataset.tip = GLOSSARY[k];
});
}
function renderFaq(){
const wrap = document.getElementById('faq-list');
wrap.innerHTML = '';
FAQ.forEach(({q,a}) => {
const d = document.createElement('details');
d.innerHTML = `<summary>${q}</summary><p>${a}</p>`;
wrap.appendChild(d);
});
}
// ---------- Quiz engine ----------
function renderQuiz(moduleId, questions, mountEl, onComplete){
let idx = 0, score = 0;
function step(){
if(idx >= questions.length){
const passed = score >= Math.ceil(questions.length * 0.66);
mountEl.innerHTML = `<div class="quiz-result ${passed?'pass':'fail'}">
${passed?'✅ Passed':'❌ Try again'} — ${score} / ${questions.length}
</div>
<button class="primary-btn" id="retry-${moduleId}">Retake quiz</button>`;
mountEl.querySelector('#retry-'+moduleId).onclick = () => renderQuiz(moduleId, questions, mountEl, onComplete);
if(passed) onComplete(score);
return;
}
const Q = questions[idx];
mountEl.innerHTML = `
<div class="q-num muted">Question ${idx+1} of ${questions.length}</div>
<div class="q-text">${Q.q}</div>
<div class="choices"></div>
<div class="feedback" style="display:none"></div>
<button class="primary-btn next-btn" style="display:none;margin-top:10px">Next →</button>
`;
const choicesEl = mountEl.querySelector('.choices');
const fb = mountEl.querySelector('.feedback');
const next = mountEl.querySelector('.next-btn');
Q.choices.forEach((c,i) => {
const btn = document.createElement('button');
btn.className = 'choice';
btn.textContent = c;
btn.onclick = () => {
Array.from(choicesEl.children).forEach(b => b.disabled = true);
if(i === Q.answer){
btn.classList.add('correct');
score++;
fb.innerHTML = `<b style="color:var(--success)">Correct.</b> ${Q.explain}`;
}else{
btn.classList.add('wrong');
choicesEl.children[Q.answer].classList.add('correct');
fb.innerHTML = `<b style="color:var(--danger)">Not quite.</b> ${Q.explain}`;
}
fb.style.display = 'block';
next.style.display = 'inline-block';
};
choicesEl.appendChild(btn);
});
next.onclick = () => { idx++; step(); };
}
step();
}
function attachQuizzes(){
document.querySelectorAll('.quiz').forEach(card => {
const id = card.dataset.quiz;
const body = card.querySelector('.quiz-body');
renderQuiz(id, QUIZ_DATA[id], body, score => {
const prev = progress[id].score || 0;
if(score > prev) progress[id].score = score;
if(!progress[id].done){
progress[id].done = true;
save(); render();
toast(`🎉 ${id} module complete!`);
}else{ save(); render(); }
});
});
}
// ============================================================
// Module widgets
// ============================================================
// ----- Qubits: Bloch toggle -----
function initQubits(){
const arrow = document.getElementById('bloch-arrow');
const explain = document.getElementById('bloch-explain');
const setActive = el => document.querySelectorAll('.state-btn').forEach(b => b.classList.toggle('active', b===el));
document.querySelectorAll('.state-btn').forEach(btn => {
btn.onclick = () => {
setActive(btn);
arrow.classList.remove('spin');
const s = btn.dataset.state;
if(s==='0'){
arrow.style.transform='translate(-50%,-100%) rotate(0deg)';
explain.textContent='Pure |0⟩ — points up. Measurement always returns 0.';
} else if(s==='1'){
arrow.style.transform='translate(-50%,-100%) rotate(180deg)';
explain.textContent='Pure |1⟩ — points down. Measurement always returns 1.';
} else {
arrow.style.transform='translate(-50%,-100%) rotate(90deg)';
explain.textContent='Equal superposition — sweeping the equator. 50/50 on measurement.';
arrow.classList.add('spin');
}
};
});
}
// ----- Bloch Sphere (3D, interactive) -----
function initBloch(){
let theta = 0; // polar from |0⟩, 0..π
let phi = 0; // azimuth, 0..2π
let viewX = -22; // current view rotation in degrees
let viewY = -30;
const R = 120; // px, sphere radius for vector
const cube = document.getElementById('bloch-cube');
const tEl = document.getElementById('bloch-theta');
const pEl = document.getElementById('bloch-phi');
const tV = document.getElementById('bloch-theta-v');
const pV = document.getElementById('bloch-phi-v');
const vec = document.getElementById('bloch-vec');
const tip = document.getElementById('bloch-tip');
const stEl = document.getElementById('bloch-state');
if(!cube) return;
// Complex helpers
const c = (re, im=0) => [re, im];
const cAdd = (a, b) => [a[0]+b[0], a[1]+b[1]];
const cMul = (a, b) => [a[0]*b[0]-a[1]*b[1], a[0]*b[1]+a[1]*b[0]];
const cAbs = (z) => Math.hypot(z[0], z[1]);
const cArg = (z) => Math.atan2(z[1], z[0]);
const I = c(1), Z0 = c(0);
const GATES = {
X: [[Z0, c(1)], [c(1), Z0]],
Y: [[Z0, c(0,-1)], [c(0,1), Z0]],
Z: [[I, Z0], [Z0, c(-1)]],
H: (() => { const s = 1/Math.SQRT2; return [[c(s),c(s)],[c(s),c(-s)]]; })(),
S: [[I, Z0], [Z0, c(0,1)]],
T: [[I, Z0], [Z0, c(Math.cos(Math.PI/4), Math.sin(Math.PI/4))]],
};
function update(){
// Display angle text
const tDeg = theta * 180 / Math.PI;
const pDeg = phi * 180 / Math.PI;
tV.textContent = tDeg.toFixed(0);
pV.textContent = pDeg.toFixed(0);
tEl.value = tDeg.toFixed(0);
pEl.value = pDeg.toFixed(0);
// Tip position in CSS coords (physics x → css x; physics y → css z; physics z → −css y).
const sx = R * Math.sin(theta) * Math.cos(phi);
const sy = -R * Math.cos(theta);
const sz = R * Math.sin(theta) * Math.sin(phi);
tip.style.transform = `translate3d(${sx}px, ${sy}px, ${sz}px)`;
// Vector orientation: rotateY(−φ) then rotateZ(θ−π/2). Length R.
vec.style.transform = `rotateY(${-phi}rad) rotateZ(${theta - Math.PI/2}rad)`;
// Dirac notation — coefficients can be negative when θ ∈ (360°, 720°), so show signs.
const cT = Math.cos(theta/2), sT = Math.sin(theta/2);
const aSign = cT < 0 ? '−' : '';
const bSign = sT < 0 ? '− ' : '+ ';
const aAbs = Math.abs(cT).toFixed(3);
const bAbs = Math.abs(sT).toFixed(3);
const phaseStr = (Math.abs(phi) < 1e-3 || Math.abs(sT) < 1e-6)
? ''
: ` · e<sup>i·${pDeg.toFixed(0)}°</sup>`;
// Spinor cycle: the state acquires a global −1 between θ = 360° and 720°.
const inSpinor = (theta > 2*Math.PI - 1e-3) && (theta < 4*Math.PI - 1e-3);
const spinorLine = inSpinor
? `<div style="margin-top:8px;font-size:.82rem;color:var(--accent-3);background:rgba(236,72,153,.08);border:1px solid rgba(236,72,153,.3);padding:6px 10px;border-radius:6px">⚡ <b>Spinor region.</b> Bloch vector points the same way as θ = ${(tDeg-360).toFixed(0)}°, but the state has picked up a global −1. Slide all the way to 720° to recover |ψ⟩.</div>`
: '';
stEl.innerHTML = `
<span class="label">State |ψ⟩</span>
<div class="eq">|ψ⟩ = ${aSign}<span class="alpha">${aAbs}</span>·|0⟩ ${bSign}<span class="beta">${bAbs}${phaseStr}</span>·|1⟩</div>
<span class="approx">θ = ${tDeg.toFixed(0)}°, φ = ${pDeg.toFixed(0)}°
· |α|² = ${(cT*cT*100).toFixed(1)}%, |β|² = ${(sT*sT*100).toFixed(1)}%</span>
${spinorLine}`;
}
function applyView(){
cube.style.transform = `rotateX(${viewX}deg) rotateY(${viewY}deg)`;
}
function applyGate(M){
// Current state ψ = [cos(θ/2), e^(iφ) sin(θ/2)]
const cT = Math.cos(theta/2), sT = Math.sin(theta/2);
const psi = [
[cT, 0],
[Math.cos(phi)*sT, Math.sin(phi)*sT],
];
const out = [
cAdd(cMul(M[0][0], psi[0]), cMul(M[0][1], psi[1])),
cAdd(cMul(M[1][0], psi[0]), cMul(M[1][1], psi[1])),
];
// Recover (θ, φ) modulo a global phase.
const m0 = cAbs(out[0]);
const m1 = cAbs(out[1]);
theta = 2 * Math.atan2(m1, m0);
if(m0 < 1e-9){
phi = ((cArg(out[1]) % (2*Math.PI)) + 2*Math.PI) % (2*Math.PI);
} else {
const dphi = cArg(out[1]) - cArg(out[0]);
phi = ((dphi % (2*Math.PI)) + 2*Math.PI) % (2*Math.PI);
}
update();
}
function setPreset(name){
switch(name){
case '0': theta = 0; phi = 0; break;
case '1': theta = Math.PI; phi = 0; break;
case '+': theta = Math.PI/2; phi = 0; break;
case '-': theta = Math.PI/2; phi = Math.PI; break;
case 'i': theta = Math.PI/2; phi = Math.PI/2; break;
case '-i': theta = Math.PI/2; phi = 3*Math.PI/2; break;
}
update();
}
tEl.oninput = () => { theta = +tEl.value * Math.PI/180; update(); };
pEl.oninput = () => { phi = +pEl.value * Math.PI/180; update(); };
document.querySelectorAll('#bloch .bloch-gate').forEach(b => {
b.onclick = () => {
if(b.dataset.gate) applyGate(GATES[b.dataset.gate]);
if(b.dataset.preset) setPreset(b.dataset.preset);
};
});
// Drag to rotate view
let dragging = false, lastX = 0, lastY = 0;
cube.addEventListener('pointerdown', (e) => {
dragging = true; lastX = e.clientX; lastY = e.clientY;
cube.setPointerCapture(e.pointerId);
});
cube.addEventListener('pointermove', (e) => {
if(!dragging) return;
const dx = e.clientX - lastX, dy = e.clientY - lastY;
viewY += dx * 0.5;
viewX -= dy * 0.5;
viewX = Math.max(-85, Math.min(85, viewX));
lastX = e.clientX; lastY = e.clientY;
applyView();
});
cube.addEventListener('pointerup', () => { dragging = false; });
cube.addEventListener('pointercancel',() => { dragging = false; });
applyView();
update();
}
// ----- Superposition: slider + bars + wave -----
function initSuperposition(){
const slider = document.getElementById('sp-slider');
const p0=document.getElementById('sp-p0'), p1=document.getElementById('sp-p1');
const b0=document.getElementById('sp-bar0'), b1=document.getElementById('sp-bar1');
const dirac = document.getElementById('sp-dirac');
const cv = document.getElementById('sp-wave'); const ctx = cv.getContext('2d');
// Render Dirac notation: |ψ⟩ = α|0⟩ + β|1⟩, where α=√P(0), β=√P(1).
// Pretty-prints familiar fractions (1/√2, 1, 0) and shows decimal approximations.
const FRAC_1_SQRT2 = '<span class="frac"><span class="num">1</span><span class="den">√2</span></span>';
function prettyAmp(p){
if(p === 0) return '0';
if(p === 100) return '1';
if(p === 50) return FRAC_1_SQRT2;
return `√<span style="font-style:normal">${(p/100).toFixed(2)}</span>`;
}
function renderDirac(p1pct){
const p0pct = 100 - p1pct;
const a = Math.sqrt(p0pct/100);
const b = Math.sqrt(p1pct/100);
const aStr = prettyAmp(p0pct);
const bStr = prettyAmp(p1pct);
// build expression, hiding zero terms cleanly
let main;
if(p0pct === 0) main = `<span class="beta">${bStr}</span><span class="ket">|1⟩</span>`;
else if(p1pct === 0) main = `<span class="alpha">${aStr}</span><span class="ket">|0⟩</span>`;
else
main = `<span class="alpha">${aStr}</span><span class="ket">|0⟩</span> + ` +
`<span class="beta">${bStr}</span><span class="ket">|1⟩</span>`;
dirac.innerHTML = `
<span class="label">Dirac notation</span>
<div class="eq">|ψ⟩ = ${main}</div>
<span class="approx">≈ ${a.toFixed(3)} |0⟩ + ${b.toFixed(3)} |1⟩
· |α|² = ${(p0pct).toFixed(0)}%, |β|² = ${(p1pct).toFixed(0)}%</span>`;
}
function update(){
const v = +slider.value; // probability of 1 in %
p1.textContent = v; p0.textContent = 100-v;
b0.style.width = (100-v)+'%';
b1.style.width = v + '%';
renderDirac(v);
}
slider.oninput = update; update();
// animated wave
let t = 0;
function frame(){
const w = cv.width = cv.clientWidth, h = cv.height;
ctx.clearRect(0,0,w,h);
const v = +slider.value/100;
const ampMix = Math.sin(Math.PI * v); // peak at 50%
ctx.lineWidth = 2;
// |0> wave (cyan)
ctx.strokeStyle = 'rgba(6,182,212,.85)';
ctx.beginPath();
for(let x=0;x<w;x++){
const y = h/2 + Math.sin((x*0.04)+t) * (h/3) * (1-v);
x===0 ? ctx.moveTo(x,y) : ctx.lineTo(x,y);
}
ctx.stroke();
// |1> wave (pink)
ctx.strokeStyle = 'rgba(236,72,153,.85)';
ctx.beginPath();
for(let x=0;x<w;x++){
const y = h/2 + Math.cos((x*0.04)+t*1.3) * (h/3) * v;
x===0 ? ctx.moveTo(x,y) : ctx.lineTo(x,y);
}
ctx.stroke();
// mix glow
ctx.fillStyle = `rgba(124,58,237,${0.04 + 0.18*ampMix})`;
ctx.fillRect(0,0,w,h);
t += 0.06;
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
// ----- Entanglement -----
function initEntanglement(){
const a = document.getElementById('qa'), b = document.getElementById('qb');
const av = a.querySelector('.qval'), bv = b.querySelector('.qval');
const msg = document.getElementById('ent-msg');
const formula = document.getElementById('ent-formula');
const ampsEl = document.getElementById('ent-amps');
const note = document.getElementById('ent-note');
// amplitudes for the four 2-qubit basis states |00>, |01>, |10>, |11>
const labels = ['|00⟩','|01⟩','|10⟩','|11⟩'];
function renderState(amps){
ampsEl.innerHTML = '';
amps.forEach((amp, i) => {
const p = amp*amp;
const row = document.createElement('div');
row.className = 'sv-row' + (Math.abs(amp) < 1e-6 ? ' zero' : '');
row.innerHTML = `
<span class="sv-label">${labels[i]}</span>
<div class="sv-bar"><div style="width:${(p*100).toFixed(0)}%"></div></div>
<span class="sv-amp">${formatAmp(amp)}</span>`;
ampsEl.appendChild(row);
});
}
function formatAmp(a){
if(Math.abs(a) < 1e-6) return '0';
if(Math.abs(a - 1) < 1e-6) return '1';
if(Math.abs(a - 1/Math.SQRT2) < 1e-6) return F12;
if(Math.abs(a + 1/Math.SQRT2) < 1e-6) return '−' + F12;
return a.toFixed(3);
}
const F12 = '<span class="frac"><span class="num">1</span><span class="den">√2</span></span>';
function setBell(){
av.textContent = '?'; bv.textContent = '?';
a.classList.remove('measured'); b.classList.remove('measured');
formula.innerHTML = `|Φ⁺⟩ = ${F12}·|00⟩ + ${F12}·|11⟩`;
note.textContent = 'An equal superposition of |00⟩ and |11⟩. Notice |01⟩ and |10⟩ have amplitude 0 — the qubits are perfectly correlated, never opposite.';
renderState([1/Math.SQRT2, 0, 0, 1/Math.SQRT2]);
msg.textContent = 'Pair entangled. Press “Measure A” to collapse it.';
}
function collapse(r){
av.textContent = r; bv.textContent = r;
a.classList.add('measured'); b.classList.add('measured');
if(r === '0'){
formula.innerHTML = '|00⟩ (collapsed)';
note.textContent = 'Measurement projected the state onto |00⟩. Both qubits read 0 — every time you re-measure them now, you keep getting 0.';
renderState([1, 0, 0, 0]);
} else {
formula.innerHTML = '|11⟩ (collapsed)';
note.textContent = 'Measurement projected the state onto |11⟩. Both qubits read 1 — the entanglement was “used up” by the measurement.';
renderState([0, 0, 0, 1]);
}
msg.textContent = `Both collapsed to ${r}. Bell |Φ⁺⟩ correlations always agree.`;
}
document.getElementById('ent-measure').onclick = () =>
collapse(Math.random() < 0.5 ? '0' : '1');
document.getElementById('ent-reset').onclick = setBell;
setBell();
}
// ----- Phase Kickback -----
function initKickback(){
// Index convention for the 4-amp vector: index = 2·c + t (c = control, t = target)
// Cases: target ∈ {|0⟩, |1⟩, |+⟩, |−⟩}. Control starts |+⟩ = (|0⟩+|1⟩)/√2.
const S = 1/Math.SQRT2;
const KB = {
'0': {
initLabel: '|+⟩ ⊗ |0⟩',
init: [S, 0, S, 0],
finalLabel: '<span class="frac"><span class="num">|00⟩ + |11⟩</span><span class="den">√2</span></span> = |Φ⁺⟩',
final: [S, 0, 0, S],
cls: 'entangle',
verdict: 'No clean kickback. Target |0⟩ is not an eigenstate of X (the operation CNOT applies), so the qubits become entangled into the Bell state |Φ⁺⟩.'
},
'1': {
initLabel: '|+⟩ ⊗ |1⟩',
init: [0, S, 0, S],
finalLabel: '<span class="frac"><span class="num">|01⟩ + |10⟩</span><span class="den">√2</span></span> = |Ψ⁺⟩',
final: [0, S, S, 0],
cls: 'entangle',
verdict: 'No kickback. Target |1⟩ is not an eigenstate of X — the qubits entangle into the Bell state |Ψ⁺⟩.'
},
'+': {
initLabel: '|+⟩ ⊗ |+⟩',
init: [0.5, 0.5, 0.5, 0.5],
finalLabel: '|+⟩ ⊗ |+⟩',
final: [0.5, 0.5, 0.5, 0.5],
cls: 'identity',
verdict: 'Kickback with phase +1 (trivial). X|+⟩ = +|+⟩, so the phase that kicks back is +1 — nothing visibly changes.'
},
'-': {
initLabel: '|+⟩ ⊗ |−⟩',
init: [0.5, -0.5, 0.5, -0.5],
finalLabel: '|−⟩ ⊗ |−⟩',
final: [0.5, -0.5, -0.5, 0.5],
cls: 'kick',
verdict: '✨ Phase kickback! X|−⟩ = −|−⟩, so a −1 phase gets kicked onto the control\'s |1⟩ branch. The control flips |+⟩ → |−⟩ — the target is unchanged, yet the "control" is what moved.'
},
};
const labels = ['|00⟩','|01⟩','|10⟩','|11⟩'];
const initEl = document.getElementById('kb-init');
const finalEl = document.getElementById('kb-final');
const initAmps = document.getElementById('kb-init-amps');
const finalAmps = document.getElementById('kb-final-amps');
const verdict = document.getElementById('kb-verdict');
const F12 = '<span class="frac"><span class="num">1</span><span class="den">√2</span></span>';
const F1_2 = '<span class="frac"><span class="num">1</span><span class="den">2</span></span>';
function fmt(a){
if(Math.abs(a) < 1e-6) return '0';
if(Math.abs(a - 1) < 1e-6) return '1';
if(Math.abs(a + 1) < 1e-6) return '−1';
if(Math.abs(a - S) < 1e-6) return F12;
if(Math.abs(a + S) < 1e-6) return '−' + F12;
if(Math.abs(a - 0.5) < 1e-6) return F1_2;
if(Math.abs(a + 0.5) < 1e-6) return '−' + F1_2;
return a.toFixed(3);
}
function renderAmps(host, vec){
host.innerHTML = '';
vec.forEach((a, i) => {
const p = a*a;
const row = document.createElement('div');
row.className = 'sv-row' + (Math.abs(a) < 1e-6 ? ' zero' : '');
row.innerHTML = `
<span class="sv-label">${labels[i]}</span>
<div class="sv-bar"><div style="width:${(p*100).toFixed(0)}%"></div></div>
<span class="sv-amp">${fmt(a)}</span>`;
host.appendChild(row);
});
}
function show(stateKey){
const c = KB[stateKey];
initEl.innerHTML = c.initLabel;
finalEl.innerHTML = c.finalLabel;
renderAmps(initAmps, c.init);
renderAmps(finalAmps, c.final);
verdict.className = 'kb-verdict ' + c.cls;
verdict.textContent = c.verdict;
document.querySelectorAll('.kb-target').forEach(b =>
b.classList.toggle('active', b.dataset.state === stateKey));
}
document.querySelectorAll('.kb-target').forEach(b =>
b.onclick = () => show(b.dataset.state));
show('-');
}
// ----- Quantum Paradoxes -----
function initParadox(){
// Tab switching
document.querySelectorAll('.pdx-tab').forEach(b => {
b.onclick = () => {
document.querySelectorAll('.pdx-tab').forEach(x => x.classList.toggle('active', x===b));
document.querySelectorAll('.pdx-panel').forEach(p => p.classList.add('hidden'));
const panel = document.getElementById('pdx-' + b.dataset.pdx);
if(panel) panel.classList.remove('hidden');
};
});
// -------- Schrödinger's Cat --------
(() => {
const box = document.getElementById('cat-box');
const lbl = document.getElementById('cat-label');
const msg = document.getElementById('cat-msg');
const time = document.getElementById('cat-time');
const timeV = document.getElementById('cat-time-v');
function update(){
const p = +time.value;
timeV.textContent = p;
if(box.classList.contains('opened')) return;
const a = Math.sqrt((100-p)/100), b = Math.sqrt(p/100);
lbl.innerHTML = `${a.toFixed(2)}·|alive⟩ + ${b.toFixed(2)}·|dead⟩`;
msg.textContent = p === 0 ? 'No time has passed — cat is definitely alive (decay impossible).'
: p === 100 ? 'Definitely decayed — cat is dead (no superposition needed).'
: `Closed box. Cat is in superposition: ${(100-p)}% alive amplitude², ${p}% dead.`;
}
time.oninput = update;
document.getElementById('cat-open').onclick = () => {
const p = +time.value / 100;
const dead = Math.random() < p;
box.classList.remove('closed');
box.classList.add('opened', dead ? 'dead' : 'alive');
lbl.innerHTML = dead ? '|dead⟩ (collapsed)' : '|alive⟩ (collapsed)';
msg.textContent = dead
? '☠ Cat collapsed to |dead⟩. The atom had decayed.'
: '😺 Cat collapsed to |alive⟩. The atom had not decayed.';
};
document.getElementById('cat-reset').onclick = () => {
box.classList.remove('opened','alive','dead');
box.classList.add('closed');
update();
};
update();
})();
// -------- Wigner's Friend --------
(() => {
const friendEl = document.getElementById('wig-friend');
const wignerEl = document.getElementById('wig-wigner');
const msg = document.getElementById('wig-msg');
let stage = 0, friendOutcome = null;
function setState(s){
stage = s;
if(s === 0){
friendEl.textContent = '|+⟩ — superposition';
wignerEl.textContent = '(qubit ⊗ Friend) in |+⟩ ⊗ |neutral⟩';
msg.innerHTML = 'Initial: the qubit is in <b>|+⟩ = (|0⟩+|1⟩)/√2</b>. Both observers describe it the same way.';
document.querySelectorAll('.wig-actor').forEach(a => a.classList.remove('measured'));
} else if(s === 1){
friendOutcome = Math.random() < 0.5 ? 0 : 1;
friendEl.innerHTML = `|${friendOutcome}⟩ <span style="color:var(--muted)">(I saw a definite outcome!)</span>`;
wignerEl.innerHTML = `<span style="color:var(--accent-3)">(|0⟩|sees-0⟩ + |1⟩|sees-1⟩)/√2</span><br><small style="color:var(--muted)">Friend & qubit jointly entangled</small>`;
document.querySelectorAll('.wig-actor')[0].classList.add('measured');
msg.innerHTML = `<b>The paradox.</b> Friend says: "I measured ${friendOutcome}, the qubit collapsed." But Wigner — outside the lab — has no way to tell collapse happened. To him, Friend + qubit are now in a 2-qubit superposition. Two valid descriptions of the same event.`;
} else if(s === 2){
wignerEl.innerHTML = `|${friendOutcome}⟩ <span style="color:var(--muted)">(I see the same answer)</span>`;
document.querySelectorAll('.wig-actor')[1].classList.add('measured');
msg.innerHTML = `Wigner finally measures the lab. He gets ${friendOutcome}, agreeing with Friend. The two pictures finally reconcile — but only retrospectively, and only because Wigner trusts that Friend's record is correct.`;
}
}
document.getElementById('wig-step1').onclick = () => stage === 0 && setState(1);
document.getElementById('wig-step2').onclick = () => stage === 1 && setState(2);
document.getElementById('wig-reset').onclick = () => setState(0);
setState(0);
})();
// -------- Double-Slit (Wave-Particle Duality) --------
(() => {
const detEl = document.getElementById('ds-detector');
const cv = document.getElementById('ds-screen');
const msg = document.getElementById('ds-msg');
const icon = document.getElementById('ds-det-icon');
if(!cv) return;
const ctx = cv.getContext('2d');
let hits = [];
function clear(){
hits = []; draw();
msg.textContent = 'Screen cleared. Click "Send" to fire photons.';
}
function draw(){
const w = cv.width = cv.clientWidth, h = cv.height;
ctx.clearRect(0,0,w,h);
ctx.fillStyle = 'rgba(168,85,247,.04)';
ctx.fillRect(0,0,w,h);
// Histogram
const BINS = 64;
const bins = new Array(BINS).fill(0);
hits.forEach(p => bins[Math.min(BINS-1, Math.max(0, Math.floor(p.x*BINS)))]++);
const max = Math.max(1, ...bins);
const bw = w / BINS;
ctx.fillStyle = 'rgba(124,58,237,.55)';
bins.forEach((c, i) => {
const bh = (c/max) * (h * 0.5);
ctx.fillRect(i*bw, h - bh, bw - 0.5, bh);
});
// Individual photon dots in the upper band
ctx.fillStyle = 'rgba(168,85,247,.95)';
hits.forEach(p => {
ctx.beginPath();
ctx.arc(p.x*w, p.y, 2, 0, Math.PI*2);
ctx.fill();
});
// Top label
ctx.fillStyle = '#8b93a7';
ctx.font = '11px system-ui';
ctx.fillText(`${hits.length} photon${hits.length===1?'':'s'}`, 10, 16);
}
function sample(detector){
// Photon-screen position x ∈ [0,1].
if(!detector){
// Wave behaviour: cos²(5πx) interference pattern (rejection sampling).
for(let i=0;i<200;i++){
const x = Math.random();
if(Math.random() < Math.cos(5*Math.PI*x)**2) return x;
}
return Math.random();
} else {
// Particle behaviour: 50/50 between two slit-centred Gaussians.
const slit = Math.random() < 0.5 ? 0.35 : 0.65;
const g = slit + (Math.random()+Math.random()+Math.random()-1.5) * 0.07;
return Math.min(0.99, Math.max(0.01, g));
}
}
function shoot(n){
const det = detEl.checked;
const h = cv.height;
for(let i=0;i<n;i++){
const x = sample(det);
const y = h*0.18 + Math.random() * (h*0.25);
hits.push({x, y});
}
draw();
const total = hits.length;
msg.innerHTML = det
? `Sent ${n} photon${n===1?'':'s'} with detector ON (slit A peek). After ${total} total → <b>two clumps</b> from each slit. No interference. Photons act as <b>particles</b>.`
: `Sent ${n} photon${n===1?'':'s'} with detector OFF. After ${total} total → <b>interference fringes</b> appear (cos² pattern). Each photon interfered with itself as a <b>wave</b>.`;
}
document.getElementById('ds-shoot1').onclick = () => shoot(1);
document.getElementById('ds-shootN').onclick = () => shoot(200);
document.getElementById('ds-clear').onclick = clear;
detEl.onchange = () => {
icon.classList.toggle('active', detEl.checked);
msg.innerHTML = detEl.checked
? '👁 Detector ON — measuring which slit forces the photon to act as a particle. Existing screen data preserved; new photons will land in two clumps.'
: '🌊 Detector OFF — no path measurement. Photons interfere with themselves and build a wave pattern.';
};
window.addEventListener('resize', draw);
clear();
})();
// -------- Quantum Eraser --------
(() => {
const detEl = document.getElementById('er-detector');
const eraEl = document.getElementById('er-eraser');
const cv = document.getElementById('er-screen');
const ctx = cv.getContext('2d');
const msg = document.getElementById('er-msg');
let hits = [];
function clear(){ hits = []; draw(); }
function draw(){
const w = cv.width = cv.clientWidth, h = cv.height;
ctx.clearRect(0,0,w,h);
// backdrop
ctx.fillStyle = 'rgba(124,58,237,.05)'; ctx.fillRect(0,0,w,h);
// bin into histogram
const BINS = 60;
const bins = new Array(BINS).fill(0);
hits.forEach(x => bins[Math.min(BINS-1, Math.max(0, Math.floor(x*BINS)))]++);
const max = Math.max(1, ...bins);
const bw = w / BINS;
bins.forEach((c, i) => {
const bh = (c/max) * (h - 20);
ctx.fillStyle = '#06b6d4';
ctx.fillRect(i*bw, h - bh, bw - 1, bh);
});
// recent hits as dots
ctx.fillStyle = 'rgba(255,255,255,.5)';
hits.slice(-20).forEach(x => {
ctx.beginPath();
ctx.arc(x*w, h - 6, 2, 0, Math.PI*2);
ctx.fill();
});
}
function sample(detector, eraser){
const interfering = !detector || (detector && eraser);
if(interfering){
// P(x) ∝ cos²(5πx) on x ∈ [0,1] — rejection sampling
for(let i=0;i<200;i++){
const x = Math.random();
const p = Math.cos(5*Math.PI*x) ** 2;
if(Math.random() < p) return x;
}
return Math.random();
} else {
// No interference: sum of two gaussians (one per slit)
const slit = Math.random() < 0.5 ? 0.35 : 0.65;
const g = slit + (Math.random()+Math.random()+Math.random()-1.5) * 0.07;
return Math.min(0.99, Math.max(0.01, g));