-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquantum_discrete_gaussian.py
More file actions
1925 lines (1562 loc) · 81.7 KB
/
quantum_discrete_gaussian.py
File metadata and controls
1925 lines (1562 loc) · 81.7 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
"""
Quantum implementation for discrete Gaussian distribution on 1D grid
with sine wave variations in mean (u) and variance (T).
Grid: 10 points
Mean: u(x) = 0.1 * sin(2π * x/10)
Variance: T(x) = T0 + 0.05 * sin(2π * x/10), where T0 = 1/3
Outcomes: {-1, 0, 1}
"""
import argparse
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit_aer import AerSimulator
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from typing import Tuple, Dict, Optional, List
class QuantumDiscreteGaussian:
def __init__(self, grid_size: int = 10, circuit_type: str = 'symmetric',
grid_3d: Optional[Tuple[int, int, int]] = None):
self.grid_size = grid_size
self.T0 = 1/3 # Base variance
self.outcomes = [-1, 0, 1]
self.circuit_type = circuit_type # Track which circuit implementation to use
self.grid_3d = grid_3d # 3D grid dimensions (Nx, Ny, Nz)
# Validate circuit type
if circuit_type not in ['symmetric', 'original']:
raise ValueError(f"circuit_type must be 'symmetric' or 'original', got '{circuit_type}'")
def compute_parameters(self) -> Tuple[np.ndarray, np.ndarray]:
"""
Compute mean and variance for each grid point.
SPATIAL VARIATIONS:
- Mean velocity: u(x) = 0.1 * sin(2π * x/10)
- Temperature: T(x) = T0 + 0.05 * sin(2π * x/10)
RETURNS:
- means: array of mean velocities (physically: u)
- variances: array of temperatures/variances (physically: T, mathematically: sigma_sq)
"""
x_points = np.arange(self.grid_size)
# Mean velocity: u(x) = 0.1 * sin(2π * x/10)
means = 0.1 * np.sin(2 * np.pi * x_points / self.grid_size)
# Temperature: T(x) = T0 + 0.05 * sin(2π * x/10)
variances = self.T0 + 0.05 * np.sin(2 * np.pi * x_points / self.grid_size)
return means, variances
def compute_parameters_3d(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""
Compute 3D grid parameters with sine wave variations.
GRID STRUCTURE:
3D grid with dimensions (Nx, Ny, Nz) specified in self.grid_3d
Default: (10, 6, 4) for 240 total grid points
PARAMETER VARIATIONS (physical notation):
- ux(x): 0.1 * sin(2π * x/Nx) - varies with x-position only
- uy(y): 0.1 * sin(2π * y/Ny) - varies with y-position only
- uz(z,x): 0.1 * sin(2π * z/Nz) + 0.02 * sin(2π * x/Nx) - varies with z (primary) and x (secondary)
- T(x): T0 + 0.05 * sin(2π * x/Nx) - temperature varies with x-position
PHYSICAL INTERPRETATION:
- Mean velocities show spatial variation (flow patterns)
- Temperature varies with x (energy gradient)
- Each dimension has independent sinusoidal variation
RETURNS:
Tuple of 4 arrays, each with shape (Nx, Ny, Nz):
- means_x: x-component mean velocities (physically: ux)
- means_y: y-component mean velocities (physically: uy)
- means_z: z-component mean velocities (physically: uz)
- temperatures: temperature field T (mathematically: sigma_sq, isotropic at each point)
"""
if self.grid_3d is None:
raise ValueError("3D grid dimensions not specified. Set grid_3d=(Nx, Ny, Nz) in __init__")
Nx, Ny, Nz = self.grid_3d
# Create coordinate arrays for each dimension
x_coords = np.arange(Nx)
y_coords = np.arange(Ny)
z_coords = np.arange(Nz)
# Create 3D meshgrid: X[i,j,k] gives x-coordinate, Y[i,j,k] gives y-coordinate, etc.
X, Y, Z = np.meshgrid(x_coords, y_coords, z_coords, indexing='ij')
# Mean velocity variations (each depends on one coordinate only)
# ux varies with x: flow in x-direction depends on x-position
means_x = 0.1 * np.sin(2 * np.pi * X / Nx)
# uy varies with y: flow in y-direction depends on y-position
means_y = 0.1 * np.sin(2 * np.pi * Y / Ny)
# uz varies with z: flow in z-direction depends on z-position
# Also add small x-variation for better visualization in 2D slices
means_z = 0.02 * np.sin(2 * np.pi * Z / Nz) + 0.08 * np.sin(2 * np.pi * X / Nx)
# Temperature varies with x (energy gradient in x-direction)
temperatures = self.T0 + 0.05 * np.sin(2 * np.pi * X / Nx)
return means_x, means_y, means_z, temperatures
def classical_discrete_gaussian_probs(self, mu: float, sigma_sq: float) -> np.ndarray:
"""
Calculate classical discrete Gaussian probabilities for outcomes {-1, 0, 1}
MATHEMATICAL FOUNDATION:
Discrete Gaussian distribution: P(x) = exp(-(x-mu)**2/(2*sigma_sq)) / Z
- mu: mean parameter (varies spatially as sine wave across grid)
- sigma_sq: variance parameter (varies spatially as sine wave across grid)
- Z: normalization constant (partition function) ensuring Sum P(x) = 1
PHYSICAL INTERPRETATION:
- When mu > 0: probability mass shifts toward +1 outcome
- When mu < 0: probability mass shifts toward -1 outcome
- When mu == 0: symmetric distribution peaked at 0
- Larger sigma_sq: broader distribution (more uncertainty)
- Smaller sigma_sq: sharper distribution (more certainty)
This classical calculation serves as the "ground truth" for our quantum implementation.
"""
# STEP 1: Compute unnormalized probabilities using Gaussian kernel
# For each outcome x in {-1, 0, 1}, calculate exp(-(x-mu)**2/(2*sigma_sq))
# This measures the "fitness" or "likelihood" of each outcome given parameters mu, sigma_sq
unnorm_probs = np.array([
np.exp(-(k - mu)**2 / (2 * sigma_sq)) for k in self.outcomes
])
# STEP 2: Normalize to satisfy probability axiom: Sum P(x) = 1
# Z is the partition function (total unnormalized probability mass)
Z = np.sum(unnorm_probs)
normalized_probs = unnorm_probs / Z
# RESULT: [P(-1), P(0), P(1)] - classical probability distribution
return normalized_probs
def standardLattice_discrete_gaussian_probs(self, mu: float, sigma_sq: float) -> np.ndarray:
"""
Calculate discrete Gaussian probabilities for outcomes {-1, 0, 1} using
Maxwell-Boltzmann formulation.
MATHEMATICAL FOUNDATION:
Reference: Section 2.2.4 of Sawant (2024)
https://doi.org/10.3929/ethz-b-000607045
Using the product form of Maxwell-Boltzmann distribution:
p = mu**2 + sigma_sq (where sigma_sq = T is temperature/variance)
Probabilities for each discrete velocity:
P(-1) = -0.5 * mu + 0.5 * p (backward motion)
P(0) = -p + 1.0 (at rest)
P(+1) = +0.5 * mu + 0.5 * p (forward motion)
These probabilities ensure:
- Sum to 1 (normalization)
- Mean = mu (physically: velocity u)
- Variance = sigma_sq (physically: temperature T)
PARAMETERS:
- mu: mean velocity (physically: u)
- sigma_sq: variance (physically: T)
RETURNS:
Array [P(-1), P(0), P(+1)] - normalized probability distribution
This classical calculation serves as the "ground truth" for our quantum implementation.
"""
p = mu * mu + sigma_sq
normalized_probs = np.array([
-0.5 * mu + 0.5 * p, # P(-1)
-p + 1.0, # P(0)
+0.5 * mu + 0.5 * p # P(+1)
])
# RESULT: [P(-1), P(0), P(1)] - classical probability distribution
return normalized_probs
#wrapper to select discrete gaussian probability calculation method
def discrete_gaussian_probs(self, mu: float, sigma_sq: float) -> np.ndarray:
return self.standardLattice_discrete_gaussian_probs(mu, sigma_sq)
def _clamp01(self, x: float) -> float:
"""Clamp numeric values into [0, 1] to avoid domain errors in sqrt/arccos/arcsin."""
if x != x: # NaN
return 0.0
if x < 0.0:
return 0.0
if x > 1.0:
return 1.0
return x
def create_quantum_circuit_symmetric(self, probs: np.ndarray) -> QuantumCircuit:
"""
Symmetric quantum circuit with improved decomposition: {-1, +1} vs {0}
QUANTUM COMPUTING FOUNDATION:
This implements a symmetric hierarchical decomposition that better matches
the symmetry of the velocity encoding formulas.
MATHEMATICAL MAPPING:
Classical: P(-1), P(0), P(+1) ∈ [0,1] with P(-1) + P(0) + P(+1) = 1
Quantum: |psi> = np.sqrt(P(-1))|00> + np.sqrt(P(+1))|01> + np.sqrt(P(0))|10>
SYMMETRIC QUBIT ENCODING SCHEME:
- |00> (both qubits in state 0) -> outcome -1
- |01> (first qubit 0, second qubit 1) -> outcome +1
- |10> (first qubit 1, second qubit 0) -> outcome 0
- |11> (both qubits in state 1) -> unused
ADVANTAGES OF THIS DECOMPOSITION:
- First qubit splits "moving" {-1, +1} vs "stationary" {0}
- Simpler angle formulas: θ₁ = 2*arccos(√(mu² + sigma_sq))
- Better captures physical symmetry of velocity distribution
- More numerically stable for velocity encoding
"""
# STEP 1: Ensure probability normalization
probs = probs / np.sum(probs)
p_minus1, p_0, p_plus1 = probs # Extract individual probabilities
# STEP 2: Initialize quantum circuit with 2 qubits + 2 classical bits
qc = QuantumCircuit(2, 2)
# STEP 3: HIERARCHICAL DECOMPOSITION - First Qubit (Coarse Splitting)
#
# QUANTUM STRATEGY: Split "moving particles" vs "stationary particles"
# Split the 3-outcome problem into: {-1, +1} vs {0}
#
# MATHEMATICAL FOUNDATION (from Section 2.2.4 of https://doi.org/10.3929/ethz-b-000607045):
# First qubit encodes: P(outcome ∈ {-1, +1}) vs P(outcome = 0)
# P(first qubit = 0) = P(-1) + P(+1) = p = mu**2 + sigma_sq
# P(first qubit = 1) = P(0) = -p + 1.0
#
# QUANTUM GATE FORMULATION:
# RY gate (rotation around Y-axis): RY(theta)|0> = cos(theta/2)|0> + sin(theta/2)|1>
# We want: |cos(theta/2)|**2 = P(first=0) and |sin(theta/2)|**2 = P(first=1)
# Solving: cos**2(theta/2) = p -> theta1 = 2 * np.arccos(np.sqrt(p)) = 2 * np.arccos(np.sqrt(mu**2 + sigma_sq))
#
# This angle depends only on the combined parameter p, making it very stable!
prob_first_0 = p_minus1 + p_plus1 # Combined probability for {-1, +1} outcomes
eps = 1e-12
# Clamp probability into [0,1] to be safe for sqrt/arccos
prob_first_0_clamped = self._clamp01(prob_first_0)
if prob_first_0 > eps and prob_first_0 < 1 - eps:
# GENERAL CASE: Create superposition between motion and rest
theta1 = 2 * np.arccos(np.sqrt(prob_first_0_clamped)) # Calculate rotation angle
qc.ry(theta1, 0) # Apply Y-rotation to first qubit
elif prob_first_0 <= eps:
# EDGE CASE: Only outcome 0 possible (P(-1)=P(+1)=0, P(0)=1)
qc.x(0) # X gate: |0> -> |1> (deterministic flip to rest state)
# EDGE CASE: If prob_first_0 == 1, first qubit stays |0⟩ (no gates needed)
# This happens when P(0) = 0, so only {-1, +1} outcomes are possible
# STEP 4: CONDITIONAL DECOMPOSITION - Second Qubit (Fine Splitting)
#
# QUANTUM STRATEGY: Conditional probability encoding for directional motion
# Given first qubit = 0 (we're in {-1, +1} subspace), distinguish -1 from +1
#
# MATHEMATICAL FOUNDATION (using Bayes' rule):
# P(outcome=+1 | first=0) = P(+1) / (P(-1) + P(+1))
# = (0.5*mu + 0.5*p) / p
# = 0.5*(1 + mu/p)
#
# This conditional probability is symmetric around 0.5:
# - When mu > 0: favors +1 (forward motion)
# - When mu < 0: favors -1 (backward motion)
# - When mu = 0: equal probability (no net flow)
#
# QUANTUM IMPLEMENTATION:
# Use controlled-RY gate: rotates second qubit only when first qubit = 0
# Angle: theta2 = 2*arcsin(np.sqrt(P(+1|first=0))) = 2*arcsin(np.sqrt(0.5*(1 + mu/p)))
#
# The control ensures this rotation applies only in the "moving" subspace!
if prob_first_0 > eps: # Only proceed if {-1,+1} outcomes are possible
# Calculate conditional probability using Bayes' rule
prob_second_1_given_first_0 = p_plus1 / prob_first_0 # P(outcome=+1 | outcome∈{-1,+1})
prob_second_1_clamped = self._clamp01(prob_second_1_given_first_0)
if prob_second_1_given_first_0 > eps and prob_second_1_given_first_0 < 1 - eps:
# GENERAL CASE: Both -1 and +1 outcomes possible within {-1,+1} subspace
# Calculate rotation angle for conditional probability (safe clamped input)
theta2 = 2 * np.arcsin(np.sqrt(prob_second_1_clamped))
# QUANTUM TRICK: Convert "control on |0⟩" to "control on |1⟩"
# Most quantum gates control on |1⟩ state, but we need control on |0⟩
qc.x(0) # X gate: |0> <-> |1> (flip first qubit state)
qc.cry(theta2, 0, 1) # Controlled-RY: rotate qubit 1 when qubit 0 is |1> (originally |0>)
qc.x(0) # X gate: flip first qubit back to original state
elif prob_second_1_given_first_0 >= 1 - eps:
# EDGE CASE: Only outcome +1 possible when first qubit is |0⟩ (P(-1)=0, P(+1)>0)
qc.x(0) # Flip first qubit: |0> -> |1>
qc.cx(0, 1) # CNOT gate: if control=|1> (originally |0>), flip target qubit
qc.x(0) # Restore first qubit to original state
# EDGE CASE: If prob_second_1_given_first_0 == 0, second qubit stays |0⟩
# This happens when P(+1)=0 but P(-1)>0, so only -1 outcome possible in {-1,+1} subspace
# STEP 5: QUANTUM MEASUREMENT
#
# NEW MEASUREMENT SCHEME:
# Measure both qubits simultaneously to get 2-bit classical string
# |00> -> classical bits "00" -> decode to outcome -1
# |01> -> classical bits "01" -> decode to outcome +1 [CHANGED]
# |10> -> classical bits "10" -> decode to outcome 0 [CHANGED]
# |11> -> classical bits "11" -> unused (should have 0 probability)
#
# QISKIT CONVENTION:
# qc.measure(qubit_index, classical_bit_index)
# Stores measurement result of quantum qubit in classical bit register
qc.measure(0, 0) # Measure first qubit -> store result in classical bit 0
qc.measure(1, 1) # Measure second qubit -> store result in classical bit 1
# CIRCUIT COMPLETE: Returns quantum circuit ready for execution
# This symmetric decomposition produces identical probability distributions
# but with simpler mathematical structure for velocity encoding
return qc
def create_quantum_circuit_original(self, probs: np.ndarray) -> QuantumCircuit:
"""
Create quantum circuit to generate discrete Gaussian distribution using amplitude encoding
QUANTUM COMPUTING FOUNDATION:
This function implements "amplitude encoding" - a fundamental quantum technique where
classical probabilities are encoded as quantum amplitudes in a superposition state.
MATHEMATICAL MAPPING:
Classical: P(-1), P(0), P(1) ∈ [0,1] with P(-1) + P(0) + P(1) = 1
Quantum: |psi = √P(-1)|00 + √P(0)|01 + √P(1)|10
WHY SQUARE ROOTS?
Born's rule in quantum mechanics: |amplitude|**2 = probability
So if amplitude = √P, then |√P|² = P (correct probability)
QUBIT ENCODING SCHEME:
- |00 (both qubits in state 0) → outcome -1
- |01 (first qubit 0, second qubit 1) → outcome 0
- |10 (first qubit 1, second qubit 0) → outcome +1
- |11 (both qubits in state 1) → unused (helps with circuit construction)
QUANTUM ADVANTAGE:
Once encoded, quantum circuits can manipulate all outcomes simultaneously
through superposition, potentially offering speedup over classical sampling.
"""
# STEP 1: Ensure probability normalization (quantum states must have unit norm)
probs = probs / np.sum(probs)
p_minus1, p_0, p_plus1 = probs # Extract individual probabilities
# STEP 2: Initialize quantum circuit with 2 qubits + 2 classical bits for measurement
# Qubit 0: "first" qubit in our encoding scheme
# Qubit 1: "second" qubit in our encoding scheme
# Classical bits: store measurement results
qc = QuantumCircuit(2, 2)
# STEP 3: HIERARCHICAL DECOMPOSITION - First Qubit (Coarse Splitting)
#
# QUANTUM STRATEGY: Use hierarchical probability tree decomposition
# Split the 3-outcome problem into: {-1,0} vs {+1}
#
# MATHEMATICAL FOUNDATION:
# First qubit encodes: P(outcome ∈ {-1, 0}) vs P(outcome = +1)
# P(first qubit = 0) = P(-1) + P(0) = combined probability of negative/zero outcomes
# P(first qubit = 1) = P(+1) = probability of positive outcome
#
# QUANTUM GATE SELECTION:
# RY gate (rotation around Y-axis) creates superposition: RY(theta)|0 = cos(theta/2)|0 + sin(theta/2)|1
# We want: |cos(theta/2)|**2 = P(first=0) and |sin(theta/2)|**2 = P(first=1)
# Solving: cos**2(theta/2) = prob_first_0 -> theta = 2*arccos(np.sqrt(prob_first_0))
prob_first_0 = p_minus1 + p_0 # Combined probability for {-1, 0} outcomes
if prob_first_0 > 0 and prob_first_0 < 1:
# GENERAL CASE: Create superposition between |0 and |1 states
theta1 = 2 * np.arccos(np.sqrt(prob_first_0)) # Calculate rotation angle
qc.ry(theta1, 0) # Apply Y-rotation to first qubit
elif prob_first_0 == 0:
# EDGE CASE: Only +1 outcome possible (P(-1)=P(0)=0, P(+1)=1)
qc.x(0) # X gate: |0 → |1 (deterministic flip to |1 state)
# EDGE CASE: If prob_first_0 == 1, first qubit stays |0 (no gates needed)
# This happens when P(+1) = 0, so only {-1, 0} outcomes are possible
# STEP 4: CONDITIONAL DECOMPOSITION - Second Qubit (Fine Splitting)
#
# QUANTUM STRATEGY: Conditional probability encoding using controlled gates
# Given first qubit = 0 (we're in {-1, 0} subspace), distinguish between -1 and 0
#
# MATHEMATICAL FOUNDATION:
# P(second=1 | first=0) = P(outcome=0) / P(outcome∈{-1,0}) = P(0) / (P(-1) + P(0))
# This uses conditional probability: P(A|B) = P(A∩B) / P(B)
# Here: A="second qubit is 1", B="first qubit is 0"
#
# QUANTUM IMPLEMENTATION:
# Use controlled-RY gate: only rotates second qubit when first qubit is in specific state
# CRY gate: applies RY rotation to target qubit conditioned on control qubit state
if prob_first_0 > 1e-10: # Only proceed if {-1,0} outcomes are possible
# Calculate conditional probability using Bayes' rule
prob_second_1_given_first_0 = p_0 / prob_first_0 # P(outcome=0 | outcome∈{-1,0})
if prob_second_1_given_first_0 > 0 and prob_second_1_given_first_0 < 1:
# GENERAL CASE: Both -1 and 0 outcomes possible within {-1,0} subspace
# Calculate rotation angle for conditional probability
theta2 = 2 * np.arcsin(np.sqrt(prob_second_1_given_first_0))
# QUANTUM TRICK: Convert "control on |0" to "control on |1"
# Most quantum gates control on |1 state, but we need control on |0
qc.x(0) # X gate: |0 ↔ |1 (flip first qubit state)
qc.cry(theta2, 0, 1) # Controlled-RY: rotate qubit 1 when qubit 0 is |1 (originally |0)
qc.x(0) # X gate: flip first qubit back to original state
elif prob_second_1_given_first_0 == 1:
# EDGE CASE: Only outcome 0 possible when first qubit is |0 (P(-1)=0, P(0)>0)
qc.x(0) # Flip first qubit: |0 → |1
qc.cx(0, 1) # CNOT gate: if control=|1 (originally |0), flip target qubit
qc.x(0) # Restore first qubit to original state
# EDGE CASE: If prob_second_1_given_first_0 == 0, second qubit stays |0
# This happens when P(0)=0 but P(-1)>0, so only -1 outcome possible in {-1,0} subspace
# STEP 5: QUANTUM MEASUREMENT
#
# MEASUREMENT FOUNDATION:
# Quantum measurement collapses superposition |psi = Sum_i alpha_i|i into classical outcome
# Probability of measuring state |i = |alpha_i|^2 (Born's rule)
# After measurement, quantum state is destroyed and becomes classical
#
# OUR MEASUREMENT SCHEME:
# Measure both qubits simultaneously to get 2-bit classical string
# |00> -> classical bits "00" -> decode to outcome -1
# |01> -> classical bits "01" -> decode to outcome 0
# |10> -> classical bits "10" -> decode to outcome +1
# |11> -> classical bits "11" -> unused (should have 0 probability by construction)
#
# QISKIT CONVENTION:
# qc.measure(qubit_index, classical_bit_index)
# Stores measurement result of quantum qubit in classical bit register
qc.measure(0, 0) # Measure first qubit -> store result in classical bit 0
qc.measure(1, 1) # Measure second qubit -> store result in classical bit 1
# CIRCUIT COMPLETE: Returns quantum circuit ready for execution
# When run multiple times (shots), produces random samples from discrete Gaussian
return qc
def create_quantum_circuit_parametric(self, mu: float, sigma_sq: float) -> QuantumCircuit:
"""
Create symmetric quantum circuit directly from (μ, σ²) parameters.
DIRECT PARAMETRIZATION:
This method computes gate angles directly from Maxwell-Boltzmann parameters
without the intermediate step of computing classical probabilities.
MATHEMATICAL FOUNDATION:
For velocity encoding with p = mu**2 + sigma_sq:
- P(-1) = -0.5*mu + 0.5*p
- P(0) = -p + 1
- P(+1) = +0.5*mu + 0.5*p
SYMMETRIC DECOMPOSITION ANGLES:
- theta1 = 2*arccos(sqrt(p)) where p = mu**2 + sigma_sq
- theta2 = 2*arcsin(sqrt(0.5*(1 + mu/p)))
ADVANTAGES:
- No classical probability computation needed
- Fewer floating-point operations
- Direct mathematical relationship to physical parameters
- Only works with symmetric circuit (simpler formulas)
PARAMETERS:
- mu: mean (physically: velocity u)
- sigma_sq: variance (physically: temperature T)
CONSTRAINT:
- Requires σ² < 1 for valid probabilities (physical: T < 1 constraint)
"""
# STEP 1: Compute the key parameter p = mu**2 + sigma_sq
# This represents the combined probability of motion: P(-1) + P(+1)
p = mu * mu + sigma_sq
# STEP 2: Validate physical constraints
# For valid probabilities, we need 0 < p < 1
# This ensures all probabilities are positive and sum to 1
if p <= 0:
raise ValueError(f"Invalid parameters: p = mu**2 + sigma_sq = {p:.4f} must be positive")
if p >= 1:
raise ValueError(f"Invalid parameters: p = mu**2 + sigma_sq = {p:.4f} must be < 1 "
f"(physical constraint T < 1 violated)")
# STEP 3: Initialize quantum circuit with 2 qubits + 2 classical bits
qc = QuantumCircuit(2, 2)
# STEP 4: FIRST ROTATION - Split motion {-1,+1} vs rest {0}
#
# DIRECT ANGLE FORMULA:
# θ₁ = 2*arccos(√p) where p = mu² + sigma_sq
#
# PHYSICAL INTERPRETATION:
# This angle encodes the probability of particle motion vs rest
# - cos²(θ₁/2) = p (probability of motion)
# - sin²(θ₁/2) = 1-p (probability of rest)
#
# SIMPLIFICATION from velocity encoding:
# Original: P(-1) + P(+1) = (-0.5*μ + 0.5*p) + (+0.5*μ + 0.5*p) = p
# Direct: θ₁ = 2*arccos(√p) - no probability computation needed!
# Clamp p into [0,1] before sqrt/arccos to guard against tiny FP errors
p_clamped = self._clamp01(p)
theta1 = 2 * np.arccos(np.sqrt(p_clamped))
qc.ry(theta1, 0) # Apply first rotation to qubit 0
# STEP 5: SECOND ROTATION (CONDITIONAL) - Split -1 vs +1 given motion
#
# DIRECT ANGLE FORMULA:
# theta2 = 2*arcsin(sqrt(0.5*(1 + mu/p)))
#
# PHYSICAL INTERPRETATION:
# Given the particle is moving (first qubit = 0), this angle determines
# whether it moves left (-1) or right (+1)
# - cos²(theta2/2) = P(-1|motion) = [-0.5*mu + 0.5*p]/p = 0.5*(1 - mu/p)
# - sin²(theta2/2) = P(+1|motion) = [+0.5*mu + 0.5*p]/p = 0.5*(1 + mu/p)
#
# SIMPLIFICATION from velocity encoding:
# Conditional probability: P(+1|motion) = P(+1)/[P(-1)+P(+1)]
# = [+0.5*mu + 0.5*p]/p
# = 0.5*(1 + mu/p)
# Direct: theta2 = 2*arcsin(sqrt(0.5*(1 + mu/p)))
# Calculate conditional probability directly
prob_plus1_given_motion = 0.5 * (1.0 + mu / p)
prob_plus1_given_motion_clamped = self._clamp01(prob_plus1_given_motion)
# Validate conditional probability is in valid range
if prob_plus1_given_motion < 0 or prob_plus1_given_motion > 1:
raise ValueError(f"Invalid conditional probability: {prob_plus1_given_motion:.4f}")
# Calculate second angle
theta2 = 2 * np.arcsin(np.sqrt(prob_plus1_given_motion_clamped))
# Apply controlled rotation (only when first qubit is |0⟩)
# Use X-gates to convert "control on |0⟩" to "control on |1⟩"
qc.x(0) # Flip first qubit
qc.cry(theta2, 0, 1) # Controlled-RY: rotate qubit 1 when qubit 0 is |1⟩
qc.x(0) # Flip first qubit back
# STEP 6: MEASUREMENT
# Symmetric encoding: |00⟩→-1, |01⟩→+1, |10⟩→0
qc.measure(0, 0) # Measure first qubit
qc.measure(1, 1) # Measure second qubit
# CIRCUIT COMPLETE: Direct parametrization without classical probability computation!
return qc
def create_quantum_circuit_3d_parametric(self, mu_x: float, mu_y: float, mu_z: float, sigma_sq: float) -> QuantumCircuit:
"""
Create 6-qubit circuit for 3D velocity sampling with parallel execution.
HARDWARE PARALLELIZATION:
All three dimensions execute simultaneously on independent qubit pairs.
Circuit depth remains 4 layers (same as 1D), achieving 3× speedup over
sequential execution of three 1D circuits.
QUBIT ALLOCATION:
- Qubits 0-1: v_x component (x-direction velocity)
- Qubits 2-3: v_y component (y-direction velocity)
- Qubits 4-5: v_z component (z-direction velocity)
PHYSICAL INTERPRETATION:
All components share same temperature/variance (isotropic kinetic energy) but have
different mean velocities (ux, uy, uz - directional flow). This represents
a 3D Maxwell-Boltzmann distribution for lattice velocities in 3D Lattice
Boltzmann Method.
ENCODING SCHEME (per dimension):
|00⟩ → -1 (negative velocity)
|01⟩ → +1 (positive velocity)
|10⟩ → 0 (zero velocity)
|11⟩ → unused
3D MEASUREMENT:
Single measurement yields 6-bit string -> (v_x, v_y, v_z) tuple
Example: |001001> -> v_x=+1, v_y=-1, v_z=+1
PARAMETERS:
- mu_x, mu_y, mu_z: mean velocities μx, μy, μz (physically: ux, uy, uz)
- sigma_sq: variance σ² (physically: temperature T, shared isotropic property)
CONSTRAINT:
- Requires sigma_sq < 1 and mu_i² + sigma_sq < 1 for all i ∈ {x,y,z}
PARALLELIZATION BENEFIT:
Time complexity: T_circuit (not 3×T_circuit for sequential)
"""
# STEP 1: Initialize 6-qubit circuit
qc = QuantumCircuit(6, 6)
# STEP 2: X-COMPONENT (qubits 0-1) - Parallel execution
p_x = mu_x * mu_x + sigma_sq
# # Validate physical constraints
# if p_x <= 0:
# raise ValueError(f"Invalid parameters for X: p_x = mu_x² + sigma_sq = {p_x:.4f} must be positive")
# if p_x >= 1:
# raise ValueError(f"Invalid parameters for X: p_x = mu_x² + sigma_sq = {p_x:.4f} must be < 1")
# Calculate angles directly from parameters
p_x_clamped = self._clamp01(p_x)
theta1_x = 2 * np.arccos(np.sqrt(p_x_clamped))
prob_plus1_x = 0.5 * (1.0 + mu_x / p_x)
prob_plus1_x = self._clamp01(prob_plus1_x)
# if prob_plus1_x < 0 or prob_plus1_x > 1:
# raise ValueError(f"Invalid conditional probability for X: {prob_plus1_x:.4f}")
theta2_x = 2 * np.arcsin(np.sqrt(prob_plus1_x))
# Apply gates to qubits 0-1
qc.ry(theta1_x, 0)
qc.x(0)
qc.cry(theta2_x, 0, 1)
qc.x(0)
# STEP 3: Y-COMPONENT (qubits 2-3) - Parallel execution
p_y = mu_y * mu_y + sigma_sq
# if p_y <= 0:
# raise ValueError(f"Invalid parameters for Y: p_y = mu_y² + sigma_sq = {p_y:.4f} must be positive")
# if p_y >= 1:
# raise ValueError(f"Invalid parameters for Y: p_y = mu_y² + sigma_sq = {p_y:.4f} must be < 1")
p_y_clamped = self._clamp01(p_y)
theta1_y = 2 * np.arccos(np.sqrt(p_y_clamped))
prob_plus1_y = 0.5 * (1.0 + mu_y / p_y)
prob_plus1_y = self._clamp01(prob_plus1_y)
# if prob_plus1_y < 0 or prob_plus1_y > 1:
# raise ValueError(f"Invalid conditional probability for Y: {prob_plus1_y:.4f}")
theta2_y = 2 * np.arcsin(np.sqrt(prob_plus1_y))
# Apply gates to qubits 2-3
qc.ry(theta1_y, 2)
qc.x(2)
qc.cry(theta2_y, 2, 3)
qc.x(2)
# STEP 4: Z-COMPONENT (qubits 4-5) - Parallel execution
p_z = mu_z * mu_z + sigma_sq
# if p_z <= 0:
# raise ValueError(f"Invalid parameters for Z: p_z = mu_z² + sigma_sq = {p_z:.4f} must be positive")
# if p_z >= 1:
# raise ValueError(f"Invalid parameters for Z: p_z = mu_z² + sigma_sq = {p_z:.4f} must be < 1")
p_z_clamped = self._clamp01(p_z)
theta1_z = 2 * np.arccos(np.sqrt(p_z_clamped))
prob_plus1_z = 0.5 * (1.0 + mu_z / p_z)
prob_plus1_z = self._clamp01(prob_plus1_z)
# if prob_plus1_z < 0 or prob_plus1_z > 1:
# raise ValueError(f"Invalid conditional probability for Z: {prob_plus1_z:.4f}")
theta2_z = 2 * np.arcsin(np.sqrt(prob_plus1_z))
# Apply gates to qubits 4-5
qc.ry(theta1_z, 4)
qc.x(4)
qc.cry(theta2_z, 4, 5)
qc.x(4)
# STEP 5: MEASURE ALL QUBITS
# Single measurement captures all 3 velocity components simultaneously
qc.measure(range(6), range(6))
# CIRCUIT COMPLETE: 3D velocity sampling with hardware parallelization!
return qc
def create_quantum_circuit_3d_parametric_template(self) -> Tuple[QuantumCircuit, List[Parameter]]:
"""
Create a parameterized template circuit for 3D velocity sampling.
Returns the circuit and the list of parameters [theta1_x, theta2_x, theta1_y, theta2_y, theta1_z, theta2_z].
"""
theta1_x = Parameter('theta1_x')
theta2_x = Parameter('theta2_x')
theta1_y = Parameter('theta1_y')
theta2_y = Parameter('theta2_y')
theta1_z = Parameter('theta1_z')
theta2_z = Parameter('theta2_z')
qc = QuantumCircuit(6, 6)
# X-component
qc.ry(theta1_x, 0)
qc.x(0)
# Decomposed CRY(theta2_x, 0, 1)
qc.ry(theta2_x/2, 1)
qc.cx(0, 1)
qc.ry(-theta2_x/2, 1)
qc.cx(0, 1)
qc.x(0)
# Y-component
qc.ry(theta1_y, 2)
qc.x(2)
# Decomposed CRY(theta2_y, 2, 3)
qc.ry(theta2_y/2, 3)
qc.cx(2, 3)
qc.ry(-theta2_y/2, 3)
qc.cx(2, 3)
qc.x(2)
# Z-component
qc.ry(theta1_z, 4)
qc.x(4)
# Decomposed CRY(theta2_z, 4, 5)
qc.ry(theta2_z/2, 5)
qc.cx(4, 5)
qc.ry(-theta2_z/2, 5)
qc.cx(4, 5)
qc.x(4)
qc.measure(range(6), range(6))
return qc, [theta1_x, theta2_x, theta1_y, theta2_y, theta1_z, theta2_z]
def create_quantum_circuit_1d_parametric_template(self) -> Tuple[QuantumCircuit, List[Parameter]]:
"""
Create a parameterized template circuit for 1D velocity sampling.
Returns the circuit and the list of parameters [theta1, theta2].
"""
theta1 = Parameter('theta1')
theta2 = Parameter('theta2')
qc = QuantumCircuit(2, 2)
# First rotation
qc.ry(theta1, 0)
qc.x(0)
# Decomposed CRY(theta2, 0, 1)
# Standard decomposition of controlled-Ry
qc.ry(theta2/2, 1)
qc.cx(0, 1)
qc.ry(-theta2/2, 1)
qc.cx(0, 1)
qc.x(0)
qc.measure(range(2), range(2))
return qc, [theta1, theta2]
def compute_angles(self, mu: float, sigma_sq: float) -> Tuple[float, float]:
"""
Compute rotation angles theta1 and theta2 for a given mu and sigma_sq.
Used for preparing parameters for the template circuit.
"""
p = mu * mu + sigma_sq
p_clamped = self._clamp01(p)
theta1 = 2 * np.arccos(np.sqrt(p_clamped))
# Avoid division by zero if p is extremely small
if abs(p) < 1e-10:
prob_plus1 = 0.5
else:
prob_plus1 = 0.5 * (1.0 + mu / p)
prob_plus1 = self._clamp01(prob_plus1)
theta2 = 2 * np.arcsin(np.sqrt(prob_plus1))
return theta1, theta2
def create_quantum_circuit(self, probs: np.ndarray) -> QuantumCircuit:
"""
Create quantum circuit using the configured circuit type.
This method automatically routes to the correct implementation based on
self.circuit_type (set in __init__):
- 'symmetric': {-1, +1} vs {0} decomposition (default, recommended)
- 'original': {-1, 0} vs {+1} decomposition
The decoder will automatically match the circuit type, so users don't need
to manually track which decoder to use.
The symmetric decomposition is preferred because it:
- Has simpler angle formulas
- Better captures physical symmetry
- Is more numerically stable for velocity encoding
"""
if self.circuit_type == 'symmetric':
return self.create_quantum_circuit_symmetric(probs)
else: # 'original'
return self.create_quantum_circuit_original(probs)
def quantum_sample_grid_point(self, mu: float, sigma_sq: float, shots: int = 1000) -> Dict[int, int]:
"""
Execute quantum sampling for discrete Gaussian distribution at single grid point
QUANTUM SAMPLING PROCESS:
1. Classical preprocessing: Calculate target probabilities P(-1), P(0), P(1)
2. Quantum encoding: Convert probabilities to quantum circuit amplitudes
3. Quantum execution: Run circuit multiple times (shots) to get samples
4. Classical postprocessing: Decode quantum measurement results to outcomes
PARAMETERS:
- mu: mean parameter for this specific grid location
- sigma_sq: variance parameter for this specific grid location
- shots: number of quantum circuit executions (sample size)
QUANTUM ADVANTAGE:
Each quantum circuit execution processes the full superposition simultaneously,
potentially offering advantages over classical rejection sampling methods.
"""
# STEP 1: CLASSICAL PREPROCESSING
# Calculate the target discrete Gaussian probabilities for this grid point
# This gives us the classical "ground truth" that our quantum circuit should reproduce
probs = self.discrete_gaussian_probs(mu, sigma_sq)
# STEP 2: QUANTUM CIRCUIT CREATION
# Convert classical probabilities into quantum circuit using amplitude encoding
# This is the core quantum advantage: encoding probabilistic information as quantum superposition
qc = self.create_quantum_circuit(probs)
# STEP 3: QUANTUM CIRCUIT COMPILATION
# Prepare circuit for execution on quantum simulator
# - AerSimulator: High-performance classical simulator of quantum circuits
# - Pass manager: Optimizes circuit for better execution (gate optimization, noise modeling, etc.)
# - Optimization level 1: Basic optimizations (gate cancellation, routing, etc.)
simulator = AerSimulator() # Create quantum circuit simulator
pass_manager = generate_preset_pass_manager(1, simulator) # Create optimization pipeline
qc_compiled = pass_manager.run(qc) # Apply optimizations to circuit
# STEP 4: QUANTUM EXECUTION
# Run the quantum circuit multiple times to collect statistical samples
# Each "shot" represents one complete quantum computation: prepare state → measure → get classical result
job = simulator.run(qc_compiled, shots=shots) # Submit job to quantum simulator
result = job.result() # Wait for completion and get results
counts = result.get_counts() # Extract measurement statistics: {'bitstring': count, ...}
return self._decode_quantum_counts(counts)
def quantum_sample_grid_point_parametric(self, mu: float, sigma_sq: float, shots: int = 1000) -> Dict[int, int]:
"""
Execute quantum sampling using direct parametrization (symmetric circuit only).
DIRECT PARAMETRIC SAMPLING:
This method bypasses classical probability computation entirely by computing
gate angles directly from (μ, σ²) parameters.
WORKFLOW:
1. Direct angle computation: θ₁, θ₂ = f(μ, σ²) - no probability step!
2. Quantum circuit creation: Build circuit with computed angles
3. Quantum execution: Run circuit multiple times (shots)
4. Classical postprocessing: Decode measurement results
ADVANTAGES over quantum_sample_grid_point:
- Fewer classical operations (no probability computation)
- Direct mathematical relationship to physical parameters
- More efficient for large-scale sampling
- Only available for symmetric circuit (simpler angle formulas)
PARAMETERS:
- mu: mean μ (physically: velocity u)
- sigma_sq: variance σ² (physically: temperature T)
- shots: number of quantum circuit executions (sample size)
CONSTRAINT:
- Only works with symmetric circuit (circuit_type='symmetric')
- Requires σ² < 1 for valid probabilities (physical: T < 1)
"""
# STEP 1: Validate circuit type
if self.circuit_type != 'symmetric':
raise ValueError(f"Parametric sampling only available for symmetric circuit, "
f"but circuit_type='{self.circuit_type}'")
# STEP 2: DIRECT QUANTUM CIRCUIT CREATION
# Compute gate angles directly from parameters without classical probability step
qc = self.create_quantum_circuit_parametric(mu, sigma_sq)
# STEP 3: QUANTUM CIRCUIT COMPILATION
simulator = AerSimulator()
pass_manager = generate_preset_pass_manager(1, simulator)
qc_compiled = pass_manager.run(qc)
# STEP 4: QUANTUM EXECUTION
job = simulator.run(qc_compiled, shots=shots)
result = job.result()
counts = result.get_counts()
# STEP 5: DECODE RESULTS
# Use symmetric decoder (automatically selected via self.circuit_type)
return self._decode_quantum_counts(counts)
def quantum_sample_grid_point_3d_parametric(
self,
mu_x: float,
mu_y: float,
mu_z: float,
sigma_sq: float,
shots: int = 1000,
simulator: Optional[AerSimulator] = None,
pass_manager: Optional[object] = None
) -> Dict[Tuple[int, int, int], int]:
"""
Execute quantum sampling for 3D velocity distribution at a single grid point.
WORKFLOW:
1. Direct circuit creation: Build 6-qubit circuit from (μₓ, μᵧ, μᵧ, σ²)
2. Quantum execution: Run circuit multiple times (shots) on simulator
3. Measurement: Single measurement yields full 3D velocity tuple
4. Decoding: Convert 6-bit strings to (vₓ, vᵧ, vᵧ) tuples
PARALLELIZATION ADVANTAGE:
All three dimensions are sampled simultaneously in a single circuit execution.
Time = T_circuit (not 3×T_circuit for sequential 1D sampling).
PARAMETERS:
- mu_x, mu_y, mu_z: mean velocities μx, μy, μz (physically: ux, uy, uz)
- sigma_sq: variance σ² (physically: temperature T, shared isotropic property)
- shots: number of quantum circuit executions (sample size)
- simulator: (Optional) Pre-configured AerSimulator instance.
- pass_manager: (Optional) Pre-configured transpiler pass manager.
OUTPUT:
Dictionary mapping (vₓ, vᵧ, vᵧ) tuples to counts
Example: {(-1, 0, +1): 235, (0, 0, 0): 189, ...}
CONSTRAINT:
- Requires sigma_sq < 1 and mu_i² + sigma_sq < 1 for all i ∈ {x,y,z}
"""
# STEP 1: Create 3D quantum circuit directly from parameters
qc = self.create_quantum_circuit_3d_parametric(mu_x, mu_y, mu_z, sigma_sq)
# STEP 2: Compile circuit for quantum simulator
# Use provided instances if available, otherwise create new ones
if simulator is None:
simulator = AerSimulator()
if pass_manager is None:
pass_manager = generate_preset_pass_manager(1, simulator)
qc_compiled = pass_manager.run(qc)
# STEP 3: Execute quantum circuit
job = simulator.run(qc_compiled, shots=shots)
result = job.result()
counts = result.get_counts()
# STEP 4: Decode 6-qubit measurements to 3D velocity tuples
return self._decode_quantum_counts_3d(counts)
def compute_moments_from_samples_3d(
self,
velocity_counts: Dict[Tuple[int, int, int], int]
) -> Dict[str, float]:
"""
Compute statistical moments from 3D velocity samples.
COMPUTED MOMENTS:
For each dimension (x, y, z):
- mean_x, mean_y, mean_z: E[vᵢ] = Σ vᵢ * P(vᵢ)
- var_x, var_y, var_z: Var[vᵢ] = E[vᵢ²] - E[vᵢ]²
These moments characterize the distribution without requiring
all 27 individual probabilities.
VALIDATION STRATEGY:
Compare empirical moments from quantum samples against theoretical
moments computed from Maxwell-Boltzmann parameters.
INPUT:
velocity_counts: {(vₓ, vᵧ, vᵧ): count} from quantum measurements
OUTPUT:
Dictionary with keys: 'mean_x', 'mean_y', 'mean_z', 'var_x', 'var_y', 'var_z'
"""
total_shots = sum(velocity_counts.values())
if total_shots == 0:
return {
'mean_x': 0.0, 'mean_y': 0.0, 'mean_z': 0.0,