Skip to main content

Creating a truth table for Noisy Toffoli gate by sampling

In this example, we will check the operation of a Toffoli gate in a noisy environment by a sampling-based truth table.

# %pip install "quri-parts[qulacs]"
from quri_parts.circuit import QuantumCircuit
from quri_parts.circuit.utils.circuit_drawer import draw_circuit


import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

n_qubits = 3
circuit = QuantumCircuit(n_qubits)
circuit.add_TOFFOLI_gate(0, 1, 2)

print("The circuit:")
draw_circuit(circuit)
#output

The circuit:


----●---
|
|
|
----●---
|
_|_
|TOF|
--|0 |-
|___|

In this example, we assume BitFlip Noise and Depolarizing Noise.

from quri_parts.circuit.noise import (
BitFlipNoise,
DepolarizingNoise,
NoiseModel,
)

noise_model = NoiseModel(
[
BitFlipNoise(error_prob=0.01),
DepolarizingNoise(error_prob=0.1),
]
)
from quri_parts.core.state import ComputationalBasisState, apply_circuit


def generate_truthtable(circuit, sampler, shots=1000):
"""
Generates a truth table for a given quantum circuit using a specified sampler.

Parameters:
circuit (QuantumCircuit): The quantum circuit for which the truth table is generated.
sampler (callable): A function that samples the given circuit.
shots (int): The number of shots used for sampling (default is 1000).

Returns:
None
"""

num_qubits = circuit.qubit_count
total_states = 2**num_qubits # Total number of initial states

results_list = []

for i in range(total_states):
init_state = ComputationalBasisState(num_qubits, bits=i)
sample_circuit = apply_circuit(circuit, init_state).circuit

results_list.append(sampler(sample_circuit, shots=shots))

# Prepare a dataframe to map initial states to sampled outcomes
data = []

for initial_state in range(total_states):
row = {}
for sampled_state in range(total_states):
# Check the correspondence between initial state and sampled outcome to get counts
count = results_list[sampled_state].get(initial_state, 0)
row[f"{sampled_state:b}".zfill(n_qubits)] = count / shots
data.append(row)

# Create a dataframe
df = pd.DataFrame(
data, index=[f"{i:b}".zfill(n_qubits) for i in range(total_states)]
)

# Display heatmap
plt.figure(figsize=(8, 6))
sns.heatmap(df, annot=True, cmap="viridis", fmt=".3f", cbar=True, vmax=1, vmin=0)

plt.xlabel("Sampled State")
plt.ylabel("Initial State")

plt.show()
from quri_parts.qulacs.sampler import create_qulacs_stochastic_state_vector_sampler

sampler = create_qulacs_stochastic_state_vector_sampler(noise_model)
shots = 1000
generate_truthtable(circuit, sampler, shots=shots)

png

We can see that the toffoli gate does not behave as expected in a noisy environment.