-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html.source
More file actions
executable file
·6165 lines (5680 loc) · 291 KB
/
Copy pathindex.html.source
File metadata and controls
executable file
·6165 lines (5680 loc) · 291 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
<html>
<head>
<title>MuqcsCraft</title>
<meta charset="utf-8"/>
<style type="text/css">
label:hover, button:hover, a:link:hover, a:visited:hover { background-color: #bbeeff; }
blockquote { margin-bottom: 0; margin-top: 0; }
</style>
<script language="JavaScript">
function toggleDisplay(stuffToToggle,elementThatExpandsStuff,elementThatCollapsesStuff) {
if ( stuffToToggle.style.display == 'none' ) {
stuffToToggle.style.display = '';
elementThatExpandsStuff.style.display = 'none';
elementThatCollapsesStuff.style.display = '';
}
else {
stuffToToggle.style.display = 'none';
elementThatExpandsStuff.style.display = '';
elementThatCollapsesStuff.style.display = 'none';
}
}
</script>
</head>
<body>
<table>
<tr>
<td>
<label><input id="displayOptionsOverlayCheckbox" type='checkbox' onclick='let div = document.getElementById("displayOptions"); if (this.checked) { let canvas_rect = document.getElementById("myCanvas").getBoundingClientRect(); div.style.backgroundColor = "rgba(192,224,255,0.75)"; div.style.position = "fixed"; div.style.top = canvas_rect.top; div.style.left = canvas_rect.left; } else { div.style.backgroundColor = div.style.position = div.style.top = div.style.left = ""; }'>Overlay<br/>Display Options</label>
<td>
<td>
Welcome to <b>MuqcsCraft</b> [<a href="https://github.com/MJMcGuffin/MuqcsCraft">source code</a>] [<a href="https://youtu.be/BCunU_gCXT4">video explainer</a>] [<a href="https://arxiv.org/abs/2510.00895">paper</a>], an open-source graphical simulator and visualizer for quantum circuits,
built on top of the <a href="https://github.com/MJMcGuffin/muqcs.js">Muqcs</a> library.
</table>
<!-- canvas id="myCanvas" width="900" height="750" style="border:2px solid #000000;" -->
<canvas id="myCanvas" width="1200" height="800" style="border:2px solid #000000;">
</canvas>
<p>
Use <b>Left mouse button</b> to drag-and-drop a gate.
To add a new qubit to the circuit, drag-and-drop any gate below the bottom qubit.
<p>
Some gates have parameters. To change a parameter, use Ctrl+left mouse button and drag left-right,
or use Shift+left mouse button and drag left-right to snap the parameter to nice values.
You can also click on a parameter to select it, and then use
Ctrl+left arrow, Ctrl+right arrow keys to adjust,
Shift+left arrow, Shift+right arrow keys to snap.
<p>
To <b>delete a gate</b>, you can
(1) left-click on the gate to select it, and then hit the Delete key;
or (2) drag the gate off the circuit and drop it outside;
or (3) press+release over the gate with the <b>Middle mouse button</b> (like in <a href="https://algassert.com/quirk">Quirk</a>).
<p>
To <b>UNDO</b>, hit the Back button in your web browser.
The state of the circuit is encoded in the query string of the browser's URL (like in Quirk),
hence circuits can be bookmarked and shared as hyperlinks in plain text.
<p>
Additional options:
<span id='g1e'>[<a href="javascript:toggleDisplay(g1,g1e,g1c)">Show...</a>]</span>
<span id='g1c' style="display:none">[<a href="javascript:toggleDisplay(g1,g1e,g1c)">Hide</a>]</span>
<blockquote>
<span id='g1' style="display:none">
<p>
Camera controls: <b>Shift+Right mouse button</b> drag to translate; <b>Ctrl+Right mouse button</b> drag left-right to zoom.
<br/>
<button onclick="frameButtonHandler()">Frame</button>
<button onclick="animatedFrameButtonHandler()">Animated Frame</button>
<p>
<button onclick="clearCircuitButtonHandler()">Clear Circuit</button>
Hit the Back button in your browser to Undo.
<p>
<button onclick="expandCircuitButtonHandler()">Expand Circuit</button>
Replaces certain gates with equivalent sequences of other gates so that their effects can be visualized on the state vector more easily, at the cost of making the circuit deeper.
If generalized gates are used, then fewer layers need to be added in the expansion.
See our paper for details.
Hit the Back button in your browser to Undo.
<br>
<label><input type='checkbox' id='useGeneralizedGatesCheckbox'>Use generalized gates in the expansion</label> to produce a shorter expansion.
<p>
<button onclick="printMagicButtonHandler()">Print Magic</button> Prints <a href="https://scholar.google.com/scholar?q=leone+Stabilizer+Renyi+Entropy">Second Stabilizer Rényi Entropy</a> of the output state to the console.
</span>
</blockquote>
<div id="displayOptions">
<p>
Display options:
<blockquote>
Local State
<blockquote>
<!--
<label><input type='checkbox' datavar="showFinalLocalState">▶Show final local state</label> <br/>
<label><input type='checkbox' datavar="showLocalStatePerLayer">▶Show local state per layer</label>
<br/>
-->
For each local state... <br/>
<label><input type='checkbox' datavar="LS_showPurity">Show Purity</label>
<label><input type='checkbox' datavar="LS_showLinearEntropy">Show Linear Entropy (= 1-Purity)</label>
<label><input type='checkbox' datavar="LS_showVonNeumannEntropy">Show Von Neumann Entropy</label>
<label><input type='checkbox' datavar="LS_showProbability">Show Probability</label>
<label><input type='checkbox' datavar="LS_showPhase">Show Phase</label>
</blockquote>
Half Matrix
<blockquote>
<!-- <label><input type='checkbox' datavar="showFinalHalfMatrix">▶Show Final Half Matrix</label> <br/> -->
In each cell of the Half Matrix, show... <br/>
<blockquote>
<label><input type='radio' name="radioGroup4" datavar="HM_cellContents" datavarvalue="HM_BARCHART">barchart</label><br/>
<blockquote>
For each pair of qubits... <br/>
<label><input type='checkbox' datavar="HM_showPurity">Show Purity</label>
<label><input type='checkbox' datavar="HM_showLinearEntropy">Show Linear Entropy (= 1-Purity)</label>
<label><input type='checkbox' datavar="HM_showVonNeumannEntropy">Show von Neumann Entropy</label>
<label><input type='checkbox' datavar="HM_showConcurrence">Show Concurrence</label>
<label><input type='checkbox' datavar="HM_showCorrelation">Show Correlation</label>
</blockquote>
<label><input type='radio' name="radioGroup4" datavar="HM_cellContents" datavarvalue="HM_RECT_GLYPHS">rectangle glyphs</label>
</blockquote>
</blockquote>
State Vectors
<blockquote>
<!-- <label><input type='checkbox' datavar="showStateVectorsPerLayer">▶Show state vectors per layer</label> <br/> -->
<label><input type='checkbox' datavar="allowMultipleColumns">Enable wrapping (multiple columns) within each state vector</label>
<label><input type='checkbox' datavar="displayOutsideBitstring">Show bitstrings outside cells</label>
<br/>
Show cells as ...
<blockquote>
<label><input type='radio' name="radioGroup2" datavar="cell_aspectRatio" datavarvalue="CELL_ASPECTRATIO_SQUARE">squares</label><br/>
<label><input type='radio' name="radioGroup2" datavar="cell_aspectRatio" datavarvalue="CELL_ASPECTRATIO_RECTANGULAR">rectangles</label>
<blockquote>
<label><input type='checkbox' datavar="displayInsideBitstring">Show bitstrings inside cells</label>
<label><input type='checkbox' datavar="displayInsideProbability">Show probabilities inside cells</label>
</blockquote>
</blockquote>
The length of the bar in each cell is<br/>
<blockquote>
<label><input type='radio' name="radioGroup3" datavar="barFunction" datavarvalue="BARFUNCTION_PROBABILITY">proportional to probability</label><br/>
<label><input type='radio' name="radioGroup3" datavar="barFunction" datavarvalue="BARFUNCTION_MAGNITUDE">proportional to magnitude of amplitude</label><br/>
<label><input type='radio' name="radioGroup3" datavar="barFunction" datavarvalue="BARFUNCTION_LOG_PROBABILITY">linear function of log<sub>2</sub> of probability</label><br/>
</blockquote>
</blockquote>
Visualizations Per Layer
<span id='g2e'>[<a href="javascript:toggleDisplay(g2,g2e,g2c)">Show...</a>]</span>
<span id='g2c' style="display:none">[<a href="javascript:toggleDisplay(g2,g2e,g2c)">Hide</a>]</span>
<blockquote>
<span id='g2' style="display:none">
<label><input type='checkbox' datavar="showVisOfAllLayers">Show all layers</label> <br/>
<label><input type='checkbox' datavar="scrollPerLayerVisHorizontally">Scroll horizontally when mouse hovers over circuit</label> <br/>
Show difference visualization on<br/>
<blockquote>
<label><input type='radio' name="radioGroup1" datavar="show_diffvis" datavarvalue="DIFFVIS_NONE">no layers</label><br/>
<label><input type='radio' name="radioGroup1" datavar="show_diffvis" datavarvalue="DIFFVIS_ONE">one layer</label><br/>
<label><input type='radio' name="radioGroup1" datavar="show_diffvis" datavarvalue="DIFFVIS_ALL">all layers</label><br/>
</blockquote>
</span>
</blockquote>
</blockquote>
<br/>
</div> <!-- displayOptions -->
Export options:
<span id='g3e'>[<a href="javascript:toggleDisplay(g3,g3e,g3c)">Show...</a>]</span>
<span id='g3c' style="display:none">[<a href="javascript:toggleDisplay(g3,g3e,g3c)">Hide</a>]</span>
<blockquote>
<span id='g3' style="display:none">
Export to Quirk:
<blockquote>
<a id="quirkLink" href="">View this circuit in Quirk</a>
(some gates may be omitted or not work)
</blockquote>
Export to IBM:
<blockquote>
<a href="https://quantum.cloud.ibm.com/composer">Open IBM Quantum Composer</a> <!-- previously https://quantum.ibm.com/composer/ -->
<br/>
OpenQASM code that you can paste into IBM Quantum Composer to get the same circuit (note that not all gates are supported by IBM Quantum Composer):
<br/>
<pre id="qasmText"></pre>
<button id="copyQASMButton">Copy OpenQASM code</button>
(some gates may be omitted or not work)
</blockquote>
Export to qcircuit for LaTeX:
<blockquote>
Qcircuit code that you can paste into a LaTeX document:
<br/>
<pre id="qcircuitText"></pre>
<button id="copyQcircuitButton">Copy qcircuit code</button>
</blockquote>
</span>
</blockquote>
<p>
Predefined circuits:
<span id='g4e'>[<a href="javascript:toggleDisplay(g4,g4e,g4c)">Show...</a>]</span>
<span id='g4c' style="display:none">[<a href="javascript:toggleDisplay(g4,g4e,g4c)">Hide</a>]</span>
<blockquote>
<span id='g4' style="display:none">
Bell states [<a href="https://en.wikipedia.org/wiki/Bell_state">reference</a>] <br/>
<blockquote>
There are four Bell states: Φ+, Φ-, Ψ+, Ψ-.
The first three are called triplet states.
Consider <a href='?circuit={"cols":[["H"],["•","X"]]}'>this circuit</a> that generates a Φ+ state
whose qubits are maximally correlated.
How does the correlation between the qubits change if we
<a href='?circuit={"cols":[["H"],["•","X"],["X^¼","X^¼"]]}'>add X<sup>0.25</sup></a> gates at the end of both qubits?
And what if we
<a href='?circuit={"cols":[["H"],["•","X"],["X^¼","X^¼"],["X^¼","X^¼"]]}'>do that again</a>?
<br/>
Now try <a href='?circuit={"cols":[["H","X"],["•","X"],[1,"Z"]]}'>this circuit</a> that generates a Ψ- state, also called a singlet state.
How does the correlation between the qubits change if we
add X<sup>0.25</sup> gates at the end of both qubits?
</blockquote>
<a href='?circuit={"cols":[["H"],["•","X"],[1,"•","X"]]}'>GHZ state</a> [<a href="https://en.wikipedia.org/wiki/Greenberger%E2%80%93Horne%E2%80%93Zeilinger_state">reference</a>] <br/>
<a href='?circuit={"cols":[["H"],["•","X"],[1,"•","X"],[1,1,"•","X"]]}'>GHZ-4 state</a> <br/>
<a href='?circuit={"cols":[["H",1,"Y^¼","X"],["•","X"],[1,"•","X"],[1,1,"•","X"]]}'>Variant of GHZ-4</a> <br/>
<a href='?circuit={%22cols%22:[[{%22id%22:%22Ryft%22,%22arg%22:%221.9106332362490184%22}],[%22%E2%80%A2%22,%22H%22],[1,%22%E2%80%A2%22,%22X%22],[%22%E2%80%A2%22,%22X%22],[%22X%22]]}'>W state</a> [<a href="https://en.wikipedia.org/wiki/W_state">reference</a>] <br/>
<a href='?circuit={"cols":[["H"],[1,1,1,"H"],["•","X",1,"•"],["X"],[1,1,1,"X"],["•",1,"X","•"],["X",1,"•"],[1,1,"•","X"]]}'>W-4 state</a> adapted from <a href="https://quantumcomputing.stackexchange.com/questions/4350/general-construction-of-w-n-state">here</a> <br/>
<a href='?circuit={"cols":[["H","Y^¼"],["•","X"],["Y^¼"],["•","X"]]}'>partial entanglement followed by partial disentanglement (1)</a> <br/>
<a href='?circuit={"cols":[["H",1,"Y^¼"],["•","X"],[1,"•","X"],[1,1,"•","X"],[1,"•","X"]]}'>partial entanglement followed by partial disentanglement (2)</a> <br/>
<a href='?circuit={"cols":[["Y^¼"],["•",1,"X"],["H"],[1,"X","•"],[1,1,"X"],[1,"H","•"],[1,1,"X"],["•","X","•"],[1,1,"X"],["•",1,"•","X"],[1,"•","•",1,"X"]]}'>variant of Werner state</a> based on Figure A1 in <a href="https://scholar.google.com/scholar?q=Bell+Diagonal+and+Werner+State+Generation+Entanglement+Non-Locality+Steering+and+Discord+on+the+IBM+Quantum+Computer">Riedel Garding et al. 2021</a><br/>
<a href='?circuit={"cols":[["Y^¼","Y^¼","Y^¼","Y^¼","Y^¼","Y^¼"]]}'>circuit generating |H>^(⊗6) magic state</a> with SSRE magic 2.490<br/>
<a href='?circuit={%22cols%22:[[{%22id%22:%22Y^ft%22,%22arg%22:%220.3040867239846964%22},{%22id%22:%22Y^ft%22,%22arg%22:%220.3040867239846964%22},{%22id%22:%22Y^ft%22,%22arg%22:%220.3040867239846964%22},{%22id%22:%22Y^ft%22,%22arg%22:%220.3040867239846964%22},{%22id%22:%22Y^ft%22,%22arg%22:%220.3040867239846964%22},{%22id%22:%22Y^ft%22,%22arg%22:%220.3040867239846964%22}],[{%22id%22:%22Z^ft%22,%22arg%22:%220.25%22},{%22id%22:%22Z^ft%22,%22arg%22:%220.25%22},{%22id%22:%22Z^ft%22,%22arg%22:%220.25%22},{%22id%22:%22Z^ft%22,%22arg%22:%220.25%22},{%22id%22:%22Z^ft%22,%22arg%22:%220.25%22},{%22id%22:%22Z^ft%22,%22arg%22:%220.25%22}]]}'>circuit generating |T>^(⊗6) magic state</a> with SSRE 3.510<br/>
<a href='?circuit={%22cols%22:[[{%22id%22:%22Ryft%22,%22arg%22:%220.9553166181245093%22},{%22id%22:%22Ryft%22,%22arg%22:%220.9553166181245093%22},{%22id%22:%22Ryft%22,%22arg%22:%220.9553166181245093%22},{%22id%22:%22Ryft%22,%22arg%22:%220.9553166181245093%22},{%22id%22:%22Ryft%22,%22arg%22:%220.9553166181245093%22},{%22id%22:%22Ryft%22,%22arg%22:%220.9553166181245093%22}],[{%22id%22:%22Rzft%22,%22arg%22:%220.7853981633974483%22},{%22id%22:%22Rzft%22,%22arg%22:%220.7853981633974483%22},{%22id%22:%22Rzft%22,%22arg%22:%220.7853981633974483%22},{%22id%22:%22Rzft%22,%22arg%22:%220.7853981633974483%22},{%22id%22:%22Rzft%22,%22arg%22:%220.7853981633974483%22},{%22id%22:%22Rzft%22,%22arg%22:%220.7853981633974483%22}]]}'>alternative circuit generating |T>^(⊗6) magic state</a> with SSRE 3.510<br/>
<a href='?circuit={"cols":[["H","H","H","H","H","H"],["•","Z^¼"],[1,"•","Z^¼"],[1,1,"•","Z^¼"],[1,1,1,"•","Z^¼"],[1,1,1,1,"•","Z^¼"]]}'>circuit with cascading CT gates</a> with SSRE magic 2.848<br/>
<a href='?circuit={"cols":[["H","H","H","H","H","H"],["•","•","Z"],[1,1,1,"•","•","Z"],[1,"•","•","Z"],["Z",1,1,1,"•","•"],[1,1,"•","•","Z"],["•","Z",1,1,1,"•"]]}'>circuit with cyclic CCZ gates</a> with SSRE magic 3.696<br/>
<a href='?circuit={"cols":[["H","H","H","H","H","H"],["•","•","Z^¼"],[1,1,1,"•","•","Z^¼"],[1,"•","•","Z^¼"],["Z^¼",1,1,1,"•","•"],[1,1,"•","•","Z^¼"],["•","Z^¼",1,1,1,"•"],["•","•","Z^¼"],[1,1,1,"•","•","Z^¼"],[1,"•","•","Z^¼"],["Z^¼",1,1,1,"•","•"],[1,1,"•","•","Z^¼"],["•","Z^¼",1,1,1,"•"],["•","•","Z^¼"],[1,1,1,"•","•","Z^¼"],[1,"•","•","Z^¼"],["Z^¼",1,1,1,"•","•"],[1,1,"•","•","Z^¼"],["•","Z^¼",1,1,1,"•"]]}'>circuit with cyclic CCT gates</a> with SSRE magic 3.920<br/>
Different ways to implement Grover's algorithm. Each one shows 1 or 2 layers that initialize, then the oracle, then the diffusion operator. Challenge: show that these are all equivalent.
<blockquote>
<a href='?circuit={"cols":[["H","H","H","H"],["•","◦","•","Z"],["H","H","H","H"],[1,1,1,"X"],["◦","◦","◦","Z"],[1,1,1,"X"],["H","H","H","H"]]}'>Grover example 1</a><br/>
<a href='?circuit={"cols":[["H","H","H","H"],["•","◦","•","Z"],["H","H","H","H"],["X","X","X","X"],["•","•","•","Z"],["X","X","X","X"],["H","H","H","H"]]}'>Grover example 2</a><br/>
<a href='?circuit={"cols":[["H","H","H","H"],["•","◦","•","Z"],["H","H","H","H"],["X","X","X","X"],[1,1,1,"H"],["•","•","•","X"],[1,1,1,"H"],["X","X","X","X"],["H","H","H","H"]]}'>Grover example 3</a><br/>
<a href='?circuit={"cols":[["X","X","X","X"],["H"],[1,"H"],[1,1,"H"],[1,1,1,"H"],["•","◦","•","Z"],["H"],[1,"H"],[1,1,"H"],["•","•","•","X"],[1,1,"H"],[1,"H"],["H"]]}'>Grover example 4</a><br/>
</blockquote>
Puzzles:
<blockquote>
Design a circuit that entangles, and then disentangles, two qubits.
<blockquote>
<a href='?circuit={"cols":[["H"],["•","X"],["•","X"]]}'>example 1</a> <br/>
<a href='?circuit={"cols":[["H"],["•","X"],["X","•"]]}'>example 2</a> <br/>
</blockquote>
Design a circuit that only <em>partially</em> entangles two qubits.
<blockquote>
<a href='?circuit={"cols":[["H","Y^¼"],["•","X"]]}'>example 1</a> <br/>
<a href='?circuit={"cols":[["H"],["•","Y^¼"]]}'>example 2</a> <br/>
<a href='?circuit={"cols":[["X^½","X^½"],["•","Z^½"]]}'>example 3</a> <br/>
</blockquote>
Design a circuit on 2 qubits, using as few gates as possible, that results in the 4 base states (00, 01, 10, 11) having 4 distinct probabilities. <br/>
<blockquote>
<a href='?circuit={"cols":[["X^¼","X^¼"],["Y^¼"]]}'>candidate solution 1</a> <br/>
<a href='?circuit={"cols":[["H"],["•","Y^¼"]]}'>candidate solution 2</a> <br/>
</blockquote>
Design a circuit that results in some of the base states having probabilities that follow a geometric sequence, for example,
a base state with probability 50%, another with a probability of 25%, another with 12.5%, etc.
<blockquote>
<a href='?circuit={"cols":[["H"],["•","H"],[1,"•","H"],[1,1,"•","H"]]}'>candidate solution</a><br/>
</blockquote>
Design a circuit on 4 qubits that results in the same amplitude on all 16 base states,
except for one base state whose phase is opposite to the others.
This opposing phase, in effect, "tags" the base state as different from the others, and can simulate an oracle in Grover's algorithm.
<blockquote>
First, do this for the state 1111, so its phase is opposite all the others,
but all amplitudes have the same magnitude.
<a href='?circuit={"cols":[["H","H","H","H"],["•","•","•","Z"]]}'>candidate solution 1</a>,
<a href='?circuit={"cols":[["H","H","H","H"],["•","Z","•","•"]]}'>candidate solution 2</a>,
<a href='?circuit={"cols":[["H","H","H","H"],[1,1,1,"H"],["•","•","•","X"],[1,1,1,"H"]]}'>candidate solution 3</a>
<br/>
Then modify the circuit so that state 1011 has its phase opposite all the others.
<a href='?circuit={"cols":[["H","H","H","H"],["•","•","◦","Z"]]}'>candidate solution 1</a>,
<a href='?circuit={"cols":[["H","H","H","H"],["•","Z","◦","•"]]}'>candidate solution 2</a>,
<a href='?circuit={"cols":[["H","H","H","H"],[1,1,"X"],["•","•","•","Z"],[1,1,"X"]]}'>candidate solution 3</a>
<br/>
Then try to do it for 0100.
<a href='?circuit={"cols":[["H","H","H","H"],["◦","◦","Z","◦"]]}'>candidate solution 1</a>
<br/>
Then try for 0000.
<a href='?circuit={"cols":[["H","H","H","H"],["Z","◦","◦","◦"],["X"]]}'>candidate solution 1</a>
<br/>
</blockquote>
Design circuits to produce examples of each of the states in the set {pure, partially mixed, maximally mixed}×{product state, separable, partially entangled, maximally entangled}<br/>
</blockquote>
</span>
</blockquote>
<p>
<a href="https://github.com/MJMcGuffin/muqcs.js?tab=readme-ov-file#matrix-definitions">List of definitions of matrices</a> for quantum gates
<br/>
<br/>
SIMPLE_INCLUDE muqcs.js
<!----- START: web analytics via https://www.goatcounter.com/ , to log visits, without tracking personal info ----->
<script>
window.goatcounter = {
path: function(p) {
// remove everything after the substring
let substring = "?circuit=";
let index = p.indexOf(substring);
if (index !== -1) {
p = p.slice(0, index + substring.length);
}
// prepend with the domain name
return location.host + p;
}
}
</script>
<script data-goatcounter="https://mjmcguffin.goatcounter.com/count"
async src="//gc.zgo.at/count.js"></script>
<!----- END: web analytics ----->
<script language="JavaScript">
// ============================================================
// Vec2 objects are for storing 2D points and 2D vectors.
// To create a new instance, use the new keyword:
// let vector_a = new Vec2();
// let vector_b = new Vec2(x,y);
// These objects are mutable. After an instance has been created,
// its coordinates can be changed by writing directly to data members:
// vector_a.x = 10;
// vector_a.y = -2;
// ============================================================
class Vec2 {
constructor(x=0,y=0) {
this.x = x;
this.y = y;
}
// Performs a deep copy.
copy(other) {
this.x = other.x; this.y = other.y;
}
// Returns the negation of the vector.
negate() { return new Vec2(-this.x,-this.y); }
// Returns the Euclidean length (also called magnitude or L2-norm) of the vector.
norm() { return Math.sqrt( this.x*this.x + this.y*this.y ); }
// Returns the squared length.
// This is useful when the caller needs to compare
// the length of a vector to a pre-defined threshold,
// or compare the lengths of two vectors:
// in such cases, comparing the squared length is sufficient,
// and saves a square root operation.
normSquared() { return this.x*this.x + this.y*this.y; }
// Returns a normalized vector of unit length.
normalize() {
let n = this.norm();
if ( n > 0 ) {
let k = 1.0/n;
return new Vec2( k*this.x, k*this.y );
}
return new Vec2();
}
angle() {
let lengthSquared = this.x*this.x + this.y*this.y;
if ( lengthSquared === 0 ) return 0;
let sine = Math.abs( this.y/Math.sqrt( lengthSquared ) );
let theta = ( sine >= 1 ) ? Math.PI/2 : Math.asin( sine );
if ( this.x < 0 ) theta = Math.PI - theta;
if ( this.y < 0 ) theta = - theta;
return theta;
}
setAngle( theta ) {
let delta_theta = theta - this.angle();
let sine = Math.sin( delta_theta );
let cosine = Math.cos( delta_theta );
let rotatedX = this.x * cosine - this.y * sine;
let rotatedY = this.x * sine + this.y * cosine;
this.x = rotatedX;
this.y = rotatedY;
}
// A static method that returns the sum of two vectors.
static sum( v1, v2 ) {
return new Vec2( v1.x+v2.x, v1.y+v2.y );
}
// A static method that returns the difference of two vectors.
static diff( v1, v2 ) {
return new Vec2( v1.x-v2.x, v1.y-v2.y );
}
// A static method that returns the product of a vector with a scalar.
static mult( v, k ) {
return new Vec2( k*v.x, k*v.y );
}
// A static method that returns the dot product of two vectors
static dot( v1, v2 ) {
return v1.x*v2.x + v1.y*v2.y;
}
// A static method that returns the centroid of two vectors
static average( v1, v2 ) {
return new Vec2( (v1.x+v2.x)*0.5, (v1.y+v2.y)*0.5 );
}
// Returns the centroid of an array of vectors
static centroid( listOfPoints ) {
let x = 0;
let y = 0;
let N = listOfPoints.length;
for ( let i = 0; i < N; i ++ ) {
x += listOfPoints[i].x;
y += listOfPoints[i].y;
}
return new Vec2( x/N, y/N );
}
static distance( v1, v2 ) {
let dx = v1.x - v2.x;
let dy = v1.y - v2.y;
return Math.sqrt( dx*dx + dy*dy );
}
static distanceSquared( v1, v2 ) {
let dx = v1.x - v2.x;
let dy = v1.y - v2.y;
return dx*dx + dy*dy;
}
}
// ============================================================
// Box2 objects are for storing 2D axis-aligned rectangles.
// To create a new instance, use the new keyword:
// let box_a = new Box2();
// let box_b = new Box2(new Vec2(-10,-10),new Vec2(10,10));
// ============================================================
class Box2 {
constructor( vec2_min = null, vec2_max = null ) {
// Internally, the min and max points are diagonally opposite,
// and are only valid if isEmpty===false.
// Below, we initialize things based on what the client passed in.
this.isEmpty = true;
this.min = new Vec2();
this.max = new Vec2();
if ( vec2_min !== null && vec2_max !== null ) {
this.boundPoint( vec2_min );
this.boundPoint( vec2_max );
}
}
clear() { this.isEmpty = true; this.min = new Vec2(); this.max = new Vec2(); }
center() { return Vec2.average(this.min,this.max); }
diagonal() { return Vec2.diff(this.max,this.min); }
width() { return this.max.x - this.min.x; }
height() { return this.max.y - this.min.y; }
containsPoint( q ) {
return !( this.isEmpty || q.x < this.min.x || q.x > this.max.x || q.y < this.min.y || q.y > this.max.y );
}
containsBox( b ) {
if ( this.isEmpty ) return false;
if ( b.isEmpty ) return true;
return this.min.x <= b.min.x && b.max.x <= this.max.x && this.min.y <= b.min.y && b.max.y <= this.max.y;
}
// Returns true if there is any overlap with the given rectangle
overlapsBox( b ) {
if ( this.isEmpty || b.isEmpty ) return false;
return ! (
b.max.x < this.min.x
|| b.min.x > this.max.x
|| b.max.y < this.min.y
|| b.min.y > this.max.y
);
}
// Enlarges the box enough to contain the given point
boundPoint( vec2 ) {
if ( this.isEmpty ) {
this.isEmpty = false;
this.min.copy( vec2 );
this.max.copy( vec2 );
}
else {
if ( vec2.x < this.min.x ) this.min.x = vec2.x;
else if ( vec2.x > this.max.x ) this.max.x = vec2.x;
if ( vec2.y < this.min.y ) this.min.y = vec2.y;
else if ( vec2.y > this.max.y ) this.max.y = vec2.y;
}
}
boundPoints( points ) {
for ( let i = 0; i < points.length; ++i ) {
this.boundPoint( points[i] );
}
}
// Enlarges the box enough to contain the given box
boundBox( box ) {
if ( ! box.isEmpty ) {
this.boundPoint( box.min );
this.boundPoint( box.max );
}
}
// Find the intersection with the given box and save the result.
intersectBox( b ) {
if ( this.isEmpty ) return;
if ( b.isEmpty ) {
clear();
return;
}
this.min.x = Math.max( this.min.x, b.min.x );
this.min.y = Math.max( this.min.y, b.min.y );
this.max.x = Math.min( this.max.x, b.max.x );
this.max.y = Math.min( this.max.y, b.max.y );
if ( this.min.x > this.max.x || this.min.y > this.max.y ) {
this.clear();
}
}
}
// ============================================================
// Draw2 objects are for managing the transformation between
// pixel space and a 2D world space, allowing a client to pan and zoom.
// The objects also manage the drawing of simple shapes on a canvas,
// allowing a client to pass in coordinates in either space
// (pixel space or world space).
// To create a new instance, use the new keyword:
// let draw2 = new Draw2(canvas);
// ============================================================
// TD_ prefix means Text Direction
const TD_HORIZONTALLY_RIGHT = 0;
const TD_VERTICALLY_DOWN = 1;
class Draw2 {
static PIXELS = "pixels";
static WORLD = "world";
constructor(canvas) {
this.canvas = canvas;
this.canvas_context = canvas.getContext("2d");
this.canvasWidth_pixels = canvas.width;
this.canvasHeight_pixels = canvas.height;
this.offsetX_pixels = 0;
this.offsetY_pixels = 0;
this.scaleFactorInWorldSpaceUnitsPerPixel = 1.0; // greater if user is more zoomed out
this.setFont(this.canvas_context.font);
this.coordinateSystem = Draw2.PIXELS;
this.resetWorldTransformation();
}
setFont(fontName/*Example: 'italic 27px Calibri'*/) {
this.canvas_context.font = fontName;
this.fontHeight = parseInt(this.canvas_context.font.match(/\d+/)[0],10);
}
setFontHeight( fontHeight /*in pixels*/ ) {
this.canvas_context.font = fontHeight.toString() + "px sans-serif";
this.fontHeight = parseInt(this.canvas_context.font.match(/\d+/)[0],10);
}
convertPixelsToWorldSpaceUnitsX( x_pixels ) {
return ( x_pixels - this.offsetX_pixels )*this.scaleFactorInWorldSpaceUnitsPerPixel;
}
convertPixelsToWorldSpaceUnitsY( y_pixels ) {
return ( y_pixels - this.offsetY_pixels )*this.scaleFactorInWorldSpaceUnitsPerPixel;
}
convertPixelsToWorldSpaceUnits( p_pixels ) {
return new Vec2(
( p_pixels.x - this.offsetX_pixels )*this.scaleFactorInWorldSpaceUnitsPerPixel,
( p_pixels.y - this.offsetY_pixels )*this.scaleFactorInWorldSpaceUnitsPerPixel
);
}
convertWorldSpaceUnitsToPixelsX( x_world ) {
return x_world / this.scaleFactorInWorldSpaceUnitsPerPixel + this.offsetX_pixels;
}
convertWorldSpaceUnitsToPixelsY( y_world ) {
return y_world / this.scaleFactorInWorldSpaceUnitsPerPixel + this.offsetY_pixels;
}
convertWorldSpaceUnitsToPixels( p_world ) {
return new Vec2(
p_world.x / this.scaleFactorInWorldSpaceUnitsPerPixel + this.offsetX_pixels,
p_world.y / this.scaleFactorInWorldSpaceUnitsPerPixel + this.offsetY_pixels
);
}
translate( deltaX_pixels, deltaY_pixels ) {
this.offsetX_pixels += deltaX_pixels;
this.offsetY_pixels += deltaY_pixels;
}
zoomIn(
zoomFactor // greater than 1 to zoom in, between 0 and 1 to zoom out
) {
let centerX_pixels = this.canvasWidth_pixels * 0.5;
let centerY_pixels = this.canvasHeight_pixels * 0.5;
this.scaleFactorInWorldSpaceUnitsPerPixel /= zoomFactor;
this.offsetX_pixels = centerX_pixels - (centerX_pixels - this.offsetX_pixels) * zoomFactor;
this.offsetY_pixels = centerY_pixels - (centerY_pixels - this.offsetY_pixels) * zoomFactor;
}
// Causes the zoom and translation to be adjusted to fit the given rectangle within the canvas
frameWithinCanvasRegion(
rect, // an instance of Box2; the rectangle (in world space) to frame
expand, // true if caller wants a margin of whitespace added around the rect
region_x,region_y, // pixel coordinates of upper left corner of region within the canvas
region_w, region_h // dimensions in pixels
) {
if ( rect.isEmpty || rect.diagonal().x === 0 || rect.diagonal().y === 0 ) {
return;
}
if ( expand ) {
let diagonal = rect.diagonal().norm() / 50;
let v = new Vec2( diagonal, diagonal );
rect = new Box2( Vec2.diff(rect.min,v), Vec2.sum(rect.max,v) );
}
if ( rect.width() / rect.height() >= region_w / region_h ) {
// The rectangle to frame is wider (or shorter) than the region of the canvas,
// so the limiting factor is the width of the rectangle.
this.offsetX_pixels = - rect.min.x * region_w / rect.width() + region_x;
this.scaleFactorInWorldSpaceUnitsPerPixel = rect.width() / region_w;
this.offsetY_pixels = region_h/2 - rect.center().y / this.scaleFactorInWorldSpaceUnitsPerPixel + region_y;
}
else {
// The limiting factor is the height of the rectangle.
this.offsetY_pixels = - rect.min.y * region_h / rect.height() + region_y;
this.scaleFactorInWorldSpaceUnitsPerPixel = rect.height() / region_h;
this.offsetX_pixels = region_w/2 - rect.center().x / this.scaleFactorInWorldSpaceUnitsPerPixel + region_x;
}
}
frameWithinEntireCanvas(
rect, // an instance of Box2; the rectangle (in world space) to frame
expand // true if caller wants a margin of whitespace added around the rect
) {
this.frameWithinCanvasRegion(rect,expand,0,0,this.canvasWidth_pixels,this.canvasHeight_pixels);
}
translateToEnclose( targetRect ) {
let canvasRect_world = new Box2(
this.convertPixelsToWorldSpaceUnits(
new Vec2( 0, 0 )
),
this.convertPixelsToWorldSpaceUnits(
new Vec2( this.canvasWidth_pixels, this.canvasHeight_pixels )
)
);
if (canvasRect_world.containsBox(targetRect)) {
// The target is already within the canvas
return;
}
let canvasCenter_world = canvasRect_world.center();
let targetCenter_world = targetRect.center();
let d1 = Vec2.diff( targetCenter_world, canvasCenter_world );
let d1_length = d1.norm();
let canvas_halfDiagonal = Vec2.mult( canvasRect_world.diagonal(), 0.5 );
let target_halfDiagonal = Vec2.mult( targetRect.diagonal(), 0.5 );
if (
target_halfDiagonal.x > canvas_halfDiagonal.x
|| target_halfDiagonal.y > canvas_halfDiagonal.y
) {
// The target is too big to fit in the canvas without zooming out,
// so just center the target in the canvas
// by applying the d1 translation.
this.offsetX_pixels -= d1.x / this.scaleFactorInWorldSpaceUnitsPerPixel;
this.offsetY_pixels -= d1.y / this.scaleFactorInWorldSpaceUnitsPerPixel;
return;
}
let distanceToTranslate = 0;
let candidateDistance = 0;
if ( d1.x < 0 ) {
// Find distance to translate toward -x, using similar triangles.
// Larger triangle's hypotenuse / base = smaller triangle's hypotenuse / base
// d1_length / (-d1.x) = candidateDistance / (-d1.x-(canvas_halfDiagonal.x - target_halfDiagonal.x))
candidateDistance = d1_length / (-d1.x) * (-d1.x-(canvas_halfDiagonal.x - target_halfDiagonal.x));
if ( candidateDistance > distanceToTranslate ) {
distanceToTranslate = candidateDistance;
}
}
else if ( d1.x > 0 ) {
// Find distance to translate toward +x, using similar triangles.
// Larger triangle's hypotenuse / base = smaller triangle's hypotenuse / base
// d1_length / (d1.x) = candidateDistance / (d1.x-(canvas_halfDiagonal.x - target_halfDiagonal.x))
candidateDistance = d1_length / (d1.x) * (d1.x-(canvas_halfDiagonal.x - target_halfDiagonal.x));
if ( candidateDistance > distanceToTranslate ) {
distanceToTranslate = candidateDistance;
}
}
if ( d1.y < 0 ) {
// Find distance to translate toward -y, using similar triangles.
// Larger triangle's hypotenuse / base = smaller triangle's hypotenuse / base
// d1_length / (-d1.y) = candidateDistance / (-d1.y-(canvas_halfDiagonal.y - target_halfDiagonal.y))
candidateDistance = d1_length / (-d1.y) * (-d1.y-(canvas_halfDiagonal.y - target_halfDiagonal.y));
if ( candidateDistance > distanceToTranslate ) {
distanceToTranslate = candidateDistance;
}
}
else if ( d1.y > 0 ) {
// Find distance to translate toward +y, using similar triangles.
// Larger triangle's hypotenuse / base = smaller triangle's hypotenuse / base
// d1_length / (d1.y) = candidateDistance / (d1.y-(canvas_halfDiagonal.y - target_halfDiagonal.y))
candidateDistance = d1_length / (d1.y) * (d1.y-(canvas_halfDiagonal.y - target_halfDiagonal.y));
if ( candidateDistance > distanceToTranslate ) {
distanceToTranslate = candidateDistance;
}
}
// Scale d1 to have length distanceToTranslate
d1 = Vec2.mult( d1.normalize(), distanceToTranslate );
// Apply the d1 translation.
this.offsetX_pixels -= d1.x / this.scaleFactorInWorldSpaceUnitsPerPixel;
this.offsetY_pixels -= d1.y / this.scaleFactorInWorldSpaceUnitsPerPixel;
}
resize(
w, h // the new canvas dimensions, in pixels
) {
let oldCenter = this.convertPixelsToWorldSpaceUnits( new Vec2(
this.canvasWidth_pixels * 0.5, this.canvasHeight_pixels * 0.5
) );
let radius = Math.min( this.canvasWidth_pixels, this.canvasHeight_pixels ) * 0.5 * this.scaleFactorInWorldSpaceUnitsPerPixel;
this.canvasWidth_pixels = w;
this.canvasHeight_pixels = h;
if ( radius > 0 ) {
this.frameWithinEntireCanvas(
new Box2(
new Vec2( oldCenter.x - radius, oldCenter.y - radius ),
new Vec2( oldCenter.x + radius, oldCenter.y + radius )
),
false
);
}
}
setCoordinateSystemToPixels() {
this.coordinateSystem = Draw2.PIXELS;
}
setCoordinateSystemToWorldSpaceUnits() {
this.coordinateSystem = Draw2.WORLD;
}
setWorldTransformation( /* Vec2 */ translation, scale, angle /*in radians*/ ) {
this.hasWorldTransform = true;
this.worldTransform_translation.copy( translation );
this.worldTransform_scale = scale;
this.worldTransform_angle = angle;
this.worldTransform_sine = Math.sin( angle );
this.worldTransform_cosine = Math.cos( angle );
//console.log( "transforming with " + scale + "," + angle + ", " + this.worldTransform_sine );
}
resetWorldTransformation() {
this.hasWorldTransform = false;
this.worldTransform_translation = new Vec2();
this.worldTransform_scale = 1.0;
this.worldTransform_angle = 0;
}
applyTransformation( x, y ) {
let rotatedX = x * this.worldTransform_cosine - y * this.worldTransform_sine;
let rotatedY = x * this.worldTransform_sine + y * this.worldTransform_cosine;
let p = Vec2.sum( Vec2.mult( new Vec2( rotatedX, rotatedY ), this.worldTransform_scale ), this.worldTransform_translation );
//console.log("apply " + x + "," + y + "; ; " + p.x + ", " + p.y + ", " + this.worldTransform_sine + ", " + this.worldTransform_cosine + " , " + this.worldTransform_scale + ", " + this.worldTransform_translation.x + ", " + this.worldTransform_translation.y );
return p;
}
setStrokeColor_array( array ) {
this.setStrokeColor(array[0],array[1],array[2],array[3]);
}
setStrokeColor(
red, green, blue, // between 0 and 255
alpha=1.0 // between 0.0 and 1.0
) {
if ( alpha === 1.0 )
this.canvas_context.strokeStyle = "rgb("+red+","+green+","+blue+")";
else
this.canvas_context.strokeStyle = "rgba("+red+","+green+","+blue+","+alpha+")";
}
setFillColor_array( array ) {
this.setFillColor(array[0],array[1],array[2],array[3]);
}
setFillColor(
red, green, blue, // between 0 and 255
alpha=1.0 // between 0.0 and 1.0
) {
if ( alpha === 1.0 )
this.canvas_context.fillStyle = "rgb("+red+","+green+","+blue+")";
else
this.canvas_context.fillStyle = "rgba("+red+","+green+","+blue+","+alpha+")";
}
setLineWidth( lw ) {
this.canvas_context.lineWidth = lw;
}
clear(
red, green, blue // between 0 and 255
) {
this.setFillColor(red,green,blue);
this.canvas_context.fillRect(0, 0, this.canvas.width, this.canvas.height);
}
drawLine( x1, y1, x2, y2 ) {
if ( this.coordinateSystem === Draw2.WORLD ) {
//console.log("drawLine " + x1 + "," + y1 + ", " + x2 + "," + y2 );
if ( this.hasWorldTransform ) {
// console.log("drawLine " + x1 + "," + y1 + ", " + x2 + "," + y2 );
let p = this.applyTransformation(x1,y1);
x1 = p.x;
y1 = p.y;
p = this.applyTransformation(x2,y2);
x2 = p.x;
y2 = p.y;
}
//console.log("drawLine " + x1 + "," + y1 + ", " + x2 + "," + y2 );
x1 = this.convertWorldSpaceUnitsToPixelsX( x1 );
y1 = this.convertWorldSpaceUnitsToPixelsY( y1 );
x2 = this.convertWorldSpaceUnitsToPixelsX( x2 );
y2 = this.convertWorldSpaceUnitsToPixelsY( y2 );
}
this.canvas_context.beginPath();
this.canvas_context.moveTo(x1,y1);
this.canvas_context.lineTo(x2,y2);
this.canvas_context.stroke();
}
drawRect( x, y, w, h, isFilled=false ) {
if ( w < 0 ) {
w = -w;
x -= w;
}
if ( h < 0 ) {
h = -h;
y -= h;
}
if ( this.coordinateSystem === Draw2.WORLD ) {
if ( this.hasWorldTransform ) {
let p = this.applyTransformation(x,y);
x = p.x;
y = p.y;
}
x = this.convertWorldSpaceUnitsToPixelsX( x );
y = this.convertWorldSpaceUnitsToPixelsY( y );
w /= this.scaleFactorInWorldSpaceUnitsPerPixel;
h /= this.scaleFactorInWorldSpaceUnitsPerPixel;
}
if ( isFilled ) this.canvas_context.fillRect( x, y, w, h );
else this.canvas_context.strokeRect( x, y, w, h );
}
fillRect( x, y, w, h ) {
this.drawRect(x,y,w,h,true);
}
drawCircle( x_center, y_center, radius, isFilled=false ) {
if ( this.coordinateSystem === Draw2.WORLD ) {
x_center = this.convertWorldSpaceUnitsToPixelsX( x_center );
y_center = this.convertWorldSpaceUnitsToPixelsY( y_center );
radius /= this.scaleFactorInWorldSpaceUnitsPerPixel;
}
this.canvas_context.beginPath();
this.canvas_context.arc(x_center, y_center, radius, 0, 2 * Math.PI, false);
if ( isFilled ) this.canvas_context.fill();
else this.canvas_context.stroke();
}
drawArc( x_center, y_center, radius, startAngle /*radians*/, endAngle /*radians*/, isFilled=false ) {
if ( this.coordinateSystem === Draw2.WORLD ) {
x_center = this.convertWorldSpaceUnitsToPixelsX( x_center );
y_center = this.convertWorldSpaceUnitsToPixelsY( y_center );
radius /= this.scaleFactorInWorldSpaceUnitsPerPixel;
}
this.canvas_context.beginPath();
if ( isFilled ) this.canvas_context.moveTo(x_center,y_center);
this.canvas_context.arc(x_center, y_center, radius, startAngle, endAngle, startAngle > endAngle /*counterclockwise*/);
if ( isFilled ) this.canvas_context.fill();
else this.canvas_context.stroke();
}
fillCircle( x_center, y_center, radius ) {
this.drawCircle( x_center, y_center, radius, true );
}
drawPolyline( points, isFilled=false, isClosed=false ) {
if ( points.length <= 1 )
return;
let x;
let y;
this.canvas_context.beginPath();
x = points[0].x;
y = points[0].y;
if ( this.coordinateSystem === Draw2.WORLD ) {
x = this.convertWorldSpaceUnitsToPixelsX( x );
y = this.convertWorldSpaceUnitsToPixelsY( y );
}
this.canvas_context.moveTo(x,y);
for ( let i = 1; i < points.length; ++i ) {
x = points[i].x;
y = points[i].y;
if ( this.coordinateSystem === Draw2.WORLD ) {
x = this.convertWorldSpaceUnitsToPixelsX( x );
y = this.convertWorldSpaceUnitsToPixelsY( y );
}
this.canvas_context.lineTo(x,y);
}
if ( isClosed ) this.canvas_context.closePath();
if ( isFilled ) this.canvas_context.fill();
else this.canvas_context.stroke();
}
drawPolygon( points, isFilled=false ) {
this.drawPolyline( points, isFilled, true );
}
fillPolygon( points ) {
this.drawPolyline( points, true, true );
}
drawArrowHead(
x, y, // the tip of the arrow
direction_x,direction_y, // a vector; its length doesn't matter
arrowHeadLength,
isFilled = true,
isStroked = true
) {
// scale the direction vector to have the appropriate length
let forwardVector = Vec2.mult( new Vec2(direction_x,direction_y).normalize(), arrowHeadLength );
let tip = new Vec2( x, y );
let back = Vec2.diff( tip, forwardVector );
let lateralVector = new Vec2( forwardVector.y / 2, - forwardVector.x / 2 );
let side1 = Vec2.diff( back, lateralVector );
let side2 = Vec2.sum( back, lateralVector );
if ( isFilled )
this.drawPolygon( [ tip, side1, side2 ], true );
if ( isStroked )
this.drawPolygon( [ tip, side1, side2 ], false );
}
drawArithmeticOperator(
x, y, // center
diameter,
symbol,
isFilled = true,
isStroked = true