In [1]:
from qiskit import *
from qiskit.visualization import plot_histogram
from qiskit.circuit.library import PhaseOracle
from qiskit_algorithms import Grover, AmplificationProblem
from qiskit.primitives import Sampler
%matplotlib inline
In [2]:
# Define the oracle using the new PhaseOracle
oracle = PhaseOracle('((James & Lars) | (Kirk & Rob)) & ~(Lars & Rob)')
In [3]:
# Create an amplification problem using the oracle
# The evaluate_bitstring function will return True for bitstrings
# that satisfy the good states and False for those that do not
# This setup will guide Grover's algorithm to look for states that satisfy
# the logical conditions defined in the oracle.
problem = AmplificationProblem(oracle=oracle, is_good_state=oracle.evaluate_bitstring)
In [4]:
# Set up the simulator backend
from qiskit_aer import Aer
simulator = Aer.get_backend("qasm_simulator")
In [5]:
# Use the new Sampler primitive to run the quantum circuit
# Instantiate Grover's algorithm without quantum_instance
grover = Grover(sampler=Sampler())
# Run the Grover algorithm
result = grover.amplify(problem)
# Get and print the results
counts = result.circuit_results
print(counts)
# Optionally, visualize the results with a histogram
plot_histogram(counts)
[{'0011': 0.2499999999999994, '0111': 0.2499999999999994, '1100': 0.2499999999999994, '1101': 0.2499999999999994}]
Out[5]:
In [6]:
# The order of variables in your oracle expression is not strictly alphabetical
# but depends on the logical structure of the expression you defined
# Given the logical expression: oracle = PhaseOracle('((James & Lars) | (Kirk & Rob)) & ~(Lars & Rob)')
# The order is James, Lars, Kirk, Rob
# But it's reversed for the bit position:
# 0011: James - Lars
# 0111: James - Lars - Kirk
# 1100: Kirk - Rob
# 1101: James - Kirk - Rob