Skip to content

Commit 5cc3732

Browse files
committed
test
1 parent c2c455b commit 5cc3732

File tree

2 files changed

+168
-0
lines changed

2 files changed

+168
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
4+
# --- Quantum Gates and Helpers ---
5+
6+
I = np.eye(2)
7+
X = np.array([[0, 1], [1, 0]])
8+
Y = np.array([[0, -1j], [1j, 0]])
9+
Z = np.array([[1, 0], [0, -1]])
10+
11+
H = (1 / np.sqrt(2)) * np.array([[1, 1], [1, -1]])
12+
13+
def kron_n(*ops):
14+
"""Kronecker product of a sequence of gates."""
15+
result = ops[0]
16+
for op in ops[1:]:
17+
result = np.kron(result, op)
18+
return result
19+
20+
def GHZ_state(n):
21+
"""Create GHZ state |00..0> + |11..1>."""
22+
state = np.zeros(2**n, dtype=complex)
23+
state[0] = 1
24+
state[-1] = 1
25+
return state / np.sqrt(2)
26+
27+
def evolve_magnetic(state, B_t, t, gamma, n):
28+
"""Evolve under H = γ B(t) ΣZ_i for time t."""
29+
phi = gamma * B_t * t
30+
U = np.eye(1, dtype=complex)
31+
for _ in range(n):
32+
U = np.kron(U, expm(-1j * phi * Z / 2))
33+
return U @ state
34+
35+
36+
def expm(matrix):
37+
"""Matrix exponential for 2x2 Hermitian matrix."""
38+
eigvals, eigvecs = np.linalg.eigh(matrix)
39+
return eigvecs @ np.diag(np.exp(eigvals)) @ eigvecs.conj().T
40+
41+
def measure_in_X_basis(state, n):
42+
"""Measure expectation value of X⊗X⊗...⊗X."""
43+
Xn = kron_n(*([X] * n))
44+
return np.real(np.vdot(state, Xn @ state))
45+
46+
# --- Parameters ---
47+
48+
n = 3 # Number of qubits (entangled sensor)
49+
gamma = 1.0 # gyromagnetic ratio
50+
B0 = 1.0 # field amplitude
51+
omega = 1.0 # frequency of magnetic field
52+
times = np.linspace(0, 5, 100)
53+
54+
# --- Sensing Simulation ---
55+
56+
expectations = []
57+
true_fields = []
58+
59+
for t in times:
60+
B_t = B0 * np.sin(omega * t)
61+
true_fields.append(B_t)
62+
63+
# Prepare GHZ state
64+
psi0 = GHZ_state(n)
65+
66+
# Evolve under collective B field
67+
psi_t = evolve_magnetic(psi0, B_t, t, gamma, n)
68+
69+
# Apply inverse GHZ preparation (H and CNOTs)
70+
# For ideal simulation, we just measure in X^⊗n basis
71+
expX = measure_in_X_basis(psi_t, n)
72+
expectations.append(expX)
73+
74+
plt.figure(figsize=(10, 5))
75+
plt.plot(times, true_fields, label='B(t) = sin(ωt)', color='orange')
76+
plt.plot(times, expectations, label=r'$\langle X^{\otimes n} \rangle$', color='blue')
77+
plt.xlabel("Time")
78+
plt.ylabel("Field / Expectation")
79+
plt.title(f"Quantum Sensor with {n}-Qubit GHZ State")
80+
plt.legend()
81+
plt.grid(True)
82+
plt.tight_layout()
83+
plt.show()
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
from scipy.optimize import curve_fit
4+
5+
# --- Quantum Gates and Helpers ---
6+
7+
I = np.eye(2)
8+
X = np.array([[0, 1], [1, 0]])
9+
Z = np.array([[1, 0], [0, -1]])
10+
11+
def kron_n(*ops):
12+
result = ops[0]
13+
for op in ops[1:]:
14+
result = np.kron(result, op)
15+
return result
16+
17+
def GHZ_state(n):
18+
state = np.zeros(2**n, dtype=complex)
19+
state[0] = 1
20+
state[-1] = 1
21+
return state / np.sqrt(2)
22+
23+
def expm(matrix):
24+
eigvals, eigvecs = np.linalg.eigh(matrix)
25+
return eigvecs @ np.diag(np.exp(eigvals)) @ eigvecs.conj().T
26+
27+
def evolve_magnetic(state, B_t, t, gamma, n):
28+
phi = gamma * B_t * t
29+
U = np.eye(1, dtype=complex)
30+
for _ in range(n):
31+
U = np.kron(U, expm(-1j * phi * Z / 2))
32+
return U @ state
33+
34+
def measure_in_X_basis(state, n):
35+
Xn = kron_n(*([X] * n))
36+
return np.real(np.vdot(state, Xn @ state))
37+
38+
# --- Sensing Parameters ---
39+
40+
n = 3 # number of entangled qubits
41+
gamma = 1.0 # gyromagnetic ratio
42+
true_B0 = 0.8 # true unknown amplitude
43+
omega = 1.0 # known frequency
44+
times = np.linspace(0.1, 5, 200) # sensing times
45+
46+
# --- Simulate Sensor Signal ---
47+
48+
def B_field(t, B0): return B0 * np.sin(omega * t)
49+
50+
expectations = []
51+
for t in times:
52+
Bt = B_field(t, true_B0)
53+
psi = GHZ_state(n)
54+
psi_t = evolve_magnetic(psi, Bt, t, gamma, n)
55+
expectations.append(measure_in_X_basis(psi_t, n))
56+
57+
expectations = np.array(expectations)
58+
59+
# --- Step 1: Optimal Measurement Time ---
60+
61+
grad = np.gradient(expectations, times)
62+
optimal_time = times[np.argmax(np.abs(grad))]
63+
64+
print(f"🧠 Optimal measurement time: t = {optimal_time:.3f} s (max |d⟨Xⁿ⟩/dt|)")
65+
66+
# --- Step 2: Estimate Unknown B₀ ---
67+
68+
# Fit model: cos(γ n B₀ sin(ω t) * t)
69+
def model(t, B0_est):
70+
return np.cos(gamma * n * B0_est * np.sin(omega * t) * t)
71+
72+
B0_fit, _ = curve_fit(model, times, expectations, p0=[0.5])
73+
print(f"🔍 Estimated B₀: {B0_fit[0]:.3f} (true: {true_B0})")
74+
75+
plt.figure(figsize=(10, 5))
76+
plt.plot(times, expectations, label="Quantum Sensor Signal", color='blue')
77+
plt.plot(times, model(times, B0_fit[0]), '--', label=f"Fitted Model (B₀ ≈ {B0_fit[0]:.3f})", color='red')
78+
plt.axvline(optimal_time, color='green', linestyle=':', label=f"Optimal t = {optimal_time:.2f}")
79+
plt.xlabel("Time [s]")
80+
plt.ylabel(r"$\langle X^{\otimes n} \rangle$")
81+
plt.title(f"Quantum Sensor with GHZ({n}) State — Estimating $B_0$")
82+
plt.legend()
83+
plt.grid(True)
84+
plt.tight_layout()
85+
plt.show()

0 commit comments

Comments
 (0)