-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
2388 lines (2218 loc) · 107 KB
/
index.html
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>
<body>
Open a console (in Chrome, this is done by selecting 'Developer Tools'). From the console prompt, you can call functions in the code and see output printed to the console.
<p>
Or go to the <a href="https://github.com/MJMcGuffin/muqcs">github repository</a> page.
</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/13.0.2/math.js"></script>
<script>
// CONVENTIONs
//
// Assume that, in a quantum circuit with n qubits, the qubits are numbered
// from top to bottom as 0 to (n-1), respectively, and furthermore that the
// top qubit is the least significant bit (LSB), and the bottom is the most
// significant bit (MSB). For example, if there are 3 qubits labeled q0, q1, q2,
// from top to bottom, these might store (q2,q1,q0) = (0,1,1) to encode 3
// or (q2,q1,q0) = (1,0,0) to encode 4. Given these assumptions, there are
// two ways to simulate the circuit, described below, that correspond to
// different matrices and different orderings for tensor products.
// Sometimes the terms "big-endian" or "little-endian" are used to refer
// to choices related to this, but I haven't found clear definitions
// or consistent usage of these terms.
//
// Common software convention:
// - Tensor products are done in order of decreasing bit significance.
// https://quantumcomputing.stackexchange.com/questions/8244/big-endian-vs-little-endian-in-qiskit
// seems to confirm that Qiskit works this way.
// - In a 2-qubit circuit, if we have a 2-qubit gate where q0 is a control
// bit and q1 has a conditionally applied operation with 2x2 matrix [a b; c d],
// the 4x4 matrix for the gate would be [1 0 0 0; 0 a 0 b; 0 0 1 0; 0 c 0 d],
// which is endian-reversed with how 4x4 matrices are usually presented in
// textbooks on quantum computing.
// See https://qiskit.org/documentation/tutorials/circuits/3_summary_of_quantum_operations.html#Basis-vector-ordering-in-Qiskit
// - In a 3-qubit circuit, the state vector would contain 8 elements,
// and the 2nd of these would correspond to (q2,q1,q0) = (0,0,1),
// which is more natural for reading. This appears to match the
// presentation of output from Quirk and IBM Quantum Composer.
// Quirk's doc/README.md file ( https://github.com/Strilanc/Quirk/blob/master/doc/README.md )
// states "Kets are big-endian. |00101> is 5, not 20",
// and https://algassert.com/post/1707 further discusses this.
//
// Textbook convention:
// - Tensor products are done in order of increasing bit significance.
// This seems to match when
// https://qiskit.org/documentation/tutorials/circuits/3_summary_of_quantum_operations.html#Basis-vector-ordering-in-Qiskit
// states "Within the physics community, the qubits of a multi-qubit systems
// are typically ordered with the first qubit on the left-most side of the
// tensor product and the last qubit on the right-most side."
// - The same 4x4 matrix mentioned earlier, with q0 acting as a control bit,
// would now be [1 0 0 0; 0 1 0 0; 0 0 a b; 0 0 c d] which is how they
// are usually presented in textbooks on quantum computing.
// - In a 3-qubit circuit, the state vector would contain 8 elements, and
// the 2nd of these would correspond to (q0,q1,q2) = (0,0,1).
// Such a vector would have to be endian-reversed for more natural reading.
//
// We could just implement one of the above conventions in the code,
// but I found it instructive to try to implement both and have a global flag
// to switch between the two.
//
let usingTextbookConvention = false;
let defaultDecimalPrecision = 3;
let precisionForApproximateComparison = 0.01;
class Util {
static assert( condition, message ) {
if ( ! condition ) {
console.log( "ASSERTION ERROR: " + message );
console.trace(); // causes line numbers to be printed
}
}
// Let n be a power of 2. This returns the reverse of i in binary, with respect to n.
// For example, if n===16, the reverse of 1 is 8, the reverse of 2 is 4, the reverse of 3 is 12,
// and the reverse of 0, 6, 9, and 15 leaves each of those numbers unchanged.
static reverseEndianness(i,n) {
Util.assert( 0<=i && i<n && 1<=n, `Util.reverseEndianness(): unexpected condition, i===${i}, n===${n}`);
let result = 0;
let bit = 1;
let reversed_bit = n >> 1;
while ( bit < n ) {
if ( i & bit )
result |= reversed_bit;
bit <<= 1;
reversed_bit >>= 1;
}
Util.assert( bit === n/*this should happen because n should be a power of 2*/, `Util.reverseEndianness(): unexpected condition, n===${n}`);
return result;
}
// Returns angle in [0,2 pi] of the given point in the cartesian plane measured counterclockwise+ with respect to x+
static angleIn2D(x,y) {
let hypotenuse = Math.sqrt(x*x+y*y);
let angle = 0;
if ( hypotenuse > 0 ) {
let sine = y / hypotenuse;
if ( sine>= 1 ) angle = Math.PI/2;
else if ( sine<=-1) angle = -Math.PI/2;
else angle = Math.asin(sine);
if ( x < 0 ) angle = Math.PI - angle;
if ( angle < 0 ) angle += 2*Math.PI; // ensures angle is in [0,2*M_PI]
}
return angle;
}
}
class StringUtil {
static numToString( x, decimalPrecision = defaultDecimalPrecision ) {
let s1 = x.toString();
let s2 = x.toFixed(decimalPrecision);
if ( s1.length < s2.length ) return s1;
else return s2;
}
// returns the given string, reversed
static reverseString(s) {
let r = "";
for ( let j = s.length-1; j >= 0; j-- )
r += s[j];
return r;
}
// returns s repeated n times
static repeatString(s,n) {
let r = "";
for ( let j = 0; j < n; j++ )
r += s;
return r;
}
// converts an integer to a binary string, padding with zeros at the front
static intToBinaryString( i, desiredWidth ) {
let binaryString = i.toString(2/*base 2 for binary*/);
return StringUtil.repeatString('0',desiredWidth-binaryString.length) + binaryString; // pad with '0's
}
// returns number of times the character c occurs in string s
static countInString(s,c) {
let r = 0;
for ( let j = s.length-1; j >= 0; j-- )
if ( s[j]===c )
r ++;
return r;
}
// Returns a single multiline string containing the given strings
// concatenated horizontally and centered vertically.
// Assumes that none of the given strings are jagged,
// i.e., assumes that for each given string, all its lines are the same length.
//
// For example, calling with arguments ("x = ", "[0,0,1,1]", " * ", "[0]\n[1]\n[0]\n[1]")
// causes a return of the string
// " [0]\n"
// +"x = [0,0,1,1] * [1]\n"
// +" [0]\n"
// +" [1]"
//
static concatMultiline(...args) {
let w = []; // widths of given strings
let h = []; // heights of given strings
let max_height = 0;
for (let s of args) {
let s2 = s.split('\n');
h.push( s2.length );
if ( s2.length > max_height ) max_height = s2.length;
w.push( s2[0].length );
}
let returnValue = "";
for ( let row = 0; row < max_height; ++row ) {
for (let stringIndex = 0; stringIndex < args.length; stringIndex ++ ) {
let s = args[ stringIndex ];
let rowWithinString = Math.round( row - max_height/2 + h[ stringIndex ]/2 );
if ( rowWithinString < 0 || rowWithinString >= h[ stringIndex ] ) {
// use spaces
returnValue += StringUtil.repeatString(' ', w[ stringIndex ] );
}
else {
//console.log("rowWithinString = " + rowWithinString + ", s =" + s + "END" );
returnValue += s.split('\n')[rowWithinString];
}
}
if ( row < max_height-1 )
returnValue += '\n';
}
return returnValue;
}
}
// Stores a complex number, with real and imaginary components.
class Complex {
constructor( re = 0, im = 0 ) {
this._r = re;
this._i = im;
}
toString( decimalPrecision = defaultDecimalPrecision ) {
if ( this._r === 0 ) {
if ( this._i === 0 ) {
return "0";
}
else {
return StringUtil.numToString(this._i,decimalPrecision) + "i";
}
}
else {
if ( this._i === 0 ) {
return StringUtil.numToString(this._r,decimalPrecision);
}
else {
let rs = StringUtil.numToString(this._r,decimalPrecision);
let is = StringUtil.numToString(this._i,decimalPrecision) + "i";
return is[0]==='-' ? ( rs+is ) : ( rs + "+" + is );
}
}
}
// returns a deep copy of the complex number
copy() {
return new Complex( this._r, this._i );
}
conjugate() {
return new Complex( this._r, - this._i );
}
mag() { // magnitude, also known as absolute value or modulus
return Math.sqrt( this._r * this._r + this._i * this._i );
}
magSquared() { // magnitude squared
return this._r * this._r + this._i * this._i;
}
arg() { // argument, also called phase, i.e. the angle of the complex number; always in [0,2 pi]
return Util.angleIn2D( this._r, this._i );
}
// Returns the sum of the two given complex numbers.
static sum(c1,c2) {
return new Complex( c1._r+c2._r, c1._i+c2._i );
}
// Returns the difference of the two given complex numbers.
static diff(c1,c2) {
return new Complex( c1._r-c2._r, c1._i-c2._i );
}
// Returns the product of the two given numbers.
static mult(c1,c2) {
if ( c1 instanceof Complex ) {
if ( c2 instanceof Complex ) {
return new Complex( c1._r*c2._r - c1._i*c2._i, c1._r*c2._i + c1._i*c2._r );
}
return new Complex( c1._r * c2, c1._i * c2 );
}
else if ( c2 instanceof Complex ) {
return new Complex( c1 * c2._r, c1 * c2._i );
}
return c1 * c2;
}
}
Complex.i = new Complex(0,1);
// This is a complex matrix, i.e., a matrix containing complex numbers.
// To save on overhead, the complex numbers are stored as consecutive pairs of numbers in a floating point number array.
class CMatrix {
// allocates space in memory containing zeros
allocate( numRows, numCols ) {
this._rows = numRows;
this._cols = numCols;
this._m = new Float32Array(
numRows * numCols
* 2 // because we're storing a real and imaginary component for each matrix element
);
}
constructor( numRows, numCols ) {
Util.assert( numRows > 0 && numCols > 0, "CMatrix.constructor(): invalid size requested" );
this.allocate( numRows, numCols );
}
// Gets the value in a cell.
// row and column indices are zero-based.
// returns a complex number.
get(row,col) {
let j = ( row * this._cols + col )*2;
return new Complex( this._m[j], this._m[j+1] );
}
// Sets the value in a cell.
// row and column indices are zero-based.
// The value passed in can be a (real) number or a complex number.
set(row,col,value) {
let j = ( row * this._cols + col )*2;
if ( typeof(value)==='number' ) {
this._m[j ] = value; // real component
this._m[j+1] = 0;
}
else if ( typeof(value)==='object' && value instanceof Complex ) {
this._m[j ] = value._r;
this._m[j+1] = value._i;
}
else Util.assert(false,"CMatrix.set(): unknown type");
}
// Returns a deep copy of the matrix
copy() {
let M = new CMatrix( this._rows, this._cols );
M._m.set( this._m ); // this copies the contents of one to the other
return M;
}
// Returns the transpose of the matrix
transpose() {
let M = new CMatrix( this._cols, this._rows );
for ( let r = 0; r < this._rows; ++r ) {
for ( let c = 0; c < this._cols; ++c ) {
M.set( c, r, this.get(r,c) );
}
}
return M;
}
conjugate() {
let M = new CMatrix( this._rows, this._cols );
for ( let r = 0; r < this._rows; ++r ) {
for ( let c = 0; c < this._cols; ++c ) {
M.set( r, c, this.get(r,c).conjugate() );
}
}
return M;
}
// Returns the transpose of the matrix, also known as adjoint matrix or transjugate
conjugateTranspose() {
let M = new CMatrix( this._cols, this._rows );
for ( let r = 0; r < this._rows; ++r ) {
for ( let c = 0; c < this._cols; ++c ) {
M.set( c, r, this.get(r,c).conjugate() );
}
}
return M;
}
// Returns a complex number equal to the trace (i.e., sum of diagonal elements) of a square matrix
trace() {
Util.assert( this._rows === this._cols, "CMatrix.trace(): matrix is not square" );
let returnValue = new Complex();
for ( let r = 0; r < this._rows; ++r ) {
returnValue = Complex.sum( returnValue, this.get(r,r) );
}
return returnValue;
}
reverseEndianness( actuallyReverseThings=true ) { // should only be called on a row vector, column vector, or matrix whose dimensions are powers of 2
if ( ! actuallyReverseThings )
return this; // never mind
let M = new CMatrix( this._rows, this._cols );
for ( let r = 0; r < this._rows; ++r ) {
let r2 = Util.reverseEndianness(r,this._rows);
for ( let c = 0; c < this._cols; ++c ) {
let c2 = Util.reverseEndianness(c,this._cols);
M.set( r2, c2, this.get(r,c) );
}
}
return M;
}
// Returns a multiline string, e.g.,
// a 4x2 matrix might yield "[0,1+2i]\n[1,1 ]\n[0,2i ]\n[1,0 ]"
toString(
// this syntax allows for something similar to named parameters
{ binaryPrefixes=false, decimalPrecision=defaultDecimalPrecision, suppressZeros=true/*makes large binary matrices easier to read*/, charToReplaceSuppressedZero='_' }={}
) {
let arrayOfPrefixStrings = [];
if ( binaryPrefixes ) {
let targetWidth = Math.ceil( Math.log2(this._rows) );
for ( let r = 0; r < this._rows; ++r ) {
let binaryString = StringUtil.intToBinaryString( r, targetWidth );
if ( usingTextbookConvention )
binaryString = '|' + StringUtil.reverseString( binaryString ) + '>';
else
binaryString = '|' + binaryString + '>';
arrayOfPrefixStrings.push( binaryString );
}
}
let arrayOfArraysOfStrings = [];
for ( let r = 0; r < this._rows; ++r ) {
arrayOfArraysOfStrings.push( [] );
for ( let c = 0; c < this._cols; ++c ) {
arrayOfArraysOfStrings[r].push( this.get(r,c).toString(decimalPrecision) );
}
}
let maxMaxWidth = 0;
for ( let c = 0; c < this._cols; ++c ) {
let maxWidth = 0;
for ( let r = 0; r < this._rows; ++r ) {
let w = arrayOfArraysOfStrings[r][c].length;
if ( w > maxWidth ) {
maxWidth = w;
if ( maxWidth > maxMaxWidth ) maxMaxWidth = maxWidth;
}
}
// now we know the max width for this column, so we can pad with spaces
for ( let r = 0; r < this._rows; ++r ) {
let w = arrayOfArraysOfStrings[r][c].length;
arrayOfArraysOfStrings[r][c] += StringUtil.repeatString(' ',maxWidth-w);
}
}
// now we have finished padding all the strings with spaces
// so we can build the multiline string
let returnValue = '';
for ( let r = 0; r < this._rows; ++r ) {
if ( binaryPrefixes )
returnValue += arrayOfPrefixStrings[r];
returnValue += '[';
for ( let c = 0; c < this._cols; ++c ) {
if ( suppressZeros && maxMaxWidth===1 && arrayOfArraysOfStrings[r][c]==='0' )
returnValue += charToReplaceSuppressedZero;
else
returnValue += arrayOfArraysOfStrings[r][c];
if ( c < this._cols-1 )
returnValue += ',';
}
returnValue += ']';
if ( r < this._rows-1 )
returnValue += '\n';
}
return returnValue;
}
// Returns the sum of the two given matrices.
static sum(a,b) {
Util.assert(a instanceof CMatrix && b instanceof CMatrix,"CMatrix.sum(): wrong type");
Util.assert(a._rows === b._rows && a._cols === b._cols, "CMatrix.sum(): incompatible dimensions" );
let M = a.copy();
for ( let j = M._m.length-1; j >= 0; j-- )
M._m[j] += b._m[j];
return M;
}
// Returns the difference of the two given matrices.
static diff(a,b) {
Util.assert(a instanceof CMatrix && b instanceof CMatrix,"CMatrix.diff(): wrong type");
Util.assert(a._rows === b._rows && a._cols === b._cols, "CMatrix.diff(): incompatible dimensions" );
let M = a.copy();
for ( let j = M._m.length-1; j >= 0; j-- )
M._m[j] -= b._m[j];
return M;
}
// Returns the product of the two given matrices,
// or of a matrix with a scalar.
static mult( a, b ) {
Util.assert(a instanceof CMatrix || b instanceof CMatrix,"CMatrix.mult(): wrong type");
if ( !( a instanceof CMatrix ) ) {
// swap a and b, so that a will be the matrix and b the scalar
let tmp = b;
b = a;
a = tmp;
}
if ( typeof(b)==='number' ) {
let M = a.copy();
for ( let j = M._m.length-1; j >= 0; j-- )
M._m[j] *= b;
return M;
}
else if ( b instanceof Complex ) {
let M = new CMatrix(a._rows,a._cols);
for ( let r = 0; r < M._rows; r++ ) {
for ( let c = 0; c < M._cols; c++ ) {
let product = Complex.mult(a.get(r,c),b);
M.set(r,c,product);
}
}
return M;
}
else if ( b instanceof CMatrix ) {
Util.assert(a._cols === b._rows, "CMatrix.mult(): matrices have incompatible dimensions" );
let M = new CMatrix(a._rows,b._cols);
for ( let r = 0; r < M._rows; r++ ) {
for ( let c = 0; c < M._cols; c++ ) {
let dotProduct = new Complex();
for ( let k = 0; k < a._cols; ++k ) {
// TODO this line creates 4 instances of Complex that ultimately aren't
// needed; this could be optimized by expanding and inlining the math ops.
dotProduct = Complex.sum(dotProduct,Complex.mult(a.get(r,k),b.get(k,c)));
}
M.set(r,c,dotProduct);
}
}
return M;
}
else Util.assert(false,"CMatrix.mult(): unknown type");
}
// The kronecker product, or tensor product, of two matrices.
static tensor(a,b,isReversed=false) {
Util.assert(a instanceof CMatrix && b instanceof CMatrix,"CMatrix.tensor(): wrong type");
if ( isReversed ) {
let tmp = a;
a = b;
b = tmp;
}
let numRows = a._rows * b._rows;
let numCols = a._cols * b._cols;
let M = new CMatrix(numRows,numCols);
for ( let ar = 0; ar < a._rows; ar++ ) {
for ( let br = 0; br < b._rows; br++ ) {
for ( let ac = 0; ac < a._cols; ac++ ) {
for ( let bc = 0; bc < b._cols; bc++ ) {
M.set(
ar*b._rows + br,
ac*b._cols + bc,
Complex.mult( a.get(ar,ac), b.get(br,bc) )
);
}
}
}
}
return M;
}
// Imagine you want to form the product of many matrices m1 x m2 x ... mN
// You can obtain this product by calling the below routine with argument [m1,m2,...,mN]
//
// Since matrix multiplication is associative, we have a choice of computing the product
// starting with whatever matrices we like.
// It turns out to be more efficient to compute the product of smaller matrices first.
// So, this routine searches through the given list for the consecutive pair
// of smallest matrices, replaces them with their product, and repeats.
static naryMult( list ) {
Util.assert( list.length>0 && list[0] instanceof CMatrix, "CMatrix.naryMult(): invalid input" );
// let totalCost = 0;
while ( list.length > 1 ) {
let lowestCost = 0;
let indexForLowestCost = -1;
for ( let i = 0; i < list.length-1; ++i ) {
// compute the cost of computing the product of the ith and (i+1)th matrices
let cost = list[i]._rows * list[i]._cols * list[i+1]._cols;
if ( indexForLowestCost < 0 || cost < lowestCost ) {
lowestCost = cost;
indexForLowestCost = i;
}
}
// Replace the lowest-cost pair of matrices with a single matrix
let a = list[ indexForLowestCost ];
let b = list[ indexForLowestCost + 1 ];
// replace the ith and (i+1)th matrices with their product
list.splice( indexForLowestCost, 2, CMatrix.mult(a,b) );
// totalCost += lowestCost;
}
// console.log("totalCost: " + totalCost);
return list[0];
}
// Imagine you want to form the tensor product of many matrices m1 x m2 x ... mN
// You can obtain this product by calling the below routine with argument [m1,m2,...,mN]
//
// Since the tensor product is associative, we have a choice of computing the product
// starting with whatever matrices we like.
// It turns out to be more efficient to compute the product of smaller matrices first.
// So, this routine searches through the given list for the consecutive pair
// of smallest matrices, replaces them with their product, and repeats.
static naryTensor( list, isReversed=false ) {
Util.assert( list.length>0 && list[0] instanceof CMatrix, "CMatrix.naryTensor(): invalid input" );
if ( isReversed ) {
list.reverse();
}
// let totalCost = 0;
while ( list.length > 1 ) {
let lowestCost = 0;
let indexForLowestCost = -1;
for ( let i = 0; i < list.length-1; ++i ) {
// compute the cost of computing the product of the ith and (i+1)th matrices
let cost = list[i]._rows * list[i]._cols * list[i+1]._rows * list[i+1]._cols;
if ( indexForLowestCost < 0 || cost < lowestCost ) {
lowestCost = cost;
indexForLowestCost = i;
}
}
// Replace the lowest-cost pair of matrices with a single matrix
let a = list[ indexForLowestCost ];
let b = list[ indexForLowestCost + 1 ];
// replace the ith and (i+1)th matrices with their product
list.splice( indexForLowestCost, 2, CMatrix.tensor(a,b) );
// totalCost += lowestCost;
}
// console.log("totalCost: " + totalCost);
return list[0];
}
// TODO This should be improved using exponentiation by squaring or binary exponentiation, and something similar could be done for a power() method that raises a matrix to a given exponent
static tensorPower( matrix, exponent ) {
Util.assert( exponent>0 && matrix instanceof CMatrix, "CMatrix.naryTensor(): invalid input" );
let list = [];
for ( let i = 0; i < exponent; ++i ) {
list.push( matrix );
}
return CMatrix.naryTensor( list );
}
// returns true if the given matrices are approximately equal, within the given tolerance
static approximatelyEqual(a,b,tolerance=precisionForApproximateComparison,printMessage=true) {
Util.assert(a instanceof CMatrix && b instanceof CMatrix,"CMatrix.approximatelyEqual(): wrong type");
Util.assert(a._rows === b._rows && a._cols === b._cols, "CMatrix.approximatelyEqual(): incompatible dimensions" );
for ( let j = a._m.length-1; j >= 0; j-- ) {
let delta = Math.abs( a._m[j] - b._m[j] );
if ( delta > tolerance ) {
if ( printMessage ) {
console.log(`CMatrix.approximatelyEqual(): difference of ${delta} found`);
}
return false;
}
}
return true;
}
// Creates and returns a matrix by copying the contents of the given array of arrays,
// which can contain numbers or complex numbers.
// Assumes that the given array is not jagged.
static create( arrayOfArrays ) {
let numRows = arrayOfArrays.length;
let numCols = arrayOfArrays[0].length;
let M = new CMatrix( numRows, numCols );
for ( let j = 0; j < numRows; ++j ) {
for ( let k = 0; k < numCols; ++k ) {
M.set( j, k, arrayOfArrays[j][k] );
}
}
return M;
}
// Creates a nx1 size matrix
static createColVector( array ) {
return this.create( array.map( x => [ x ] ) );
}
// Creates a 1xn size matrix
static createRowVector( array ) {
return this.create( [ array ] );
}
// Returns an identity matrix of the given size
static identity( numRows ) {
let M = new CMatrix( numRows, numRows );
for ( let k = 0; k < numRows; ++k )
M.set(k,k,1);
return M;
}
}
class Sim { // Simulator
static GlobalPhase( angleInDegrees ) {
let angleInRadians = angleInDegrees / 180.0 * Math.PI;
let globalPhaseChange = new Complex( Math.cos(angleInRadians), Math.sin(angleInRadians) );
return CMatrix.create([[globalPhaseChange,0],[0,globalPhaseChange]]);
}
// Note that
// Phase(angle) * GlobalPhase( -angle/2 ) = RZ( angle )
// Phase(angle) = RZ( angle ) * GlobalPhase( angle/2 )
static Phase( angleInDegrees ) {
let angleInRadians = angleInDegrees / 180.0 * Math.PI;
let phaseChange = new Complex( Math.cos(angleInRadians), Math.sin(angleInRadians) );
return CMatrix.create([[1,0],[0,phaseChange]]);
}
// Returns a 2x2 matrix that rotates around an axis of the Bloch sphere.
// With a 180 degree angle, this is equivalent to a Pauli X gate (also called NOT gate)
// but differs by a global phase.
// More particularly, the following print statements should output the same thing:
// console.log(CMatrix.mult(Sim.RX(180),Sim.GlobalPhase(90)).toString());
// console.log(Sim.X.toString());
//
static RX( angleInDegrees ) {
let angleInRadians = angleInDegrees / 180.0 * Math.PI;
let halfAngle = angleInRadians / 2;
let sine = Math.sin( halfAngle );
let cosine = Math.cos( halfAngle );
return CMatrix.create( [
[ new Complex(cosine,0), new Complex(0,-sine) ],
[ new Complex(0,-sine), new Complex(cosine,0) ],
] );
}
// Returns a 2x2 matrix that rotates around an axis of the Bloch sphere.
// With a 180 degree angle, this is equivalent to a Pauli Y gate
// but differs by a global phase.
// More particularly, the following print statements should output the same thing:
// console.log(CMatrix.mult(Sim.RY(180),Sim.GlobalPhase(90)).toString());
// console.log(Sim.Y.toString());
//
static RY( angleInDegrees ) {
let angleInRadians = angleInDegrees / 180.0 * Math.PI;
let halfAngle = angleInRadians / 2;
let sine = Math.sin( halfAngle );
let cosine = Math.cos( halfAngle );
return CMatrix.create( [
[ new Complex(cosine,0), new Complex(-sine,0) ],
[ new Complex(sine,0), new Complex(cosine,0) ],
] );
}
// Returns a 2x2 matrix that rotates around an axis of the Bloch sphere.
// With a 180 degree angle, this is equivalent to a Pauli Z gate
// but differs by a global phase.
// More particularly, the following print statements should output the same thing:
// console.log(CMatrix.mult(Sim.RZ(180),Sim.GlobalPhase(90)).toString());
// console.log(Sim.Z.toString());
//
static RZ( angleInDegrees ) {
let angleInRadians = angleInDegrees / 180.0 * Math.PI;
let halfAngle = angleInRadians / 2;
let sine = Math.sin( halfAngle );
let cosine = Math.cos( halfAngle );
return CMatrix.create( [
[ new Complex(cosine,-sine), new Complex(0,0) ],
[ new Complex(0,0), new Complex(cosine,sine) ],
] );
}
// This rotates around the given vector by an angle in radians equal to the magnitude of the given vector.
// This way of encoding the angle in the vector of the axis of rotation might seem strange,
// but it means that the output is continuous in all 3 input variables and therefore easier to optimize,
// which would not be the case with a parametrization where the angle is separate from the vector components of the axis.
// (To see why, consider the latter parametrization, and imagine what would happen as the input shifts
// from (ax,ay-epsilon,az,angle) to (ax,ay+epsilon,az,angle).
// This would result in a 180 degree change of axis direction and a discontinuous change in output.
// The same kind of change of axis direction in the first parametrization would require the angle to pass through zero,
// avoiding a discontinuity in the output.)
//
// For the definition of the matrix, see
// https://arxiv.org/abs/2104.14875
// Hiroshi C. Watanabe, Rudy Raymond, Yu-ya Ohnishi, Eriko Kaminishi, Michihiko Sugawara
// Optimizing Parameterized Quantum Circuits with Free-Axis Selection
// in particular equation (1) on page 4.
// See also the documentation for the RVGate in Qiskit
// https://docs.quantum.ibm.com/api/qiskit/qiskit.circuit.library.RVGate
// although, at the time of writing, that documentation contains typos.
// See also the source code for the RVGate in Qiskit
// https://github.com/Qiskit/qiskit/blob/stable/0.46/qiskit/circuit/library/generalized_gates/rv.py
//
// If (ax,ay,az) is proportional to (1,0,0), or to (0,1,0), or to (0,0,1),
// the result is equivalent to RX, RY, or RZ, respectively.
static RotFreeAxis( ax, ay, az ) {
let magSquared = ax*ax + ay*ay + az*az;
if ( magSquared === 0 ) {
return Sim.I;
}
let angleInRadians = Math.sqrt( magSquared );
ax /= angleInRadians;
ay /= angleInRadians;
az /= angleInRadians;
let halfAngle = angleInRadians / 2;
let sine = Math.sin( halfAngle );
let cosine = Math.cos( halfAngle );
return CMatrix.create( [
[ new Complex(cosine,-az*sine), new Complex(-ay*sine,-ax*sine) ],
[ new Complex(ay*sine,-ax*sine), new Complex(cosine,az*sine) ],
] );
}
static RotFreeAxisAngle( ax, ay, az, angleInDegrees ) { // rotates around the given axis by the given angle
let angleInRadians = angleInDegrees / 180.0 * Math.PI;
let magSquared = ax*ax + ay*ay + az*az;
if ( magSquared === 0 || angleInDegrees === 0 ) {
return Sim.I;
}
let k = angleInRadians / Math.sqrt( magSquared );
return Sim.RotFreeAxis( ax * k, ay * k, az * k );
}
// Returns a matrix for swapping wires i and j in a quantum circuit with n wires.
// i and j are zero-based, i.e., they are between 0 and (n-1).
// The matrix that is returned has size (2**n)x(2**n)
static SWAP(i,j,n) {
Util.assert( 0<=i && i<n && 0<=j && j<n, "Sim.SWAP(): invalid indices" );
Util.assert( i!=j, "Sim.SWAP(): indices are unexpectedly equal" );
let matrixSize = 2 ** n;
if ( i === j ) {
return CMatrix.identity( matrixSize );
}
let M = new CMatrix( matrixSize, matrixSize );
if ( usingTextbookConvention ) {
// inverting the wire indices like this is equivalent to calling reverseEndianness() on the matrix just before returning it, but this is more efficient
i = n-1 - i;
j = n-1 - j;
}
// define stuff for operating on bits
let mask_i = 1 << i;
let mask_j = 1 << j;
let antimask = ~( mask_i | mask_j );
for ( let r = 0; r < matrixSize; ++r ) {
let c = r;
// BEGIN: swap the ith and jth bits of c
let extracted_bit_i = c & mask_i;
let extracted_bit_j = c & mask_j;
c &= antimask; // turns off bits i and j
if ( extracted_bit_i !== 0 ) c |= mask_j; // turns on bit j
if ( extracted_bit_j !== 0 ) c |= mask_i; // turns on bit i
// END
M.set(r,c,1);
}
return M;
}
// Given a 4x4 matrix, which operates on two qubits q0 and q1,
// this routine modifies it so that it will operate on the ith and jth qubits
// of an n-qubit circuit.
// The matrix that is returned has size (2**n)x(2**n)
// For example, passing in arguments (m,1,0,2)
// returns an 'upside-down' version of the original matrix.
static expand4x4ForNWires(m/*a 4x4 matrix*/,i,j,n/*number of qubits in the circuit*/) {
Util.assert( 0<=i && i<n && 0<=j && j<n && i!=j, "Sim.expand4x4ForNWires(): invalid indices" );
Util.assert( m._rows===m._cols && m._rows===4, "Sim.expand4x4ForNWires(): invalid size" );
// Step 1: turn the matrix upside down, if necessary
let m1 = null;
if ( i > j ) {
//
// +----+ +---+
// q_0 --| |-- q_0 --X--| |--X--
// | m1 | = | | m | |
// q_1 --| |-- q_1 --X--| |--X--
// +----+ +---+
//
// +----+ +---+
// q_i' = q_j --| |-- q_j --X--| |--X--
// | m1 | = | | m | |
// q_j' = q_i --| |-- q_i --X--| |--X--
// +----+ +---+
//
m1 = CMatrix.naryMult([ Sim.SWAP_2, m, Sim.SWAP_2 ]);
let tmp = i;
i = j;
j = tmp;
Util.assert(i<j,"Sim.expand4x4ForNWires(): unexpected condition");
}
else {
m1 = m.copy();
}
// Step 2: account for wires in between i and j
let m2 = null;
let numInnerWires = j-i-1;
if ( numInnerWires > 0 ) {
//
// q_0 --+----+-- q_0 -----+----+-----
// | | | m1 |
// q_1 --| |-- q_1 --X--+----+--X--
// | | | |
// ... --| |-- ... --|----------|--
// | m2 | = | |
// | | ...
// | | | |
// ... --| |-- ... --|----------|--
// | | | |
// q_{j-i} --+----+-- q_{j-i} --X----------X--
//
let swapStep = CMatrix.tensor( Sim.SWAP(0,numInnerWires,numInnerWires+1), Sim.I, usingTextbookConvention );
m2 = CMatrix.naryMult( [
swapStep,
CMatrix.tensor( CMatrix.identity(2**numInnerWires), m1, usingTextbookConvention ),
swapStep
] );
}
else {
m2 = m1;
}
// Step 3: if there are wires before i, and/or after j,
// we must perform a tensor product with an appropriately sized identity matrix,
// either before and/or after m2, respectively.
// Rather than do these tensor products separately here,
// we put the relevant matrices in a list and let naryTensor()
// perform the tensor products in the optimal associative order.
//
let listOfMatrices = [ m2 ];
let numWiresBefore = i;
if ( numWiresBefore > 0 ) {
listOfMatrices.push( CMatrix.identity(2**numWiresBefore) ); // add to end of list
}
let numWiresAfter = n-1-j;
if ( numWiresAfter > 0 ) {
listOfMatrices.unshift( CMatrix.identity(2**numWiresAfter) ); // insert at beginning of list
}
let m3 = CMatrix.naryTensor( listOfMatrices, usingTextbookConvention );
return m3;
}
// Returns a new state vector.
// Avoids computing an explicit matrix of size (2**n)x(2**n), saving a lot of memory and time.
//
// Imagine the state vector partitioned into contiguous blocks of equal size,
// with each block partitioned into two half blocks.
// The below code steps through the blocks, and within each block, for each i,
// it will take the ith amplitude of the first half block and the ith amplitude
// of the second half block, store those two amplitudes in a temporary vector
// (this is the "collect" step, since it collects the amplitudes into the temporary vector),
// apply the 2x2 matrix to that temporary vector, and store the resulting amplitudes
// back in the ith positions of the half blocks (the "scatter" step).
//
// The below code is similar to the code in Quirk ( https://github.com/Strilanc/Quirk/ ,
// src/math/Matrix.js , applyToStateVectorAtQubitWithControls() )
// and also similar to the pseudocode in Figure 6.1 of the book by Viamontes et al.
// (Viamontes, G. F., Markov, I. L., & Hayes, J. P. (2009) "Quantum circuit simulation")
// Viamontes et al. call this algorithm "qubit-wise multiplication".
//
// To compare with Quirk's version of the code, it helps to know that Quirk's source code
// calls the tempVector a 'chunk', and it uses different names for several variables,
// listed below. Also, our version has indices and sizes of things in complex numbers
// (i.e., in amplitudes), whereas Quirk's corresponding quantities are in floats and
// are therefore doubled.
//
// Some quantities in our code, and the corresponding quantities in Quirk's code:
// sizeOfHalfBlock (in complex numbers) is (strideLength (in floats))/2
// sizeOfBlock (in complex numbers) is (strideChunkSize (in floats))/2
// indexOfStartOfBlock (in complex numbers) is (strideChunkStart (in floats))/2
// offsetWithinBlock (in complex numbers) is (strideOffset (in floats))/2
//
// Viamontes et al., Figure 6.1, appears to be the same algorithm. The inner "for" loop
// in it performs the "collect" step, and the line of code immediately following,
// which uses slice notation (res[a:...:gap]), performs the "scatter" step.
// The 'gap' variable in Viamontes et al.'s version is sizeOfHalfBlock in our code.
// However, Viamontes et al., Figure 6.1 also contains errors: it mentions a
// "group_factor" that is undefined, and contains a stray closing brace.
// There are other things about it that are confusing which I haven't
// fully analyzed. Finally, Viamontes et al.'s version has no support for control bits.
//
static transformStateVectorWith2x2(
m, // a 2x2 matrix
i, // index of wire on which to apply m
n, // number of qubits in the circuit
stateVector, // a matrix of size (2**n)x1, i.e. a column vector
listOfControlBits = [] // a list of pairs of the form [wire_index, flag] where 0<=wire_index<n and flag is true for a control bit and false for an anti-control bit
) {
Util.assert( 0<=i && i<n, "Sim.transformStateVectorWith2x2(): invalid index" );
Util.assert( m._rows===m._cols && m._rows===2, "Sim.transformStateVectorWith2x2(): invalid size" );
Util.assert( stateVector._rows===(2**n) && stateVector._cols===1, "Sim.transformStateVectorWith2x2(): state vector has invalid size" );
let inclusionMask = 0;
let desiredValueMask = 0;
for ( let iter of listOfControlBits ) {
let [wireIndex,flag] = iter;
if ( usingTextbookConvention )
wireIndex = n-1 - wireIndex;
let bit = 1 << wireIndex;
inclusionMask |= bit;
if ( flag )
desiredValueMask |= bit;
}
if ( usingTextbookConvention )
i = n-1 - i;
let tempVector = new CMatrix(2,1);
let sizeOfHalfBlock = 1 << i; // could be 1, 2, 4, ...
let sizeOfBlock = sizeOfHalfBlock * 2; // could be 2, 4, 8 ...
let result = stateVector.copy();
for ( let indexOfStartOfBlock = 0; indexOfStartOfBlock < stateVector._rows; indexOfStartOfBlock += sizeOfBlock ) {
for ( let offsetWithinBlock = 0; offsetWithinBlock < sizeOfHalfBlock; offsetWithinBlock ++ ) {
Util.assert( indexOfStartOfBlock | offsetWithinBlock === indexOfStartOfBlock + offsetWithinBlock, "Sim.transformStateVectorWith2x2(): unexpected numbers" );
let stateIndex1 = indexOfStartOfBlock | offsetWithinBlock;
if ( (stateIndex1 & inclusionMask) !== desiredValueMask )
continue;
let stateIndex2 = stateIndex1 + sizeOfHalfBlock;
// Collect inputs into a small contiguous vector.
tempVector.set( 0, 0, stateVector.get( stateIndex1, 0 ) );
tempVector.set( 1, 0, stateVector.get( stateIndex2, 0 ) );
let transformedVector = CMatrix.mult( m, tempVector );
// Scatter outputs.
result.set( stateIndex1, 0, transformedVector.get( 0, 0 ) );
result.set( stateIndex2, 0, transformedVector.get( 1, 0 ) );
}
}
return result;
}
// Returns a new state vector.
// Avoids computing an explicit swap matrix of size (2**n)x(2**n), saving a lot of memory and time.
static transformStateVectorWithSwap(
i, // index of 1st wire on which to apply the swap
j, // index of 2nd wire on which to apply the swap
n, // number of qubits in the circuit
stateVector, // a matrix of size (2**n)x1, i.e. a column vector
listOfControlBits = [] // a list of pairs of the form [wire_index, flag] where 0<=wire_index<n and flag is true for a control bit and false for an anti-control bit
) {
Util.assert( 0<=i && i<n && 0<=j && j<n, "Sim.transformStateVectorWithSwap(): invalid indices" );
Util.assert( i!=j, "Sim.transformStateVectorWithSwap(): indices are unexpectedly equal" );
Util.assert( stateVector._rows===(2**n) && stateVector._cols===1, "Sim.transformStateVectorWithSwap(): state vector has invalid size" );
let result = stateVector.copy();
if ( i === j ) {
return result;
}
let inclusionMask = 0;
let desiredValueMask = 0;
for ( let iter of listOfControlBits ) {
let [wireIndex,flag] = iter;
if ( usingTextbookConvention )
wireIndex = n-1 - wireIndex;
let bit = 1 << wireIndex;
inclusionMask |= bit;
if ( flag )
desiredValueMask |= bit;
}
if ( usingTextbookConvention ) {
i = n-1 - i;
j = n-1 - j;
}
if ( i > j ) {
let tmp = i;
i = j;
j = tmp;
}
let numStates = 2 ** n;