Skip to content

Commit c2da469

Browse files
committed
added examples
1 parent d4718d0 commit c2da469

File tree

2 files changed

+129
-0
lines changed

2 files changed

+129
-0
lines changed

doc/Programs/QuantumML/circuit.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import pennylane as qml
2+
import torch
3+
from torch.autograd import Variable
4+
import matplotlib.pyplot as plt
5+
6+
7+
dev = qml.device("default.qubit.torch", wires=1)
8+
9+
@qml.qnode(dev, interface='torch')
10+
def circuit(phi, theta):
11+
qml.RX(theta, wires=0)
12+
qml.RZ(phi, wires=0)
13+
return qml.expval(qml.PauliZ(0))
14+
15+
def cost(phi, theta, step):
16+
# Classical node
17+
target = -(-1)**(step // 100)
18+
return torch.abs(circuit(phi, theta) - target)**2
19+
20+
phi = Variable(torch.tensor(1.), requires_grad=True)
21+
theta = Variable(torch.tensor(0.05), requires_grad=True)
22+
opt = torch.optim.Adam([phi, theta], lr=0.1)
23+
24+
# Training Loop with Output Visualization:
25+
losses = []
26+
27+
for i in range(1000):
28+
opt.zero_grad()
29+
loss = cost(phi, theta, i)
30+
loss.backward()
31+
opt.step()
32+
33+
losses.append(loss.item())
34+
35+
# Print the final values of phi and theta
36+
print("Final phi:", phi.item())
37+
print("Final theta:", theta.item())
38+
39+
# Calculate and print the final expectation value of Pauli-Z
40+
final_expectation = circuit(phi, theta).item()
41+
print("Final Expectation Value of Pauli-Z:", final_expectation)
42+
43+
# Plot the loss curve
44+
plt.plot(range(1000), losses, label='Loss')
45+
plt.xlabel('Optimization Step')
46+
plt.ylabel('Loss')
47+
plt.legend()
48+
plt.show()
49+
50+
# Plot the circuit output over optimization steps
51+
plt.plot(range(1000), outputs, label='Circuit Output')
52+
plt.xlabel('Optimization Step')
53+
plt.ylabel('Circuit Output')
54+
plt.legend()
55+
plt.show()

doc/Programs/QuantumML/sensor.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
from qiskit import QuantumCircuit, Aer, transpile, assemble, execute
2+
import numpy as np
3+
import matplotlib.pyplot as plt
4+
5+
def create_quantum_circuit(theta):
6+
circuit = QuantumCircuit(1, 1)
7+
circuit.h(0) # Hadamard gate
8+
circuit.ry(theta, 0) # RY gate with parameter theta
9+
circuit.measure(0, 0)
10+
return circuit
11+
12+
def simulate_quantum_circuit(circuit, shots=1024):
13+
simulator = Aer.get_backend('qasm_simulator')
14+
compiled_circuit = transpile(circuit, simulator)
15+
result = execute(compiled_circuit, simulator, shots=shots).result()
16+
counts = result.get_counts(compiled_circuit)
17+
return counts
18+
19+
def parameter_shift(theta, target, shots=1024, delta=0.001, learning_rate=0.01):
20+
forward_circuit = create_quantum_circuit(theta + delta)
21+
backward_circuit = create_quantum_circuit(theta - delta)
22+
23+
forward_counts = simulate_quantum_circuit(forward_circuit, shots)
24+
backward_counts = simulate_quantum_circuit(backward_circuit, shots)
25+
26+
forward_expectation = forward_counts.get('0', 0) / shots
27+
backward_expectation = backward_counts.get('0', 0) / shots
28+
29+
gradient = (forward_expectation - backward_expectation) / (2 * delta)
30+
31+
return theta - learning_rate * gradient
32+
33+
def train_quantum_sensor(target, epochs=200, convergence_threshold=0.01):
34+
theta = -1.0
35+
# Lists to store data for final plot
36+
epochs_list = []
37+
cost_values = []
38+
39+
for epoch in range(epochs):
40+
circuit = create_quantum_circuit(theta)
41+
counts = simulate_quantum_circuit(circuit)
42+
43+
# Evaluate the cost function (simple example)
44+
cost = np.abs(counts.get('0', 0) / 1024 - target)
45+
46+
# Update theta using the parameter-shift rule
47+
theta = parameter_shift(theta, convergence_threshold) # Pass convergence threshold here
48+
49+
# Append data for final plot
50+
epochs_list.append(epoch + 1)
51+
cost_values.append(cost)
52+
53+
# Print numbers
54+
print(f"Epoch {epoch + 1}/{epochs}, Cost: {cost}, Theta: {theta}")
55+
56+
# Check for convergence
57+
if cost < convergence_threshold:
58+
print(f"Converged at epoch {epoch + 1} with cost {cost}")
59+
break
60+
61+
# Final plot
62+
plt.plot(epochs_list, cost_values, marker='o', linestyle='-', color='b')
63+
plt.title('Cost Function Over Epochs')
64+
plt.xlabel('Epochs')
65+
plt.ylabel('Cost')
66+
plt.grid(True)
67+
plt.show()
68+
69+
return theta
70+
# Example usage
71+
target_value = 0.9 # Replace with your target value
72+
trained_theta = train_quantum_sensor(target_value, convergence_threshold=0.0005
73+
)
74+
print(f"Trained Theta: {trained_theta}")

0 commit comments

Comments
 (0)