本文整理匯總了Python中pyquil.paulis.PauliSum方法的典型用法代碼示例。如果您正苦於以下問題:Python paulis.PauliSum方法的具體用法?Python paulis.PauliSum怎麽用?Python paulis.PauliSum使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pyquil.paulis
的用法示例。
在下文中一共展示了paulis.PauliSum方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: commuting_sets_trivial
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def commuting_sets_trivial(pauli_sum):
"""
Group a pauli term into commuting sets using trivial check
:param pauli_sum: PauliSum term
:return: list of lists containing individual Pauli Terms
"""
if not isinstance(pauli_sum, (PauliTerm, PauliSum)):
raise TypeError("This method can only group PauliTerm or PauliSum objects")
if isinstance(pauli_sum, PauliTerm):
pauli_sum = PauliSum([pauli_sum])
commuting_terms = []
for term in pauli_sum:
# find the group that it trivially commutes with
for term_group in commuting_terms:
if check_trivial_commutation(term_group, term):
term_group.append(term)
break
else:
commuting_terms.append([term])
return commuting_terms
示例2: remove_identity
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def remove_identity(psum: PauliSum) -> Tuple[Union[PauliSum, PauliTerm],
Union[float, PauliSum, PauliTerm]]:
"""
Remove the identity term from a Pauli sum.
:param psum: The PauliSum to process.
:return: The sums of the non-identity and identity PauliSums.
"""
new_psum = []
identity_terms = []
for term in psum:
if not is_identity(term):
new_psum.append(term)
else:
identity_terms.append(term)
return sum(new_psum), sum(identity_terms)
示例3: test_imaginary_removal
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def test_imaginary_removal():
"""
remove terms with imaginary coefficients from a pauli sum
"""
test_term = 0.25 * sX(1) * sZ(2) * sX(3) + 0.25j * sX(1) * sZ(2) * sY(3)
test_term += -0.25j * sY(1) * sZ(2) * sX(3) + 0.25 * sY(1) * sZ(2) * sY(3)
true_term = 0.25 * sX(1) * sZ(2) * sX(3) + 0.25 * sY(1) * sZ(2) * sY(3)
assert remove_imaginary_terms(test_term) == true_term
test_term = (0.25 + 1j) * sX(0) * sZ(2) + 1j * sZ(2)
# is_identity in pyquil apparently thinks zero is identity
assert remove_imaginary_terms(test_term) == 0.25 * sX(0) * sZ(2)
test_term = 0.25 * sX(0) * sZ(2) + 1j * sZ(2)
assert remove_imaginary_terms(test_term) == PauliSum([0.25 * sX(0) * sZ(2)])
with pytest.raises(TypeError):
remove_imaginary_terms(5)
with pytest.raises(TypeError):
remove_imaginary_terms(sX(0))
示例4: test_mutation_free_estimation
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def test_mutation_free_estimation():
"""
Make sure the estimation routines do not mutate the programs the user sends.
This is accomplished by a deep copy in `estimate_pauli_sum'.
"""
prog = Program().inst(I(0))
pauli_sum = sX(0) # measure in the X-basis
# set up fake QVM
with patch("pyquil.api.QuantumComputer") as qc:
# Mock the response
qc.run.return_value = [[0], [1]]
_, _, _ = estimate_locally_commuting_operator(prog,
pauli_sum=PauliSum([pauli_sum]),
variance_bound=1.0E-3,
quantum_resource=qc)
# make sure RY(-pi/2) 0\nMEASURE 0 [0] was not added to the program the user sees
assert prog.out() == 'I 0\n'
示例5: test_pass_hamiltonians
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def test_pass_hamiltonians():
ref_ham = [PauliSum([PauliTerm("X", 0, -1.0)]), PauliSum([PauliTerm("X", 1, -1.0)])]
cost_ham = [PauliTerm("I", 0, 0.5) + PauliTerm("Z", 0, -0.5) * PauliTerm("Z", 1, 1.0)]
fake_qc = Mock()
inst = QAOA(fake_qc, list(range(2)), steps=1,
cost_ham=cost_ham, ref_ham=ref_ham)
c = inst.cost_ham
r = inst.ref_ham
assert isinstance(c, list)
assert isinstance(r, list)
assert isinstance(c[0], PauliSum)
assert isinstance(r[0], PauliSum)
assert len(c) == 1
assert len(r) == 2
with pytest.raises(TypeError):
QAOA(fake_qc, 2, steps=1,
cost_ham=PauliTerm("X", 0, 1.0), ref_ham=ref_ham,
rand_seed=42)
示例6: kron_eigs
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def kron_eigs(ham: PauliSum, qubits: List[int]) -> np.array:
"""
Calculate the eigenvalues of `ham` ordered as a tensorproduct
on `qubits`. Each qubit should be acted on with the same operator
by each term or not at all.
"""
diag = np.zeros((2**len(qubits)))
for term in ham:
out = term.coefficient.real
for qubit in qubits:
if term[qubit] != 'I':
out = np.kron([1, -1], out)
else:
out = np.kron([1, 1], out)
diag += out
return diag
示例7: __init__
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def __init__(self,
hamiltonian: PauliSum,
params: Type[AbstractParams],
sim: WavefunctionSimulator = None,
scalar_cost_function: bool = True,
nshots: int = 0,
enable_logging: bool = False,
initial_state: Program = None,
qubit_mapping: Dict[QubitPlaceholder,
Union[Qubit, int]] = None):
"""The constructor. See class documentation."""
if initial_state is None:
initial_state = _all_plus_state(params.reg)
self.params = params
super().__init__(prepare_qaoa_ansatz(initial_state, params),
make_memory_map=make_qaoa_memory_map,
hamiltonian=hamiltonian,
sim=sim,
scalar_cost_function=scalar_cost_function,
nshots=nshots,
enable_logging=enable_logging,
qubit_mapping=qubit_mapping,
hamiltonian_is_diagonal=True)
示例8: linear_ramp_from_hamiltonian
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def linear_ramp_from_hamiltonian(cls,
hamiltonian: PauliSum,
n_steps: int,
time: float = None):
"""Alternative to ``__init__`` that already fills ``parameters``.
Calculate initial parameters from a hamiltonian corresponding to a
linear ramp annealing schedule and return a ``QAOAParams`` object.
Parameters
----------
hamiltonian:
``hamiltonian`` for which to calculate the initial QAOA parameters.
n_steps:
Number of timesteps.
time:
Total annealing time. Defaults to ``0.7*n_steps``.
Returns
-------
Type[AbstractParams]
The initial parameters for a linear ramp for ``hamiltonian``.
"""
raise NotImplementedError()
示例9: test_compute_action_type_checks
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def test_compute_action_type_checks():
"""
Make sure type checks are consistent and working
"""
with pytest.raises(TypeError):
compute_action([0, 0, 0, 0, 0], PauliSum([sX(0)]), 5)
with pytest.raises(TypeError):
compute_action([0, 0, 0, 0, 0], sX(0), 4)
with pytest.raises(TypeError):
compute_action(3, 'a', 4)
with pytest.raises(TypeError):
compute_action(-3, sX(0), 4)
with pytest.raises(TypeError):
compute_action('0001', sX(0), 4)
示例10: test_tensor_up_correctness
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def test_tensor_up_correctness():
"""Check the correctness of the tensor up routine"""
xy_term = PauliSum([PauliTerm("X", 0)*PauliTerm("Y", 1)])
# test correctness
trial_matrix = tensor_up(xy_term, 2)
true_matrix = np.kron(gate_matrix['Y'], gate_matrix['X'])
np.testing.assert_allclose(trial_matrix, true_matrix)
x1_term = PauliSum([PauliTerm("X", 1)])
trial_matrix = tensor_up(x1_term, 2)
true_matrix = np.kron(gate_matrix['X'], gate_matrix['I'])
np.testing.assert_allclose(trial_matrix, true_matrix)
zpz_term = PauliTerm("Z", 0) + PauliTerm("Z", 1)
trial_matrix = tensor_up(zpz_term, 2)
true_matrix = np.zeros((4, 4))
true_matrix[0, 0] = 2
true_matrix[-1, -1] = -2
np.testing.assert_allclose(trial_matrix, true_matrix)
示例11: __init__
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def __init__(
self,
gate_name: str,
parameters: List[Parameter],
arguments: List[QubitDesignator],
body: "PauliSum",
):
if not isinstance(gate_name, str):
raise TypeError("Gate name must be a string")
if gate_name in RESERVED_WORDS:
raise ValueError(f"Cannot use {gate_name} for a gate name since it's a reserved word")
self.name = gate_name
self.parameters = parameters
self.arguments = arguments
self.body = body
示例12: test_measure_observables_many_progs
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def test_measure_observables_many_progs(forest):
expts = [
ExperimentSetting(TensorProductState(), o1 * o2)
for o1, o2 in itertools.product([sI(0), sX(0), sY(0), sZ(0)], [sI(1), sX(1), sY(1), sZ(1)])
]
qc = get_qc("2q-qvm")
qc.qam.random_seed = 0
for prog in _random_2q_programs():
suite = Experiment(expts, program=prog)
assert len(suite) == 4 * 4
gsuite = group_experiments(suite)
assert len(gsuite) == 3 * 3 # can get all the terms with I for free in this case
wfn = WavefunctionSimulator()
wfn_exps = {}
for expt in expts:
wfn_exps[expt] = wfn.expectation(gsuite.program, PauliSum([expt.out_operator]))
for res in measure_observables(qc, gsuite):
np.testing.assert_allclose(wfn_exps[res.setting], res.expectation, atol=2e-2)
示例13: qubitop_to_pyquilpauli
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def qubitop_to_pyquilpauli(qubit_operator):
"""
Convert a OpenFermion QubitOperator to a PauliSum
:param QubitOperator qubit_operator: OpenFermion QubitOperator to convert to a pyquil.PauliSum
:return: PauliSum representing the qubit operator
:rtype: PauliSum
"""
if not isinstance(qubit_operator, QubitOperator):
raise TypeError("qubit_operator must be a OpenFermion "
"QubitOperator object")
transformed_term = PauliTerm("I", 0, 0.0)
for qubit_terms, coefficient in qubit_operator.terms.items():
base_term = PauliTerm('I', 0)
for tensor_term in qubit_terms:
base_term *= PauliTerm(tensor_term[1], tensor_term[0])
transformed_term += base_term * coefficient
return transformed_term
示例14: pyquilpauli_to_qubitop
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def pyquilpauli_to_qubitop(pyquil_pauli):
"""
Convert a pyQuil PauliSum to a OpenFermion QubitOperator
:param [PauliTerm, PauliSum] pyquil_pauli: pyQuil PauliTerm or PauliSum to convert to an
OpenFermion QubitOperator
:returns: a QubitOperator representing the PauliSum or PauliTerm
:rtype: QubitOperator
"""
if not isinstance(pyquil_pauli, (PauliSum, PauliTerm)):
raise TypeError("pyquil_pauli must be a pyquil PauliSum or "
"PauliTerm object")
if isinstance(pyquil_pauli, PauliTerm):
pyquil_pauli = PauliSum([pyquil_pauli])
transformed_term = QubitOperator()
# iterate through the PauliTerms of PauliSum
for pauli_term in pyquil_pauli.terms:
transformed_term += QubitOperator(
term=tuple(zip(pauli_term._ops.keys(), pauli_term._ops.values())),
coefficient=pauli_term.coefficient)
return transformed_term
示例15: pauli_term_relabel
# 需要導入模塊: from pyquil import paulis [as 別名]
# 或者: from pyquil.paulis import PauliSum [as 別名]
def pauli_term_relabel(pauli_sum, label_map):
"""
Relabel the elements of a pauli_sum via the `label_map`
:param pauli_sum: pauli sum to relabel. this can be a PauliTerm, PauliSum,
or even better a LIST!
:param label_map: a dictionary mapping old label to new label
:return: a list of pauli_terms relabeled
"""
if isinstance(pauli_sum, PauliTerm):
pauli_sum = PauliSum([pauli_sum])
if isinstance(pauli_sum, PauliSum):
pauli_sum = pauli_sum.terms
relabeled_terms = []
for term in pauli_sum:
new_term_as_list = []
for qlabel, pauli_element in term._ops.items():
new_term_as_list.append((pauli_element, label_map[qlabel]))
relabeled_terms.append(PauliTerm.from_list(
new_term_as_list, coefficient=term.coefficient))
return relabeled_terms