Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
from pyquil.api import local_qvm, WavefunctionSimulator
from pyquil import get_qc, Program
from pyquil.paulis import PauliSum, PauliTerm
from pyquil.quil import QubitPlaceholder
from forest_qaoa.qaoa.cost_function import (QAOACostFunctionOnQVM,
QAOACostFunctionOnWFSim)
from forest_qaoa.qaoa.parameters import (AnnealingParams,
StandardWithBiasParams)
# Create a mixed and somehwat more complicated hamiltonian
# TODO fix the whole Qubit Placeholder Business
hamiltonian = PauliSum.from_compact_str("1.0*Z0Z1")
hamiltonian += PauliTerm("Z", 1, 0.5)
next_term = PauliTerm("Z", 0, -2.0)
next_term *= PauliTerm("Z", 1)
hamiltonian += next_term
# TODO verfiy, that the results actually make sense
def test_QAOACostFunctionOnWFSim():
sim = WavefunctionSimulator()
params = AnnealingParams.linear_ramp_from_hamiltonian(hamiltonian, n_steps=4)
with local_qvm():
cost_function = QAOACostFunctionOnWFSim(hamiltonian,
params=params,
sim=sim,
scalar_cost_function=False,
noisy=True,
def test_PrepareAndMeasureOnQVM_QubitPlaceholders():
q1, q2 = QubitPlaceholder(), QubitPlaceholder()
prepare_ansatz = Program()
param_register = prepare_ansatz.declare(
"params", memory_type="REAL", memory_size=2)
prepare_ansatz.inst(RX(param_register[0], q1))
prepare_ansatz.inst(RX(param_register[1], q2))
def make_memory_map(params):
return {"params": params}
ham = PauliSum([PauliTerm("Z", q1), PauliTerm("Z",q2)])
qubit_mapping = get_default_qubit_mapping(prepare_ansatz)
qvm = get_qc("2q-qvm")
with local_qvm():
# qvm = proc.qvm
cost_fn = PrepareAndMeasureOnQVM(prepare_ansatz, make_memory_map,
qvm=qvm,
hamiltonian=ham, enable_logging=True,
scalar_cost_function=False,
base_numshots=10,
qubit_mapping=qubit_mapping)
out = cost_fn([np.pi, np.pi / 2], nshots=10)
assert np.allclose(cost_fn.log[0].fun, (-1.0, 0.1), rtol=1.1)
assert np.allclose(out, (-1, 0.1), rtol=1.1)
def ID() -> PauliTerm:
"""
The identity operator.
"""
return PauliTerm("I", 0, 1)
'disp': False}
:param vqe_option: (Optional. Default=None). VQE optional
arguments. If None set to
vqe_option = {'disp': print_fun, 'return_all': True,
'samples': samples}
:return: Most frequent Ising string, Energy of the Ising string, Circuit used to obtain result.
"""
if num_steps == 0:
num_steps = 2 * len(h)
n_nodes = len(h)
cost_operators = []
driver_operators = []
for i, j in J.keys():
cost_operators.append(PauliSum([PauliTerm("Z", i, J[(i, j)]) * PauliTerm("Z", j)]))
for i in range(n_nodes):
cost_operators.append(PauliSum([PauliTerm("Z", i, h[i])]))
driver_operators.append(PauliSum([PauliTerm("X", i, -1.0)]))
if connection is None:
qubits = list(sum(J.keys(), ()))
connection = get_qc(f"{len(qubits)}q-qvm")
if minimizer_kwargs is None:
minimizer_kwargs = {'method': 'Nelder-Mead',
'options': {'fatol': 1.0e-2, 'xatol': 1.0e-2,
'disp': False}}
if vqe_option is None:
vqe_option = {'disp': print, 'return_all': True,
'samples': samples}
maxcut_graph = nx.Graph()
for edge in graph:
maxcut_graph.add_edge(*edge)
graph = maxcut_graph.copy()
cost_operators = []
driver_operators = []
set_length = len(graph.nodes())
for node in xrange(set_length):
one_driver_term = PauliTerm("X", node, -1.0) * PauliTerm("X", (node + 1) % set_length, 1.0)
one_driver_term = one_driver_term + PauliTerm("Y", node, -1.0) * PauliTerm("Y", (node + 1) % set_length, 1.0)
driver_operators.append(one_driver_term)
for i, j in graph.edges():
cost_operators.append(PauliTerm("Z", i, -0.5)*PauliTerm("Z", j, 1.0) + PauliTerm("I", 0, 0.5))
# set number of qubits
n_qubits = len(graph.nodes())
# prepare driver initial state program
driver_init_prog = pq.Program()
for x in xrange(n_qubits/2):
driver_init_prog.inst(X(x))
if minimizer_kwargs is None:
minimizer_kwargs = {'method': 'Nelder-Mead',
'options': {'ftol': 1.0e-2,
'xtol': 1.0e-1,
'disp': True,
'maxfev': 100}}
:param minimizer_kwargs: (Optional. Default=None). Minimizer optional arguments. If None set to
``{'method': 'Nelder-Mead', 'options': {'ftol': 1.0e-2, 'xtol': 1.0e-2, 'disp': False}``
:param vqe_option: (Optional. Default=None). VQE optional arguments. If None set to
``vqe_option = {'disp': print_fun, 'return_all': True, 'samples': samples}``
"""
if not isinstance(graph, nx.Graph) and isinstance(graph, list):
maxcut_graph = nx.Graph()
for edge in graph:
maxcut_graph.add_edge(*edge)
graph = maxcut_graph.copy()
cost_operators = []
driver_operators = []
for i, j in graph.edges():
cost_operators.append(PauliTerm("Z", i, 0.5)*PauliTerm("Z", j) + PauliTerm("I", 0, -0.5))
for i in graph.nodes():
driver_operators.append(PauliSum([PauliTerm("X", i, -1.0)]))
if connection is None:
connection = get_qc(f"{len(graph.nodes)}q-qvm")
if minimizer_kwargs is None:
minimizer_kwargs = {'method': 'Nelder-Mead',
'options': {'ftol': 1.0e-2, 'xtol': 1.0e-2,
'disp': False}}
if vqe_option is None:
vqe_option = {'disp': print, 'return_all': True,
'samples': samples}
qaoa_inst = QAOA(connection, list(graph.nodes()), steps=steps, cost_ham=cost_operators,
ref_ham=driver_operators, store_basis=True,
def _operator_generator(index, conj):
"""
Internal method to generate the appropriate operator
"""
pterm = PauliTerm('I', 0, 1.0)
Zstring = PauliTerm('I', 0, 1.0)
for j in range(index):
Zstring = Zstring*PauliTerm('Z', j, 1.0)
pterm1 = Zstring*PauliTerm('X', index, 0.5)
scalar = 0.5 * conj * 1.0j
pterm2 = Zstring*PauliTerm('Y', index, scalar)
pterm = pterm * (pterm1 + pterm2)
pterm = pterm.simplify()
return pterm