Spaces:
Paused
Paused
Commit
·
51422a5
1
Parent(s):
4e14814
Feature :(QLBM: IBM Qiskit Simulator )
Browse files- fluid.py → qlbm/fluid.py +0 -0
- qlbm/qlbm_sample_app.py +901 -0
- qlbm_embedded.py +303 -76
- requirements.txt +1 -1
fluid.py → qlbm/fluid.py
RENAMED
|
File without changes
|
qlbm/qlbm_sample_app.py
ADDED
|
@@ -0,0 +1,901 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister,transpile
|
| 2 |
+
from qiskit.synthesis.qft import synth_qft_full as QFT
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
from sympy import sympify, symbols, lambdify
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
from qiskit_ibm_runtime import QiskitRuntimeService
|
| 10 |
+
|
| 11 |
+
import plotly.graph_objects as go
|
| 12 |
+
|
| 13 |
+
dim=3
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def bin_to_gray(bin_s):
|
| 17 |
+
XOR=lambda x,y: (x or y) and not (x and y)
|
| 18 |
+
gray_s=bin_s[0]
|
| 19 |
+
for i in range(len(bin_s)-1):
|
| 20 |
+
c_bool=XOR(bool(int(bin_s[i])),bool(int(bin_s[i+1])))
|
| 21 |
+
gray_s+=str(int(c_bool))
|
| 22 |
+
return gray_s
|
| 23 |
+
|
| 24 |
+
def gray_to_bin(gray_s):
|
| 25 |
+
XOR=lambda x,y: (x or y) and not (x and y)
|
| 26 |
+
bin_s=gray_s[0]
|
| 27 |
+
for i in range(len(gray_s)-1):
|
| 28 |
+
c_bool=XOR(bool(int(bin_s[i])),bool(int(gray_s[i+1])))
|
| 29 |
+
bin_s+=str(int(c_bool))
|
| 30 |
+
return bin_s
|
| 31 |
+
|
| 32 |
+
def bin_to_int(bin_s):
|
| 33 |
+
return int(bin_s,2)
|
| 34 |
+
|
| 35 |
+
def int_to_bin(i,pad):
|
| 36 |
+
return bin(i)[2:].zfill(pad)
|
| 37 |
+
|
| 38 |
+
def fwht_approx(f,N,num_points_per_dim,threshold=1e-10):
|
| 39 |
+
linear_block_size=int(N//num_points_per_dim)
|
| 40 |
+
num_angles_per_block=int(np.log2(linear_block_size))
|
| 41 |
+
|
| 42 |
+
thetas={}
|
| 43 |
+
|
| 44 |
+
for k in range(num_points_per_dim):
|
| 45 |
+
for j in range(num_points_per_dim):
|
| 46 |
+
for i in range(num_points_per_dim):
|
| 47 |
+
|
| 48 |
+
avg_f=2*np.arccos(f(i*linear_block_size+(linear_block_size-1)/2,j*linear_block_size+(linear_block_size-1)/2,k*linear_block_size+(linear_block_size-1)/2))
|
| 49 |
+
thetas[k*(N**2)*linear_block_size+j*N*linear_block_size+i*linear_block_size]=avg_f
|
| 50 |
+
|
| 51 |
+
slope_x=(2*np.arccos(f(i*linear_block_size,j*linear_block_size+(linear_block_size-1)/2,k*linear_block_size+(linear_block_size-1)/2))-2*np.arccos(f(((i+1)%N)*linear_block_size,j*linear_block_size+(linear_block_size-1)/2,k*linear_block_size+(linear_block_size-1)/2)))/linear_block_size
|
| 52 |
+
slope_y=(2*np.arccos(f(i*linear_block_size+(linear_block_size-1)/2,j*linear_block_size,k*linear_block_size+(linear_block_size-1)/2))-2*np.arccos(f(i*linear_block_size+(linear_block_size-1)/2,((j+1)%N)*linear_block_size,k*linear_block_size+(linear_block_size-1)/2)))/linear_block_size
|
| 53 |
+
slope_z=(2*np.arccos(f(i*linear_block_size+(linear_block_size-1)/2,j*linear_block_size+(linear_block_size-1)/2,k*linear_block_size))-2*np.arccos(f(i*linear_block_size+(linear_block_size-1)/2,j*linear_block_size+(linear_block_size-1)/2,((k+1)%N)*linear_block_size)))/linear_block_size
|
| 54 |
+
|
| 55 |
+
for m in range(num_angles_per_block):
|
| 56 |
+
thetas[k*(N**2)*linear_block_size+j*N*linear_block_size+i*linear_block_size + 2**m]=slope_x*(2**(m-1))
|
| 57 |
+
thetas[k*(N**2)*linear_block_size+j*N*linear_block_size+i*linear_block_size + N*(2**m)]=slope_y*(2**(m-1))
|
| 58 |
+
thetas[k*(N**2)*linear_block_size+j*N*linear_block_size+i*linear_block_size + (N**2)*(2**m)]=slope_z*(2**(m-1))
|
| 59 |
+
|
| 60 |
+
h = linear_block_size
|
| 61 |
+
while h < N**3:
|
| 62 |
+
for i in range(0, N**3, h * 2):
|
| 63 |
+
if (i//N)%linear_block_size!=0:
|
| 64 |
+
continue
|
| 65 |
+
if (i//(N**2))%linear_block_size!=0:
|
| 66 |
+
continue
|
| 67 |
+
j=i
|
| 68 |
+
while j<i+h:
|
| 69 |
+
index=j
|
| 70 |
+
x = thetas[index]
|
| 71 |
+
y = thetas[index + h]
|
| 72 |
+
thetas[index] = (x + y)/2
|
| 73 |
+
thetas[index + h] = (x - y)/2
|
| 74 |
+
|
| 75 |
+
for ax in range(3):
|
| 76 |
+
for m in range(num_angles_per_block):
|
| 77 |
+
index=j+(N**ax)*(2**m)
|
| 78 |
+
x = thetas[index]
|
| 79 |
+
y = thetas[index + h]
|
| 80 |
+
thetas[index] = (x + y)/2
|
| 81 |
+
thetas[index + h] = (x - y)/2
|
| 82 |
+
|
| 83 |
+
j+=linear_block_size
|
| 84 |
+
if (j//N)%linear_block_size==1:
|
| 85 |
+
j+=(linear_block_size-1)*N
|
| 86 |
+
if (j//(N**2))%linear_block_size==1:
|
| 87 |
+
j+=(linear_block_size-1)*(N**2)
|
| 88 |
+
|
| 89 |
+
h *= 2
|
| 90 |
+
if h==N:
|
| 91 |
+
h=N*linear_block_size
|
| 92 |
+
if h==N**2:
|
| 93 |
+
h=(N**2)*linear_block_size
|
| 94 |
+
|
| 95 |
+
theta_sorted=sorted(np.abs(list(thetas.values())))
|
| 96 |
+
|
| 97 |
+
sum_=0
|
| 98 |
+
for th in theta_sorted:
|
| 99 |
+
sum_+=th
|
| 100 |
+
if sum_>threshold:
|
| 101 |
+
threshold=sum_-th
|
| 102 |
+
break
|
| 103 |
+
|
| 104 |
+
return [theta for theta in thetas.values() if abs(theta)>threshold],[key for key in thetas.keys() if abs(thetas[key])>threshold]
|
| 105 |
+
|
| 106 |
+
def get_circuit_inputs(f,num_reg_qubits,num_points_per_dim):
|
| 107 |
+
theta_vec,indices=fwht_approx(f,2**num_reg_qubits,num_points_per_dim,1e-4)
|
| 108 |
+
circ_pos=[]
|
| 109 |
+
for ind in indices:
|
| 110 |
+
circ_pos+=[bin_to_int(gray_to_bin(int_to_bin(ind,num_reg_qubits*3)))]
|
| 111 |
+
|
| 112 |
+
sorted_theta_vec=sorted(zip(theta_vec,circ_pos),key=lambda el:el[1])
|
| 113 |
+
ctrls=[]
|
| 114 |
+
|
| 115 |
+
current_bs="0"*(3*num_reg_qubits)
|
| 116 |
+
for el in sorted_theta_vec:
|
| 117 |
+
new_bs=bin_to_gray(int_to_bin((el[1])%(2**(3*num_reg_qubits)),(3*num_reg_qubits)))
|
| 118 |
+
ctrls += [[i for i, (char1, char2) in enumerate(zip(current_bs[::-1], new_bs[::-1])) if char1 != char2]]
|
| 119 |
+
current_bs=new_bs
|
| 120 |
+
new_bs="0"*(3*num_reg_qubits)
|
| 121 |
+
ctrls += [[i for i, (char1, char2) in enumerate(zip(current_bs[::-1], new_bs[::-1])) if char1 != char2]]
|
| 122 |
+
|
| 123 |
+
return [el[0] for el in sorted_theta_vec],ctrls
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def get_coeffs(n,ux,uy,uz,resolution=32):
|
| 127 |
+
current_N=2**n
|
| 128 |
+
|
| 129 |
+
x_coeffs,x_coeff_var_indices=get_circuit_inputs(lambda x,y,z: ((1+ux(x/current_N,y/current_N,z/current_N))/2)**0.5,n,min(current_N,resolution))
|
| 130 |
+
y_coeffs,y_coeff_var_indices=get_circuit_inputs(lambda x,y,z: ((1+uy(x/current_N,y/current_N,z/current_N))/2)**0.5,n,min(current_N,resolution))
|
| 131 |
+
z_coeffs,z_coeff_var_indices=get_circuit_inputs(lambda x,y,z: ((1+uz(x/current_N,y/current_N,z/current_N))/2)**0.5,n,min(current_N,resolution))
|
| 132 |
+
x_coeffs_,x_coeff_var_indices_=get_circuit_inputs(lambda x,y,z: 0 if (1+ux((x-1)/current_N,y/current_N,z/current_N))==0 else \
|
| 133 |
+
((1+ux((x-1)/current_N,y/current_N,z/current_N))/(2+ux((x-1)/current_N,y/current_N,z/current_N)-ux((x+1)/current_N,y/current_N,z/current_N)))**0.5,n,min(current_N,resolution))
|
| 134 |
+
y_coeffs_,y_coeff_var_indices_=get_circuit_inputs(lambda x,y,z: 0 if (1+uy(x/current_N,(y-1)/current_N,z/current_N))==0 else \
|
| 135 |
+
((1+uy(x/current_N,(y-1)/current_N,z/current_N))/(2+uy(x/current_N,(y-1)/current_N,z/current_N)-uy(x/current_N,(y+1)/current_N,z/current_N)))**0.5,n,min(current_N,resolution))
|
| 136 |
+
z_coeffs_,z_coeff_var_indices_=get_circuit_inputs(lambda x,y,z: 0 if (1+uz(x/current_N,y/current_N,(z-1)/current_N))==0 else \
|
| 137 |
+
((1+uz(x/current_N,y/current_N,(z-1)/current_N))/(2+uz(x/current_N,y/current_N,(z-1)/current_N)-uz(x/current_N,y/current_N,(z+1)/current_N)))**0.5,n,min(current_N,resolution))
|
| 138 |
+
unprep1_coeffs,unprep1_coeff_var_indices=get_circuit_inputs(lambda x,y,z:\
|
| 139 |
+
(1/3**0.5)*(1+(ux((x-1)/current_N,y/current_N,z/current_N)-ux((x+1)/current_N,y/current_N,z/current_N))/2)**0.5,n,min(current_N,resolution))
|
| 140 |
+
unprep2_coeffs,unprep2_coeff_var_indices=get_circuit_inputs(lambda x,y,z:\
|
| 141 |
+
((1+(uy(x/current_N,(y-1)/current_N,z/current_N)-uy(x/current_N,(y+1)/current_N,z/current_N))/2)/(2-(ux((x-1)/current_N,y/current_N,z/current_N)-ux((x+1)/current_N,y/current_N,z/current_N))/2))**0.5,n,min(current_N,resolution))
|
| 142 |
+
|
| 143 |
+
return x_coeffs,x_coeff_var_indices, y_coeffs,y_coeff_var_indices, z_coeffs,z_coeff_var_indices,\
|
| 144 |
+
x_coeffs_,x_coeff_var_indices_, y_coeffs_,y_coeff_var_indices_, z_coeffs_,z_coeff_var_indices_,\
|
| 145 |
+
unprep1_coeffs,unprep1_coeff_var_indices, unprep2_coeffs,unprep2_coeff_var_indices
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def get_coll_ops(n,ux,uy,uz,resolution=32):
|
| 149 |
+
|
| 150 |
+
x_coeffs,x_coeff_var_indices, y_coeffs,y_coeff_var_indices, z_coeffs,z_coeff_var_indices,\
|
| 151 |
+
x_coeffs_,x_coeff_var_indices_, y_coeffs_,y_coeff_var_indices_, z_coeffs_,z_coeff_var_indices_,\
|
| 152 |
+
unprep1_coeffs,unprep1_coeff_var_indices, unprep2_coeffs,unprep2_coeff_var_indices = get_coeffs(n,ux,uy,uz,resolution)
|
| 153 |
+
|
| 154 |
+
def prep(qc,pos_qr,dir_qr):
|
| 155 |
+
|
| 156 |
+
qc.h(dir_qr[0])
|
| 157 |
+
qc.h(dir_qr[4])
|
| 158 |
+
|
| 159 |
+
qc.cx(dir_qr[0],dir_qr[2])
|
| 160 |
+
|
| 161 |
+
qc.ry(-np.pi/4,dir_qr[4])
|
| 162 |
+
qc.cx(dir_qr[2],dir_qr[4])
|
| 163 |
+
qc.ry(np.pi/4,dir_qr[4])
|
| 164 |
+
qc.cx(dir_qr[2],dir_qr[4])
|
| 165 |
+
|
| 166 |
+
qc.ry(-np.pi/4,dir_qr[2])
|
| 167 |
+
qc.cx(dir_qr[0],dir_qr[2])
|
| 168 |
+
qc.ry(np.pi/4,dir_qr[2])
|
| 169 |
+
qc.cx(dir_qr[0],dir_qr[2])
|
| 170 |
+
|
| 171 |
+
qc.cx(dir_qr[2],dir_qr[0])
|
| 172 |
+
|
| 173 |
+
qc.cx(dir_qr[0],dir_qr[1])
|
| 174 |
+
for i in range(len(x_coeff_var_indices)):
|
| 175 |
+
for ind in x_coeff_var_indices[i]:
|
| 176 |
+
qc.cx([q for reg in pos_qr for q in reg][ind],dir_qr[0])
|
| 177 |
+
if i<len(x_coeffs):
|
| 178 |
+
qc.cry(x_coeffs[i],dir_qr[1],dir_qr[0])
|
| 179 |
+
qc.cx(dir_qr[0],dir_qr[1])
|
| 180 |
+
|
| 181 |
+
qc.cx(dir_qr[2],dir_qr[3])
|
| 182 |
+
for i in range(len(y_coeff_var_indices)):
|
| 183 |
+
for ind in y_coeff_var_indices[i]:
|
| 184 |
+
qc.cx([q for reg in pos_qr for q in reg][ind],dir_qr[2])
|
| 185 |
+
if i<len(y_coeffs):
|
| 186 |
+
qc.cry(y_coeffs[i],dir_qr[3],dir_qr[2])
|
| 187 |
+
qc.cx(dir_qr[2],dir_qr[3])
|
| 188 |
+
|
| 189 |
+
qc.cx(dir_qr[4],dir_qr[5])
|
| 190 |
+
for i in range(len(z_coeff_var_indices)):
|
| 191 |
+
for ind in z_coeff_var_indices[i]:
|
| 192 |
+
qc.cx([q for reg in pos_qr for q in reg][ind],dir_qr[4])
|
| 193 |
+
if i<len(z_coeffs):
|
| 194 |
+
qc.cry(z_coeffs[i],dir_qr[5],dir_qr[4])
|
| 195 |
+
qc.cx(dir_qr[4],dir_qr[5])
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def unprep(qc,pos_qr,dir_qr):
|
| 200 |
+
qc.cx(dir_qr[0],dir_qr[1])
|
| 201 |
+
for i in range(len(x_coeff_var_indices_)):
|
| 202 |
+
for ind in x_coeff_var_indices_[i]:
|
| 203 |
+
qc.cx([q for reg in pos_qr for q in reg][ind],dir_qr[0])
|
| 204 |
+
if i<len(x_coeffs_):
|
| 205 |
+
qc.cry(-x_coeffs_[i],dir_qr[1],dir_qr[0])
|
| 206 |
+
qc.cx(dir_qr[0],dir_qr[1])
|
| 207 |
+
|
| 208 |
+
qc.cx(dir_qr[2],dir_qr[3])
|
| 209 |
+
for i in range(len(y_coeff_var_indices_)):
|
| 210 |
+
for ind in y_coeff_var_indices_[i]:
|
| 211 |
+
qc.cx([q for reg in pos_qr for q in reg][ind],dir_qr[2])
|
| 212 |
+
if i<len(y_coeffs_):
|
| 213 |
+
qc.cry(-y_coeffs_[i],dir_qr[3],dir_qr[2])
|
| 214 |
+
qc.cx(dir_qr[2],dir_qr[3])
|
| 215 |
+
|
| 216 |
+
qc.cx(dir_qr[4],dir_qr[5])
|
| 217 |
+
for i in range(len(z_coeff_var_indices_)):
|
| 218 |
+
for ind in z_coeff_var_indices_[i]:
|
| 219 |
+
qc.cx([q for reg in pos_qr for q in reg][ind],dir_qr[4])
|
| 220 |
+
if i<len(z_coeffs_):
|
| 221 |
+
qc.cry(-z_coeffs_[i],dir_qr[5],dir_qr[4])
|
| 222 |
+
qc.cx(dir_qr[4],dir_qr[5])
|
| 223 |
+
|
| 224 |
+
qc.cx(dir_qr[2],dir_qr[4])
|
| 225 |
+
for i in range(len(unprep2_coeff_var_indices)):
|
| 226 |
+
for ind in unprep2_coeff_var_indices[i]:
|
| 227 |
+
qc.cx([q for reg in pos_qr for q in reg][ind],dir_qr[2])
|
| 228 |
+
if i<len(unprep2_coeffs):
|
| 229 |
+
qc.cry(unprep2_coeffs[i],dir_qr[4],dir_qr[2])
|
| 230 |
+
qc.cx(dir_qr[2],dir_qr[4])
|
| 231 |
+
|
| 232 |
+
qc.cx(dir_qr[0],dir_qr[2])
|
| 233 |
+
for i in range(len(unprep1_coeff_var_indices)):
|
| 234 |
+
for ind in unprep1_coeff_var_indices[i]:
|
| 235 |
+
qc.cx([q for reg in pos_qr for q in reg][ind],dir_qr[0])
|
| 236 |
+
if i<len(unprep1_coeffs):
|
| 237 |
+
qc.cry(unprep1_coeffs[i],dir_qr[2],dir_qr[0])
|
| 238 |
+
qc.cx(dir_qr[0],dir_qr[2])
|
| 239 |
+
|
| 240 |
+
qc.ry(-2*np.pi/3,dir_qr[0])
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
return prep,unprep
|
| 244 |
+
|
| 245 |
+
def stream(qc,pos_qr,dir_qr,n):
|
| 246 |
+
|
| 247 |
+
for i in range(dim):
|
| 248 |
+
forw_ctrl=dir_qr[2*i]
|
| 249 |
+
backw_ctrl=dir_qr[2*i+1]
|
| 250 |
+
for m in range(n):
|
| 251 |
+
qc.cp( np.pi / (2 ** m), forw_ctrl, pos_qr[i][m])
|
| 252 |
+
qc.cp(-np.pi / (2 ** m), backw_ctrl, pos_qr[i][m])
|
| 253 |
+
|
| 254 |
+
def get_circuit(n,ux,uy,uz,init_state_prep_circ,T_list,vel_resolution=32,measure=True):
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
dirs=[[0,0,0],[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]]
|
| 258 |
+
wts = np.array([2/8, 1/8, 1/8, 1/8, 1/8, 1/8, 1/8])
|
| 259 |
+
|
| 260 |
+
dir_indices=["".join(["0"+str(el) if el>=0 else str(-el)+"0" for el in dir_[::-1]]) for dir_ in dirs]
|
| 261 |
+
dirs_state=np.zeros(2**7)
|
| 262 |
+
for i,dir_ind in enumerate(dir_indices):
|
| 263 |
+
ind=int(dir_ind,2)
|
| 264 |
+
dirs_state[ind]=wts[i]**0.5
|
| 265 |
+
|
| 266 |
+
qc_list=[]
|
| 267 |
+
|
| 268 |
+
prep, unprep=get_coll_ops(n,ux,uy,uz,vel_resolution)
|
| 269 |
+
|
| 270 |
+
for T_total in T_list:
|
| 271 |
+
pos_qr=[QuantumRegister(n) for _ in range(dim)]
|
| 272 |
+
pos_cr=[ClassicalRegister(n) for _ in range(dim)]
|
| 273 |
+
dir_qr=QuantumRegister(2*dim)
|
| 274 |
+
dir_cr=[ClassicalRegister(2*dim) for _ in range(T_total)]
|
| 275 |
+
|
| 276 |
+
qc=QuantumCircuit(*pos_qr,dir_qr,*pos_cr,*dir_cr)
|
| 277 |
+
|
| 278 |
+
qc.compose(init_state_prep_circ,[qubit for qr in pos_qr for qubit in list(qr)], inplace=True)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
for i in range(dim):
|
| 282 |
+
qc.compose(QFT(n, inverse=False, do_swaps=False), pos_qr[i], inplace=True)
|
| 283 |
+
|
| 284 |
+
for T in list(range(T_total))[::-1]:
|
| 285 |
+
|
| 286 |
+
prep(qc,pos_qr,dir_qr)
|
| 287 |
+
stream(qc,pos_qr,dir_qr,n)
|
| 288 |
+
unprep(qc,pos_qr,dir_qr)
|
| 289 |
+
|
| 290 |
+
qc.measure(dir_qr,dir_cr[T])
|
| 291 |
+
|
| 292 |
+
for i in range(dim):
|
| 293 |
+
qc.compose(QFT(n, inverse=True, do_swaps=False), pos_qr[i], inplace=True)
|
| 294 |
+
|
| 295 |
+
if measure:
|
| 296 |
+
for i in range(dim):
|
| 297 |
+
qc.measure(pos_qr[i],pos_cr[i])
|
| 298 |
+
|
| 299 |
+
qc_list+=[qc]
|
| 300 |
+
|
| 301 |
+
return qc_list
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def str_to_lambda(vx_param,vy_param,vz_param):
|
| 306 |
+
|
| 307 |
+
vx_val = str(vx_param)
|
| 308 |
+
vy_val = str(vy_param)
|
| 309 |
+
vz_val = str(vz_param)
|
| 310 |
+
|
| 311 |
+
x_sym, y_sym, z_sym = symbols('x y z')
|
| 312 |
+
vx_sympified = sympify(vx_val)
|
| 313 |
+
vy_sympified = sympify(vy_val)
|
| 314 |
+
vz_sympified = sympify(vz_val)
|
| 315 |
+
|
| 316 |
+
vx=lambdify((x_sym, y_sym, z_sym), vx_sympified, modules="numpy")
|
| 317 |
+
vy=lambdify((x_sym, y_sym, z_sym), vy_sympified, modules="numpy")
|
| 318 |
+
vz=lambdify((x_sym, y_sym, z_sym), vz_sympified, modules="numpy")
|
| 319 |
+
|
| 320 |
+
return vx,vy,vz
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def get_named_init_state_circuit(
|
| 324 |
+
n: int,
|
| 325 |
+
init_state_name: str,
|
| 326 |
+
# Sinusoidal parameters (frequency multipliers)
|
| 327 |
+
sine_k_x: float = 1.0,
|
| 328 |
+
sine_k_y: float = 1.0,
|
| 329 |
+
sine_k_z: float = 1.0,
|
| 330 |
+
# Gaussian parameters
|
| 331 |
+
gauss_cx: float = None, # Center X (0-1 normalized), defaults to 0.5
|
| 332 |
+
gauss_cy: float = None, # Center Y (0-1 normalized), defaults to 0.5
|
| 333 |
+
gauss_cz: float = None, # Center Z (0-1 normalized), defaults to 0.5
|
| 334 |
+
gauss_sigma: float = None, # Spread, defaults to 0.2 in normalized units
|
| 335 |
+
):
|
| 336 |
+
"""
|
| 337 |
+
Create initial state preparation circuit with configurable parameters.
|
| 338 |
+
|
| 339 |
+
Parameters
|
| 340 |
+
----------
|
| 341 |
+
n : int
|
| 342 |
+
Number of qubits per spatial dimension (grid size = 2^n per axis)
|
| 343 |
+
init_state_name : str
|
| 344 |
+
One of "dirac_delta", "sin", "gaussian"
|
| 345 |
+
sine_k_x, sine_k_y, sine_k_z : float
|
| 346 |
+
Frequency multipliers for sinusoidal distribution (default=1.0)
|
| 347 |
+
gauss_cx, gauss_cy, gauss_cz : float
|
| 348 |
+
Center coordinates in [0,1] for Gaussian (default=0.5)
|
| 349 |
+
gauss_sigma : float
|
| 350 |
+
Spread of Gaussian in normalized units (default=0.2)
|
| 351 |
+
|
| 352 |
+
Returns
|
| 353 |
+
-------
|
| 354 |
+
QuantumCircuit
|
| 355 |
+
State preparation circuit
|
| 356 |
+
"""
|
| 357 |
+
N = 2**n
|
| 358 |
+
init_state_prep_circ = QuantumCircuit(3*n)
|
| 359 |
+
|
| 360 |
+
if init_state_name == "dirac_delta":
|
| 361 |
+
init_state_prep_circ.x(n-1)
|
| 362 |
+
init_state_prep_circ.x(2*n-1)
|
| 363 |
+
init_state_prep_circ.x(3*n-1)
|
| 364 |
+
|
| 365 |
+
elif init_state_name == "sin":
|
| 366 |
+
# Configurable frequency sinusoidal distribution
|
| 367 |
+
# f(x,y,z) = 1 + sin(2π * kx * x) * sin(2π * ky * y) * sin(2π * kz * z)
|
| 368 |
+
kx = max(1, int(round(float(sine_k_x))))
|
| 369 |
+
ky = max(1, int(round(float(sine_k_y))))
|
| 370 |
+
kz = max(1, int(round(float(sine_k_z))))
|
| 371 |
+
|
| 372 |
+
coords = np.arange(N) / N # Normalized [0, 1)
|
| 373 |
+
|
| 374 |
+
sin_x = np.sin(2 * np.pi * kx * coords)
|
| 375 |
+
sin_y = np.sin(2 * np.pi * ky * coords)
|
| 376 |
+
sin_z = np.sin(2 * np.pi * kz * coords)
|
| 377 |
+
|
| 378 |
+
# Build 3D state via Kronecker products
|
| 379 |
+
# Order matches original: z ⊗ (y ⊗ x)
|
| 380 |
+
init_state = 1 + (
|
| 381 |
+
np.kron(sin_z, np.ones(N**2)) *
|
| 382 |
+
np.kron(np.ones(N**2), sin_x) *
|
| 383 |
+
np.kron(np.ones(N), np.kron(sin_y, np.ones(N)))
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
init_state_prep_circ.prepare_state(init_state.astype(np.complex128), normalize=True)
|
| 387 |
+
init_state_prep_circ = transpile(init_state_prep_circ, basis_gates=['u1', 'u2', 'u3', 'cx'])
|
| 388 |
+
|
| 389 |
+
elif init_state_name == "gaussian":
|
| 390 |
+
# Configurable Gaussian distribution
|
| 391 |
+
# f(x,y,z) = exp(-((x-cx)^2 + (y-cy)^2 + (z-cz)^2) / (2*sigma^2))
|
| 392 |
+
|
| 393 |
+
# Default centers to 0.5 (middle of domain)
|
| 394 |
+
cx = float(gauss_cx) if gauss_cx is not None else 0.5
|
| 395 |
+
cy = float(gauss_cy) if gauss_cy is not None else 0.5
|
| 396 |
+
cz = float(gauss_cz) if gauss_cz is not None else 0.5
|
| 397 |
+
|
| 398 |
+
# Default sigma to 0.2 (similar to original sig=1 with mu=0.5 behavior)
|
| 399 |
+
sigma = float(gauss_sigma) if gauss_sigma is not None else 0.2
|
| 400 |
+
|
| 401 |
+
coords = np.arange(N) / N # Normalized [0, 1)
|
| 402 |
+
|
| 403 |
+
gauss_x = np.exp(-((coords - cx)**2) / (2 * sigma**2))
|
| 404 |
+
gauss_y = np.exp(-((coords - cy)**2) / (2 * sigma**2))
|
| 405 |
+
gauss_z = np.exp(-((coords - cz)**2) / (2 * sigma**2))
|
| 406 |
+
|
| 407 |
+
# Build 3D state via Kronecker products (same order as original)
|
| 408 |
+
init_state = (
|
| 409 |
+
np.kron(gauss_z, np.ones(N**2)) *
|
| 410 |
+
np.kron(np.ones(N**2), gauss_x) *
|
| 411 |
+
np.kron(np.ones(N), np.kron(gauss_y, np.ones(N)))
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
init_state_prep_circ.prepare_state(init_state.astype(np.complex128), normalize=True)
|
| 415 |
+
init_state_prep_circ = transpile(init_state_prep_circ, basis_gates=['u1', 'u2', 'u3', 'cx'])
|
| 416 |
+
|
| 417 |
+
return init_state_prep_circ
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
##########################################################################################
|
| 421 |
+
|
| 422 |
+
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2 as Sampler
|
| 423 |
+
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
|
| 424 |
+
import pprint
|
| 425 |
+
# import mthree
|
| 426 |
+
# from ...Quantum_LBM_AdvecDiff.qlbm.visualize_counts import load_samples, estimate_density, plot_density_isosurface
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def run_sampling_hw_ibm(
|
| 430 |
+
n,
|
| 431 |
+
ux,
|
| 432 |
+
uy,
|
| 433 |
+
uz,
|
| 434 |
+
init_state_prep_circ,
|
| 435 |
+
T_list,
|
| 436 |
+
shots=2**19,
|
| 437 |
+
vel_resolution=32,
|
| 438 |
+
output_resolution=40,
|
| 439 |
+
):
|
| 440 |
+
"""
|
| 441 |
+
Run QLBM simulation on IBM quantum hardware.
|
| 442 |
+
|
| 443 |
+
Parameters
|
| 444 |
+
----------
|
| 445 |
+
n : int
|
| 446 |
+
Number of qubits per spatial dimension
|
| 447 |
+
ux, uy, uz : callable or str
|
| 448 |
+
Velocity field components
|
| 449 |
+
init_state_prep_circ : QuantumCircuit
|
| 450 |
+
Pre-built initial state preparation circuit from get_named_init_state_circuit()
|
| 451 |
+
T_list : list[int]
|
| 452 |
+
List of timesteps to simulate
|
| 453 |
+
shots : int
|
| 454 |
+
Number of measurement shots (default: 2^19)
|
| 455 |
+
vel_resolution : int
|
| 456 |
+
Resolution for velocity field discretization
|
| 457 |
+
output_resolution : int
|
| 458 |
+
Grid resolution for density estimation output
|
| 459 |
+
|
| 460 |
+
Returns
|
| 461 |
+
-------
|
| 462 |
+
job : IBMJob
|
| 463 |
+
The submitted job object
|
| 464 |
+
get_job_result : callable
|
| 465 |
+
Callback function to retrieve and process results
|
| 466 |
+
"""
|
| 467 |
+
|
| 468 |
+
if type(ux)==str:
|
| 469 |
+
ux,uy,uz=str_to_lambda(ux,uy,uz)
|
| 470 |
+
|
| 471 |
+
qc_list=get_circuit(n,ux,uy,uz,init_state_prep_circ,T_list,vel_resolution)
|
| 472 |
+
|
| 473 |
+
pm_optimization_level = 3
|
| 474 |
+
|
| 475 |
+
service = QiskitRuntimeService(channel="ibm_cloud", token="UMeZUDI5D7fjPJHD5x3MJFwURg4PrGzBnTm142ka9-Hj",instance="crn:v1:bluemix:public:quantum-computing:us-east:a/15157e4350c04a9dab51b8b8a4a93c86:e29afd91-64bf-4a82-8dbf-731e6c213595::") # reads stored credentials / environment
|
| 476 |
+
backend = service.least_busy()
|
| 477 |
+
|
| 478 |
+
qc_compiled_list=[]
|
| 479 |
+
|
| 480 |
+
for qc in qc_list:
|
| 481 |
+
pm = generate_preset_pass_manager(backend=backend, optimization_level=pm_optimization_level)
|
| 482 |
+
print("Generating ISA circuit via PassManager (preserves measurements/conditionals).")
|
| 483 |
+
qc_compiled = pm.run(qc) # this is the recommended replacement for transpile(..., backend=backend)
|
| 484 |
+
print("Compiled circuit qubits/clbits:", qc_compiled.num_qubits, qc_compiled.num_clbits)
|
| 485 |
+
print("Depth: ", qc_compiled.depth())
|
| 486 |
+
qc_compiled_list+=[qc_compiled]
|
| 487 |
+
|
| 488 |
+
# Create Sampler primitive bound to the backend
|
| 489 |
+
sampler = Sampler(mode=backend)
|
| 490 |
+
|
| 491 |
+
# Submit job: pass a list of PUBs (we send one PUB [qc_compiled])
|
| 492 |
+
job = sampler.run(qc_compiled_list, shots=shots)
|
| 493 |
+
print("Job submitted; waiting for result...")
|
| 494 |
+
|
| 495 |
+
def get_job_result(j):
|
| 496 |
+
result = j.result() # PrimitiveResult (a container of PubResults)
|
| 497 |
+
print(result)
|
| 498 |
+
|
| 499 |
+
output=[]
|
| 500 |
+
|
| 501 |
+
for T_total,pub in zip(T_list,result):
|
| 502 |
+
|
| 503 |
+
# We'll inspect the first PUB result
|
| 504 |
+
print("PUB metadata:", pub.metadata if hasattr(pub, "metadata") else "<no metadata>")
|
| 505 |
+
|
| 506 |
+
# 1) Try to obtain counts via the recommended API
|
| 507 |
+
try:
|
| 508 |
+
counts = pub.data.meas.get_counts()
|
| 509 |
+
print("\nCounts (pub.data.meas.get_counts()) sample:")
|
| 510 |
+
pprint.pprint({k: counts[k] for k in list(counts)[:10]})
|
| 511 |
+
except Exception as e:
|
| 512 |
+
print("Couldn't call pub.data.meas.get_counts():", e)
|
| 513 |
+
counts = None
|
| 514 |
+
|
| 515 |
+
# 2) Try join_data() (to combine multiple regs) and get_counts() on it
|
| 516 |
+
try:
|
| 517 |
+
joined = pub.join_data() # join_data concatenates registers along bits axis
|
| 518 |
+
joined_counts = joined.get_counts()
|
| 519 |
+
print("\nJoined counts (pub.join_data().get_counts()) sample:")
|
| 520 |
+
pprint.pprint({k: joined_counts[k] for k in list(joined_counts)[:10]})
|
| 521 |
+
except Exception as e:
|
| 522 |
+
print("join_data()/joined.get_counts() not available or failed:", e)
|
| 523 |
+
joined_counts = None
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
pts, counts = load_samples(joined_counts,T_total)
|
| 527 |
+
output+=[estimate_density(pts, counts, bandwidth=0.05, grid_size=output_resolution)]
|
| 528 |
+
|
| 529 |
+
return output
|
| 530 |
+
|
| 531 |
+
return job,get_job_result
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
from qiskit_aer import AerSimulator
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def run_sampling_sim(
|
| 538 |
+
n,
|
| 539 |
+
ux,
|
| 540 |
+
uy,
|
| 541 |
+
uz,
|
| 542 |
+
init_state_prep_circ,
|
| 543 |
+
T_list,
|
| 544 |
+
vel_resolution=32,
|
| 545 |
+
):
|
| 546 |
+
"""
|
| 547 |
+
Run QLBM simulation on local Aer statevector simulator.
|
| 548 |
+
|
| 549 |
+
Parameters
|
| 550 |
+
----------
|
| 551 |
+
n : int
|
| 552 |
+
Number of qubits per spatial dimension
|
| 553 |
+
ux, uy, uz : callable or str
|
| 554 |
+
Velocity field components
|
| 555 |
+
init_state_prep_circ : QuantumCircuit
|
| 556 |
+
Pre-built initial state preparation circuit from get_named_init_state_circuit()
|
| 557 |
+
T_list : list[int]
|
| 558 |
+
List of timesteps to simulate
|
| 559 |
+
vel_resolution : int
|
| 560 |
+
Resolution for velocity field discretization
|
| 561 |
+
|
| 562 |
+
Returns
|
| 563 |
+
-------
|
| 564 |
+
output : list[ndarray]
|
| 565 |
+
List of 3D density arrays, one per timestep
|
| 566 |
+
fig : go.Figure
|
| 567 |
+
Plotly figure with slider animation through all timesteps
|
| 568 |
+
"""
|
| 569 |
+
|
| 570 |
+
if type(ux)==str:
|
| 571 |
+
ux,uy,uz=str_to_lambda(ux,uy,uz)
|
| 572 |
+
|
| 573 |
+
qc_list=get_circuit(n,ux,uy,uz,init_state_prep_circ,T_list,vel_resolution,measure=False)
|
| 574 |
+
backend = AerSimulator(method = 'statevector')
|
| 575 |
+
output=[]
|
| 576 |
+
|
| 577 |
+
for qc in qc_list:
|
| 578 |
+
qc_transpiled=qc
|
| 579 |
+
qc_transpiled.save_statevector(conditional=True)
|
| 580 |
+
|
| 581 |
+
# Try multiple shots to find a successful (zero-branch) outcome
|
| 582 |
+
max_attempts = 10
|
| 583 |
+
success = False
|
| 584 |
+
|
| 585 |
+
for attempt in range(max_attempts):
|
| 586 |
+
job = backend.run(qc_transpiled, memory=True, shots=1)
|
| 587 |
+
result = job.result()
|
| 588 |
+
data_all = result.data()
|
| 589 |
+
|
| 590 |
+
statevector_keys = list(dict(data_all['statevector']).keys())
|
| 591 |
+
|
| 592 |
+
# Look for the zero branch (0x0)
|
| 593 |
+
zero_key = None
|
| 594 |
+
for key in statevector_keys:
|
| 595 |
+
if '0x' in key:
|
| 596 |
+
if int(key[2:], 16) == 0:
|
| 597 |
+
zero_key = key
|
| 598 |
+
break
|
| 599 |
+
elif key == '0' or key == '00' or key.replace('0', '') == '':
|
| 600 |
+
zero_key = key
|
| 601 |
+
break
|
| 602 |
+
|
| 603 |
+
if zero_key is not None:
|
| 604 |
+
success = True
|
| 605 |
+
break
|
| 606 |
+
|
| 607 |
+
if attempt < max_attempts - 1:
|
| 608 |
+
print(f"Attempt {attempt + 1} failed (got branch {statevector_keys[0]}), retrying...")
|
| 609 |
+
|
| 610 |
+
if not success:
|
| 611 |
+
# If all attempts failed, use the first available branch with a warning
|
| 612 |
+
print(f"Warning: Could not get zero branch after {max_attempts} attempts. Using first available branch.")
|
| 613 |
+
zero_key = statevector_keys[0]
|
| 614 |
+
|
| 615 |
+
zero_branch_state = data_all['statevector'][zero_key]
|
| 616 |
+
sv_mean=np.mean(np.array(zero_branch_state)[:(2**n)**dim])
|
| 617 |
+
sv_phase=sv_mean/np.abs(sv_mean)
|
| 618 |
+
|
| 619 |
+
final_answer = np.real(np.array(zero_branch_state)[:(2**n)**dim]/sv_phase)
|
| 620 |
+
|
| 621 |
+
C = np.reshape(np.array(final_answer),tuple(2**n for _ in range(dim)))
|
| 622 |
+
output+=[C]
|
| 623 |
+
|
| 624 |
+
# Create meshgrid for coordinates (used for plotting)
|
| 625 |
+
x_coords = np.linspace(0, 1, 2**n)
|
| 626 |
+
X = np.meshgrid(x_coords, x_coords, x_coords, indexing='ij')
|
| 627 |
+
|
| 628 |
+
# Create figure with slider for all timesteps
|
| 629 |
+
fig = _create_slider_figure(output, T_list, X)
|
| 630 |
+
return output, fig
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
def _create_slider_figure(output_list, T_list, X):
|
| 634 |
+
"""
|
| 635 |
+
Create a Plotly figure with slider to animate through timesteps.
|
| 636 |
+
Uses visibility toggling instead of frames for better compatibility.
|
| 637 |
+
|
| 638 |
+
Parameters
|
| 639 |
+
----------
|
| 640 |
+
output_list : list[ndarray]
|
| 641 |
+
List of 3D density arrays from simulation
|
| 642 |
+
T_list : list[int]
|
| 643 |
+
List of timestep values
|
| 644 |
+
X : tuple of ndarrays
|
| 645 |
+
Meshgrid coordinates
|
| 646 |
+
|
| 647 |
+
Returns
|
| 648 |
+
-------
|
| 649 |
+
fig : go.Figure
|
| 650 |
+
Plotly figure with slider animation
|
| 651 |
+
"""
|
| 652 |
+
# Compute global min/max for consistent color scaling
|
| 653 |
+
global_min = min(np.min(C) for C in output_list)
|
| 654 |
+
global_max = max(np.max(C) for C in output_list)
|
| 655 |
+
|
| 656 |
+
fig = go.Figure()
|
| 657 |
+
|
| 658 |
+
# Add a trace for each timestep
|
| 659 |
+
for i, (C, T) in enumerate(zip(output_list, T_list)):
|
| 660 |
+
visible = (i == 0) # Only the first trace is visible initially
|
| 661 |
+
fig.add_trace(go.Isosurface(
|
| 662 |
+
x=X[2].flatten(),
|
| 663 |
+
y=X[1].flatten(),
|
| 664 |
+
z=X[0].flatten(),
|
| 665 |
+
value=C.flatten(),
|
| 666 |
+
isomin=global_min,
|
| 667 |
+
isomax=global_max,
|
| 668 |
+
opacity=0.4,
|
| 669 |
+
surface_count=10,
|
| 670 |
+
caps=dict(x_show=False, y_show=False, z_show=False),
|
| 671 |
+
colorscale='Viridis',
|
| 672 |
+
colorbar=dict(title="Density"),
|
| 673 |
+
visible=visible,
|
| 674 |
+
name=f"T={T}"
|
| 675 |
+
))
|
| 676 |
+
|
| 677 |
+
# Create slider steps
|
| 678 |
+
steps = []
|
| 679 |
+
for i, T in enumerate(T_list):
|
| 680 |
+
# Create visibility array: only the i-th trace is True
|
| 681 |
+
step = dict(
|
| 682 |
+
method="update",
|
| 683 |
+
args=[{"visible": [False] * len(output_list)},
|
| 684 |
+
{"title": f"QLBM Simulation - Timestep T={T}"}],
|
| 685 |
+
label=str(T)
|
| 686 |
+
)
|
| 687 |
+
step["args"][0]["visible"][i] = True # Toggle i-th trace to True
|
| 688 |
+
steps.append(step)
|
| 689 |
+
|
| 690 |
+
sliders = [dict(
|
| 691 |
+
active=0,
|
| 692 |
+
currentvalue={"prefix": "Timestep: "},
|
| 693 |
+
pad={"t": 50},
|
| 694 |
+
steps=steps
|
| 695 |
+
)]
|
| 696 |
+
|
| 697 |
+
fig.update_layout(
|
| 698 |
+
title=f"QLBM Simulation - Timestep T={T_list[0]}",
|
| 699 |
+
scene=dict(
|
| 700 |
+
xaxis_title="X",
|
| 701 |
+
yaxis_title="Y",
|
| 702 |
+
zaxis_title="Z",
|
| 703 |
+
aspectmode='cube',
|
| 704 |
+
),
|
| 705 |
+
sliders=sliders
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
return fig
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
def show_initial_distribution(
|
| 712 |
+
n: int,
|
| 713 |
+
init_state_name: str,
|
| 714 |
+
# Sinusoidal parameters (frequency multipliers)
|
| 715 |
+
sine_k_x: float = 1.0,
|
| 716 |
+
sine_k_y: float = 1.0,
|
| 717 |
+
sine_k_z: float = 1.0,
|
| 718 |
+
# Gaussian parameters
|
| 719 |
+
gauss_cx: float = None,
|
| 720 |
+
gauss_cy: float = None,
|
| 721 |
+
gauss_cz: float = None,
|
| 722 |
+
gauss_sigma: float = None,
|
| 723 |
+
# Display options
|
| 724 |
+
plot: bool = True,
|
| 725 |
+
return_data: bool = False,
|
| 726 |
+
):
|
| 727 |
+
"""
|
| 728 |
+
Visualize the initial distribution by running the state preparation circuit
|
| 729 |
+
from get_named_init_state_circuit and extracting the resulting statevector.
|
| 730 |
+
|
| 731 |
+
Parameters
|
| 732 |
+
----------
|
| 733 |
+
n : int
|
| 734 |
+
Number of qubits per spatial dimension (grid size = 2^n per axis)
|
| 735 |
+
init_state_name : str
|
| 736 |
+
One of "dirac_delta", "sin", "gaussian"
|
| 737 |
+
sine_k_x, sine_k_y, sine_k_z : float
|
| 738 |
+
Frequency multipliers for sinusoidal distribution (default=1.0)
|
| 739 |
+
gauss_cx, gauss_cy, gauss_cz : float
|
| 740 |
+
Center coordinates in [0,1] for Gaussian (default=0.5)
|
| 741 |
+
gauss_sigma : float
|
| 742 |
+
Spread of Gaussian in normalized units (default=0.2)
|
| 743 |
+
plot : bool
|
| 744 |
+
Whether to display the 3D isosurface plot (default=True)
|
| 745 |
+
return_data : bool
|
| 746 |
+
Whether to return the distribution data (default=False)
|
| 747 |
+
|
| 748 |
+
Returns
|
| 749 |
+
-------
|
| 750 |
+
If return_data is True:
|
| 751 |
+
C : ndarray
|
| 752 |
+
3D array of shape (2^n, 2^n, 2^n) containing the initial distribution
|
| 753 |
+
X : tuple of ndarrays
|
| 754 |
+
Meshgrid coordinates (X[0], X[1], X[2]) for x, y, z axes
|
| 755 |
+
If return_data is False:
|
| 756 |
+
None
|
| 757 |
+
"""
|
| 758 |
+
N = 2**n
|
| 759 |
+
|
| 760 |
+
# Get the state preparation circuit from get_named_init_state_circuit
|
| 761 |
+
init_state_prep_circ = get_named_init_state_circuit(
|
| 762 |
+
n,
|
| 763 |
+
init_state_name,
|
| 764 |
+
sine_k_x=sine_k_x,
|
| 765 |
+
sine_k_y=sine_k_y,
|
| 766 |
+
sine_k_z=sine_k_z,
|
| 767 |
+
gauss_cx=gauss_cx,
|
| 768 |
+
gauss_cy=gauss_cy,
|
| 769 |
+
gauss_cz=gauss_cz,
|
| 770 |
+
gauss_sigma=gauss_sigma,
|
| 771 |
+
)
|
| 772 |
+
|
| 773 |
+
# Run the circuit on statevector simulator to extract the initial state
|
| 774 |
+
backend = AerSimulator(method='statevector')
|
| 775 |
+
|
| 776 |
+
# Create a copy of the circuit and save statevector
|
| 777 |
+
qc = init_state_prep_circ.copy()
|
| 778 |
+
qc.save_statevector()
|
| 779 |
+
|
| 780 |
+
job = backend.run(qc, shots=1)
|
| 781 |
+
result = job.result()
|
| 782 |
+
statevector = np.array(result.get_statevector())
|
| 783 |
+
|
| 784 |
+
# The statevector represents the initial distribution (amplitudes)
|
| 785 |
+
# Take the real part of the amplitudes (they should be real for these distributions)
|
| 786 |
+
init_state = np.real(statevector)
|
| 787 |
+
|
| 788 |
+
# Reshape to 3D grid
|
| 789 |
+
C = np.reshape(init_state, (N, N, N))
|
| 790 |
+
|
| 791 |
+
# Create meshgrid for coordinates
|
| 792 |
+
x_coords = np.linspace(0, 1, N)
|
| 793 |
+
X = np.meshgrid(x_coords, x_coords, x_coords, indexing='ij')
|
| 794 |
+
|
| 795 |
+
if plot:
|
| 796 |
+
print(f"Initial distribution: {init_state_name}")
|
| 797 |
+
print(f"Grid size: {N} x {N} x {N}")
|
| 798 |
+
if init_state_name == "sin":
|
| 799 |
+
print(f"Sine frequencies: kx={sine_k_x}, ky={sine_k_y}, kz={sine_k_z}")
|
| 800 |
+
elif init_state_name == "gaussian":
|
| 801 |
+
cx = float(gauss_cx) if gauss_cx is not None else 0.5
|
| 802 |
+
cy = float(gauss_cy) if gauss_cy is not None else 0.5
|
| 803 |
+
cz = float(gauss_cz) if gauss_cz is not None else 0.5
|
| 804 |
+
sigma = float(gauss_sigma) if gauss_sigma is not None else 0.2
|
| 805 |
+
print(f"Gaussian center: ({cx}, {cy}, {cz}), sigma={sigma}")
|
| 806 |
+
|
| 807 |
+
print("Distribution stats:")
|
| 808 |
+
print(f" Min: {np.min(C):.6f}, Max: {np.max(C):.6f}")
|
| 809 |
+
print(f" Mean: {np.mean(C):.6f}, Std: {np.std(C):.6f}")
|
| 810 |
+
|
| 811 |
+
Cmax, Cmin = np.max(C.flatten()), np.min(C.flatten())
|
| 812 |
+
|
| 813 |
+
fig = go.Figure(data=go.Isosurface(
|
| 814 |
+
x=X[2].flatten(),
|
| 815 |
+
y=X[1].flatten(),
|
| 816 |
+
z=X[0].flatten(),
|
| 817 |
+
value=C.flatten(),
|
| 818 |
+
isomin=Cmin,
|
| 819 |
+
isomax=Cmax,
|
| 820 |
+
opacity=0.4,
|
| 821 |
+
surface_count=10,
|
| 822 |
+
caps=dict(x_show=False, y_show=False, z_show=False),
|
| 823 |
+
colorscale='Viridis',
|
| 824 |
+
))
|
| 825 |
+
|
| 826 |
+
fig.update_layout(
|
| 827 |
+
title=f"Initial Distribution: {init_state_name}",
|
| 828 |
+
scene=dict(
|
| 829 |
+
xaxis_title="X",
|
| 830 |
+
yaxis_title="Y",
|
| 831 |
+
zaxis_title="Z",
|
| 832 |
+
),
|
| 833 |
+
)
|
| 834 |
+
|
| 835 |
+
fig.show()
|
| 836 |
+
|
| 837 |
+
if return_data:
|
| 838 |
+
return C, X
|
| 839 |
+
|
| 840 |
+
return None
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
if __name__=="__main__":
|
| 844 |
+
|
| 845 |
+
n=3
|
| 846 |
+
# plot = show_initial_distribution(
|
| 847 |
+
# n=n,
|
| 848 |
+
# init_state_name="sin",
|
| 849 |
+
# sine_k_x=1.0,
|
| 850 |
+
# sine_k_y=1.0,
|
| 851 |
+
# sine_k_z=1.0,
|
| 852 |
+
# plot=True,
|
| 853 |
+
# return_data=False
|
| 854 |
+
# )
|
| 855 |
+
|
| 856 |
+
# Step 1: Create the initial state circuit ONCE with all parameters
|
| 857 |
+
init_state_prep_circ = get_named_init_state_circuit(
|
| 858 |
+
n=n,
|
| 859 |
+
init_state_name="sin", # or "gaussian", "dirac_delta"
|
| 860 |
+
sine_k_x=1.0,
|
| 861 |
+
sine_k_y=1.0,
|
| 862 |
+
sine_k_z=1.0
|
| 863 |
+
# gauss_cx=0.5, # Uncomment for Gaussian
|
| 864 |
+
# gauss_cy=0.5,
|
| 865 |
+
# gauss_cz=0.5,
|
| 866 |
+
# gauss_sigma=0.2,
|
| 867 |
+
)
|
| 868 |
+
|
| 869 |
+
# Alternative: Run on local simulator
|
| 870 |
+
output, fig = run_sampling_sim(
|
| 871 |
+
n=n,
|
| 872 |
+
ux="sin(2*pi*y)*sin(2*pi*z)",
|
| 873 |
+
uy="sin(2*pi*x)*sin(2*pi*z)",
|
| 874 |
+
uz="sin(2*pi*x)*sin(2*pi*y)",
|
| 875 |
+
init_state_prep_circ=init_state_prep_circ,
|
| 876 |
+
T_list=[1,3,5],
|
| 877 |
+
vel_resolution=2
|
| 878 |
+
)
|
| 879 |
+
fig.show()
|
| 880 |
+
|
| 881 |
+
# Step 2: (Optional) Preview the initial distribution
|
| 882 |
+
# show_initial_distribution(n=n, init_state_name="sin", sine_k_x=1, sine_k_y=1, sine_k_z=1)
|
| 883 |
+
|
| 884 |
+
# Step 3: Run simulation - pass the pre-built circuit
|
| 885 |
+
# job, get_job_result = run_sampling_hw_ibm(
|
| 886 |
+
# n=n,
|
| 887 |
+
# ux=lambda x,y,z: 1,
|
| 888 |
+
# uy=lambda x,y,z: 1,
|
| 889 |
+
# uz=lambda x,y,z: 1,
|
| 890 |
+
# init_state_prep_circ=init_state_prep_circ, # Pass the circuit directly
|
| 891 |
+
# T_list=[1],
|
| 892 |
+
# shots=2**19,
|
| 893 |
+
# vel_resolution=2,
|
| 894 |
+
# )
|
| 895 |
+
|
| 896 |
+
# output = get_job_result(job)
|
| 897 |
+
# for xx, yy, zz, dens in output:
|
| 898 |
+
# plot_density_isosurface(xx, yy, zz, dens)
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
|
qlbm_embedded.py
CHANGED
|
@@ -22,7 +22,23 @@ from pyvista.trame.ui import plotter_ui
|
|
| 22 |
# Set offscreen before pyvista usage
|
| 23 |
pv.OFF_SCREEN = True
|
| 24 |
|
| 25 |
-
# --- Backend Detection ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
def _env_flag(name: str) -> bool:
|
| 27 |
return os.environ.get(name, "").strip().lower() in ("1", "true", "yes")
|
| 28 |
|
|
@@ -182,6 +198,11 @@ def init_state():
|
|
| 182 |
|
| 183 |
# Pick point text
|
| 184 |
"qlbm_pick_text": "",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
})
|
| 186 |
_initialized = True
|
| 187 |
|
|
@@ -810,6 +831,142 @@ def export_simulation_mp4():
|
|
| 810 |
pass
|
| 811 |
|
| 812 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 813 |
# --- Main Simulation ---
|
| 814 |
def run_simulation():
|
| 815 |
"""Run the QLBM simulation."""
|
|
@@ -826,19 +983,33 @@ def run_simulation():
|
|
| 826 |
_state.qlbm_is_running = True
|
| 827 |
_state.qlbm_run_error = ""
|
| 828 |
_state.qlbm_simulation_has_run = False
|
|
|
|
| 829 |
_state.qlbm_show_progress = True
|
| 830 |
_state.qlbm_simulation_progress = 0
|
| 831 |
_state.qlbm_status_message = "Running simulation..."
|
| 832 |
_state.qlbm_status_type = "info"
|
| 833 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 834 |
# Log initial configuration
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 835 |
config_lines = [
|
| 836 |
"Job Initiated",
|
| 837 |
f" Grid Size: {_state.qlbm_grid_size} × {_state.qlbm_grid_size} × {_state.qlbm_grid_size}",
|
| 838 |
f" Time Steps: {_state.qlbm_time_steps}",
|
| 839 |
f" Distribution: {_state.qlbm_dist_type}",
|
| 840 |
f" Boundary: {_state.qlbm_boundary_condition}",
|
| 841 |
-
f" Backend: {
|
| 842 |
f" Velocity: vx={_state.qlbm_vx_expr}, vy={_state.qlbm_vy_expr}, vz={_state.qlbm_vz_expr}",
|
| 843 |
]
|
| 844 |
for line in config_lines:
|
|
@@ -853,84 +1024,116 @@ def run_simulation():
|
|
| 853 |
last_logged_percent = percent
|
| 854 |
|
| 855 |
try:
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
_plotter.clear()
|
| 871 |
-
_, frames, times, grid_obj = simulate_qlbm_3D_and_animate(
|
| 872 |
-
num_reg_qubits=num_reg_qubits,
|
| 873 |
-
T=T,
|
| 874 |
-
distribution_type=distribution_type,
|
| 875 |
-
vx_input=vx_func,
|
| 876 |
-
vy_input=vy_func,
|
| 877 |
-
vz_input=vz_func,
|
| 878 |
-
boundary_condition=boundary_condition,
|
| 879 |
-
plotter=_plotter,
|
| 880 |
-
add_slider=False,
|
| 881 |
-
progress_callback=_progress_callback
|
| 882 |
-
)
|
| 883 |
-
else:
|
| 884 |
-
log_to_console("Running CPU Demo Simulation...")
|
| 885 |
-
frames, times, grid_obj = _run_cpu_demo_simulation(
|
| 886 |
-
grid_size=grid_size,
|
| 887 |
-
T=T,
|
| 888 |
-
distribution_type=distribution_type or "Sinusoidal",
|
| 889 |
-
vx_func=vx_func,
|
| 890 |
-
vy_func=vy_func,
|
| 891 |
-
vz_func=vz_func,
|
| 892 |
-
progress_callback=_progress_callback
|
| 893 |
-
)
|
| 894 |
-
|
| 895 |
-
_progress_callback(100)
|
| 896 |
-
|
| 897 |
-
# Update plotter with results
|
| 898 |
-
if grid_obj:
|
| 899 |
-
_plotter.clear()
|
| 900 |
-
isosurfaces = grid_obj.contour(isosurfaces=7, scalars="scalars")
|
| 901 |
-
_plotter.add_mesh(isosurfaces, cmap="Blues", opacity=0.3, show_scalar_bar=True)
|
| 902 |
-
_plotter.add_axes()
|
| 903 |
-
_plotter.show_grid()
|
| 904 |
-
|
| 905 |
-
# Store Results
|
| 906 |
-
if frames and len(frames) > 0:
|
| 907 |
-
simulation_data_frames = frames
|
| 908 |
-
simulation_times = times
|
| 909 |
-
current_grid_object = grid_obj
|
| 910 |
|
| 911 |
-
_state.qlbm_max_time_step = len(
|
| 912 |
_state.qlbm_time_val = 0
|
| 913 |
-
_state.qlbm_time_slider_labels = [f"{t
|
| 914 |
_state.qlbm_simulation_has_run = True
|
|
|
|
| 915 |
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
if hasattr(_ctrl, "qlbm_view_update"):
|
| 919 |
-
_ctrl.qlbm_view_update()
|
| 920 |
-
log_to_console("Simulation completed successfully.")
|
| 921 |
_state.qlbm_status_message = "Simulation completed successfully."
|
| 922 |
_state.qlbm_status_type = "success"
|
| 923 |
-
|
|
|
|
| 924 |
else:
|
| 925 |
-
_state.
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 929 |
|
| 930 |
except Exception as e:
|
| 931 |
_state.qlbm_run_error = f"Simulation failed: {str(e)}"
|
| 932 |
log_to_console(f"Simulation Error: {e}")
|
| 933 |
print(f"Simulation Error: {e}")
|
|
|
|
|
|
|
| 934 |
_state.qlbm_status_message = "Simulation failed"
|
| 935 |
_state.qlbm_status_type = "error"
|
| 936 |
finally:
|
|
@@ -955,6 +1158,7 @@ def reset_simulation():
|
|
| 955 |
_state.qlbm_is_running = False
|
| 956 |
_state.qlbm_run_error = ""
|
| 957 |
_state.qlbm_simulation_has_run = False
|
|
|
|
| 958 |
_state.qlbm_dist_type = None
|
| 959 |
_state.qlbm_show_edges = False
|
| 960 |
_state.qlbm_problems_selection = None
|
|
@@ -1263,7 +1467,7 @@ def _build_control_panels(plotter):
|
|
| 1263 |
with vuetify3.VCard(classes="mb-2"):
|
| 1264 |
vuetify3.VCardTitle("Time", classes="text-subtitle-2 font-weight-bold text-primary")
|
| 1265 |
with vuetify3.VCardText():
|
| 1266 |
-
vuetify3.VSlider(label="Total Time", v_model=("qlbm_time_steps", 10), min=0, max=
|
| 1267 |
thumb_label="always", show_ticks="always", color="primary", density="compact", hide_details=True)
|
| 1268 |
vuetify3.VAlert(v_if="qlbm_time_steps > 100", type="warning", variant="tonal", density="compact",
|
| 1269 |
children=["Warning: High time steps may increase runtime."], classes="mt-2")
|
|
@@ -1357,19 +1561,19 @@ def _build_visualization_panel(plotter):
|
|
| 1357 |
# Main Plot Card
|
| 1358 |
with vuetify3.VCard(classes="mb-1 flex-grow-1 d-flex flex-column", elevation=2, style="min-height: 0;"):
|
| 1359 |
|
| 1360 |
-
# Geometry Preview (Plotly)
|
| 1361 |
with vuetify3.VContainer(v_if="!qlbm_simulation_has_run && !qlbm_dist_type && qlbm_geometry_selection",
|
| 1362 |
fluid=True, classes="pa-0 flex-grow-1", style="width: 100%; height: 100%;"):
|
| 1363 |
geom_fig = plotly_widgets.Figure(figure=go.Figure(), style="width: 100%; height: 100%;", responsive=True)
|
| 1364 |
_ctrl.qlbm_geometry_plot_update = geom_fig.update
|
| 1365 |
|
| 1366 |
-
# Distribution Preview (Plotly)
|
| 1367 |
with vuetify3.VContainer(v_if="!qlbm_simulation_has_run && qlbm_dist_type",
|
| 1368 |
fluid=True, classes="pa-0 flex-grow-1", style="width: 100%; height: 100%;"):
|
| 1369 |
preview_fig = plotly_widgets.Figure(figure=go.Figure(), style="width:100%; height:100%;", responsive=True)
|
| 1370 |
_ctrl.qlbm_preview_update = preview_fig.update
|
| 1371 |
|
| 1372 |
-
# Download controls
|
| 1373 |
with vuetify3.VContainer(v_if="qlbm_simulation_has_run", classes="px-4 pt-3 pb-1 d-flex justify-end",
|
| 1374 |
style="width: 100%; flex: 0 0 auto;"):
|
| 1375 |
with vuetify3.VMenu(location="bottom end"):
|
|
@@ -1382,25 +1586,48 @@ def _build_visualization_panel(plotter):
|
|
| 1382 |
prepend_icon="mdi-download"
|
| 1383 |
)
|
| 1384 |
with vuetify3.VList(density="compact"):
|
|
|
|
| 1385 |
vuetify3.VListItem(
|
|
|
|
| 1386 |
title="Export as VTK",
|
| 1387 |
prepend_icon="mdi-content-save",
|
| 1388 |
click=export_simulation_vtk
|
| 1389 |
)
|
| 1390 |
vuetify3.VListItem(
|
|
|
|
| 1391 |
title="Export as MP4",
|
| 1392 |
prepend_icon="mdi-movie",
|
| 1393 |
click=export_simulation_mp4
|
| 1394 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1395 |
|
| 1396 |
-
# Simulation Result (
|
| 1397 |
-
with vuetify3.VContainer(v_if="qlbm_simulation_has_run
|
|
|
|
| 1398 |
style="width: 100%; height: 100%;"):
|
| 1399 |
view = plotter_ui(plotter)
|
| 1400 |
_ctrl.qlbm_view_update = view.update
|
| 1401 |
|
| 1402 |
-
# Time Slider
|
| 1403 |
-
with vuetify3.VContainer(v_if="qlbm_simulation_has_run
|
|
|
|
| 1404 |
with vuetify3.VSlider(
|
| 1405 |
v_model=("qlbm_time_val", 0),
|
| 1406 |
min=0,
|
|
|
|
| 22 |
# Set offscreen before pyvista usage
|
| 23 |
pv.OFF_SCREEN = True
|
| 24 |
|
| 25 |
+
# --- Qiskit Backend Detection ---
|
| 26 |
+
_QISKIT_BACKEND_AVAILABLE = False
|
| 27 |
+
_QISKIT_IMPORT_ERROR = None
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
from qlbm.qlbm_sample_app import (
|
| 31 |
+
run_sampling_sim,
|
| 32 |
+
get_named_init_state_circuit,
|
| 33 |
+
str_to_lambda,
|
| 34 |
+
_create_slider_figure,
|
| 35 |
+
)
|
| 36 |
+
_QISKIT_BACKEND_AVAILABLE = True
|
| 37 |
+
except ImportError as e:
|
| 38 |
+
_QISKIT_IMPORT_ERROR = str(e)
|
| 39 |
+
print(f"Qiskit backend not available: {e}")
|
| 40 |
+
|
| 41 |
+
# --- CUDA-Q Backend Detection ---
|
| 42 |
def _env_flag(name: str) -> bool:
|
| 43 |
return os.environ.get(name, "").strip().lower() in ("1", "true", "yes")
|
| 44 |
|
|
|
|
| 198 |
|
| 199 |
# Pick point text
|
| 200 |
"qlbm_pick_text": "",
|
| 201 |
+
|
| 202 |
+
# Qiskit backend state
|
| 203 |
+
"qlbm_qiskit_mode": False, # True when using Qiskit backend (shows Plotly slider)
|
| 204 |
+
"qlbm_qiskit_backend_available": _QISKIT_BACKEND_AVAILABLE,
|
| 205 |
+
"qlbm_qiskit_fig": None, # Stores the Plotly figure for Qiskit results
|
| 206 |
})
|
| 207 |
_initialized = True
|
| 208 |
|
|
|
|
| 831 |
pass
|
| 832 |
|
| 833 |
|
| 834 |
+
# --- Qiskit Simulation Functions ---
|
| 835 |
+
def _map_state_to_qiskit_params():
|
| 836 |
+
"""
|
| 837 |
+
Map qlbm_embedded state variables to qlbm_sample_app parameters.
|
| 838 |
+
|
| 839 |
+
Returns
|
| 840 |
+
-------
|
| 841 |
+
dict or None
|
| 842 |
+
Dictionary of parameters for run_sampling_sim, or None if state is unavailable
|
| 843 |
+
"""
|
| 844 |
+
if _state is None:
|
| 845 |
+
return None
|
| 846 |
+
|
| 847 |
+
# Map distribution type
|
| 848 |
+
dist_type = _state.qlbm_dist_type
|
| 849 |
+
if dist_type == "Sinusoidal":
|
| 850 |
+
init_state_name = "sin"
|
| 851 |
+
elif dist_type == "Gaussian":
|
| 852 |
+
init_state_name = "gaussian"
|
| 853 |
+
else:
|
| 854 |
+
init_state_name = "sin" # Default
|
| 855 |
+
|
| 856 |
+
# Calculate n from grid_size (grid_size = 2^n)
|
| 857 |
+
grid_size = int(_state.qlbm_grid_size)
|
| 858 |
+
n = int(math.log2(grid_size)) if grid_size > 0 else 3
|
| 859 |
+
|
| 860 |
+
# Map Gaussian parameters from grid units to normalized [0,1]
|
| 861 |
+
# In the UI, gauss_cx/cy/cz are in grid units (0 to nx)
|
| 862 |
+
# qlbm_sample_app expects normalized [0,1]
|
| 863 |
+
nx = float(_state.qlbm_nx) if _state.qlbm_nx else float(grid_size)
|
| 864 |
+
gauss_cx = float(_state.qlbm_gauss_cx) / nx if nx > 0 else 0.5
|
| 865 |
+
gauss_cy = float(_state.qlbm_gauss_cy) / nx if nx > 0 else 0.5
|
| 866 |
+
gauss_cz = float(_state.qlbm_gauss_cz) / nx if nx > 0 else 0.5
|
| 867 |
+
gauss_sigma = float(_state.qlbm_gauss_sigma) / nx if nx > 0 else 0.2
|
| 868 |
+
|
| 869 |
+
# Create T_list from time_steps: [1, 2, 3, ..., T]
|
| 870 |
+
time_steps = int(_state.qlbm_time_steps)
|
| 871 |
+
if time_steps <= 0:
|
| 872 |
+
T_list = [1]
|
| 873 |
+
else:
|
| 874 |
+
T_list = list(range(1, time_steps + 1))
|
| 875 |
+
|
| 876 |
+
return {
|
| 877 |
+
"n": n,
|
| 878 |
+
"init_state_name": init_state_name,
|
| 879 |
+
"sine_k_x": float(_state.qlbm_sine_k_x),
|
| 880 |
+
"sine_k_y": float(_state.qlbm_sine_k_y),
|
| 881 |
+
"sine_k_z": float(_state.qlbm_sine_k_z),
|
| 882 |
+
"gauss_cx": gauss_cx,
|
| 883 |
+
"gauss_cy": gauss_cy,
|
| 884 |
+
"gauss_cz": gauss_cz,
|
| 885 |
+
"gauss_sigma": gauss_sigma,
|
| 886 |
+
"vx_expr": str(_state.qlbm_vx_expr),
|
| 887 |
+
"vy_expr": str(_state.qlbm_vy_expr),
|
| 888 |
+
"vz_expr": str(_state.qlbm_vz_expr),
|
| 889 |
+
"T_list": T_list,
|
| 890 |
+
"grid_size": grid_size,
|
| 891 |
+
}
|
| 892 |
+
|
| 893 |
+
|
| 894 |
+
def _run_qiskit_simulation(progress_callback=None):
|
| 895 |
+
"""
|
| 896 |
+
Run QLBM simulation using Qiskit Aer statevector simulator.
|
| 897 |
+
|
| 898 |
+
Parameters
|
| 899 |
+
----------
|
| 900 |
+
progress_callback : callable, optional
|
| 901 |
+
Function to report progress (0-100)
|
| 902 |
+
|
| 903 |
+
Returns
|
| 904 |
+
-------
|
| 905 |
+
output : list[ndarray]
|
| 906 |
+
List of 3D density arrays, one per timestep
|
| 907 |
+
fig : go.Figure
|
| 908 |
+
Plotly figure with slider animation
|
| 909 |
+
T_list : list[int]
|
| 910 |
+
List of timesteps
|
| 911 |
+
"""
|
| 912 |
+
if not _QISKIT_BACKEND_AVAILABLE:
|
| 913 |
+
raise RuntimeError(f"Qiskit backend not available: {_QISKIT_IMPORT_ERROR}")
|
| 914 |
+
|
| 915 |
+
params = _map_state_to_qiskit_params()
|
| 916 |
+
if params is None:
|
| 917 |
+
raise RuntimeError("Failed to map state parameters")
|
| 918 |
+
|
| 919 |
+
log_to_console(f"Qiskit Simulation Parameters:")
|
| 920 |
+
log_to_console(f" n={params['n']} (grid {params['grid_size']}³)")
|
| 921 |
+
log_to_console(f" T_list={params['T_list']}")
|
| 922 |
+
log_to_console(f" Distribution: {params['init_state_name']}")
|
| 923 |
+
log_to_console(f" Velocity: vx={params['vx_expr']}, vy={params['vy_expr']}, vz={params['vz_expr']}")
|
| 924 |
+
|
| 925 |
+
if progress_callback:
|
| 926 |
+
progress_callback(5)
|
| 927 |
+
|
| 928 |
+
# Create initial state circuit using qlbm_sample_app function
|
| 929 |
+
log_to_console("Creating initial state circuit...")
|
| 930 |
+
init_state_prep_circ = get_named_init_state_circuit(
|
| 931 |
+
n=params["n"],
|
| 932 |
+
init_state_name=params["init_state_name"],
|
| 933 |
+
sine_k_x=params["sine_k_x"],
|
| 934 |
+
sine_k_y=params["sine_k_y"],
|
| 935 |
+
sine_k_z=params["sine_k_z"],
|
| 936 |
+
gauss_cx=params["gauss_cx"],
|
| 937 |
+
gauss_cy=params["gauss_cy"],
|
| 938 |
+
gauss_cz=params["gauss_cz"],
|
| 939 |
+
gauss_sigma=params["gauss_sigma"],
|
| 940 |
+
)
|
| 941 |
+
|
| 942 |
+
if progress_callback:
|
| 943 |
+
progress_callback(15)
|
| 944 |
+
|
| 945 |
+
log_to_console("Running Qiskit Aer statevector simulation...")
|
| 946 |
+
log_to_console(f" Processing {len(params['T_list'])} timestep(s)...")
|
| 947 |
+
|
| 948 |
+
# Determine velocity resolution (cap for performance)
|
| 949 |
+
vel_resolution = min(params['grid_size'], 32)
|
| 950 |
+
|
| 951 |
+
# Run simulation using qlbm_sample_app function
|
| 952 |
+
output, fig = run_sampling_sim(
|
| 953 |
+
n=params["n"],
|
| 954 |
+
ux=params["vx_expr"],
|
| 955 |
+
uy=params["vy_expr"],
|
| 956 |
+
uz=params["vz_expr"],
|
| 957 |
+
init_state_prep_circ=init_state_prep_circ,
|
| 958 |
+
T_list=params["T_list"],
|
| 959 |
+
vel_resolution=vel_resolution,
|
| 960 |
+
)
|
| 961 |
+
|
| 962 |
+
if progress_callback:
|
| 963 |
+
progress_callback(95)
|
| 964 |
+
|
| 965 |
+
log_to_console(f"Simulation complete: {len(output)} frame(s) generated")
|
| 966 |
+
|
| 967 |
+
return output, fig, params["T_list"]
|
| 968 |
+
|
| 969 |
+
|
| 970 |
# --- Main Simulation ---
|
| 971 |
def run_simulation():
|
| 972 |
"""Run the QLBM simulation."""
|
|
|
|
| 983 |
_state.qlbm_is_running = True
|
| 984 |
_state.qlbm_run_error = ""
|
| 985 |
_state.qlbm_simulation_has_run = False
|
| 986 |
+
_state.qlbm_qiskit_mode = False # Reset Qiskit mode
|
| 987 |
_state.qlbm_show_progress = True
|
| 988 |
_state.qlbm_simulation_progress = 0
|
| 989 |
_state.qlbm_status_message = "Running simulation..."
|
| 990 |
_state.qlbm_status_type = "info"
|
| 991 |
|
| 992 |
+
# Determine if using Qiskit backend
|
| 993 |
+
use_qiskit = (
|
| 994 |
+
_state.qlbm_backend_type == "Simulator" and
|
| 995 |
+
_state.qlbm_selected_simulator == "IBM Qiskit simulator" and
|
| 996 |
+
_QISKIT_BACKEND_AVAILABLE
|
| 997 |
+
)
|
| 998 |
+
|
| 999 |
# Log initial configuration
|
| 1000 |
+
backend_info = f"{_state.qlbm_backend_type}"
|
| 1001 |
+
if _state.qlbm_backend_type == "Simulator":
|
| 1002 |
+
backend_info += f" - {_state.qlbm_selected_simulator}"
|
| 1003 |
+
elif _state.qlbm_backend_type == "QPU":
|
| 1004 |
+
backend_info += f" - {_state.qlbm_selected_qpu}"
|
| 1005 |
+
|
| 1006 |
config_lines = [
|
| 1007 |
"Job Initiated",
|
| 1008 |
f" Grid Size: {_state.qlbm_grid_size} × {_state.qlbm_grid_size} × {_state.qlbm_grid_size}",
|
| 1009 |
f" Time Steps: {_state.qlbm_time_steps}",
|
| 1010 |
f" Distribution: {_state.qlbm_dist_type}",
|
| 1011 |
f" Boundary: {_state.qlbm_boundary_condition}",
|
| 1012 |
+
f" Backend: {backend_info}",
|
| 1013 |
f" Velocity: vx={_state.qlbm_vx_expr}, vy={_state.qlbm_vy_expr}, vz={_state.qlbm_vz_expr}",
|
| 1014 |
]
|
| 1015 |
for line in config_lines:
|
|
|
|
| 1024 |
last_logged_percent = percent
|
| 1025 |
|
| 1026 |
try:
|
| 1027 |
+
# === Qiskit Backend (IBM Qiskit Simulator) ===
|
| 1028 |
+
if use_qiskit:
|
| 1029 |
+
log_to_console("Using IBM Qiskit Simulator backend...")
|
| 1030 |
+
|
| 1031 |
+
# Run Qiskit simulation
|
| 1032 |
+
output, plotly_fig, T_list = _run_qiskit_simulation(progress_callback=_progress_callback)
|
| 1033 |
+
|
| 1034 |
+
# Store results
|
| 1035 |
+
simulation_data_frames = output
|
| 1036 |
+
simulation_times = [float(t) for t in T_list]
|
| 1037 |
+
|
| 1038 |
+
# Update the Plotly figure widget for Qiskit results
|
| 1039 |
+
if hasattr(_ctrl, "qlbm_qiskit_result_update"):
|
| 1040 |
+
_ctrl.qlbm_qiskit_result_update(plotly_fig)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1041 |
|
| 1042 |
+
_state.qlbm_max_time_step = len(output) - 1
|
| 1043 |
_state.qlbm_time_val = 0
|
| 1044 |
+
_state.qlbm_time_slider_labels = [f"T={t}" for t in T_list]
|
| 1045 |
_state.qlbm_simulation_has_run = True
|
| 1046 |
+
_state.qlbm_qiskit_mode = True # Use Plotly display instead of PyVista
|
| 1047 |
|
| 1048 |
+
_progress_callback(100)
|
| 1049 |
+
log_to_console("Qiskit simulation completed successfully.")
|
|
|
|
|
|
|
|
|
|
| 1050 |
_state.qlbm_status_message = "Simulation completed successfully."
|
| 1051 |
_state.qlbm_status_type = "success"
|
| 1052 |
+
|
| 1053 |
+
# === CUDA-Q or CPU Demo Backend ===
|
| 1054 |
else:
|
| 1055 |
+
_state.qlbm_qiskit_mode = False # Use PyVista display
|
| 1056 |
+
|
| 1057 |
+
grid_size = int(_state.qlbm_grid_size)
|
| 1058 |
+
num_reg_qubits = int(math.log2(grid_size)) if grid_size > 0 else 3
|
| 1059 |
+
T = int(_state.qlbm_time_steps)
|
| 1060 |
+
distribution_type = _state.qlbm_dist_type
|
| 1061 |
+
boundary_condition = _state.qlbm_boundary_condition
|
| 1062 |
+
|
| 1063 |
+
vx_func = make_velocity_func(_state.qlbm_vx_expr)
|
| 1064 |
+
vy_func = make_velocity_func(_state.qlbm_vy_expr)
|
| 1065 |
+
vz_func = make_velocity_func(_state.qlbm_vz_expr)
|
| 1066 |
+
|
| 1067 |
+
_progress_callback(0)
|
| 1068 |
+
|
| 1069 |
+
if simulate_qlbm_3D_and_animate is not None:
|
| 1070 |
+
log_to_console("Running CUDA-Q Simulation...")
|
| 1071 |
+
_plotter.clear()
|
| 1072 |
+
_, frames, times, grid_obj = simulate_qlbm_3D_and_animate(
|
| 1073 |
+
num_reg_qubits=num_reg_qubits,
|
| 1074 |
+
T=T,
|
| 1075 |
+
distribution_type=distribution_type,
|
| 1076 |
+
vx_input=vx_func,
|
| 1077 |
+
vy_input=vy_func,
|
| 1078 |
+
vz_input=vz_func,
|
| 1079 |
+
boundary_condition=boundary_condition,
|
| 1080 |
+
plotter=_plotter,
|
| 1081 |
+
add_slider=False,
|
| 1082 |
+
progress_callback=_progress_callback
|
| 1083 |
+
)
|
| 1084 |
+
else:
|
| 1085 |
+
log_to_console("Running CPU Demo Simulation...")
|
| 1086 |
+
frames, times, grid_obj = _run_cpu_demo_simulation(
|
| 1087 |
+
grid_size=grid_size,
|
| 1088 |
+
T=T,
|
| 1089 |
+
distribution_type=distribution_type or "Sinusoidal",
|
| 1090 |
+
vx_func=vx_func,
|
| 1091 |
+
vy_func=vy_func,
|
| 1092 |
+
vz_func=vz_func,
|
| 1093 |
+
progress_callback=_progress_callback
|
| 1094 |
+
)
|
| 1095 |
+
|
| 1096 |
+
_progress_callback(100)
|
| 1097 |
+
|
| 1098 |
+
# Update plotter with results
|
| 1099 |
+
if grid_obj:
|
| 1100 |
+
_plotter.clear()
|
| 1101 |
+
isosurfaces = grid_obj.contour(isosurfaces=7, scalars="scalars")
|
| 1102 |
+
_plotter.add_mesh(isosurfaces, cmap="Blues", opacity=0.3, show_scalar_bar=True)
|
| 1103 |
+
_plotter.add_axes()
|
| 1104 |
+
_plotter.show_grid()
|
| 1105 |
+
|
| 1106 |
+
# Store Results
|
| 1107 |
+
if frames and len(frames) > 0:
|
| 1108 |
+
simulation_data_frames = frames
|
| 1109 |
+
simulation_times = times
|
| 1110 |
+
current_grid_object = grid_obj
|
| 1111 |
+
|
| 1112 |
+
_state.qlbm_max_time_step = len(frames) - 1
|
| 1113 |
+
_state.qlbm_time_val = 0
|
| 1114 |
+
_state.qlbm_time_slider_labels = [f"{t:.1f}" for t in times] if times else [str(i) for i in range(len(frames))]
|
| 1115 |
+
_state.qlbm_simulation_has_run = True
|
| 1116 |
+
|
| 1117 |
+
_ensure_point_picking(on_pick_point)
|
| 1118 |
+
|
| 1119 |
+
if hasattr(_ctrl, "qlbm_view_update"):
|
| 1120 |
+
_ctrl.qlbm_view_update()
|
| 1121 |
+
log_to_console("Simulation completed successfully.")
|
| 1122 |
+
_state.qlbm_status_message = "Simulation completed successfully."
|
| 1123 |
+
_state.qlbm_status_type = "success"
|
| 1124 |
+
_state.qlbm_simulation_progress = 100
|
| 1125 |
+
else:
|
| 1126 |
+
_state.qlbm_run_error = "Simulation produced no data."
|
| 1127 |
+
log_to_console("Error: Simulation produced no data.")
|
| 1128 |
+
_state.qlbm_status_message = "Error: No data produced"
|
| 1129 |
+
_state.qlbm_status_type = "error"
|
| 1130 |
|
| 1131 |
except Exception as e:
|
| 1132 |
_state.qlbm_run_error = f"Simulation failed: {str(e)}"
|
| 1133 |
log_to_console(f"Simulation Error: {e}")
|
| 1134 |
print(f"Simulation Error: {e}")
|
| 1135 |
+
import traceback
|
| 1136 |
+
traceback.print_exc()
|
| 1137 |
_state.qlbm_status_message = "Simulation failed"
|
| 1138 |
_state.qlbm_status_type = "error"
|
| 1139 |
finally:
|
|
|
|
| 1158 |
_state.qlbm_is_running = False
|
| 1159 |
_state.qlbm_run_error = ""
|
| 1160 |
_state.qlbm_simulation_has_run = False
|
| 1161 |
+
_state.qlbm_qiskit_mode = False # Reset Qiskit mode
|
| 1162 |
_state.qlbm_dist_type = None
|
| 1163 |
_state.qlbm_show_edges = False
|
| 1164 |
_state.qlbm_problems_selection = None
|
|
|
|
| 1467 |
with vuetify3.VCard(classes="mb-2"):
|
| 1468 |
vuetify3.VCardTitle("Time", classes="text-subtitle-2 font-weight-bold text-primary")
|
| 1469 |
with vuetify3.VCardText():
|
| 1470 |
+
vuetify3.VSlider(label="Total Time", v_model=("qlbm_time_steps", 10), min=0, max=50, step=2,
|
| 1471 |
thumb_label="always", show_ticks="always", color="primary", density="compact", hide_details=True)
|
| 1472 |
vuetify3.VAlert(v_if="qlbm_time_steps > 100", type="warning", variant="tonal", density="compact",
|
| 1473 |
children=["Warning: High time steps may increase runtime."], classes="mt-2")
|
|
|
|
| 1561 |
# Main Plot Card
|
| 1562 |
with vuetify3.VCard(classes="mb-1 flex-grow-1 d-flex flex-column", elevation=2, style="min-height: 0;"):
|
| 1563 |
|
| 1564 |
+
# Geometry Preview (Plotly) - when no simulation and no distribution selected
|
| 1565 |
with vuetify3.VContainer(v_if="!qlbm_simulation_has_run && !qlbm_dist_type && qlbm_geometry_selection",
|
| 1566 |
fluid=True, classes="pa-0 flex-grow-1", style="width: 100%; height: 100%;"):
|
| 1567 |
geom_fig = plotly_widgets.Figure(figure=go.Figure(), style="width: 100%; height: 100%;", responsive=True)
|
| 1568 |
_ctrl.qlbm_geometry_plot_update = geom_fig.update
|
| 1569 |
|
| 1570 |
+
# Distribution Preview (Plotly) - when distribution selected but no simulation
|
| 1571 |
with vuetify3.VContainer(v_if="!qlbm_simulation_has_run && qlbm_dist_type",
|
| 1572 |
fluid=True, classes="pa-0 flex-grow-1", style="width: 100%; height: 100%;"):
|
| 1573 |
preview_fig = plotly_widgets.Figure(figure=go.Figure(), style="width:100%; height:100%;", responsive=True)
|
| 1574 |
_ctrl.qlbm_preview_update = preview_fig.update
|
| 1575 |
|
| 1576 |
+
# Download controls (for both modes)
|
| 1577 |
with vuetify3.VContainer(v_if="qlbm_simulation_has_run", classes="px-4 pt-3 pb-1 d-flex justify-end",
|
| 1578 |
style="width: 100%; flex: 0 0 auto;"):
|
| 1579 |
with vuetify3.VMenu(location="bottom end"):
|
|
|
|
| 1586 |
prepend_icon="mdi-download"
|
| 1587 |
)
|
| 1588 |
with vuetify3.VList(density="compact"):
|
| 1589 |
+
# VTK and MP4 exports only for non-Qiskit mode
|
| 1590 |
vuetify3.VListItem(
|
| 1591 |
+
v_if="!qlbm_qiskit_mode",
|
| 1592 |
title="Export as VTK",
|
| 1593 |
prepend_icon="mdi-content-save",
|
| 1594 |
click=export_simulation_vtk
|
| 1595 |
)
|
| 1596 |
vuetify3.VListItem(
|
| 1597 |
+
v_if="!qlbm_qiskit_mode",
|
| 1598 |
title="Export as MP4",
|
| 1599 |
prepend_icon="mdi-movie",
|
| 1600 |
click=export_simulation_mp4
|
| 1601 |
)
|
| 1602 |
+
# TODO: Add Plotly HTML export for Qiskit mode
|
| 1603 |
+
vuetify3.VListItem(
|
| 1604 |
+
v_if="qlbm_qiskit_mode",
|
| 1605 |
+
title="Export as HTML (Plotly)",
|
| 1606 |
+
prepend_icon="mdi-language-html5",
|
| 1607 |
+
disabled=True, # Not yet implemented
|
| 1608 |
+
)
|
| 1609 |
+
|
| 1610 |
+
# === Qiskit Simulation Result (Plotly with built-in slider) ===
|
| 1611 |
+
with vuetify3.VContainer(v_if="qlbm_simulation_has_run && qlbm_qiskit_mode",
|
| 1612 |
+
fluid=True, classes="pa-0 flex-grow-1",
|
| 1613 |
+
style="width: 100%; height: 100%;"):
|
| 1614 |
+
qiskit_fig = plotly_widgets.Figure(
|
| 1615 |
+
figure=go.Figure(),
|
| 1616 |
+
style="width:100%; height:100%;",
|
| 1617 |
+
responsive=True
|
| 1618 |
+
)
|
| 1619 |
+
_ctrl.qlbm_qiskit_result_update = qiskit_fig.update
|
| 1620 |
|
| 1621 |
+
# === PyVista Simulation Result (for CUDA-Q/CPU demo) ===
|
| 1622 |
+
with vuetify3.VContainer(v_if="qlbm_simulation_has_run && !qlbm_qiskit_mode",
|
| 1623 |
+
fluid=True, classes="pa-0 flex-grow-1",
|
| 1624 |
style="width: 100%; height: 100%;"):
|
| 1625 |
view = plotter_ui(plotter)
|
| 1626 |
_ctrl.qlbm_view_update = view.update
|
| 1627 |
|
| 1628 |
+
# Time Slider (only for non-Qiskit mode - Qiskit Plotly has built-in slider)
|
| 1629 |
+
with vuetify3.VContainer(v_if="qlbm_simulation_has_run && !qlbm_qiskit_mode",
|
| 1630 |
+
classes="px-4 pb-4", style="width: 90%; flex: 0 0 auto;"):
|
| 1631 |
with vuetify3.VSlider(
|
| 1632 |
v_model=("qlbm_time_val", 0),
|
| 1633 |
min=0,
|
requirements.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# Core scientific computing
|
| 2 |
numpy==2.2.6
|
| 3 |
-
scipy==1.
|
| 4 |
cudaq
|
| 5 |
|
| 6 |
# 3D Visualization
|
|
|
|
| 1 |
# Core scientific computing
|
| 2 |
numpy==2.2.6
|
| 3 |
+
scipy==1.15.3
|
| 4 |
cudaq
|
| 5 |
|
| 6 |
# 3D Visualization
|